@trainheroic-unofficial/cli 2.0.1 → 2.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
@@ -336,13 +336,24 @@ const leaderboardSpecSchema = z.union([
336
336
  instruction: z.string().optional()
337
337
  })
338
338
  ]);
339
- /** A block (group of exercises); two exercises render as a superset. */
339
+ /**
340
+ * A block (group of exercises); two exercises render as a superset.
341
+ * Empty `exercises` is allowed only with a non-empty `instruction` — that is TrainHeroic's
342
+ * free-text Circuit / Conditioning block (type 1): title + instruction blurb, no linked lifts.
343
+ */
340
344
  const blockSpecSchema = z.object({
341
345
  title: z.string(),
342
346
  type: z.number().optional(),
343
347
  instruction: z.string().optional(),
344
348
  leaderboard: leaderboardSpecSchema.optional(),
345
349
  exercises: z.array(exerciseSpecSchema)
350
+ }).superRefine((block, ctx) => {
351
+ if (block.exercises.length > 0) return;
352
+ if ((block.instruction?.trim() ?? "") === "") ctx.addIssue({
353
+ code: "custom",
354
+ message: "A block with no exercises needs a non-empty instruction (text-only Circuit / Conditioning block). Otherwise provide at least one exercise.",
355
+ path: ["exercises"]
356
+ });
346
357
  });
347
358
  /** A full session spec: the blocks plus an optional session note (Coach Instructions). */
348
359
  const workoutSpecSchema = z.object({
@@ -706,7 +717,7 @@ async function getJson(client, path, label) {
706
717
  if (!res.ok) throw new Error(`${label} failed (HTTP ${res.status}).`);
707
718
  return res.data;
708
719
  }
709
- async function getArray(client, path, label) {
720
+ async function getArray$1(client, path, label) {
710
721
  const res = await client.request("GET", path);
711
722
  if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
712
723
  return res.data;
@@ -789,10 +800,10 @@ function fetchAthletePrefs(client) {
789
800
  return getJson(client, "/1.0/athlete/prefs", "athlete prefs");
790
801
  }
791
802
  function fetchWorkingMaxes(client) {
792
- return getArray(client, "/2.0/athlete/workingMax", "athlete working maxes");
803
+ return getArray$1(client, "/2.0/athlete/workingMax", "athlete working maxes");
793
804
  }
794
805
  function fetchExerciseHistoryList(client) {
795
- return getArray(client, "/v5/users/exercises/history", "athlete exercise history list");
806
+ return getArray$1(client, "/v5/users/exercises/history", "athlete exercise history list");
796
807
  }
797
808
  /** Free-text search over the athlete's logged exercises (FTS replacement via rankSearch). */
798
809
  async function searchExerciseHistory(client, query, limit = 20) {
@@ -802,7 +813,7 @@ function fetchExerciseHistoryDetail(client, exerciseId, userId) {
802
813
  return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
803
814
  }
804
815
  function fetchPersonalRecords(client, exerciseId) {
805
- return getArray(client, `/v5/exercises/${exerciseId}/personalRecords`, "athlete personal records");
816
+ return getArray$1(client, `/v5/exercises/${exerciseId}/personalRecords`, "athlete personal records");
806
817
  }
807
818
  /** Last performance + PR for an exercise. `date` (YYYY-MM-DD) is required by the API. */
808
819
  function fetchExerciseStats(client, exerciseId, userId, date) {
@@ -810,7 +821,7 @@ function fetchExerciseStats(client, exerciseId, userId, date) {
810
821
  }
811
822
  /** Scheduled + completed workouts in an inclusive YYYY-MM-DD window. */
812
823
  function fetchAthleteWorkouts(client, startDate, endDate) {
813
- return getArray(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
824
+ return getArray$1(client, `/3.0/athlete/programworkout/range?startDate=${startDate}&endDate=${endDate}`, "athlete workouts");
814
825
  }
815
826
  /** Add `days` to a `YYYY-MM-DD` date (UTC), returning `YYYY-MM-DD`. */
816
827
  function shiftDate(iso, days) {
@@ -872,24 +883,6 @@ async function fetchAthleteWorkoutsChunked(client, startDate, endDate, opts = {}
872
883
  return page;
873
884
  }));
874
885
  }
875
- /**
876
- * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
877
- * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
878
- * `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
879
- * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
880
- */
881
- function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
882
- return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
883
- }
884
- /**
885
- * A coach's month view of a roster athlete's logged sessions
886
- * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
887
- * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
888
- * `userId` in each row is the roster athlete, not the calling coach.
889
- */
890
- function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
891
- return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
892
- }
893
886
  function fetchLeaderboard(client, workoutId, opts = {}) {
894
887
  const qs = new URLSearchParams();
895
888
  if (opts.page !== void 0) qs.set("page", String(opts.page));
@@ -1354,6 +1347,70 @@ function presentExerciseHistory(detail) {
1354
1347
  };
1355
1348
  }
1356
1349
  //#endregion
1350
+ //#region ../js/src/coach-athlete-calendar.ts
1351
+ async function getArray(client, path, label) {
1352
+ const res = await client.request("GET", path);
1353
+ if (!res.ok || !Array.isArray(res.data)) throw new Error(`${label} failed (HTTP ${res.status}).`);
1354
+ return res.data;
1355
+ }
1356
+ /**
1357
+ * A coach's view of a roster athlete's scheduled + completed workouts in an inclusive
1358
+ * YYYY-MM-DD window (`/3.0/coach/athlete/programworkout/range/{athleteId}`). Returns the same
1359
+ * `ProgramWorkout[]` shape as `fetchAthleteWorkouts`, so the same presenters and
1360
+ * `findSavedWorkoutSet` apply — it just reads another athlete's data through the coach surface.
1361
+ */
1362
+ function fetchCoachAthleteWorkouts(client, athleteId, startDate, endDate) {
1363
+ return getArray(client, `/3.0/coach/athlete/programworkout/range/${athleteId}?startDate=${startDate}&endDate=${endDate}`, "coach athlete workouts");
1364
+ }
1365
+ /**
1366
+ * A coach's month view of a roster athlete's logged sessions
1367
+ * (`/2.0/coach/athlete/calendar/summary`). The trailing path segment is required by the API but
1368
+ * ignored (any value returns the whole month); it mirrors the coach web app, which sends 7. The
1369
+ * `userId` in each row is the roster athlete, not the calling coach.
1370
+ */
1371
+ function fetchCoachAthleteCalendarSummary(client, athleteId, year, month) {
1372
+ return getArray(client, `/2.0/coach/athlete/calendar/summary/${athleteId}/${year}/${month}/7`, "coach athlete calendar summary");
1373
+ }
1374
+ /**
1375
+ * Resolve a roster athlete's coach-writable calendar program id
1376
+ * (`GET /v5/calendars/athletes/{athleteId}?year=&month=`).
1377
+ *
1378
+ * Year and month are required by the API (HTTP 400 without them); the returned `programId` is
1379
+ * stable for the athlete, so any month works. This is the calendar the coach web app writes
1380
+ * with `createWorkoutForDay` when you open an athlete from My Athletes → calendar — distinct
1381
+ * from athlete-created `personal_cal` ad-hoc sessions.
1382
+ */
1383
+ async function fetchCoachAthleteCalendar(client, athleteId, year, month) {
1384
+ const path = `/v5/calendars/athletes/${athleteId}?year=${year}&month=${month}`;
1385
+ const res = await client.request("GET", path);
1386
+ if (!res.ok) {
1387
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
1388
+ throw new Error(`GET ${path} failed (HTTP ${res.status}): ${detail}`);
1389
+ }
1390
+ if (!isRecord(res.data)) throw new Error("Unexpected athlete calendar response.");
1391
+ const programId = coerceInt(res.data.id);
1392
+ if (programId === null || programId <= 0) throw new Error(`Athlete calendar for ${athleteId} did not include a program id.`);
1393
+ return {
1394
+ programId,
1395
+ title: str$1(res.data.title) ?? "",
1396
+ type: coerceInt(res.data.type),
1397
+ groupId: coerceInt(res.data.group_id)
1398
+ };
1399
+ }
1400
+ /**
1401
+ * Resolve the calendar program id for `workout_build` / `coach workout build`: either an
1402
+ * explicit team/group `programId`, or a roster `athleteId` (+ date) via
1403
+ * `fetchCoachAthleteCalendar`. Exactly one of programId / athleteId is required.
1404
+ */
1405
+ async function resolveBuildProgramId(client, args) {
1406
+ if (args.programId !== void 0 && args.athleteId !== void 0) throw new Error("Pass programId or athleteId, not both.");
1407
+ if (args.programId !== void 0) return args.programId;
1408
+ if (args.athleteId === void 0) throw new Error("Provide programId (team calendar) or athleteId (athlete calendar).");
1409
+ if (args.date === void 0) throw new Error("athleteId requires date (YYYY-M-D) to resolve the athlete calendar.");
1410
+ const [y, m] = parseWorkoutDate(args.date);
1411
+ return (await fetchCoachAthleteCalendar(client, args.athleteId, y, m)).programId;
1412
+ }
1413
+ //#endregion
1357
1414
  //#region ../js/src/exercise-set-payload.ts
1358
1415
  function slotData(exercise, key) {
1359
1416
  const value = exercise?.[key];
@@ -2120,875 +2177,929 @@ function serializeWorkoutHistory(workouts, format, opts = {}) {
2120
2177
  filename: `${base}.${meta.extension}`
2121
2178
  };
2122
2179
  }
2123
- /** Normalize one-or-many emails into a deduped, trimmed list. */
2124
- function emailList(emails) {
2125
- return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
2126
- }
2127
- /** The display name on a /v5/athletes row: `fullName` (e.g. "Cohen, A"), else first+last. */
2128
- function rosterName(rec) {
2129
- const full = typeof rec.fullName === "string" ? rec.fullName.trim() : "";
2130
- if (full !== "") return full;
2131
- const combined = `${typeof rec.firstName === "string" ? rec.firstName : ""} ${typeof rec.lastName === "string" ? rec.lastName : ""}`.trim();
2132
- return combined !== "" ? combined : null;
2180
+ //#endregion
2181
+ //#region ../js/src/workout-encode.ts
2182
+ const LEADERBOARD_TYPE = {
2183
+ completion: 0,
2184
+ "for completion": 0,
2185
+ weight: 1,
2186
+ lb: 1,
2187
+ load: 1,
2188
+ reps: 2,
2189
+ rep: 2,
2190
+ rounds: 3,
2191
+ round: 3,
2192
+ time: 4,
2193
+ yards: 5,
2194
+ yd: 5,
2195
+ meters: 6,
2196
+ m: 6,
2197
+ feet: 7,
2198
+ ft: 7,
2199
+ calories: 8,
2200
+ cal: 8,
2201
+ cals: 8,
2202
+ miles: 10,
2203
+ mi: 10,
2204
+ inches: 12,
2205
+ in: 12,
2206
+ watts: 15,
2207
+ w: 15,
2208
+ velocity: 17,
2209
+ "m/s": 17,
2210
+ seconds: 18,
2211
+ sec: 18,
2212
+ s: 18
2213
+ };
2214
+ const LEADERBOARD_LABEL = {
2215
+ 0: "For Completion",
2216
+ 1: "Weight",
2217
+ 2: "Reps",
2218
+ 3: "Rounds",
2219
+ 4: "Time",
2220
+ 5: "Yards",
2221
+ 6: "Meters",
2222
+ 7: "Feet",
2223
+ 8: "Calories",
2224
+ 10: "Miles",
2225
+ 12: "Inches",
2226
+ 13: "Other",
2227
+ 15: "Watts",
2228
+ 16: "Percent",
2229
+ 17: "Velocity",
2230
+ 18: "Seconds"
2231
+ };
2232
+ function resolveLeaderboard(block) {
2233
+ const lb = block.leaderboard;
2234
+ if (lb === void 0 || lb === null) return {
2235
+ isRedzone: null,
2236
+ redzoneType: 0,
2237
+ smallerIsBetter: null,
2238
+ redzoneInstruction: ""
2239
+ };
2240
+ let unit;
2241
+ let instruction = "";
2242
+ let lowest;
2243
+ if (typeof lb === "object") {
2244
+ unit = lb.unit ?? lb.type;
2245
+ instruction = lb.instruction ?? "";
2246
+ lowest = lb.lowest_wins;
2247
+ } else unit = lb;
2248
+ let rz;
2249
+ if (typeof unit === "string") {
2250
+ const found = LEADERBOARD_TYPE[unit.trim().toLowerCase()];
2251
+ if (found === void 0) throw new Error(`Unknown leaderboard unit '${unit}'. Use one of: ${Object.keys(LEADERBOARD_TYPE).join(", ")}.`);
2252
+ rz = found;
2253
+ } else if (typeof unit === "number") rz = Math.trunc(unit);
2254
+ else throw new Error("Leaderboard requires a unit.");
2255
+ if (lowest === void 0) lowest = rz === 4 || rz === 18;
2256
+ return {
2257
+ isRedzone: 1,
2258
+ redzoneType: rz,
2259
+ smallerIsBetter: lowest ? 1 : 0,
2260
+ redzoneInstruction: instruction
2261
+ };
2133
2262
  }
2134
- /**
2135
- * The coach's roster as id + display name, from /v5/athletes. One home for the id coercion and the
2136
- * name-field choice (the API uses `fullName` / `firstName`+`lastName`), so the CLI, the MCP tools,
2137
- * and the warehouse store map the roster identically. Includes the account owner and
2138
- * demo/placeholder athletes (the raw roster does); pass `ids` to keep only a subset.
2139
- */
2140
- async function fetchCoachRoster(client, ids) {
2141
- const res = await client.request("GET", "/v5/athletes");
2142
- if (!res.ok || !Array.isArray(res.data)) throw new Error(`List athletes failed (HTTP ${res.status}).`);
2143
- const keep = ids && ids.length > 0 ? new Set(ids) : null;
2263
+ function slots(values, n = 10) {
2144
2264
  const out = [];
2145
- for (const row of res.data) {
2146
- if (typeof row !== "object" || row === null) continue;
2147
- const rec = row;
2148
- const id = coerceInt(rec.id);
2149
- if (id === null || id <= 0) continue;
2150
- if (keep && !keep.has(id)) continue;
2151
- out.push({
2152
- id,
2153
- name: rosterName(rec)
2154
- });
2155
- }
2265
+ for (let i = 0; i < n; i += 1) out.push(values && i < values.length ? values[i] ?? "" : "");
2156
2266
  return out;
2157
2267
  }
2158
- /**
2159
- * Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
2160
- * addresses (`POST /v5/emails/validate`), then invite the validated ones
2161
- * (`POST /v5/athletes/inviteToTeam`). Throws with the API detail on failure.
2162
- */
2163
- async function inviteAthletes(client, args) {
2164
- const list = emailList(args.emails);
2165
- if (list.length === 0) throw new Error("Provide at least one email address to invite.");
2166
- const validation = await client.request("POST", "/v5/emails/validate", { body: { emails: list.join(",") } });
2167
- if (!validation.ok) {
2168
- const detail = typeof validation.data === "string" ? validation.data : JSON.stringify(validation.data);
2169
- throw new Error(`Email validation failed (HTTP ${validation.status}): ${detail}`);
2170
- }
2171
- const valid = Array.isArray(validation.data) ? validation.data : list;
2172
- if (valid.length === 0) throw new Error(`No valid addresses among: ${list.join(", ")}. They may be malformed or already on the team.`);
2173
- const invite = await client.request("POST", "/v5/athletes/inviteToTeam", { body: {
2174
- teamType: 0,
2175
- teamId: args.teamId,
2176
- orgId: null,
2177
- emails: valid,
2178
- message: args.message ?? "Follow these steps and you'll be set up and ready to go!"
2179
- } });
2180
- if (!invite.ok) {
2181
- const detail = typeof invite.data === "string" ? invite.data : JSON.stringify(invite.data);
2182
- throw new Error(`Invite failed (HTTP ${invite.status}): ${detail}`);
2268
+ function repsList(ex) {
2269
+ const reps = ex.reps;
2270
+ if (Array.isArray(reps)) return reps.map((r) => String(r));
2271
+ if (reps === void 0 || reps === null) return [];
2272
+ const sets = Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2273
+ return Array.from({ length: sets }, () => String(reps));
2274
+ }
2275
+ /** Build one saveWorkoutSetExercises payload entry with all ten param slots filled. */
2276
+ function makeExercise(ex, workoutSetId, order, key) {
2277
+ const reps = repsList(ex);
2278
+ let instruction = ex.instr ?? "";
2279
+ if (instruction === "" && ex.rpe !== void 0 && ex.rpe !== null) instruction = `RPE ${ex.rpe}`;
2280
+ const hasWeight = ex.weight !== void 0 && ex.weight !== null;
2281
+ const weightArr = Array.isArray(ex.weight) ? ex.weight : null;
2282
+ let count = reps.length;
2283
+ if (count === 0 && hasWeight) count = weightArr ? weightArr.length : Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2284
+ let param2Type;
2285
+ let param2Values;
2286
+ if (hasWeight) {
2287
+ param2Type = ex.param_2_type ?? 1;
2288
+ param2Values = (weightArr ?? Array.from({ length: count }, () => ex.weight)).map((v) => String(v));
2289
+ } else {
2290
+ param2Type = 0;
2291
+ param2Values = null;
2183
2292
  }
2184
- return {
2185
- teamId: args.teamId,
2186
- invited: valid,
2187
- result: invite.data
2293
+ const entry = {
2294
+ exercise_id: ex.id,
2295
+ workout_set_id: workoutSetId,
2296
+ set_id: workoutSetId,
2297
+ setKey: workoutSetId,
2298
+ title: ex.title ?? "",
2299
+ instruction,
2300
+ order,
2301
+ param_1_type: ex.param_1_type ?? 3,
2302
+ param_2_type: param2Type,
2303
+ workout_set_exercise_template_id: null,
2304
+ no_sets: 0,
2305
+ param_count: count,
2306
+ set_num: count,
2307
+ key,
2308
+ video_url: "",
2309
+ thumbnail_url: "",
2310
+ tags: [],
2311
+ eType: "e",
2312
+ use_count: 0
2188
2313
  };
2314
+ const p1 = slots(reps);
2315
+ const p2 = slots(param2Values);
2316
+ for (let i = 0; i < 10; i += 1) {
2317
+ entry[`param_1_data_${i + 1}`] = p1[i] ?? "";
2318
+ entry[`param_2_data_${i + 1}`] = p2[i] ?? "";
2319
+ }
2320
+ return entry;
2189
2321
  }
2190
2322
  /**
2191
- * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
2192
- * The API wants the target date as a structured object (with weekday and an isToday flag),
2193
- * which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
2323
+ * Default block type: text-only (empty exercises) blocks are Conditioning / Circuit (type 1);
2324
+ * structured exercise blocks default to Hypertrophy (type 2). An explicit `type` always wins.
2194
2325
  */
2195
- async function copySession(client, args) {
2196
- const [year, month, day] = parseWorkoutDate(args.toDate);
2197
- const dayOfWeek = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
2198
- const iso = `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
2199
- const res = await client.request("POST", "/2.0/coach/calendar/copyProgramWorkout", { body: {
2200
- toProgramId: args.toProgramId,
2201
- pwId: args.pwId,
2202
- toDate: {
2203
- date: iso,
2204
- day,
2205
- month,
2206
- year,
2207
- dayOfWeek,
2208
- isToday: false
2209
- }
2210
- } });
2211
- if (!res.ok) throw new Error(`Copy session failed (HTTP ${res.status}).`);
2212
- return res.data;
2326
+ function defaultBlockType(block) {
2327
+ if (block.type !== void 0) return block.type;
2328
+ return block.exercises.length === 0 ? 1 : 2;
2213
2329
  }
2214
- const ANALYTICS_METRIC_KEYS = [
2215
- "readiness-team",
2216
- "readiness-athlete",
2217
- "lift-1rm-history",
2218
- "training-summary-athlete",
2219
- "compliance-team",
2220
- "lift-progress-team",
2221
- "working-max-history"
2222
- ];
2223
- const ANALYTICS_METRICS = {
2224
- "readiness-team": {
2225
- path: "/v5/analytics/readiness/teams",
2226
- scope: "team",
2227
- inputs: ["date"],
2228
- requires: ["date"]
2229
- },
2230
- "readiness-athlete": {
2231
- path: "/v5/analytics/readiness/users",
2232
- scope: "user",
2233
- inputs: ["dateStart", "dateEnd"],
2234
- requires: ["dateStart", "dateEnd"]
2235
- },
2236
- "lift-1rm-history": {
2237
- path: "/v5/analytics/lift-one-rep-max-history/users",
2238
- scope: "user",
2239
- inputs: [
2240
- "dateStart",
2241
- "dateEnd",
2242
- "exerciseId",
2243
- "useMetric"
2244
- ],
2245
- requires: [
2246
- "dateStart",
2247
- "dateEnd",
2248
- "exerciseId"
2249
- ]
2250
- },
2251
- "training-summary-athlete": {
2252
- path: "/v5/analytics/training-summary/users",
2253
- scope: "user",
2254
- inputs: ["dateStart", "dateEnd"],
2255
- requires: ["dateStart", "dateEnd"]
2256
- },
2257
- "compliance-team": {
2258
- path: "/v5/analytics/compliance",
2259
- scope: "team",
2260
- inputs: ["dateStart", "dateEnd"],
2261
- requires: ["dateStart", "dateEnd"]
2262
- },
2263
- "lift-progress-team": {
2264
- path: "/v5/analytics/lift-progress/teams",
2265
- scope: "team",
2266
- inputs: [
2267
- "exerciseId",
2268
- "dateStart",
2269
- "dateEnd"
2270
- ],
2271
- requires: [
2272
- "exerciseId",
2273
- "dateStart",
2274
- "dateEnd"
2275
- ]
2276
- },
2277
- "working-max-history": {
2278
- path: "/v5/analytics/working-max-history/users",
2279
- scope: "user",
2280
- inputs: [
2281
- "exerciseId",
2282
- "dateStart",
2283
- "dateEnd",
2284
- "useMetric"
2285
- ],
2286
- requires: ["exerciseId"]
2287
- }
2288
- };
2289
- /**
2290
- * A serializable description of every analytics metric: its scope (does it need a `teamId` or
2291
- * `userIds`) and which date/exercise inputs it requires vs. optionally accepts. The CLI/MCP
2292
- * surface this so an agent picks a valid `metric` + params up front, instead of discovering the
2293
- * shape by trial and error. These curated keys are deliberately NOT the raw category names from
2294
- * `GET /v5/analytics`; this catalog is the source of truth for `analytics-query`.
2295
- */
2296
- function analyticsMetricCatalog() {
2297
- return ANALYTICS_METRIC_KEYS.map((metric) => {
2298
- const spec = ANALYTICS_METRICS[metric];
2330
+ function buildBlockPayload(blocks, workoutId) {
2331
+ return blocks.map((b, i) => {
2332
+ const lb = resolveLeaderboard(b);
2299
2333
  return {
2300
- metric,
2301
- scope: spec.scope,
2302
- scopeParam: spec.scope === "team" ? "teamId" : "userIds",
2303
- requires: [...spec.requires],
2304
- optional: spec.inputs.filter((i) => !spec.requires.includes(i))
2334
+ workout_id: workoutId,
2335
+ order: i + 1,
2336
+ type: defaultBlockType(b),
2337
+ instruction: b.instruction ?? "",
2338
+ is_redzone: lb.isRedzone,
2339
+ redzone_type: lb.redzoneType,
2340
+ smaller_is_better: lb.smallerIsBetter,
2341
+ redzone_instruction: lb.redzoneInstruction,
2342
+ exercises: [],
2343
+ exerciseKeys: [],
2344
+ key: `k::${workoutId}${i + 1}`,
2345
+ title: b.title
2305
2346
  };
2306
2347
  });
2307
2348
  }
2308
- const ANALYTICS_BODY_KEY = {
2309
- date: "date",
2310
- dateStart: "date_start",
2311
- dateEnd: "date_end",
2312
- exerciseId: "exercise_id",
2313
- useMetric: "use_metric"
2314
- };
2349
+ function unitOr(t) {
2350
+ return unitLabel(t) ?? "?";
2351
+ }
2352
+ /** Flag spec params the API will silently override to the exercise's fixed units. */
2353
+ function unitAdvisory(blockTitle, ex, defaults) {
2354
+ const notes = [];
2355
+ const warnings = [];
2356
+ const u = unitOr;
2357
+ const label = `${blockTitle} / ${ex.title ?? ex.id}`;
2358
+ if (Array.isArray(ex.reps) && ex.sets !== void 0 && ex.reps.length !== ex.sets) warnings.push(`${label}: reps array has ${ex.reps.length} entr${ex.reps.length === 1 ? "y" : "ies"}; sets:${ex.sets} is ignored — building ${ex.reps.length} set(s).`);
2359
+ const sentP1 = ex.param_1_type;
2360
+ if (sentP1 !== void 0 && sentP1 !== null && Math.trunc(Number(sentP1)) !== defaults.param1) {
2361
+ const sp1 = Math.trunc(Number(sentP1));
2362
+ warnings.push(`${label}: param_1_type ${sentP1} (${u(sp1)}) is ignored — this exercise is fixed to ${u(defaults.param1)}; values render as ${u(defaults.param1)}.`);
2363
+ } else if (defaults.param1 !== 3 && defaults.param1 !== null) notes.push(`${label}: values are in ${u(defaults.param1)} (the exercise's fixed primary unit).`);
2364
+ if (ex.weight !== void 0 && ex.weight !== null) {
2365
+ const sentP2 = Math.trunc(Number(ex.param_2_type ?? 1));
2366
+ const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
2367
+ if (sentP2 !== effP2) if (sentP2 === 2 || sentP2 === 14) warnings.push(`${label}: ${u(sentP2)} does not stick on this exercise — it renders as ${u(effP2)}. Put it in the exercise 'instr' text and leave load blank.`);
2368
+ else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
2369
+ }
2370
+ return {
2371
+ notes,
2372
+ warnings
2373
+ };
2374
+ }
2315
2375
  /**
2316
- * Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
2317
- * athlete metrics need one or more `userIds` (passed together — the report returns a row per
2318
- * athlete). Throws a readable Error when a required input is missing or the call fails.
2376
+ * Run unit advisories across a whole block list against an exercise index. Shared by the
2377
+ * MCP workout_build tool and the CLI so both surface the same notes/warnings. Ensures the
2378
+ * index is loaded first, otherwise `defaults` returns null on a cold index and every
2379
+ * advisory is silently dropped.
2319
2380
  */
2320
- async function queryAnalytics(client, args) {
2321
- const spec = ANALYTICS_METRICS[args.metric];
2322
- const body = {};
2323
- if (spec.scope === "team") {
2324
- if (args.teamId === void 0) throw new Error(`${args.metric} needs teamId.`);
2325
- body.teamId = args.teamId;
2326
- } else {
2327
- if (args.userIds === void 0 || args.userIds.length === 0) throw new Error(`${args.metric} needs userIds (one or more athlete ids).`);
2328
- body.user_ids = args.userIds.map((u) => String(u));
2329
- }
2330
- const inputs = {
2331
- date: args.date,
2332
- dateStart: args.dateStart,
2333
- dateEnd: args.dateEnd,
2334
- exerciseId: args.exerciseId,
2335
- useMetric: args.useMetric
2381
+ async function collectAdvisories(blocks, index) {
2382
+ await index.ensureFresh();
2383
+ const pairs = blocks.flatMap((b) => b.exercises.map((ex) => ({
2384
+ block: b,
2385
+ ex
2386
+ })));
2387
+ const defaults = await Promise.all(pairs.map((p) => {
2388
+ const id = Number(p.ex.id);
2389
+ return Number.isFinite(id) ? index.defaults(id) : Promise.resolve(null);
2390
+ }));
2391
+ const notes = [];
2392
+ const warnings = [];
2393
+ pairs.forEach((p, i) => {
2394
+ const def = defaults[i];
2395
+ if (!def) return;
2396
+ const advisory = unitAdvisory(p.block.title, p.ex, def);
2397
+ notes.push(...advisory.notes);
2398
+ warnings.push(...advisory.warnings);
2399
+ });
2400
+ return {
2401
+ notes,
2402
+ warnings
2336
2403
  };
2337
- const missing = spec.requires.filter((k) => inputs[k] === void 0);
2338
- if (missing.length > 0) throw new Error(`${args.metric} also needs: ${missing.join(", ")}.`);
2339
- for (const k of spec.inputs) {
2340
- const v = inputs[k];
2341
- if (v === void 0) continue;
2342
- body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
2343
- }
2344
- const res = await client.request("POST", spec.path, { body });
2345
- if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
2346
- return res.data;
2347
2404
  }
2405
+ //#endregion
2406
+ //#region ../js/src/workout-session.ts
2348
2407
  /**
2349
- * Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
2350
- * place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
2351
- * there is no per-team roster endpoint. Returns the ids of athletes whose `groups` include the
2352
- * given id, matched as a string. Throws when the roster fetch fails.
2408
+ * Coach calendar writes (`createWorkoutForDay`, timeline create, `copyProgramWorkout`) 500/401
2409
+ * on personal calendars (Coach Plan / `personal_cal`). Shared by `buildSession` and
2410
+ * `copySession` so the hint stays in one place.
2353
2411
  */
2354
- async function fetchTeamAthleteIds(client, teamId) {
2355
- const res = await client.request("GET", "/v5/athletes");
2356
- if (!res.ok) throw new Error(`List athletes failed (HTTP ${res.status}).`);
2357
- const rows = Array.isArray(res.data) ? res.data : [];
2358
- const want = String(teamId);
2359
- const ids = [];
2360
- for (const row of rows) {
2361
- if (row === null || typeof row !== "object") continue;
2362
- const rec = row;
2363
- if (!(Array.isArray(rec.groups) ? rec.groups.map((g) => String(g)) : []).includes(want)) continue;
2364
- const id = typeof rec.id === "string" ? Number(rec.id) : rec.id;
2365
- if (typeof id === "number" && Number.isFinite(id)) ids.push(id);
2412
+ function calendarWriteError(method, path, status, detail) {
2413
+ const base = `${method} ${path} failed (HTTP ${status}): ${detail}`;
2414
+ if (!(path.includes("/createWorkoutForDay/") || path.includes("/createWorkoutForTimelineDay/") || path.includes("/copyProgramWorkout")) || status !== 500 && status !== 401) return new Error(base);
2415
+ return /* @__PURE__ */ new Error(`${base}. This often means the programId is not a coach-writable calendar — use a team/group programId (list_teams → group_program) or resolve a roster athlete's calendar via GET /v5/calendars/athletes/{athleteId}?year=&month= (workout_build athleteId). Athlete-created personal_cal ad-hoc sessions are a different surface.`);
2416
+ }
2417
+ async function req(client, method, path, body) {
2418
+ const res = await client.request(method, path, body === void 0 ? void 0 : { body });
2419
+ if (!res.ok) {
2420
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2421
+ throw calendarWriteError(method, path, res.status, detail);
2366
2422
  }
2367
- return ids;
2423
+ return res.data;
2368
2424
  }
2369
- function toNum(v) {
2370
- const n = typeof v === "string" ? Number(v) : typeof v === "number" ? v : NaN;
2371
- return Number.isFinite(n) ? n : 0;
2425
+ function createPath(opts) {
2426
+ if (opts.timelineDay !== void 0) return `/2.0/coach/calendar/workout/createWorkoutForTimelineDay/${opts.programId}/${opts.timelineDay}/null`;
2427
+ if (!opts.date) throw new Error("workout build requires either date or timelineDay");
2428
+ const [y, m, d] = opts.date;
2429
+ return `/2.0/coach/calendar/workout/createWorkoutForDay/${opts.programId}/${y}/${m}/${d}/0`;
2372
2430
  }
2373
- /**
2374
- * Team-wide training volume over an inclusive date window. The `training-summary-athlete`
2375
- * analytics report already returns the team in one call — one row per logged session across all
2376
- * `athleteIds` — so this fans nothing out: it queries once, groups rows by athlete (summing
2377
- * volume/reps and counting sessions), and rolls the athletes up into a team total. Athletes who
2378
- * logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
2379
- * all-time `fetchRosterActivity` snapshot, which has no date range.
2380
- */
2381
- async function teamVolume(client, args) {
2382
- if (args.athleteIds.length === 0) throw new Error("teamVolume needs at least one athleteId.");
2383
- const report = await queryAnalytics(client, {
2384
- metric: "training-summary-athlete",
2385
- userIds: args.athleteIds,
2386
- dateStart: args.dateStart,
2387
- dateEnd: args.dateEnd
2388
- });
2389
- const rows = report !== null && typeof report === "object" && Array.isArray(report.rows) ? report.rows : [];
2390
- const byAthlete = /* @__PURE__ */ new Map();
2391
- for (const row of rows) {
2392
- const athleteId = toNum(row.user_id);
2393
- if (athleteId === 0) continue;
2394
- const date = typeof row.date_completed === "string" ? row.date_completed.slice(0, 10) : null;
2395
- const name = [row.name_first, row.name_last].filter((s) => typeof s === "string" && s !== "").join(" ") || null;
2396
- const existing = byAthlete.get(athleteId);
2397
- if (existing) {
2398
- existing.sessions += 1;
2399
- existing.reps += toNum(row.reps);
2400
- existing.volume += toNum(row.volume);
2401
- if (date !== null) {
2402
- if (existing.firstLoggedDate === null || date < existing.firstLoggedDate) existing.firstLoggedDate = date;
2403
- if (existing.lastLoggedDate === null || date > existing.lastLoggedDate) existing.lastLoggedDate = date;
2404
- }
2405
- } else byAthlete.set(athleteId, {
2406
- athleteId,
2407
- name,
2408
- sessions: 1,
2409
- reps: toNum(row.reps),
2410
- volume: toNum(row.volume),
2411
- firstLoggedDate: date,
2412
- lastLoggedDate: date
2431
+ async function buildSession(client, opts) {
2432
+ const blocks = z.array(blockSpecSchema).parse(opts.blocks);
2433
+ const sess = await req(client, "POST", createPath(opts), {});
2434
+ checkResponse(sessionCreateResponseSchema, sess, "session create");
2435
+ const workoutId = Number(sess.workout_id);
2436
+ const pwId = Number(sess.id);
2437
+ const created = await req(client, "POST", "/2.0/coach/calendar/saveProgramWorkoutSets", buildBlockPayload(blocks, workoutId));
2438
+ const byOrder = new Map(created.map((b) => [b.order, b.id]));
2439
+ let counter = 0;
2440
+ const payloads = blocks.map((block, i) => {
2441
+ const wsid = byOrder.get(i + 1);
2442
+ if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
2443
+ return block.exercises.map((ex, j) => {
2444
+ counter += 1;
2445
+ return makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`);
2413
2446
  });
2414
- }
2415
- const athletes = [...byAthlete.values()].sort((a, b) => b.volume - a.volume);
2416
- const totals = athletes.reduce((acc, a) => ({
2417
- athletes: acc.athletes + 1,
2418
- sessions: acc.sessions + a.sessions,
2419
- reps: acc.reps + a.reps,
2420
- volume: acc.volume + a.volume
2421
- }), {
2422
- athletes: 0,
2423
- sessions: 0,
2424
- reps: 0,
2425
- volume: 0
2426
2447
  });
2448
+ await Promise.all(payloads.filter((p) => p.length > 0).map((p) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", p)));
2449
+ if (opts.instruction !== void 0 && opts.instruction !== "") {
2450
+ const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
2451
+ await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
2452
+ }
2453
+ if (opts.publish ?? false) await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
2427
2454
  return {
2428
- window: {
2429
- start: args.dateStart,
2430
- end: args.dateEnd
2431
- },
2432
- athletes,
2433
- totals
2455
+ pwId,
2456
+ workoutId
2434
2457
  };
2435
2458
  }
2436
- //#endregion
2437
- //#region ../js/src/main-lifts.ts
2438
2459
  /**
2439
- * The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
2440
- * first family that matches, so the more specific / easily-confused families come before the broad
2441
- * overhead-press rule. That ordering is why "Bench Press" classifies as `bench` and never gets
2442
- * swept up as an overhead press, and why "Clean & Jerk" is not mistaken for a clean-only movement.
2443
- * This is the single place to edit the lift set.
2460
+ * Set a session's Coach Instructions (the day-note at the top of a session). `pw` is the
2461
+ * programWorkout object (the create-time response or a day's edit-GET entry). The PUT wants
2462
+ * the whole object back with `instruction` set and `sets`/`setKeys` as a flat list of block
2463
+ * ids. This does NOT change publish state: `published` is sent exactly as it is on `pw`.
2444
2464
  */
2445
- const MAIN_LIFT_FAMILIES = [
2446
- {
2447
- key: "cleanjerk",
2448
- label: "Clean & Jerk",
2449
- matches: (t) => t.includes("jerk") || t.includes("clean") && !t.includes("clean pull")
2450
- },
2451
- {
2452
- key: "snatch",
2453
- label: "Snatch",
2454
- matches: (t) => t.includes("snatch")
2455
- },
2456
- {
2457
- key: "deadlift",
2458
- label: "Deadlift",
2459
- matches: (t) => t.includes("deadlift")
2460
- },
2461
- {
2462
- key: "squat",
2463
- label: "Squat",
2464
- matches: (t) => t.includes("squat")
2465
- },
2466
- {
2467
- key: "bench",
2468
- label: "Bench Press",
2469
- matches: (t) => t.includes("bench")
2470
- },
2471
- {
2472
- key: "overhead",
2473
- label: "Overhead Press",
2474
- matches: (t) => t.includes("ohp") || (t.includes("overhead") || t.includes("shoulder") || t.includes("military") || t.includes("strict") || t.includes("push")) && t.includes("press")
2475
- }
2476
- ];
2477
- /** The lift family a logged exercise title belongs to, or null if it is not a main lift. */
2478
- function classifyMainLift(title) {
2479
- const t = title.toLowerCase();
2480
- for (const family of MAIN_LIFT_FAMILIES) if (family.matches(t)) return family.key;
2481
- return null;
2465
+ async function setSessionInstruction(client, workoutId, pw, instruction, blockIds) {
2466
+ const body = {
2467
+ ...pw,
2468
+ instruction,
2469
+ sets: blockIds,
2470
+ setKeys: blockIds
2471
+ };
2472
+ await req(client, "PUT", `/3.0/coach/workout/${workoutId}`, body);
2482
2473
  }
2483
- const DEFAULT_MONTHS = 12;
2484
- function pad2(n) {
2485
- return String(n).padStart(2, "0");
2474
+ async function removeSession(client, programId, pwId) {
2475
+ await req(client, "POST", "/2.0/coach/calendar/removeProgramWorkout", {
2476
+ programId,
2477
+ pwId
2478
+ });
2486
2479
  }
2487
- /** A local Date as a YYYY-MM-DD day string (the range endpoint's date format). */
2488
- function isoDay(d) {
2489
- return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
2480
+ async function publishSession(client, pwId) {
2481
+ await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
2490
2482
  }
2491
- /**
2492
- * Discover a roster athlete's main lifts from what they actually logged. Reads the athlete's
2493
- * logged workouts over the last `months` (default 12) — the program-workout range, the reliable
2494
- * record of performed sets — buckets every performed exercise into a lift family, and for each
2495
- * family picks the variant logged most often. Returns one entry per family the athlete has logged;
2496
- * families they never trained are simply absent. (The monthly calendar summary is not used: it
2497
- * comes back empty for some accounts that have logged sets in the range endpoint.)
2498
- */
2499
- async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
2500
- const months = opts.months ?? DEFAULT_MONTHS;
2501
- const now = opts.now ?? /* @__PURE__ */ new Date();
2502
- const start = new Date(now.getFullYear(), now.getMonth() - (months - 1), 1);
2503
- const tally = /* @__PURE__ */ new Map();
2504
- let workouts = [];
2505
- try {
2506
- workouts = await fetchCoachAthleteWorkouts(client, athleteId, isoDay(start), isoDay(now));
2507
- } catch {
2508
- workouts = [];
2509
- }
2510
- for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
2511
- if (ex.performed.length === 0 || ex.exerciseId === null) continue;
2512
- const family = classifyMainLift(ex.title);
2513
- if (family === null) continue;
2514
- const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
2515
- const prev = byId.get(ex.exerciseId);
2516
- byId.set(ex.exerciseId, {
2517
- count: (prev?.count ?? 0) + 1,
2518
- title: prev?.title ?? ex.title
2519
- });
2520
- tally.set(family, byId);
2521
- }
2522
- const lifts = [];
2523
- for (const family of MAIN_LIFT_FAMILIES) {
2524
- const byId = tally.get(family.key);
2525
- if (!byId || byId.size === 0) continue;
2526
- let best = null;
2527
- for (const [exerciseId, { count, title }] of byId) if (best === null || count > best.count || count === best.count && exerciseId < best.exerciseId) best = {
2528
- exerciseId,
2529
- count,
2530
- title
2531
- };
2532
- if (best) lifts.push({
2533
- family: family.key,
2534
- label: family.label,
2535
- exerciseId: best.exerciseId,
2536
- title: best.title
2537
- });
2538
- }
2483
+ function str(value) {
2484
+ return value === void 0 || value === null ? "" : String(value);
2485
+ }
2486
+ async function readSession(client, programId, date, pwId) {
2487
+ const [y, m, d] = date;
2488
+ const data = await req(client, "GET", `/1.0/coach/programs/edit/${programId}/${y}/${m}/${d}`);
2489
+ checkResponse(programsEditResponseSchema, data, "programs edit");
2490
+ const pw = (data.programWorkouts ?? []).find((p) => coerceInt(p.id) === pwId);
2491
+ if (!pw) throw new Error(`programWorkout ${pwId} not found on ${y}-${m}-${d}.`);
2492
+ const setsObj = pw.sets ?? {};
2493
+ const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
2539
2494
  return {
2540
- athleteId,
2541
- athleteName: null,
2542
- lifts
2495
+ pwId,
2496
+ date: `${str(pw.year)}-${str(pw.month)}-${str(pw.day)}`,
2497
+ published: pw.published,
2498
+ instruction: str(pw.instruction),
2499
+ blocks
2543
2500
  };
2544
2501
  }
2545
- const PR_CONCURRENCY = 5;
2546
- /** The heaviest PR on an exercise's board (ties broken by more reps). */
2547
- function bestPr(liftPRs) {
2548
- let best = null;
2549
- for (const pr of liftPRs) {
2550
- const weight = coerceNum(pr.weight);
2551
- if (weight === null) continue;
2552
- const reps = coerceInt(pr.reps);
2553
- if (best === null || weight > best.weight || weight === best.weight && (reps ?? 0) > (best.reps ?? 0)) best = {
2554
- weight,
2555
- reps,
2556
- units: pr.units,
2557
- date: pr.date
2558
- };
2502
+ function readBlock(b) {
2503
+ const rz = coerceInt(b.redzone_type);
2504
+ let leaderboard = null;
2505
+ if (rz && rz > 0) leaderboard = `FOR ${(LEADERBOARD_LABEL[rz] ?? `type ${rz}`).toUpperCase()}${b.smaller_is_better ? " (lowest wins)" : ""}`;
2506
+ const exercises = (Array.isArray(b.exercises) ? b.exercises : []).filter((ex) => coerceInt(ex.id) !== null || str(ex.title) !== "").sort((a, e) => Number(a.order) - Number(e.order)).map((ex) => readExercise(ex));
2507
+ return {
2508
+ order: Number(b.order),
2509
+ title: str(b.title),
2510
+ instruction: str(b.instruction),
2511
+ leaderboard,
2512
+ exercises
2513
+ };
2514
+ }
2515
+ function readExercise(ex) {
2516
+ const reps = [];
2517
+ const load = [];
2518
+ for (let i = 1; i <= 10; i += 1) {
2519
+ const r = str(ex[`param_1_data_${i}`]);
2520
+ if (r !== "") reps.push(r);
2521
+ const w = str(ex[`param_2_data_${i}`]);
2522
+ if (w !== "") load.push(w);
2559
2523
  }
2560
- return best;
2524
+ return {
2525
+ order: Number(ex.order),
2526
+ title: str(ex.title),
2527
+ reps,
2528
+ primaryUnit: unitLabel(coerceInt(ex.param_1_type)),
2529
+ load,
2530
+ loadUnit: unitLabel(coerceInt(ex.param_2_type)),
2531
+ instruction: str(ex.instruction)
2532
+ };
2533
+ }
2534
+ /** Normalize one-or-many emails into a deduped, trimmed list. */
2535
+ function emailList(emails) {
2536
+ return [...new Set(emails.map((e) => e.trim()).filter((e) => e.length > 0))];
2537
+ }
2538
+ /** The display name on a /v5/athletes row: `fullName` (e.g. "Cohen, A"), else first+last. */
2539
+ function rosterName(rec) {
2540
+ const full = typeof rec.fullName === "string" ? rec.fullName.trim() : "";
2541
+ if (full !== "") return full;
2542
+ const combined = `${typeof rec.firstName === "string" ? rec.firstName : ""} ${typeof rec.lastName === "string" ? rec.lastName : ""}`.trim();
2543
+ return combined !== "" ? combined : null;
2561
2544
  }
2562
2545
  /**
2563
- * A roster athlete's best PR for each main lift. Discovers the lift variants they log
2564
- * ({@link resolveAthleteMainLifts}), then pulls each variant's PR board and keeps the heaviest set.
2565
- * The result always carries one entry per family in {@link MAIN_LIFT_FAMILIES} order; a family the
2566
- * athlete has not logged comes back with null fields (the "no PR yet" case), so a dashboard can
2567
- * render a stable row of columns.
2546
+ * The coach's roster as id + display name, from /v5/athletes. One home for the id coercion and the
2547
+ * name-field choice (the API uses `fullName` / `firstName`+`lastName`), so the CLI, the MCP tools,
2548
+ * and the warehouse store map the roster identically. Includes the account owner and
2549
+ * demo/placeholder athletes (the raw roster does); pass `ids` to keep only a subset.
2568
2550
  */
2569
- async function fetchAthleteMainLiftPRs(client, athleteId, opts = {}) {
2570
- const { athleteName, lifts } = await resolveAthleteMainLifts(client, athleteId, opts);
2571
- const byFamily = new Map(lifts.map((l) => [l.family, l]));
2572
- return {
2573
- athleteId,
2574
- athleteName,
2575
- prs: await mapPool(MAIN_LIFT_FAMILIES, PR_CONCURRENCY, async (family) => {
2576
- const lift = byFamily.get(family.key);
2577
- const base = {
2578
- family: family.key,
2579
- label: family.label
2580
- };
2581
- const empty = {
2582
- exerciseId: null,
2583
- title: null,
2584
- weight: null,
2585
- reps: null,
2586
- units: null,
2587
- date: null
2588
- };
2589
- if (!lift) return {
2590
- ...base,
2591
- ...empty
2592
- };
2593
- const known = {
2594
- exerciseId: lift.exerciseId,
2595
- title: lift.title
2596
- };
2597
- try {
2598
- const best = bestPr(presentExerciseHistory(await fetchExerciseHistoryDetail(client, lift.exerciseId, athleteId)).liftPRs);
2599
- return {
2600
- ...base,
2601
- ...known,
2602
- weight: best?.weight ?? null,
2603
- reps: best?.reps ?? null,
2604
- units: best?.units ?? null,
2605
- date: best?.date ?? null
2606
- };
2607
- } catch {
2608
- return {
2609
- ...base,
2610
- ...known,
2611
- weight: null,
2612
- reps: null,
2613
- units: null,
2614
- date: null
2615
- };
2616
- }
2617
- })
2618
- };
2551
+ async function fetchCoachRoster(client, ids) {
2552
+ const res = await client.request("GET", "/v5/athletes");
2553
+ if (!res.ok || !Array.isArray(res.data)) throw new Error(`List athletes failed (HTTP ${res.status}).`);
2554
+ const keep = ids && ids.length > 0 ? new Set(ids) : null;
2555
+ const out = [];
2556
+ for (const row of res.data) {
2557
+ if (typeof row !== "object" || row === null) continue;
2558
+ const rec = row;
2559
+ const id = coerceInt(rec.id);
2560
+ if (id === null || id <= 0) continue;
2561
+ if (keep && !keep.has(id)) continue;
2562
+ out.push({
2563
+ id,
2564
+ name: rosterName(rec)
2565
+ });
2566
+ }
2567
+ return out;
2619
2568
  }
2620
- const ROSTER_CONCURRENCY = 4;
2621
2569
  /**
2622
- * Every roster athlete's main-lift PRs in one call: list the roster ({@link fetchCoachRoster}) and
2623
- * resolve each athlete's board ({@link fetchAthleteMainLiftPRs}), fanned out with a bounded pool.
2624
- * `athleteIds` restricts to a subset (else the whole roster). Each entry's `athleteName` falls back
2625
- * to the roster name when the per-athlete read can't supply one. This is the single roster-level
2626
- * primitive the CLI, the MCP tool, and the warehouse store all build on.
2570
+ * Invite athletes to a team — TrainHeroic's two-step "create athlete" flow: validate the
2571
+ * addresses (`POST /v5/emails/validate`), then invite the validated ones
2572
+ * (`POST /v5/athletes/inviteToTeam`). Throws with the API detail on failure.
2627
2573
  */
2628
- async function fetchRosterMainLiftPRs(client, opts = {}) {
2629
- const roster = await fetchCoachRoster(client, opts.athleteIds);
2630
- const inner = {
2631
- ...opts.months !== void 0 ? { months: opts.months } : {},
2632
- ...opts.now !== void 0 ? { now: opts.now } : {}
2574
+ async function inviteAthletes(client, args) {
2575
+ const list = emailList(args.emails);
2576
+ if (list.length === 0) throw new Error("Provide at least one email address to invite.");
2577
+ const validation = await client.request("POST", "/v5/emails/validate", { body: { emails: list.join(",") } });
2578
+ if (!validation.ok) {
2579
+ const detail = typeof validation.data === "string" ? validation.data : JSON.stringify(validation.data);
2580
+ throw new Error(`Email validation failed (HTTP ${validation.status}): ${detail}`);
2581
+ }
2582
+ const valid = Array.isArray(validation.data) ? validation.data : list;
2583
+ if (valid.length === 0) throw new Error(`No valid addresses among: ${list.join(", ")}. They may be malformed or already on the team.`);
2584
+ const invite = await client.request("POST", "/v5/athletes/inviteToTeam", { body: {
2585
+ teamType: 0,
2586
+ teamId: args.teamId,
2587
+ orgId: null,
2588
+ emails: valid,
2589
+ message: args.message ?? "Follow these steps and you'll be set up and ready to go!"
2590
+ } });
2591
+ if (!invite.ok) {
2592
+ const detail = typeof invite.data === "string" ? invite.data : JSON.stringify(invite.data);
2593
+ throw new Error(`Invite failed (HTTP ${invite.status}): ${detail}`);
2594
+ }
2595
+ return {
2596
+ teamId: args.teamId,
2597
+ invited: valid,
2598
+ result: invite.data
2633
2599
  };
2634
- return mapPool(roster, opts.concurrency ?? ROSTER_CONCURRENCY, async (athlete) => {
2635
- const result = await fetchAthleteMainLiftPRs(client, athlete.id, inner);
2636
- return {
2637
- athleteId: athlete.id,
2638
- athleteName: result.athleteName ?? athlete.name,
2639
- prs: result.prs
2640
- };
2641
- });
2642
2600
  }
2643
- //#endregion
2644
- //#region ../js/src/util.ts
2645
2601
  /**
2646
- * Drop the keys whose value is `undefined`, so the result can be passed to a function or
2647
- * spread into an object under `exactOptionalPropertyTypes` without the per-key
2648
- * `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
2649
- * optional ones lose `undefined` from their value type.
2602
+ * Update a team's title and/or reassign its calendar (`PUT /v5/teams/{teamId}`).
2650
2603
  *
2651
- * Example:
2652
- * definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
2604
+ * The live API accepts `group_program` to point the team at an existing parent program /
2605
+ * calendar (e.g. another team's `group_program` from `list_teams`), but rejects a body that
2606
+ * has only `group_program` (HTTP 400 "Invalid parameters"). When `title` is omitted we read
2607
+ * the current title first so callers can re-link without renaming.
2653
2608
  */
2654
- function definedProps(obj) {
2655
- const result = {};
2656
- for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
2657
- return result;
2658
- }
2659
- //#endregion
2660
- //#region ../js/src/workout-encode.ts
2661
- const LEADERBOARD_TYPE = {
2662
- completion: 0,
2663
- "for completion": 0,
2664
- weight: 1,
2665
- lb: 1,
2666
- load: 1,
2667
- reps: 2,
2668
- rep: 2,
2669
- rounds: 3,
2670
- round: 3,
2671
- time: 4,
2672
- yards: 5,
2673
- yd: 5,
2674
- meters: 6,
2675
- m: 6,
2676
- feet: 7,
2677
- ft: 7,
2678
- calories: 8,
2679
- cal: 8,
2680
- cals: 8,
2681
- miles: 10,
2682
- mi: 10,
2683
- inches: 12,
2684
- in: 12,
2685
- watts: 15,
2686
- w: 15,
2687
- velocity: 17,
2688
- "m/s": 17,
2689
- seconds: 18,
2690
- sec: 18,
2691
- s: 18
2692
- };
2693
- const LEADERBOARD_LABEL = {
2694
- 0: "For Completion",
2695
- 1: "Weight",
2696
- 2: "Reps",
2697
- 3: "Rounds",
2698
- 4: "Time",
2699
- 5: "Yards",
2700
- 6: "Meters",
2701
- 7: "Feet",
2702
- 8: "Calories",
2703
- 10: "Miles",
2704
- 12: "Inches",
2705
- 13: "Other",
2706
- 15: "Watts",
2707
- 16: "Percent",
2708
- 17: "Velocity",
2709
- 18: "Seconds"
2710
- };
2711
- function resolveLeaderboard(block) {
2712
- const lb = block.leaderboard;
2713
- if (lb === void 0 || lb === null) return {
2714
- isRedzone: null,
2715
- redzoneType: 0,
2716
- smallerIsBetter: null,
2717
- redzoneInstruction: ""
2718
- };
2719
- let unit;
2720
- let instruction = "";
2721
- let lowest;
2722
- if (typeof lb === "object") {
2723
- unit = lb.unit ?? lb.type;
2724
- instruction = lb.instruction ?? "";
2725
- lowest = lb.lowest_wins;
2726
- } else unit = lb;
2727
- let rz;
2728
- if (typeof unit === "string") {
2729
- const found = LEADERBOARD_TYPE[unit.trim().toLowerCase()];
2730
- if (found === void 0) throw new Error(`Unknown leaderboard unit '${unit}'. Use one of: ${Object.keys(LEADERBOARD_TYPE).join(", ")}.`);
2731
- rz = found;
2732
- } else if (typeof unit === "number") rz = Math.trunc(unit);
2733
- else throw new Error("Leaderboard requires a unit.");
2734
- if (lowest === void 0) lowest = rz === 4 || rz === 18;
2735
- return {
2736
- isRedzone: 1,
2737
- redzoneType: rz,
2738
- smallerIsBetter: lowest ? 1 : 0,
2739
- redzoneInstruction: instruction
2740
- };
2741
- }
2742
- function slots(values, n = 10) {
2743
- const out = [];
2744
- for (let i = 0; i < n; i += 1) out.push(values && i < values.length ? values[i] ?? "" : "");
2745
- return out;
2746
- }
2747
- function repsList(ex) {
2748
- const reps = ex.reps;
2749
- if (Array.isArray(reps)) return reps.map((r) => String(r));
2750
- if (reps === void 0 || reps === null) return [];
2751
- const sets = Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2752
- return Array.from({ length: sets }, () => String(reps));
2753
- }
2754
- /** Build one saveWorkoutSetExercises payload entry with all ten param slots filled. */
2755
- function makeExercise(ex, workoutSetId, order, key) {
2756
- const reps = repsList(ex);
2757
- let instruction = ex.instr ?? "";
2758
- if (instruction === "" && ex.rpe !== void 0 && ex.rpe !== null) instruction = `RPE ${ex.rpe}`;
2759
- const hasWeight = ex.weight !== void 0 && ex.weight !== null;
2760
- const weightArr = Array.isArray(ex.weight) ? ex.weight : null;
2761
- let count = reps.length;
2762
- if (count === 0 && hasWeight) count = weightArr ? weightArr.length : Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2763
- let param2Type;
2764
- let param2Values;
2765
- if (hasWeight) {
2766
- param2Type = ex.param_2_type ?? 1;
2767
- param2Values = (weightArr ?? Array.from({ length: count }, () => ex.weight)).map((v) => String(v));
2768
- } else {
2769
- param2Type = 0;
2770
- param2Values = null;
2609
+ async function updateTeam(client, args) {
2610
+ if (args.title === void 0 && args.groupProgram === void 0) throw new Error("Provide title and/or groupProgram.");
2611
+ let title = args.title;
2612
+ if (title === void 0) {
2613
+ const existing = await client.request("GET", `/v5/teams/${args.teamId}`);
2614
+ if (!existing.ok) {
2615
+ const detail = typeof existing.data === "string" ? existing.data : JSON.stringify(existing.data);
2616
+ throw new Error(`GET /v5/teams/${args.teamId} failed (HTTP ${existing.status}): ${detail}`);
2617
+ }
2618
+ const rec = existing.data && typeof existing.data === "object" ? existing.data : null;
2619
+ title = typeof rec?.title === "string" ? rec.title : "";
2620
+ if (title.trim() === "") throw new Error(`Could not read current title for team ${args.teamId}; pass title explicitly.`);
2771
2621
  }
2772
- const entry = {
2773
- exercise_id: ex.id,
2774
- workout_set_id: workoutSetId,
2775
- set_id: workoutSetId,
2776
- setKey: workoutSetId,
2777
- title: ex.title ?? "",
2778
- instruction,
2779
- order,
2780
- param_1_type: ex.param_1_type ?? 3,
2781
- param_2_type: param2Type,
2782
- workout_set_exercise_template_id: null,
2783
- no_sets: 0,
2784
- param_count: count,
2785
- set_num: count,
2786
- key,
2787
- video_url: "",
2788
- thumbnail_url: "",
2789
- tags: [],
2790
- eType: "e",
2791
- use_count: 0
2792
- };
2793
- const p1 = slots(reps);
2794
- const p2 = slots(param2Values);
2795
- for (let i = 0; i < 10; i += 1) {
2796
- entry[`param_1_data_${i + 1}`] = p1[i] ?? "";
2797
- entry[`param_2_data_${i + 1}`] = p2[i] ?? "";
2622
+ const body = { title };
2623
+ if (args.groupProgram !== void 0) body.group_program = args.groupProgram;
2624
+ const res = await client.request("PUT", `/v5/teams/${args.teamId}`, { body });
2625
+ if (!res.ok) {
2626
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2627
+ throw new Error(`PUT /v5/teams/${args.teamId} failed (HTTP ${res.status}): ${detail}`);
2798
2628
  }
2799
- return entry;
2629
+ return res.data;
2800
2630
  }
2801
- function buildBlockPayload(blocks, workoutId) {
2802
- return blocks.map((b, i) => {
2803
- const lb = resolveLeaderboard(b);
2631
+ /**
2632
+ * Copy/repeat a session to a target date on a program (`POST /2.0/coach/calendar/copyProgramWorkout`).
2633
+ * The API wants the target date as a structured object (with weekday and an isToday flag),
2634
+ * which is computed here from `toDate` (YYYY-M-D). Creates a new (unpublished) session.
2635
+ */
2636
+ async function copySession(client, args) {
2637
+ const [year, month, day] = parseWorkoutDate(args.toDate);
2638
+ const dayOfWeek = new Date(Date.UTC(year, month - 1, day)).getUTCDay();
2639
+ const iso = `${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
2640
+ const path = "/2.0/coach/calendar/copyProgramWorkout";
2641
+ const res = await client.request("POST", path, { body: {
2642
+ toProgramId: args.toProgramId,
2643
+ pwId: args.pwId,
2644
+ toDate: {
2645
+ date: iso,
2646
+ day,
2647
+ month,
2648
+ year,
2649
+ dayOfWeek,
2650
+ isToday: false
2651
+ }
2652
+ } });
2653
+ if (!res.ok) {
2654
+ const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2655
+ throw calendarWriteError("POST", path, res.status, detail);
2656
+ }
2657
+ return res.data;
2658
+ }
2659
+ const ANALYTICS_METRIC_KEYS = [
2660
+ "readiness-team",
2661
+ "readiness-athlete",
2662
+ "lift-1rm-history",
2663
+ "training-summary-athlete",
2664
+ "compliance-team",
2665
+ "lift-progress-team",
2666
+ "working-max-history"
2667
+ ];
2668
+ const ANALYTICS_METRICS = {
2669
+ "readiness-team": {
2670
+ path: "/v5/analytics/readiness/teams",
2671
+ scope: "team",
2672
+ inputs: ["date"],
2673
+ requires: ["date"]
2674
+ },
2675
+ "readiness-athlete": {
2676
+ path: "/v5/analytics/readiness/users",
2677
+ scope: "user",
2678
+ inputs: ["dateStart", "dateEnd"],
2679
+ requires: ["dateStart", "dateEnd"]
2680
+ },
2681
+ "lift-1rm-history": {
2682
+ path: "/v5/analytics/lift-one-rep-max-history/users",
2683
+ scope: "user",
2684
+ inputs: [
2685
+ "dateStart",
2686
+ "dateEnd",
2687
+ "exerciseId",
2688
+ "useMetric"
2689
+ ],
2690
+ requires: [
2691
+ "dateStart",
2692
+ "dateEnd",
2693
+ "exerciseId"
2694
+ ]
2695
+ },
2696
+ "training-summary-athlete": {
2697
+ path: "/v5/analytics/training-summary/users",
2698
+ scope: "user",
2699
+ inputs: ["dateStart", "dateEnd"],
2700
+ requires: ["dateStart", "dateEnd"]
2701
+ },
2702
+ "compliance-team": {
2703
+ path: "/v5/analytics/compliance",
2704
+ scope: "team",
2705
+ inputs: ["dateStart", "dateEnd"],
2706
+ requires: ["dateStart", "dateEnd"]
2707
+ },
2708
+ "lift-progress-team": {
2709
+ path: "/v5/analytics/lift-progress/teams",
2710
+ scope: "team",
2711
+ inputs: [
2712
+ "exerciseId",
2713
+ "dateStart",
2714
+ "dateEnd"
2715
+ ],
2716
+ requires: [
2717
+ "exerciseId",
2718
+ "dateStart",
2719
+ "dateEnd"
2720
+ ]
2721
+ },
2722
+ "working-max-history": {
2723
+ path: "/v5/analytics/working-max-history/users",
2724
+ scope: "user",
2725
+ inputs: [
2726
+ "exerciseId",
2727
+ "dateStart",
2728
+ "dateEnd",
2729
+ "useMetric"
2730
+ ],
2731
+ requires: ["exerciseId"]
2732
+ }
2733
+ };
2734
+ /**
2735
+ * A serializable description of every analytics metric: its scope (does it need a `teamId` or
2736
+ * `userIds`) and which date/exercise inputs it requires vs. optionally accepts. The CLI/MCP
2737
+ * surface this so an agent picks a valid `metric` + params up front, instead of discovering the
2738
+ * shape by trial and error. These curated keys are deliberately NOT the raw category names from
2739
+ * `GET /v5/analytics`; this catalog is the source of truth for `analytics-query`.
2740
+ */
2741
+ function analyticsMetricCatalog() {
2742
+ return ANALYTICS_METRIC_KEYS.map((metric) => {
2743
+ const spec = ANALYTICS_METRICS[metric];
2804
2744
  return {
2805
- workout_id: workoutId,
2806
- order: i + 1,
2807
- type: b.type ?? 2,
2808
- instruction: b.instruction ?? "",
2809
- is_redzone: lb.isRedzone,
2810
- redzone_type: lb.redzoneType,
2811
- smaller_is_better: lb.smallerIsBetter,
2812
- redzone_instruction: lb.redzoneInstruction,
2813
- exercises: [],
2814
- exerciseKeys: [],
2815
- key: `k::${workoutId}${i + 1}`,
2816
- title: b.title
2745
+ metric,
2746
+ scope: spec.scope,
2747
+ scopeParam: spec.scope === "team" ? "teamId" : "userIds",
2748
+ requires: [...spec.requires],
2749
+ optional: spec.inputs.filter((i) => !spec.requires.includes(i))
2817
2750
  };
2818
2751
  });
2819
2752
  }
2820
- function unitOr(t) {
2821
- return unitLabel(t) ?? "?";
2822
- }
2823
- /** Flag spec params the API will silently override to the exercise's fixed units. */
2824
- function unitAdvisory(blockTitle, ex, defaults) {
2825
- const notes = [];
2826
- const warnings = [];
2827
- const u = unitOr;
2828
- const label = `${blockTitle} / ${ex.title ?? ex.id}`;
2829
- if (Array.isArray(ex.reps) && ex.sets !== void 0 && ex.reps.length !== ex.sets) warnings.push(`${label}: reps array has ${ex.reps.length} entr${ex.reps.length === 1 ? "y" : "ies"}; sets:${ex.sets} is ignored — building ${ex.reps.length} set(s).`);
2830
- const sentP1 = ex.param_1_type;
2831
- if (sentP1 !== void 0 && sentP1 !== null && Math.trunc(Number(sentP1)) !== defaults.param1) {
2832
- const sp1 = Math.trunc(Number(sentP1));
2833
- warnings.push(`${label}: param_1_type ${sentP1} (${u(sp1)}) is ignored — this exercise is fixed to ${u(defaults.param1)}; values render as ${u(defaults.param1)}.`);
2834
- } else if (defaults.param1 !== 3 && defaults.param1 !== null) notes.push(`${label}: values are in ${u(defaults.param1)} (the exercise's fixed primary unit).`);
2835
- if (ex.weight !== void 0 && ex.weight !== null) {
2836
- const sentP2 = Math.trunc(Number(ex.param_2_type ?? 1));
2837
- const effP2 = defaults.param2 === 0 || defaults.param2 === null ? 1 : defaults.param2;
2838
- if (sentP2 !== effP2) if (sentP2 === 2 || sentP2 === 14) warnings.push(`${label}: ${u(sentP2)} does not stick on this exercise — it renders as ${u(effP2)}. Put it in the exercise 'instr' text and leave load blank.`);
2839
- else warnings.push(`${label}: load renders as ${u(effP2)}, not ${u(sentP2)} (this exercise's secondary unit is fixed).`);
2753
+ const ANALYTICS_BODY_KEY = {
2754
+ date: "date",
2755
+ dateStart: "date_start",
2756
+ dateEnd: "date_end",
2757
+ exerciseId: "exercise_id",
2758
+ useMetric: "use_metric"
2759
+ };
2760
+ /**
2761
+ * Build the request body for an analytics metric and POST it. Team metrics need `teamId`;
2762
+ * athlete metrics need one or more `userIds` (passed together — the report returns a row per
2763
+ * athlete). Throws a readable Error when a required input is missing or the call fails.
2764
+ */
2765
+ async function queryAnalytics(client, args) {
2766
+ const spec = ANALYTICS_METRICS[args.metric];
2767
+ const body = {};
2768
+ if (spec.scope === "team") {
2769
+ if (args.teamId === void 0) throw new Error(`${args.metric} needs teamId.`);
2770
+ body.teamId = args.teamId;
2771
+ } else {
2772
+ if (args.userIds === void 0 || args.userIds.length === 0) throw new Error(`${args.metric} needs userIds (one or more athlete ids).`);
2773
+ body.user_ids = args.userIds.map((u) => String(u));
2840
2774
  }
2841
- return {
2842
- notes,
2843
- warnings
2775
+ const inputs = {
2776
+ date: args.date,
2777
+ dateStart: args.dateStart,
2778
+ dateEnd: args.dateEnd,
2779
+ exerciseId: args.exerciseId,
2780
+ useMetric: args.useMetric
2844
2781
  };
2782
+ const missing = spec.requires.filter((k) => inputs[k] === void 0);
2783
+ if (missing.length > 0) throw new Error(`${args.metric} also needs: ${missing.join(", ")}.`);
2784
+ for (const k of spec.inputs) {
2785
+ const v = inputs[k];
2786
+ if (v === void 0) continue;
2787
+ body[ANALYTICS_BODY_KEY[k]] = k === "exerciseId" ? String(v) : v;
2788
+ }
2789
+ const res = await client.request("POST", spec.path, { body });
2790
+ if (!res.ok) throw new Error(`Analytics ${args.metric} failed (HTTP ${res.status}).`);
2791
+ return res.data;
2845
2792
  }
2846
2793
  /**
2847
- * Run unit advisories across a whole block list against an exercise index. Shared by the
2848
- * MCP workout_build tool and the CLI so both surface the same notes/warnings. Ensures the
2849
- * index is loaded first, otherwise `defaults` returns null on a cold index and every
2850
- * advisory is silently dropped.
2794
+ * Resolve a team's roster to athlete user ids. `/v5/athletes` is the org-wide roster and the only
2795
+ * place per-team membership lives (each row's `groups` holds the team/group ids it belongs to);
2796
+ * there is no per-team roster endpoint. Returns the ids of athletes whose `groups` include the
2797
+ * given id, matched as a string. Throws when the roster fetch fails.
2851
2798
  */
2852
- async function collectAdvisories(blocks, index) {
2853
- await index.ensureFresh();
2854
- const pairs = blocks.flatMap((b) => b.exercises.map((ex) => ({
2855
- block: b,
2856
- ex
2857
- })));
2858
- const defaults = await Promise.all(pairs.map((p) => {
2859
- const id = Number(p.ex.id);
2860
- return Number.isFinite(id) ? index.defaults(id) : Promise.resolve(null);
2861
- }));
2862
- const notes = [];
2863
- const warnings = [];
2864
- pairs.forEach((p, i) => {
2865
- const def = defaults[i];
2866
- if (!def) return;
2867
- const advisory = unitAdvisory(p.block.title, p.ex, def);
2868
- notes.push(...advisory.notes);
2869
- warnings.push(...advisory.warnings);
2799
+ async function fetchTeamAthleteIds(client, teamId) {
2800
+ const res = await client.request("GET", "/v5/athletes");
2801
+ if (!res.ok) throw new Error(`List athletes failed (HTTP ${res.status}).`);
2802
+ const rows = Array.isArray(res.data) ? res.data : [];
2803
+ const want = String(teamId);
2804
+ const ids = [];
2805
+ for (const row of rows) {
2806
+ if (row === null || typeof row !== "object") continue;
2807
+ const rec = row;
2808
+ if (!(Array.isArray(rec.groups) ? rec.groups.map((g) => String(g)) : []).includes(want)) continue;
2809
+ const id = typeof rec.id === "string" ? Number(rec.id) : rec.id;
2810
+ if (typeof id === "number" && Number.isFinite(id)) ids.push(id);
2811
+ }
2812
+ return ids;
2813
+ }
2814
+ function toNum(v) {
2815
+ const n = typeof v === "string" ? Number(v) : typeof v === "number" ? v : NaN;
2816
+ return Number.isFinite(n) ? n : 0;
2817
+ }
2818
+ /**
2819
+ * Team-wide training volume over an inclusive date window. The `training-summary-athlete`
2820
+ * analytics report already returns the team in one call — one row per logged session across all
2821
+ * `athleteIds` — so this fans nothing out: it queries once, groups rows by athlete (summing
2822
+ * volume/reps and counting sessions), and rolls the athletes up into a team total. Athletes who
2823
+ * logged nothing in range simply have no rows and are omitted. The windowed counterpart to the
2824
+ * all-time `fetchRosterActivity` snapshot, which has no date range.
2825
+ */
2826
+ async function teamVolume(client, args) {
2827
+ if (args.athleteIds.length === 0) throw new Error("teamVolume needs at least one athleteId.");
2828
+ const report = await queryAnalytics(client, {
2829
+ metric: "training-summary-athlete",
2830
+ userIds: args.athleteIds,
2831
+ dateStart: args.dateStart,
2832
+ dateEnd: args.dateEnd
2833
+ });
2834
+ const rows = report !== null && typeof report === "object" && Array.isArray(report.rows) ? report.rows : [];
2835
+ const byAthlete = /* @__PURE__ */ new Map();
2836
+ for (const row of rows) {
2837
+ const athleteId = toNum(row.user_id);
2838
+ if (athleteId === 0) continue;
2839
+ const date = typeof row.date_completed === "string" ? row.date_completed.slice(0, 10) : null;
2840
+ const name = [row.name_first, row.name_last].filter((s) => typeof s === "string" && s !== "").join(" ") || null;
2841
+ const existing = byAthlete.get(athleteId);
2842
+ if (existing) {
2843
+ existing.sessions += 1;
2844
+ existing.reps += toNum(row.reps);
2845
+ existing.volume += toNum(row.volume);
2846
+ if (date !== null) {
2847
+ if (existing.firstLoggedDate === null || date < existing.firstLoggedDate) existing.firstLoggedDate = date;
2848
+ if (existing.lastLoggedDate === null || date > existing.lastLoggedDate) existing.lastLoggedDate = date;
2849
+ }
2850
+ } else byAthlete.set(athleteId, {
2851
+ athleteId,
2852
+ name,
2853
+ sessions: 1,
2854
+ reps: toNum(row.reps),
2855
+ volume: toNum(row.volume),
2856
+ firstLoggedDate: date,
2857
+ lastLoggedDate: date
2858
+ });
2859
+ }
2860
+ const athletes = [...byAthlete.values()].sort((a, b) => b.volume - a.volume);
2861
+ const totals = athletes.reduce((acc, a) => ({
2862
+ athletes: acc.athletes + 1,
2863
+ sessions: acc.sessions + a.sessions,
2864
+ reps: acc.reps + a.reps,
2865
+ volume: acc.volume + a.volume
2866
+ }), {
2867
+ athletes: 0,
2868
+ sessions: 0,
2869
+ reps: 0,
2870
+ volume: 0
2870
2871
  });
2871
2872
  return {
2872
- notes,
2873
- warnings
2873
+ window: {
2874
+ start: args.dateStart,
2875
+ end: args.dateEnd
2876
+ },
2877
+ athletes,
2878
+ totals
2874
2879
  };
2875
2880
  }
2876
2881
  //#endregion
2877
- //#region ../js/src/workout-session.ts
2878
- async function req(client, method, path, body) {
2879
- const res = await client.request(method, path, body === void 0 ? void 0 : { body });
2880
- if (!res.ok) {
2881
- const detail = typeof res.data === "string" ? res.data : JSON.stringify(res.data);
2882
- throw new Error(`${method} ${path} failed (HTTP ${res.status}): ${detail}`);
2882
+ //#region ../js/src/main-lifts.ts
2883
+ /**
2884
+ * The "main lifts" — Big 4 plus the two Olympic lifts. ORDER MATTERS: a title is classified by the
2885
+ * first family that matches, so the more specific / easily-confused families come before the broad
2886
+ * overhead-press rule. That ordering is why "Bench Press" classifies as `bench` and never gets
2887
+ * swept up as an overhead press, and why "Clean & Jerk" is not mistaken for a clean-only movement.
2888
+ * This is the single place to edit the lift set.
2889
+ */
2890
+ const MAIN_LIFT_FAMILIES = [
2891
+ {
2892
+ key: "cleanjerk",
2893
+ label: "Clean & Jerk",
2894
+ matches: (t) => t.includes("jerk") || t.includes("clean") && !t.includes("clean pull")
2895
+ },
2896
+ {
2897
+ key: "snatch",
2898
+ label: "Snatch",
2899
+ matches: (t) => t.includes("snatch")
2900
+ },
2901
+ {
2902
+ key: "deadlift",
2903
+ label: "Deadlift",
2904
+ matches: (t) => t.includes("deadlift")
2905
+ },
2906
+ {
2907
+ key: "squat",
2908
+ label: "Squat",
2909
+ matches: (t) => t.includes("squat")
2910
+ },
2911
+ {
2912
+ key: "bench",
2913
+ label: "Bench Press",
2914
+ matches: (t) => t.includes("bench")
2915
+ },
2916
+ {
2917
+ key: "overhead",
2918
+ label: "Overhead Press",
2919
+ matches: (t) => t.includes("ohp") || (t.includes("overhead") || t.includes("shoulder") || t.includes("military") || t.includes("strict") || t.includes("push")) && t.includes("press")
2920
+ }
2921
+ ];
2922
+ /** The lift family a logged exercise title belongs to, or null if it is not a main lift. */
2923
+ function classifyMainLift(title) {
2924
+ const t = title.toLowerCase();
2925
+ for (const family of MAIN_LIFT_FAMILIES) if (family.matches(t)) return family.key;
2926
+ return null;
2927
+ }
2928
+ const DEFAULT_MONTHS = 12;
2929
+ function pad2(n) {
2930
+ return String(n).padStart(2, "0");
2931
+ }
2932
+ /** A local Date as a YYYY-MM-DD day string (the range endpoint's date format). */
2933
+ function isoDay(d) {
2934
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
2935
+ }
2936
+ /**
2937
+ * Discover a roster athlete's main lifts from what they actually logged. Reads the athlete's
2938
+ * logged workouts over the last `months` (default 12) — the program-workout range, the reliable
2939
+ * record of performed sets — buckets every performed exercise into a lift family, and for each
2940
+ * family picks the variant logged most often. Returns one entry per family the athlete has logged;
2941
+ * families they never trained are simply absent. (The monthly calendar summary is not used: it
2942
+ * comes back empty for some accounts that have logged sets in the range endpoint.)
2943
+ */
2944
+ async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
2945
+ const months = opts.months ?? DEFAULT_MONTHS;
2946
+ const now = opts.now ?? /* @__PURE__ */ new Date();
2947
+ const start = new Date(now.getFullYear(), now.getMonth() - (months - 1), 1);
2948
+ const tally = /* @__PURE__ */ new Map();
2949
+ let workouts = [];
2950
+ try {
2951
+ workouts = await fetchCoachAthleteWorkouts(client, athleteId, isoDay(start), isoDay(now));
2952
+ } catch {
2953
+ workouts = [];
2883
2954
  }
2884
- return res.data;
2885
- }
2886
- function createPath(opts) {
2887
- if (opts.timelineDay !== void 0) return `/2.0/coach/calendar/workout/createWorkoutForTimelineDay/${opts.programId}/${opts.timelineDay}/null`;
2888
- if (!opts.date) throw new Error("workout build requires either date or timelineDay");
2889
- const [y, m, d] = opts.date;
2890
- return `/2.0/coach/calendar/workout/createWorkoutForDay/${opts.programId}/${y}/${m}/${d}/0`;
2891
- }
2892
- async function buildSession(client, opts) {
2893
- const sess = await req(client, "POST", createPath(opts), {});
2894
- checkResponse(sessionCreateResponseSchema, sess, "session create");
2895
- const workoutId = Number(sess.workout_id);
2896
- const pwId = Number(sess.id);
2897
- const created = await req(client, "POST", "/2.0/coach/calendar/saveProgramWorkoutSets", buildBlockPayload(opts.blocks, workoutId));
2898
- const byOrder = new Map(created.map((b) => [b.order, b.id]));
2899
- let counter = 0;
2900
- const payloads = opts.blocks.map((block, i) => {
2901
- const wsid = byOrder.get(i + 1);
2902
- if (wsid === void 0) throw new Error(`No saved block for order ${i + 1}.`);
2903
- return block.exercises.map((ex, j) => {
2904
- counter += 1;
2905
- return makeExercise(ex, wsid, j + 1, `k::${workoutId}${String(counter).padStart(3, "0")}`);
2955
+ for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
2956
+ if (ex.performed.length === 0 || ex.exerciseId === null) continue;
2957
+ const family = classifyMainLift(ex.title);
2958
+ if (family === null) continue;
2959
+ const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
2960
+ const prev = byId.get(ex.exerciseId);
2961
+ byId.set(ex.exerciseId, {
2962
+ count: (prev?.count ?? 0) + 1,
2963
+ title: prev?.title ?? ex.title
2964
+ });
2965
+ tally.set(family, byId);
2966
+ }
2967
+ const lifts = [];
2968
+ for (const family of MAIN_LIFT_FAMILIES) {
2969
+ const byId = tally.get(family.key);
2970
+ if (!byId || byId.size === 0) continue;
2971
+ let best = null;
2972
+ for (const [exerciseId, { count, title }] of byId) if (best === null || count > best.count || count === best.count && exerciseId < best.exerciseId) best = {
2973
+ exerciseId,
2974
+ count,
2975
+ title
2976
+ };
2977
+ if (best) lifts.push({
2978
+ family: family.key,
2979
+ label: family.label,
2980
+ exerciseId: best.exerciseId,
2981
+ title: best.title
2906
2982
  });
2907
- });
2908
- await Promise.all(payloads.map((p) => req(client, "POST", "/2.0/coach/calendar/saveWorkoutSetExercises", p)));
2909
- if (opts.instruction !== void 0 && opts.instruction !== "") {
2910
- const blockIds = [...byOrder.entries()].sort((a, b) => a[0] - b[0]).map(([, id]) => id);
2911
- await setSessionInstruction(client, workoutId, sess, opts.instruction, blockIds);
2912
2983
  }
2913
- if (opts.publish ?? false) await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
2914
2984
  return {
2915
- pwId,
2916
- workoutId
2985
+ athleteId,
2986
+ athleteName: null,
2987
+ lifts
2917
2988
  };
2918
2989
  }
2990
+ const PR_CONCURRENCY = 5;
2991
+ /** The heaviest PR on an exercise's board (ties broken by more reps). */
2992
+ function bestPr(liftPRs) {
2993
+ let best = null;
2994
+ for (const pr of liftPRs) {
2995
+ const weight = coerceNum(pr.weight);
2996
+ if (weight === null) continue;
2997
+ const reps = coerceInt(pr.reps);
2998
+ if (best === null || weight > best.weight || weight === best.weight && (reps ?? 0) > (best.reps ?? 0)) best = {
2999
+ weight,
3000
+ reps,
3001
+ units: pr.units,
3002
+ date: pr.date
3003
+ };
3004
+ }
3005
+ return best;
3006
+ }
2919
3007
  /**
2920
- * Set a session's Coach Instructions (the day-note at the top of a session). `pw` is the
2921
- * programWorkout object (the create-time response or a day's edit-GET entry). The PUT wants
2922
- * the whole object back with `instruction` set and `sets`/`setKeys` as a flat list of block
2923
- * ids. This does NOT change publish state: `published` is sent exactly as it is on `pw`.
3008
+ * A roster athlete's best PR for each main lift. Discovers the lift variants they log
3009
+ * ({@link resolveAthleteMainLifts}), then pulls each variant's PR board and keeps the heaviest set.
3010
+ * The result always carries one entry per family in {@link MAIN_LIFT_FAMILIES} order; a family the
3011
+ * athlete has not logged comes back with null fields (the "no PR yet" case), so a dashboard can
3012
+ * render a stable row of columns.
2924
3013
  */
2925
- async function setSessionInstruction(client, workoutId, pw, instruction, blockIds) {
2926
- const body = {
2927
- ...pw,
2928
- instruction,
2929
- sets: blockIds,
2930
- setKeys: blockIds
2931
- };
2932
- await req(client, "PUT", `/3.0/coach/workout/${workoutId}`, body);
2933
- }
2934
- async function removeSession(client, programId, pwId) {
2935
- await req(client, "POST", "/2.0/coach/calendar/removeProgramWorkout", {
2936
- programId,
2937
- pwId
2938
- });
2939
- }
2940
- async function publishSession(client, pwId) {
2941
- await req(client, "POST", "/2.0/coach/calendar/programWorkout/publish", [pwId]);
2942
- }
2943
- function str(value) {
2944
- return value === void 0 || value === null ? "" : String(value);
2945
- }
2946
- async function readSession(client, programId, date, pwId) {
2947
- const [y, m, d] = date;
2948
- const data = await req(client, "GET", `/1.0/coach/programs/edit/${programId}/${y}/${m}/${d}`);
2949
- checkResponse(programsEditResponseSchema, data, "programs edit");
2950
- const pw = (data.programWorkouts ?? []).find((p) => coerceInt(p.id) === pwId);
2951
- if (!pw) throw new Error(`programWorkout ${pwId} not found on ${y}-${m}-${d}.`);
2952
- const setsObj = pw.sets ?? {};
2953
- const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
3014
+ async function fetchAthleteMainLiftPRs(client, athleteId, opts = {}) {
3015
+ const { athleteName, lifts } = await resolveAthleteMainLifts(client, athleteId, opts);
3016
+ const byFamily = new Map(lifts.map((l) => [l.family, l]));
2954
3017
  return {
2955
- pwId,
2956
- date: `${str(pw.year)}-${str(pw.month)}-${str(pw.day)}`,
2957
- published: pw.published,
2958
- instruction: str(pw.instruction),
2959
- blocks
3018
+ athleteId,
3019
+ athleteName,
3020
+ prs: await mapPool(MAIN_LIFT_FAMILIES, PR_CONCURRENCY, async (family) => {
3021
+ const lift = byFamily.get(family.key);
3022
+ const base = {
3023
+ family: family.key,
3024
+ label: family.label
3025
+ };
3026
+ const empty = {
3027
+ exerciseId: null,
3028
+ title: null,
3029
+ weight: null,
3030
+ reps: null,
3031
+ units: null,
3032
+ date: null
3033
+ };
3034
+ if (!lift) return {
3035
+ ...base,
3036
+ ...empty
3037
+ };
3038
+ const known = {
3039
+ exerciseId: lift.exerciseId,
3040
+ title: lift.title
3041
+ };
3042
+ try {
3043
+ const best = bestPr(presentExerciseHistory(await fetchExerciseHistoryDetail(client, lift.exerciseId, athleteId)).liftPRs);
3044
+ return {
3045
+ ...base,
3046
+ ...known,
3047
+ weight: best?.weight ?? null,
3048
+ reps: best?.reps ?? null,
3049
+ units: best?.units ?? null,
3050
+ date: best?.date ?? null
3051
+ };
3052
+ } catch {
3053
+ return {
3054
+ ...base,
3055
+ ...known,
3056
+ weight: null,
3057
+ reps: null,
3058
+ units: null,
3059
+ date: null
3060
+ };
3061
+ }
3062
+ })
2960
3063
  };
2961
3064
  }
2962
- function readBlock(b) {
2963
- const rz = coerceInt(b.redzone_type);
2964
- let leaderboard = null;
2965
- if (rz && rz > 0) leaderboard = `FOR ${(LEADERBOARD_LABEL[rz] ?? `type ${rz}`).toUpperCase()}${b.smaller_is_better ? " (lowest wins)" : ""}`;
2966
- const exercises = (Array.isArray(b.exercises) ? b.exercises : []).sort((a, e) => Number(a.order) - Number(e.order)).map((ex) => readExercise(ex));
2967
- return {
2968
- order: Number(b.order),
2969
- title: str(b.title),
2970
- leaderboard,
2971
- exercises
3065
+ const ROSTER_CONCURRENCY = 4;
3066
+ /**
3067
+ * Every roster athlete's main-lift PRs in one call: list the roster ({@link fetchCoachRoster}) and
3068
+ * resolve each athlete's board ({@link fetchAthleteMainLiftPRs}), fanned out with a bounded pool.
3069
+ * `athleteIds` restricts to a subset (else the whole roster). Each entry's `athleteName` falls back
3070
+ * to the roster name when the per-athlete read can't supply one. This is the single roster-level
3071
+ * primitive the CLI, the MCP tool, and the warehouse store all build on.
3072
+ */
3073
+ async function fetchRosterMainLiftPRs(client, opts = {}) {
3074
+ const roster = await fetchCoachRoster(client, opts.athleteIds);
3075
+ const inner = {
3076
+ ...opts.months !== void 0 ? { months: opts.months } : {},
3077
+ ...opts.now !== void 0 ? { now: opts.now } : {}
2972
3078
  };
3079
+ return mapPool(roster, opts.concurrency ?? ROSTER_CONCURRENCY, async (athlete) => {
3080
+ const result = await fetchAthleteMainLiftPRs(client, athlete.id, inner);
3081
+ return {
3082
+ athleteId: athlete.id,
3083
+ athleteName: result.athleteName ?? athlete.name,
3084
+ prs: result.prs
3085
+ };
3086
+ });
2973
3087
  }
2974
- function readExercise(ex) {
2975
- const reps = [];
2976
- const load = [];
2977
- for (let i = 1; i <= 10; i += 1) {
2978
- const r = str(ex[`param_1_data_${i}`]);
2979
- if (r !== "") reps.push(r);
2980
- const w = str(ex[`param_2_data_${i}`]);
2981
- if (w !== "") load.push(w);
2982
- }
2983
- return {
2984
- order: Number(ex.order),
2985
- title: str(ex.title),
2986
- reps,
2987
- primaryUnit: unitLabel(coerceInt(ex.param_1_type)),
2988
- load,
2989
- loadUnit: unitLabel(coerceInt(ex.param_2_type)),
2990
- instruction: str(ex.instruction)
2991
- };
3088
+ //#endregion
3089
+ //#region ../js/src/util.ts
3090
+ /**
3091
+ * Drop the keys whose value is `undefined`, so the result can be passed to a function or
3092
+ * spread into an object under `exactOptionalPropertyTypes` without the per-key
3093
+ * `...(x !== undefined ? { x } : {})` dance. Required keys stay required in the result type;
3094
+ * optional ones lose `undefined` from their value type.
3095
+ *
3096
+ * Example:
3097
+ * definedProps({ metric, teamId: maybeId, date }) // omits teamId/date if they're undefined
3098
+ */
3099
+ function definedProps(obj) {
3100
+ const result = {};
3101
+ for (const [key, value] of Object.entries(obj)) if (value !== void 0) result[key] = value;
3102
+ return result;
2992
3103
  }
2993
3104
  //#endregion
2994
3105
  //#region ../js/src/messaging.ts
@@ -3337,7 +3448,7 @@ Coach — manage a roster (needs a coach account):
3337
3448
 
3338
3449
  teams & join codes:
3339
3450
  coach team-create --title "..."
3340
- coach team-update --team <id> --title "..."
3451
+ coach team-update --team <id> [--title "..."] [--group-program <id>]
3341
3452
  coach team-delete --team <id> --yes
3342
3453
  coach team-code-create --team <id> [--type N]
3343
3454
  coach team-code-delete --code <id> --yes (--code is the id from team-code-create, not the join-code number)
@@ -3363,7 +3474,7 @@ Coach — manage a roster (needs a coach account):
3363
3474
 
3364
3475
  workouts (spec: {"blocks":[{"title","exercises":[{"id","sets"?,"reps"?,"weight"?,"rpe"?}]}],"instruction"?};
3365
3476
  reps/weight may be a scalar or per-set array; omit --publish to leave a draft):
3366
- coach workout build --program <id> (--date Y-M-D | --timeline-day <n>) [--publish --yes] <spec.json>|--file f
3477
+ coach workout build (--program <id> | --athlete <id>) (--date Y-M-D | --timeline-day <n>) [--publish --yes] <spec.json>|--file f
3367
3478
  coach workout read --program <id> --date Y-M-D --pw <id>
3368
3479
  coach workout publish --pw <id> --yes
3369
3480
  coach workout remove --program <id> --pw <id> --yes
@@ -3510,42 +3621,57 @@ async function cmdExercise(client, rest) {
3510
3621
  default: return fail("usage: trainheroic coach exercise <resolve|search|get|sync|create|forget|stats>");
3511
3622
  }
3512
3623
  }
3624
+ async function cmdWorkoutBuild(client, a) {
3625
+ const { values, positionals } = parse(a, {
3626
+ program: { type: "string" },
3627
+ athlete: { type: "string" },
3628
+ date: { type: "string" },
3629
+ "timeline-day": { type: "string" },
3630
+ publish: { type: "boolean" },
3631
+ yes: { type: "boolean" },
3632
+ file: { type: "string" }
3633
+ });
3634
+ const usage = "coach workout build (--program <id> | --athlete <id>) (--date Y-M-D | --timeline-day <n>) ...";
3635
+ const programRaw = values.program;
3636
+ const athleteRaw = values.athlete;
3637
+ if (values.date === void 0 && values["timeline-day"] === void 0) fail("provide --date YYYY-M-D or --timeline-day <n>.");
3638
+ let programId;
3639
+ try {
3640
+ programId = await resolveBuildProgramId(client, {
3641
+ ...programRaw !== void 0 ? { programId: toInt(programRaw, "--program") } : {},
3642
+ ...athleteRaw !== void 0 ? { athleteId: toInt(athleteRaw, "--athlete") } : {},
3643
+ ...values.date !== void 0 ? { date: values.date } : {}
3644
+ });
3645
+ } catch (err) {
3646
+ fail(err instanceof Error ? `${usage}: ${err.message}` : String(err));
3647
+ }
3648
+ const parsed = await jsonInput(positionals[0], values.file);
3649
+ const spec = validate(workoutSpecSchema, Array.isArray(parsed) ? { blocks: parsed } : parsed, "workout spec", "run 'trainheroic skill' for the workout spec format and copy-paste examples.");
3650
+ const publish = values.publish === true;
3651
+ if (publish && values.yes !== true) fail("publishing is athlete-facing; add --yes to build and publish.");
3652
+ const opts = {
3653
+ programId,
3654
+ blocks: spec.blocks,
3655
+ publish
3656
+ };
3657
+ if (values.date !== void 0) opts.date = parseWorkoutDate(values.date);
3658
+ if (values["timeline-day"] !== void 0) opts.timelineDay = toInt(values["timeline-day"], "--timeline-day");
3659
+ if (spec.instruction !== void 0) opts.instruction = spec.instruction;
3660
+ const advice = await collectAdvisories(spec.blocks, library(client));
3661
+ const built = await buildSession(client, opts);
3662
+ const readback = opts.date ? await readSession(client, programId, opts.date, built.pwId) : null;
3663
+ return out({
3664
+ ...built,
3665
+ programId,
3666
+ published: publish,
3667
+ advisories: advice,
3668
+ readback
3669
+ });
3670
+ }
3513
3671
  async function cmdWorkout(client, rest) {
3514
3672
  const [sub, ...a] = rest;
3515
3673
  switch (sub) {
3516
- case "build": {
3517
- const { values, positionals } = parse(a, {
3518
- program: { type: "string" },
3519
- date: { type: "string" },
3520
- "timeline-day": { type: "string" },
3521
- publish: { type: "boolean" },
3522
- yes: { type: "boolean" },
3523
- file: { type: "string" }
3524
- });
3525
- const programId = toInt(need(values.program, "coach workout build --program <id> ..."), "--program");
3526
- if (values.date === void 0 && values["timeline-day"] === void 0) fail("provide --date YYYY-M-D or --timeline-day <n>.");
3527
- const parsed = await jsonInput(positionals[0], values.file);
3528
- const spec = validate(workoutSpecSchema, Array.isArray(parsed) ? { blocks: parsed } : parsed, "workout spec", "run 'trainheroic skill' for the workout spec format and copy-paste examples.");
3529
- const publish = values.publish === true;
3530
- if (publish && values.yes !== true) fail("publishing is athlete-facing; add --yes to build and publish.");
3531
- const opts = {
3532
- programId,
3533
- blocks: spec.blocks,
3534
- publish
3535
- };
3536
- if (values.date !== void 0) opts.date = parseWorkoutDate(values.date);
3537
- if (values["timeline-day"] !== void 0) opts.timelineDay = toInt(values["timeline-day"], "--timeline-day");
3538
- if (spec.instruction !== void 0) opts.instruction = spec.instruction;
3539
- const advice = await collectAdvisories(spec.blocks, library(client));
3540
- const built = await buildSession(client, opts);
3541
- const readback = opts.date ? await readSession(client, programId, opts.date, built.pwId) : null;
3542
- return out({
3543
- ...built,
3544
- published: publish,
3545
- advisories: advice,
3546
- readback
3547
- });
3548
- }
3674
+ case "build": return cmdWorkoutBuild(client, a);
3549
3675
  case "read": {
3550
3676
  const { values } = parse(a, {
3551
3677
  program: { type: "string" },
@@ -4135,14 +4261,20 @@ async function cmdCoachTeamCreate(client, a) {
4135
4261
  return out(await mutate(client, "POST", "/1.0/coach/team/createWithTitleAndCode", { title: need(values.title, "coach team-create --title \"...\"") }));
4136
4262
  }
4137
4263
  async function cmdCoachTeamUpdate(client, a) {
4138
- const usage = "coach team-update --team <id> --title \"...\"";
4264
+ const usage = "coach team-update --team <id> [--title \"...\"] [--group-program <id>] (at least one of --title / --group-program)";
4139
4265
  const { values } = parse(a, {
4140
4266
  team: { type: "string" },
4141
- title: { type: "string" }
4267
+ title: { type: "string" },
4268
+ "group-program": { type: "string" }
4142
4269
  });
4143
4270
  const teamId = toInt(need(values.team, usage), "--team");
4144
- const title = need(values.title, usage);
4145
- return out(await mutate(client, "PUT", `/v5/teams/${teamId}`, { title }));
4271
+ const title = values.title;
4272
+ const groupProgramRaw = values["group-program"];
4273
+ if (title === void 0 && groupProgramRaw === void 0) fail(usage);
4274
+ const args = { teamId };
4275
+ if (title !== void 0) args.title = title;
4276
+ if (groupProgramRaw !== void 0) args.groupProgram = toInt(groupProgramRaw, "--group-program");
4277
+ return out(await updateTeam(client, args));
4146
4278
  }
4147
4279
  async function cmdCoachTeamDelete(client, a) {
4148
4280
  const usage = "coach team-delete --team <id> --yes";