@trainheroic-unofficial/coach-mcp 3.5.0 → 3.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/server.mjs +420 -318
  2. package/package.json +3 -3
package/dist/server.mjs CHANGED
@@ -701,6 +701,12 @@ const exerciseSpecSchema = z.object({
701
701
  instr: z.string().optional(),
702
702
  param_1_type: z.number().optional(),
703
703
  param_2_type: z.number().optional()
704
+ }).superRefine((exercise, ctx) => {
705
+ if (Array.isArray(exercise.reps) && Array.isArray(exercise.weight) && exercise.reps.length !== exercise.weight.length) ctx.addIssue({
706
+ code: "custom",
707
+ message: `Per-set reps and weight arrays must have the same length; received ${exercise.reps.length} reps and ${exercise.weight.length} weights.`,
708
+ path: ["weight"]
709
+ });
704
710
  });
705
711
  /** A block's Red-Zone leaderboard: a unit string/number, or an object with options. */
706
712
  const leaderboardSpecSchema = z.union([
@@ -739,15 +745,19 @@ z.object({
739
745
  /**
740
746
  * Parse a `YYYY-M-D` string into the `WorkoutDate` tuple. The single home for this
741
747
  * conversion, shared by the MCP tools and the CLI so they cannot drift on what counts
742
- * as a valid date. Each part must be an integer.
748
+ * as a valid date. Each part must be a run of digits (`Number("")` is 0, so a blank part such as
749
+ * the trailing one in "2026-9-" must be rejected explicitly), and month/day must be in range so
750
+ * a typo cannot land a session on a date the calendar does not have.
743
751
  */
744
752
  function parseWorkoutDate(s) {
745
- const parts = s.split("-").map((p) => Number(p));
746
- if (parts.length !== 3 || parts.some((n) => !Number.isInteger(n))) throw new Error(`date must be YYYY-M-D, got "${s}".`);
753
+ const parts = s.split("-");
754
+ if (parts.length !== 3 || parts.some((p) => !/^\d+$/u.test(p))) throw new Error(`date must be YYYY-M-D, got "${s}".`);
755
+ const [year, month, day] = parts.map(Number);
756
+ if (month < 1 || month > 12 || day < 1 || day > 31) throw new Error(`date must be YYYY-M-D with a real month and day, got "${s}".`);
747
757
  return [
748
- parts[0],
749
- parts[1],
750
- parts[2]
758
+ year,
759
+ month,
760
+ day
751
761
  ];
752
762
  }
753
763
  /** Body for `POST /v5/sessions/template` (library create, not save-from-session). */
@@ -831,12 +841,16 @@ function resultBudget() {
831
841
  function isPlainObject(value) {
832
842
  return typeof value === "object" && value !== null && !Array.isArray(value);
833
843
  }
834
- /** Largest count k such that the JSON of the first k pre-serialized pieces fits. O(n). */
835
- function largestPrefixCount(pieces, charBudget) {
844
+ /**
845
+ * Largest count k such that the JSON of the first k elements fits. Elements are serialized one
846
+ * at a time and the walk stops at the first overflow, so an oversized 10k-row result costs the
847
+ * serialization of the rows that fit, not of every row.
848
+ */
849
+ function largestPrefixCount(elements, charBudget) {
836
850
  let used = 2;
837
851
  let k = 0;
838
- for (const piece of pieces) {
839
- const add = piece.length + (k > 0 ? 1 : 0);
852
+ for (const element of elements) {
853
+ const add = (JSON.stringify(element) ?? "null").length + (k > 0 ? 1 : 0);
840
854
  if (used + add > charBudget) break;
841
855
  used += add;
842
856
  k += 1;
@@ -851,11 +865,12 @@ function hardCap(text, budget, hint) {
851
865
  return text.slice(0, keep) + note;
852
866
  }
853
867
  function largestArrayValuedKey(obj) {
868
+ const arrayKeys = Object.keys(obj).filter((key) => Array.isArray(obj[key]));
869
+ if (arrayKeys.length <= 1) return arrayKeys[0] ?? null;
854
870
  let best = null;
855
871
  let bestLen = -1;
856
- for (const [key, value] of Object.entries(obj)) {
857
- if (!Array.isArray(value)) continue;
858
- const len = (JSON.stringify(value) ?? "[]").length;
872
+ for (const key of arrayKeys) {
873
+ const len = (JSON.stringify(obj[key]) ?? "[]").length;
859
874
  if (len > bestLen) {
860
875
  best = key;
861
876
  bestLen = len;
@@ -863,9 +878,6 @@ function largestArrayValuedKey(obj) {
863
878
  }
864
879
  return best;
865
880
  }
866
- function jsonValue(data) {
867
- return JSON.parse(JSON.stringify(data) ?? "null");
868
- }
869
881
  function previewEnvelope(source, budget, hint) {
870
882
  const total = source.length;
871
883
  const makeValue = (preview, markerHint) => ({
@@ -892,8 +904,8 @@ function boundedResult(data, budget, hint) {
892
904
  text: data,
893
905
  value: data
894
906
  };
895
- const value = jsonValue(data);
896
- const compact = JSON.stringify(value);
907
+ const compact = JSON.stringify(data) ?? "null";
908
+ const value = JSON.parse(compact);
897
909
  if (compact.length <= budget) {
898
910
  const pretty = JSON.stringify(value, null, 2);
899
911
  return {
@@ -902,7 +914,7 @@ function boundedResult(data, budget, hint) {
902
914
  };
903
915
  }
904
916
  if (Array.isArray(value)) {
905
- const truncated = clipArray(value, largestPrefixCount(value.map((element) => JSON.stringify(element)), budget - MARKER_RESERVE), hint);
917
+ const truncated = clipArray(value, largestPrefixCount(value, budget - MARKER_RESERVE), hint);
906
918
  const text = JSON.stringify(truncated);
907
919
  if (text.length <= budget) return {
908
920
  text,
@@ -912,7 +924,7 @@ function boundedResult(data, budget, hint) {
912
924
  const key = largestArrayValuedKey(value);
913
925
  if (key !== null) {
914
926
  const array = value[key];
915
- const truncated = clipArray(array, largestPrefixCount(array.map((element) => JSON.stringify(element)), budget - MARKER_RESERVE), hint ?? DEFAULT_OBJECT_HINT, key);
927
+ const truncated = clipArray(array, largestPrefixCount(array, budget - MARKER_RESERVE), hint ?? DEFAULT_OBJECT_HINT, key);
916
928
  const text = JSON.stringify(truncated);
917
929
  if (text.length <= budget) return {
918
930
  text,
@@ -1214,6 +1226,26 @@ function checkResponse(schema, data, label) {
1214
1226
  console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
1215
1227
  }
1216
1228
  //#endregion
1229
+ //#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/uniq.mjs
1230
+ /**
1231
+ * Creates a duplicate-free version of an array.
1232
+ *
1233
+ * This function takes an array and returns a new array containing only the unique values
1234
+ * from the original array, preserving the order of first occurrence.
1235
+ *
1236
+ * @template T - The type of elements in the array.
1237
+ * @param arr - The array to process.
1238
+ * @returns A new array with only unique values from the original array.
1239
+ *
1240
+ * @example
1241
+ * const array = [1, 2, 2, 3, 4, 4, 5];
1242
+ * const result = uniq(array);
1243
+ * // result will be [1, 2, 3, 4, 5]
1244
+ */
1245
+ function uniq(arr) {
1246
+ return [...new Set(arr)];
1247
+ }
1248
+ //#endregion
1217
1249
  //#region ../js/src/exercise-util.ts
1218
1250
  /**
1219
1251
  * Display labels for TrainHeroic parameter types. The unit is FIXED PER EXERCISE
@@ -1343,14 +1375,6 @@ function exerciseTitle(ex, fallback = "") {
1343
1375
  return typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || fallback;
1344
1376
  }
1345
1377
  /**
1346
- * True when a program-workout range item is a personal (athlete-created) session rather than a
1347
- * coach-scheduled one. The API marks these with `personal_cal === true`; this is the single
1348
- * definition every consumer (presenter, find-or-create, the remove guard) reads through.
1349
- */
1350
- function isPersonalSession(pw) {
1351
- return isRecord(pw) && pw.personal_cal === true;
1352
- }
1353
- /**
1354
1378
  * The `saved_workout` blob on a program-workout range item, or null if the athlete has no saved
1355
1379
  * copy yet. Session notes, RPE, and set writes all resolve through this.
1356
1380
  */
@@ -1387,18 +1411,76 @@ function rankSearch(rows, query, limit) {
1387
1411
  * on workerd, blowing the subrequest budget.
1388
1412
  */
1389
1413
  async function mapPool(items, limit, fn) {
1414
+ assertPositiveInteger(limit, "Concurrency limit");
1390
1415
  const out = Array.from({ length: items.length });
1391
1416
  let next = 0;
1417
+ const state = { failure: null };
1392
1418
  const worker = async () => {
1393
- while (next < items.length) {
1419
+ while (next < items.length && state.failure === null) {
1394
1420
  const i = next;
1395
1421
  next += 1;
1396
- out[i] = await fn(items[i], i);
1422
+ try {
1423
+ out[i] = await fn(items[i], i);
1424
+ } catch (error) {
1425
+ state.failure ??= { error };
1426
+ }
1397
1427
  }
1398
1428
  };
1399
1429
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
1430
+ if (state.failure !== null) throw state.failure.error;
1400
1431
  return out;
1401
1432
  }
1433
+ function createLimiter(max) {
1434
+ assertPositiveInteger(max, "Maximum concurrency");
1435
+ let active = 0;
1436
+ let cancelled = null;
1437
+ const waiting = [];
1438
+ const acquire = (finalizer) => new Promise((resolve, reject) => {
1439
+ if (cancelled !== null && !finalizer) reject(cancelled.error);
1440
+ else if (active < max) {
1441
+ active += 1;
1442
+ resolve();
1443
+ } else waiting.push({
1444
+ start: () => {
1445
+ active += 1;
1446
+ resolve();
1447
+ },
1448
+ abort: reject,
1449
+ finalizer
1450
+ });
1451
+ });
1452
+ const release = () => {
1453
+ active -= 1;
1454
+ waiting.shift()?.start();
1455
+ };
1456
+ return {
1457
+ async run(task) {
1458
+ await acquire(false);
1459
+ try {
1460
+ return await task();
1461
+ } finally {
1462
+ release();
1463
+ }
1464
+ },
1465
+ async runFinalizer(task) {
1466
+ await acquire(true);
1467
+ try {
1468
+ return await task();
1469
+ } finally {
1470
+ release();
1471
+ }
1472
+ },
1473
+ cancel(error) {
1474
+ cancelled ??= { error };
1475
+ const queued = waiting.splice(0);
1476
+ for (const entry of queued) if (entry.finalizer) waiting.push(entry);
1477
+ else entry.abort(error);
1478
+ }
1479
+ };
1480
+ }
1481
+ function assertPositiveInteger(value, label) {
1482
+ if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
1483
+ }
1402
1484
  //#endregion
1403
1485
  //#region ../js/src/athlete.ts
1404
1486
  async function getJson(client, path, label) {
@@ -1433,39 +1515,25 @@ function sortRosterByRecency(rows) {
1433
1515
  * summary becomes a null-data row (sorted last), not an error.
1434
1516
  */
1435
1517
  async function fetchRosterActivity(client, athleteIds, useMetric = false) {
1436
- const rows = [];
1437
- const concurrency = 6;
1438
- const uniqueAthleteIds = [...new Set(athleteIds)];
1439
- for (let i = 0; i < uniqueAthleteIds.length; i += concurrency) {
1440
- const chunk = uniqueAthleteIds.slice(i, i + concurrency);
1441
- const settled = await Promise.all(chunk.map(async (id) => {
1442
- try {
1443
- return {
1444
- id,
1445
- summary: await fetchAthleteProfileSummary(client, id, useMetric)
1446
- };
1447
- } catch {
1448
- return {
1449
- id,
1450
- summary: null
1451
- };
1452
- }
1453
- }));
1454
- for (const { id, summary } of settled) {
1455
- const count = summary?.sessions_count ?? null;
1456
- const hasSessions = count !== null && count > 0;
1457
- const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
1458
- rows.push({
1459
- athleteId: id,
1460
- sessionsCount: count,
1461
- firstLoggedDate: normDate(summary?.first_logged_date),
1462
- lastLoggedDate: normDate(summary?.last_logged_date),
1463
- totalReps: summary?.reps_sum ?? null,
1464
- totalVolume: summary?.volume_sum ?? null
1465
- });
1518
+ return sortRosterByRecency(await mapPool(uniq(athleteIds), 6, async (id) => {
1519
+ let summary;
1520
+ try {
1521
+ summary = await fetchAthleteProfileSummary(client, id, useMetric);
1522
+ } catch {
1523
+ summary = null;
1466
1524
  }
1467
- }
1468
- return sortRosterByRecency(rows);
1525
+ const count = summary?.sessions_count ?? null;
1526
+ const hasSessions = count !== null && count > 0;
1527
+ const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
1528
+ return {
1529
+ athleteId: id,
1530
+ sessionsCount: count,
1531
+ firstLoggedDate: normDate(summary?.first_logged_date),
1532
+ lastLoggedDate: normDate(summary?.last_logged_date),
1533
+ totalReps: summary?.reps_sum ?? null,
1534
+ totalVolume: summary?.volume_sum ?? null
1535
+ };
1536
+ }));
1469
1537
  }
1470
1538
  function fetchExerciseHistoryDetail(client, exerciseId, userId) {
1471
1539
  return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
@@ -1492,6 +1560,28 @@ function slotValues(ex, requireMade) {
1492
1560
  }
1493
1561
  return map;
1494
1562
  }
1563
+ /**
1564
+ * The slots carrying data that the athlete has NOT marked performed (`param_i_made !== 1`). On a
1565
+ * saved-copy row these are the row's own targets: the pre-filled prescription, an athlete- or
1566
+ * coach-level override written with `made = 0` (`prescribeAthleteSet`), or a personal session's
1567
+ * only prescription, since personal work has no template tree at all.
1568
+ */
1569
+ function unmadeSlotValues(ex) {
1570
+ const map = slotValues(ex, false);
1571
+ for (const i of map.keys()) if (coerceInt(ex[`param_${i}_made`]) === 1) map.delete(i);
1572
+ return map;
1573
+ }
1574
+ /**
1575
+ * The prescription for one exercise: the template row's slots, with any target the saved copy
1576
+ * still holds unperformed taking precedence per set index (that is what the athlete's app shows,
1577
+ * and where a per-athlete override lives). Without a template row the saved copy's unperformed
1578
+ * slots are the whole prescription.
1579
+ */
1580
+ function prescriptionSlots(template, saved) {
1581
+ const map = template ? slotValues(template, false) : /* @__PURE__ */ new Map();
1582
+ if (saved) for (const [i, v] of unmadeSlotValues(saved)) map.set(i, v);
1583
+ return map;
1584
+ }
1495
1585
  /** The joined display for a slot, kept verbatim (`"5 @ 225"`, `"AMRAP"`, `"@ 225"`). */
1496
1586
  function fmtSlot(slot) {
1497
1587
  const has1 = slot.p1 !== null;
@@ -1501,10 +1591,6 @@ function fmtSlot(slot) {
1501
1591
  if (has2) return `@ ${slot.p2}`;
1502
1592
  return "";
1503
1593
  }
1504
- /** Every slot carrying data, joined for display (the prescription reader): `["5 @ 225", "AMRAP"]`. */
1505
- function prescribedStrings(ex) {
1506
- return [...slotValues(ex, false).values()].map(fmtSlot);
1507
- }
1508
1594
  /** The slots the athlete logged (`param_i_made === 1`), joined for display (the performed reader). */
1509
1595
  function performedStrings(ex) {
1510
1596
  return [...slotValues(ex, true).values()].map(fmtSlot);
@@ -1526,179 +1612,45 @@ function savedSets(saved) {
1526
1612
  return out;
1527
1613
  }
1528
1614
  /**
1529
- * Map each prescription exercise id to the slot-indexed values the athlete logged against it. In
1530
- * the saved copy `workout_set_exercise_id` points back at the prescription exercise's `id`, and the
1531
- * entered values live in the same `param_N_data` slots as a prescription.
1615
+ * Every exercise the athlete performed (logged at least one `param_i_made === 1` slot) across a
1616
+ * list of range items, read straight off the saved copies. This is the cheap tally for callers
1617
+ * that only need "which exercises were logged" (the main-lift discovery over a year of sessions)
1618
+ * and skips the prescription merge and string formatting `presentAthleteWorkouts` does per set.
1532
1619
  */
1533
- function performedSlotsByExerciseId(sets) {
1534
- const map = /* @__PURE__ */ new Map();
1535
- for (const { exercises } of sets) for (const ex of exercises) {
1536
- const id = coerceInt(ex.workout_set_exercise_id);
1537
- if (id === null) continue;
1538
- const slots = slotValues(ex, true);
1539
- if (slots.size > 0) map.set(id, slots);
1540
- }
1541
- return map;
1542
- }
1543
- /** Per-exercise athlete notes keyed by the prescription template id (`workout_set_exercise_id`). */
1544
- function notesByTemplateId(sets) {
1545
- const map = /* @__PURE__ */ new Map();
1546
- for (const { exercises } of sets) for (const ex of exercises) {
1547
- const id = coerceInt(ex.workout_set_exercise_id);
1548
- const notes = str$1(ex.notes);
1549
- if (id !== null && notes !== null) map.set(id, notes);
1550
- }
1551
- return map;
1552
- }
1553
- /** Align an exercise's prescribed slots with the slots the athlete logged, per set index. */
1554
- function mergeExercise(prescribed, performed, meta) {
1555
- const indices = [.../* @__PURE__ */ new Set([...prescribed.keys(), ...performed.keys()])].sort((a, b) => a - b);
1556
- return {
1557
- ...meta,
1558
- sets: indices.map((i) => ({
1559
- set: i,
1560
- prescribed: prescribed.get(i) ?? null,
1561
- performed: performed.get(i) ?? null
1562
- }))
1563
- };
1564
- }
1565
- /** A prescription block, each exercise aligned with the slots the athlete logged against it. */
1566
- function mergePrescriptionBlock(set, performedById, notesById) {
1567
- const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
1568
- return {
1569
- order: coerceInt(set.order) ?? 0,
1570
- title: str$1(set.title),
1571
- instruction: str$1(set.instruction),
1572
- isTest: coerceInt(set.is_test) === 1,
1573
- exercises: exercises.filter(isRecord).map((ex) => {
1574
- const id = coerceInt(ex.id);
1575
- const performed = (id !== null ? performedById.get(id) : void 0) ?? /* @__PURE__ */ new Map();
1576
- return mergeExercise(slotValues(ex, false), performed, {
1577
- exerciseId: coerceInt(ex.exercise_id),
1578
- title: typeof ex.title === "string" ? ex.title : "",
1579
- instruction: str$1(ex.instruction),
1580
- notes: id !== null ? notesById.get(id) ?? null : null,
1581
- units: exerciseUnits(ex.param_1_type, ex.param_2_type)
1620
+ function performedExercises(workouts) {
1621
+ const out = [];
1622
+ for (const pw of workouts) {
1623
+ const rec = pw;
1624
+ const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
1625
+ const workout = isRecord(ssw.workout) ? ssw.workout : {};
1626
+ const templates = /* @__PURE__ */ new Map();
1627
+ for (const set of Array.isArray(workout.workoutSets) ? workout.workoutSets : []) {
1628
+ if (!isRecord(set)) continue;
1629
+ const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
1630
+ for (const ex of exercises) {
1631
+ if (!isRecord(ex)) continue;
1632
+ const id = coerceInt(ex.id);
1633
+ if (id !== null) templates.set(id, {
1634
+ exerciseId: coerceInt(ex.exercise_id),
1635
+ title: exerciseTitle(ex)
1636
+ });
1637
+ }
1638
+ }
1639
+ const saved = savedWorkoutOf(pw);
1640
+ if (!saved) continue;
1641
+ for (const { exercises } of savedSets(saved)) for (const ex of exercises) {
1642
+ const templateId = coerceInt(ex.workout_set_exercise_id);
1643
+ const template = templateId === null ? void 0 : templates.get(templateId);
1644
+ const exerciseId = coerceInt(ex.exercise_id) ?? template?.exerciseId ?? null;
1645
+ if (exerciseId === null || slotValues(ex, true).size === 0) continue;
1646
+ out.push({
1647
+ exerciseId,
1648
+ title: exerciseTitle(ex, template?.title)
1582
1649
  });
1583
- })
1584
- };
1585
- }
1586
- /** A logged block straight from the saved copy (athlete-added or personal work; no prescription). */
1587
- function mergeSavedBlock(set, exercises) {
1588
- return {
1589
- order: coerceInt(set.order) ?? 0,
1590
- title: str$1(set.title),
1591
- instruction: str$1(set.instruction),
1592
- isTest: coerceInt(set.is_test) === 1,
1593
- exercises: exercises.map((ex) => mergeExercise(/* @__PURE__ */ new Map(), slotValues(ex, true), {
1594
- exerciseId: coerceInt(ex.exercise_id),
1595
- title: typeof ex.exercise_title === "string" ? ex.exercise_title : "",
1596
- instruction: str$1(ex.instruction),
1597
- notes: str$1(ex.notes),
1598
- units: exerciseUnits(ex.param_1_type, ex.param_2_type)
1599
- }))
1600
- };
1601
- }
1602
- /**
1603
- * Flatten one `/3.0/athlete/programworkout/range` item into the canonical merged form, joining the
1604
- * prescription (`summarizedSavedWorkout.workout`) with what the athlete logged
1605
- * (`summarizedSavedWorkout.saved_workout`). Prescription blocks are enriched with logged slots;
1606
- * athlete-added / personal work with no prescription is appended as its own block.
1607
- */
1608
- function mergeAthleteWorkout(raw) {
1609
- const rec = raw;
1610
- const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
1611
- const workout = isRecord(ssw.workout) ? ssw.workout : {};
1612
- const saved = savedWorkoutOf(rec) ?? {};
1613
- const prescriptionSets = (Array.isArray(workout.workoutSets) ? workout.workoutSets : []).filter(isRecord);
1614
- const logged = savedSets(saved);
1615
- const performedById = performedSlotsByExerciseId(logged);
1616
- const notesById = notesByTemplateId(logged);
1617
- const blocks = prescriptionSets.map((s) => mergePrescriptionBlock(s, performedById, notesById)).sort((a, b) => a.order - b.order);
1618
- const prescribedIds = /* @__PURE__ */ new Set();
1619
- for (const s of prescriptionSets) {
1620
- const exs = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
1621
- for (const ex of exs) {
1622
- if (!isRecord(ex)) continue;
1623
- const id = coerceInt(ex.id);
1624
- if (id !== null) prescribedIds.add(id);
1625
1650
  }
1626
1651
  }
1627
- for (const { set, exercises } of logged) {
1628
- const extra = exercises.filter((ex) => {
1629
- if (slotValues(ex, true).size === 0) return false;
1630
- const id = coerceInt(ex.workout_set_exercise_id);
1631
- return id === null || !prescribedIds.has(id);
1632
- });
1633
- if (extra.length > 0) blocks.push(mergeSavedBlock(set, extra));
1634
- }
1635
- return {
1636
- id: coerceInt(rec.id),
1637
- date: str$1(rec.date) ?? "",
1638
- title: str$1(rec.workout_title) ?? "",
1639
- program: str$1(rec.program_title),
1640
- team: str$1(rec.team_title),
1641
- instruction: str$1(workout.instruction),
1642
- notes: str$1(saved.notes),
1643
- rpe: coerceInt(saved.rpe),
1644
- logged: blocks.some((b) => b.exercises.some((e) => e.sets.some((s) => s.performed !== null))),
1645
- personal: isPersonalSession(rec),
1646
- blocks
1647
- };
1648
- }
1649
- /** The per-set displays for one side (prescribed or performed), in slot order. */
1650
- function sideStrings(sets, pick) {
1651
- const out = [];
1652
- for (const s of sets) {
1653
- const slot = pick(s);
1654
- if (slot) out.push(fmtSlot(slot));
1655
- }
1656
1652
  return out;
1657
1653
  }
1658
- function toStringExercise(ex) {
1659
- return {
1660
- exerciseId: ex.exerciseId,
1661
- title: ex.title,
1662
- instruction: ex.instruction,
1663
- notes: ex.notes,
1664
- units: ex.units,
1665
- prescribed: sideStrings(ex.sets, (s) => s.prescribed),
1666
- performed: sideStrings(ex.sets, (s) => s.performed)
1667
- };
1668
- }
1669
- function toStringBlock(b) {
1670
- return {
1671
- order: b.order,
1672
- title: b.title,
1673
- instruction: b.instruction,
1674
- isTest: b.isTest,
1675
- exercises: b.exercises.map(toStringExercise)
1676
- };
1677
- }
1678
- /**
1679
- * Flatten one range item into a readable workout: each exercise carries its `prescribed` and
1680
- * `performed` sets as joined `"5 @ 225"` strings; athlete-added/personal work that has no
1681
- * prescription is appended as its own blocks. No `raw` is needed to see logged results.
1682
- */
1683
- function presentAthleteWorkout(raw) {
1684
- const w = mergeAthleteWorkout(raw);
1685
- return {
1686
- id: w.id,
1687
- date: w.date,
1688
- title: w.title,
1689
- program: w.program,
1690
- team: w.team,
1691
- instruction: w.instruction,
1692
- notes: w.notes,
1693
- rpe: w.rpe,
1694
- logged: w.logged,
1695
- personal: w.personal,
1696
- blocks: w.blocks.map(toStringBlock)
1697
- };
1698
- }
1699
- function presentAthleteWorkouts(list) {
1700
- return list.map(presentAthleteWorkout);
1701
- }
1702
1654
  /**
1703
1655
  * Narrow a coach-athlete workout range to a single program or team. The range endpoint returns
1704
1656
  * every program the athlete is enrolled in on a date; for a high-enrollment athlete that is many
@@ -1737,6 +1689,16 @@ function presentLogTargets(list) {
1737
1689
  const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
1738
1690
  const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
1739
1691
  if (!saved) continue;
1692
+ const workout = isRecord(ssw.workout) ? ssw.workout : {};
1693
+ const templatesById = /* @__PURE__ */ new Map();
1694
+ for (const tSet of Array.isArray(workout.workoutSets) ? workout.workoutSets : []) {
1695
+ if (!isRecord(tSet)) continue;
1696
+ const tExs = Array.isArray(tSet.workoutSetExercises) ? tSet.workoutSetExercises : [];
1697
+ for (const tEx of tExs) {
1698
+ const tId = isRecord(tEx) ? coerceInt(tEx.id) : null;
1699
+ if (tId !== null && isRecord(tEx)) templatesById.set(tId, tEx);
1700
+ }
1701
+ }
1740
1702
  const date = str$1(rec.date) ?? "";
1741
1703
  const workoutTitle = str$1(rec.workout_title) ?? "";
1742
1704
  const program = str$1(rec.program_title);
@@ -1751,12 +1713,14 @@ function presentLogTargets(list) {
1751
1713
  const exercises = (Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : []).filter(isRecord).map((ex) => {
1752
1714
  const id = coerceInt(ex.id);
1753
1715
  if (id === null) return null;
1716
+ const templateId = coerceInt(ex.workout_set_exercise_id);
1717
+ const template = templateId === null ? void 0 : templatesById.get(templateId);
1754
1718
  return {
1755
1719
  savedWorkoutSetExerciseId: id,
1756
1720
  title: exerciseTitle(ex),
1757
1721
  units: exerciseUnits(ex.param_1_type, ex.param_2_type),
1758
1722
  notes: str$1(ex.notes),
1759
- prescribed: prescribedStrings(ex),
1723
+ prescribed: [...prescriptionSlots(template, ex).values()].map(fmtSlot),
1760
1724
  performed: performedStrings(ex)
1761
1725
  };
1762
1726
  }).filter((e) => e !== null);
@@ -1846,6 +1810,28 @@ function presentExerciseHistory(detail) {
1846
1810
  };
1847
1811
  }
1848
1812
  //#endregion
1813
+ //#region ../js/src/exercise-history.ts
1814
+ /**
1815
+ * Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
1816
+ * The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
1817
+ * first 10 chars so both "YYYY-MM-DD" and "YYYY-MM-DDThh:mm" values filter correctly. The one
1818
+ * window rule shared by the athlete's own history tool, the coach's per-roster-athlete history
1819
+ * tool, and the CLI, so a timestamped session cannot fall out of an inclusive upper bound.
1820
+ */
1821
+ function historyInRange(presented, since, until) {
1822
+ if (since === void 0 && until === void 0) return presented;
1823
+ const sessions = presented.sessions.filter((s) => {
1824
+ const d = (s.date ?? "").slice(0, 10);
1825
+ if (since !== void 0 && d < since) return false;
1826
+ if (until !== void 0 && d > until) return false;
1827
+ return true;
1828
+ });
1829
+ return {
1830
+ ...presented,
1831
+ sessions
1832
+ };
1833
+ }
1834
+ //#endregion
1849
1835
  //#region ../js/src/coach-athlete-calendar.ts
1850
1836
  async function getArray(client, path, label) {
1851
1837
  const res = await client.request("GET", path);
@@ -1980,6 +1966,7 @@ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, w
1980
1966
  }
1981
1967
  //#endregion
1982
1968
  //#region ../js/src/athlete-set-write.ts
1969
+ const WRITE_CONCURRENCY = 4;
1983
1970
  /**
1984
1971
  * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
1985
1972
  * {@link SetResult}[]. The dto schemas validate ids as a number or a numeric string and leave
@@ -2182,6 +2169,41 @@ async function swapAthleteExercise(client, args) {
2182
2169
  originalTeamExerciseId: coerceInt(template.exercise_id)
2183
2170
  };
2184
2171
  }
2172
+ function prepareSetWrite(target, workouts, savedWorkoutSetId, results, mode) {
2173
+ const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
2174
+ assertUniqueExerciseResults(results);
2175
+ const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
2176
+ const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
2177
+ return {
2178
+ savedWorkoutSetId,
2179
+ exercises,
2180
+ rawSet,
2181
+ suffix,
2182
+ extra,
2183
+ writes: results.map((result) => {
2184
+ const ex = exercises.find((candidate) => coerceInt(candidate.id) === result.savedWorkoutSetExerciseId);
2185
+ if (!ex) {
2186
+ const valid = exercises.map((candidate) => {
2187
+ const id = coerceInt(candidate.id);
2188
+ return id === null ? null : `${id} (${exerciseTitle(candidate, "exercise")})`;
2189
+ }).filter((label) => label !== null);
2190
+ throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
2191
+ }
2192
+ const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
2193
+ if (!workoutSetExerciseId) throw new Error(`savedWorkoutSetExercise ${result.savedWorkoutSetExerciseId} is missing its workout_set_exercise_id (the prescription-template pointer the write needs). This is the savedWorkoutSetExerciseId, not an exercise_id — re-read the ids from athlete_saved_workouts.`);
2194
+ return {
2195
+ id: result.savedWorkoutSetExerciseId,
2196
+ body: {
2197
+ ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
2198
+ ...extra
2199
+ }
2200
+ };
2201
+ })
2202
+ };
2203
+ }
2204
+ function errorMessage(error) {
2205
+ return error instanceof Error ? error.message : String(error);
2206
+ }
2185
2207
  /**
2186
2208
  * Shared set-write behind {@link logAthleteSet}, {@link prescribeAthleteSet},
2187
2209
  * {@link logForAthlete}, and {@link prescribeForAthlete}. `target` selects the surface: `athlete`
@@ -2195,36 +2217,40 @@ async function swapAthleteExercise(client, args) {
2195
2217
  * the written ones); `"prescribe"` writes them as a prescription and skips Step 2, leaving the set
2196
2218
  * open.
2197
2219
  */
2198
- async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode) {
2199
- const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
2200
- assertUniqueExerciseResults(results);
2201
- const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
2202
- const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
2203
- let exercisesWritten = 0;
2204
- const projectedCompletion = /* @__PURE__ */ new Map();
2205
- for (const result of results) {
2206
- const ex = exercises.find((e) => coerceInt(e.id) === result.savedWorkoutSetExerciseId);
2207
- if (!ex) {
2208
- const valid = exercises.map((e) => {
2209
- const id = coerceInt(e.id);
2210
- return id === null ? null : `${id} (${exerciseTitle(e, "exercise")})`;
2211
- }).filter((x) => x !== null);
2212
- throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
2213
- }
2214
- const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
2215
- if (!workoutSetExerciseId) throw new Error(`savedWorkoutSetExercise ${result.savedWorkoutSetExerciseId} is missing its workout_set_exercise_id (the prescription-template pointer the write needs). This is the savedWorkoutSetExerciseId, not an exercise_id — re-read the ids from athlete_saved_workouts.`);
2216
- const body = {
2217
- ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
2218
- ...extra
2220
+ async function executeSetWrite(client, target, prepared, mode, limit, sessionProgress) {
2221
+ const { savedWorkoutSetId, exercises, rawSet, suffix, extra, writes } = prepared;
2222
+ const put = (path, body, failureMessage, finalizer = false) => {
2223
+ const request = async () => {
2224
+ try {
2225
+ const res = await client.request("PUT", path, { body });
2226
+ if (!res.ok) throw new Error(failureMessage(res.status));
2227
+ } catch (error) {
2228
+ limit.cancel(error);
2229
+ throw error;
2230
+ }
2219
2231
  };
2220
- const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
2221
- if (!res.ok) {
2222
- const readOnly = target.role === "coach" && (res.status === 401 || res.status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for changes — TrainHeroic's seeded demo/sample athletes return ${res.status} here; writes only persist for real (invited) athletes.` : "";
2223
- throw new Error(`Failed to write exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).${readOnly}`);
2224
- }
2225
- projectedCompletion.set(result.savedWorkoutSetExerciseId, body.completed === 1);
2226
- exercisesWritten += 1;
2232
+ return finalizer ? limit.runFinalizer(request) : limit.run(request);
2233
+ };
2234
+ const confirmed = [];
2235
+ try {
2236
+ await mapPool(writes, WRITE_CONCURRENCY, async ({ id, body }) => {
2237
+ await put(`/1.0/${target.role}/savedworkoutsetexercise/${id}${suffix}`, body, (status) => {
2238
+ return `Failed to write exercise ${id} (HTTP ${status}).${target.role === "coach" && (status === 401 || status === 403) ? ` Athlete ${target.athleteId} appears to be read-only for changes — TrainHeroic's seeded demo/sample athletes return ${status} here; writes only persist for real (invited) athletes.` : ""}`;
2239
+ });
2240
+ confirmed.push(id);
2241
+ if (sessionProgress) {
2242
+ const sessionConfirmed = sessionProgress.get(savedWorkoutSetId) ?? [];
2243
+ sessionConfirmed.push(id);
2244
+ sessionProgress.set(savedWorkoutSetId, sessionConfirmed);
2245
+ }
2246
+ });
2247
+ } catch (error) {
2248
+ if (sessionProgress || confirmed.length === 0) throw error;
2249
+ confirmed.sort((a, b) => a - b);
2250
+ throw new Error(`${errorMessage(error)} Confirmed exercise writes before the failure: ${confirmed.join(", ")}. The set was not marked complete; retry the same request to reconcile it.`, { cause: error });
2227
2251
  }
2252
+ const exercisesWritten = writes.length;
2253
+ const projectedCompletion = new Map(writes.map((w) => [w.id, w.body.completed === 1]));
2228
2254
  let setCompleted = false;
2229
2255
  if (mode === "log") {
2230
2256
  if (isSetFullyLogged(exercises, projectedCompletion)) {
@@ -2232,8 +2258,11 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
2232
2258
  ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
2233
2259
  ...extra
2234
2260
  };
2235
- const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
2236
- if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
2261
+ try {
2262
+ await put(`/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, setBody, (status) => `Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${status}).`, true);
2263
+ } catch (error) {
2264
+ throw new Error(`${errorMessage(error)} Exercise values were written successfully; retry the same request to complete the set.`, { cause: error });
2265
+ }
2237
2266
  setCompleted = true;
2238
2267
  }
2239
2268
  }
@@ -2243,6 +2272,9 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
2243
2272
  setCompleted
2244
2273
  };
2245
2274
  }
2275
+ async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode, limit = createLimiter(WRITE_CONCURRENCY)) {
2276
+ return executeSetWrite(client, target, prepareSetWrite(target, workouts, savedWorkoutSetId, results, mode), mode, limit);
2277
+ }
2246
2278
  /**
2247
2279
  * Flatten a day's saved sets into `{ pw, savedWorkoutSetId, ex }` rows (both saved-set keys),
2248
2280
  * carrying the parent program-workout so a caller can read its identity (`personal_cal`, program
@@ -2297,7 +2329,7 @@ function prescribedExerciseLabels(workouts) {
2297
2329
  return labels;
2298
2330
  }
2299
2331
  /** Group resolved exercises by saved set and write each set via the given log target. */
2300
- async function logResolvedExercises(client, target, workouts, resolved) {
2332
+ async function logResolvedExercises(client, target, workouts, resolved, retryGuidance) {
2301
2333
  const bySet = /* @__PURE__ */ new Map();
2302
2334
  for (const r of resolved) {
2303
2335
  const list = bySet.get(r.savedWorkoutSetId) ?? [];
@@ -2307,15 +2339,28 @@ async function logResolvedExercises(client, target, workouts, resolved) {
2307
2339
  });
2308
2340
  bySet.set(r.savedWorkoutSetId, list);
2309
2341
  }
2310
- const out = [];
2311
- for (const [savedWorkoutSetId, results] of bySet) {
2312
- const written = await writeSetResults(client, target, workouts, savedWorkoutSetId, results, "log");
2313
- out.push({
2314
- savedWorkoutSetId: written.savedWorkoutSetId,
2315
- exercisesLogged: written.exercisesWritten
2342
+ const prepared = [...bySet].map(([savedWorkoutSetId, results]) => prepareSetWrite(target, workouts, savedWorkoutSetId, results, "log"));
2343
+ const limit = createLimiter(WRITE_CONCURRENCY);
2344
+ const confirmedBySet = /* @__PURE__ */ new Map();
2345
+ const succeeded = [];
2346
+ try {
2347
+ return await mapPool(prepared, WRITE_CONCURRENCY, async (set) => {
2348
+ const written = await executeSetWrite(client, target, set, "log", limit, confirmedBySet);
2349
+ succeeded.push(written.savedWorkoutSetId);
2350
+ return {
2351
+ savedWorkoutSetId: written.savedWorkoutSetId,
2352
+ exercisesLogged: written.exercisesWritten
2353
+ };
2316
2354
  });
2355
+ } catch (error) {
2356
+ const completed = new Set(succeeded);
2357
+ const incomplete = [...confirmedBySet].filter(([savedWorkoutSetId]) => !completed.has(savedWorkoutSetId)).sort(([a], [b]) => a - b).map(([savedWorkoutSetId, ids]) => `set ${savedWorkoutSetId}: ${ids.toSorted((a, b) => a - b).join(", ")}`);
2358
+ if (incomplete.length === 0 && succeeded.length === 0) throw error;
2359
+ succeeded.sort((a, b) => a - b);
2360
+ const partial = incomplete.length === 0 ? "" : ` Confirmed exercise writes in incomplete sets before the failure: ${incomplete.join("; ")}.${retryGuidance ? ` ${retryGuidance}` : ""}`;
2361
+ const complete = succeeded.length === 0 ? "" : ` Set writes confirmed before the failure: ${succeeded.join(", ")}.`;
2362
+ throw new Error(`${errorMessage(error)}${partial}${complete}`, { cause: error });
2317
2363
  }
2318
- return out;
2319
2364
  }
2320
2365
  /**
2321
2366
  * Coach "log a session for a roster athlete" by exercise. The API offers no way to put an
@@ -2345,7 +2390,7 @@ async function logSessionForAthlete(client, args) {
2345
2390
  const sets = await logResolvedExercises(client, {
2346
2391
  role: "coach",
2347
2392
  athleteId: args.athleteId
2348
- }, day, resolved);
2393
+ }, day, resolved, "Retry the same request to reconcile them.");
2349
2394
  return {
2350
2395
  date: args.date,
2351
2396
  created: false,
@@ -2460,9 +2505,75 @@ function repsList(ex) {
2460
2505
  const reps = ex.reps;
2461
2506
  if (Array.isArray(reps)) return reps.map((r) => String(r));
2462
2507
  if (reps === void 0 || reps === null) return [];
2463
- const sets = Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2508
+ const sets = Array.isArray(ex.weight) ? ex.weight.length : Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2464
2509
  return Array.from({ length: sets }, () => String(reps));
2465
2510
  }
2511
+ /** Number of sets that the encoder will write for an exercise. */
2512
+ function exerciseSetCount(ex) {
2513
+ if (Array.isArray(ex.reps) && ex.reps.length > 0) return ex.reps.length;
2514
+ if (Array.isArray(ex.weight)) return ex.weight.length;
2515
+ if (!Array.isArray(ex.reps) && ex.reps !== void 0 && ex.reps !== null || ex.weight !== void 0 && ex.weight !== null) return Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2516
+ return 0;
2517
+ }
2518
+ function findSetSplits(blocks) {
2519
+ return blocks.flatMap((block) => block.exercises.flatMap((exercise) => {
2520
+ const setCount = exerciseSetCount(exercise);
2521
+ if (setCount <= 10) return [];
2522
+ return [{
2523
+ blockTitle: block.title,
2524
+ exerciseTitle: exercise.title ?? String(exercise.id),
2525
+ setCount,
2526
+ blockCount: Math.ceil(setCount / 10)
2527
+ }];
2528
+ }));
2529
+ }
2530
+ function setSplitSummary(blocks) {
2531
+ const splits = findSetSplits(blocks);
2532
+ if (splits.length === 0) return null;
2533
+ return `TrainHeroic supports at most 10 sets per exercise block. The following will be split into consecutive same-titled blocks: ${splits.map(({ blockTitle, exerciseTitle, setCount, blockCount }) => `${blockTitle} / ${exerciseTitle}: ${setCount} sets into ${blockCount} blocks`).join("; ")}.`;
2534
+ }
2535
+ function sliceExercise(exercise, setCount, start) {
2536
+ if (start > 0 && setCount <= start) return null;
2537
+ const chunkCount = setCount === 0 ? 0 : Math.min(10, Math.max(0, setCount - start));
2538
+ const chunk = { ...exercise };
2539
+ const hasPerSetReps = Array.isArray(exercise.reps) && exercise.reps.length > 0;
2540
+ const hasScalarReps = !Array.isArray(exercise.reps) && exercise.reps !== void 0 && exercise.reps !== null;
2541
+ if (Array.isArray(exercise.reps) && exercise.reps.length > 0) {
2542
+ chunk.reps = exercise.reps.slice(start, start + 10);
2543
+ delete chunk.sets;
2544
+ } else if (hasScalarReps) chunk.sets = chunkCount;
2545
+ if (Array.isArray(exercise.weight)) {
2546
+ chunk.weight = exercise.weight.slice(start, start + 10);
2547
+ if (!hasPerSetReps && !hasScalarReps) delete chunk.sets;
2548
+ } else if (!hasPerSetReps && exercise.weight !== void 0 && exercise.weight !== null) chunk.sets = chunkCount;
2549
+ return chunk;
2550
+ }
2551
+ /**
2552
+ * Split blocks so no encoded exercise exceeds TrainHeroic's ten parameter slots.
2553
+ * Exercises in a superset stay aligned by set range; shorter exercises appear only in
2554
+ * chunks where they still have sets.
2555
+ */
2556
+ function splitOversizedBlocks(blocks) {
2557
+ return blocks.flatMap((block) => {
2558
+ const setCounts = block.exercises.map(exerciseSetCount);
2559
+ const largestSetCount = Math.max(0, ...setCounts);
2560
+ const chunkCount = Math.max(1, Math.ceil(largestSetCount / 10));
2561
+ if (chunkCount === 1) return [block];
2562
+ return Array.from({ length: chunkCount }, (_, index) => {
2563
+ const start = index * 10;
2564
+ const exercises = block.exercises.map((exercise, exerciseIndex) => sliceExercise(exercise, setCounts[exerciseIndex] ?? 0, start)).filter((exercise) => exercise !== null);
2565
+ if (index === 0) return {
2566
+ ...block,
2567
+ exercises
2568
+ };
2569
+ return {
2570
+ title: block.title,
2571
+ ...block.type === void 0 ? {} : { type: block.type },
2572
+ exercises
2573
+ };
2574
+ });
2575
+ });
2576
+ }
2466
2577
  /** Build one saveWorkoutSetExercises payload entry with all ten param slots filled. */
2467
2578
  function makeExercise(ex, workoutSetId, order, key) {
2468
2579
  const reps = repsList(ex);
@@ -2470,8 +2581,7 @@ function makeExercise(ex, workoutSetId, order, key) {
2470
2581
  if (instruction === "" && ex.rpe !== void 0 && ex.rpe !== null) instruction = `RPE ${ex.rpe}`;
2471
2582
  const hasWeight = ex.weight !== void 0 && ex.weight !== null;
2472
2583
  const weightArr = Array.isArray(ex.weight) ? ex.weight : null;
2473
- let count = reps.length;
2474
- if (count === 0 && hasWeight) count = weightArr ? weightArr.length : Math.max(1, Math.trunc(Number(ex.sets ?? 1)) || 1);
2584
+ const count = exerciseSetCount(ex);
2475
2585
  let param2Type;
2476
2586
  let param2Values;
2477
2587
  if (hasWeight) {
@@ -2502,8 +2612,8 @@ function makeExercise(ex, workoutSetId, order, key) {
2502
2612
  eType: "e",
2503
2613
  use_count: 0
2504
2614
  };
2505
- const p1 = slots(reps);
2506
- const p2 = slots(param2Values);
2615
+ const p1 = slots(reps, 10);
2616
+ const p2 = slots(param2Values, 10);
2507
2617
  for (let i = 0; i < 10; i += 1) {
2508
2618
  entry[`param_1_data_${i + 1}`] = p1[i] ?? "";
2509
2619
  entry[`param_2_data_${i + 1}`] = p2[i] ?? "";
@@ -2621,7 +2731,10 @@ function createPath(opts) {
2621
2731
  return `/2.0/coach/calendar/workout/createWorkoutForDay/${opts.programId}/${y}/${m}/${d}/0`;
2622
2732
  }
2623
2733
  async function buildSession(client, opts) {
2624
- const blocks = z.array(blockSpecSchema).parse(opts.blocks);
2734
+ const validatedBlocks = z.array(blockSpecSchema).parse(opts.blocks);
2735
+ const splitSummary = setSplitSummary(validatedBlocks);
2736
+ if (splitSummary !== null && opts.confirmSetSplit !== true) throw new Error(`${splitSummary} Set confirmSetSplit:true to allow this change.`);
2737
+ const blocks = splitSummary === null ? validatedBlocks : splitOversizedBlocks(validatedBlocks);
2625
2738
  const sess = await req(client, "POST", createPath(opts), {});
2626
2739
  checkResponse(sessionCreateResponseSchema, sess, "session create");
2627
2740
  const workoutId = Number(sess.workout_id);
@@ -2684,7 +2797,7 @@ async function readSession(client, programId, date, pwId) {
2684
2797
  const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
2685
2798
  return {
2686
2799
  pwId,
2687
- date: `${str(pw.year)}-${str(pw.month)}-${str(pw.day)}`,
2800
+ date: `${str(pw.year)}-${str(pw.month).padStart(2, "0")}-${str(pw.day).padStart(2, "0")}`,
2688
2801
  published: pw.published,
2689
2802
  instruction: str(pw.instruction),
2690
2803
  blocks
@@ -2704,14 +2817,13 @@ function readBlock(b) {
2704
2817
  };
2705
2818
  }
2706
2819
  function readExercise(ex) {
2707
- const reps = [];
2708
- const load = [];
2709
- for (let i = 1; i <= 10; i += 1) {
2710
- const r = str(ex[`param_1_data_${i}`]);
2711
- if (r !== "") reps.push(r);
2712
- const w = str(ex[`param_2_data_${i}`]);
2713
- if (w !== "") load.push(w);
2714
- }
2820
+ let last = 0;
2821
+ for (let i = 1; i <= 10; i += 1) if (str(ex[`param_1_data_${i}`]) !== "" || str(ex[`param_2_data_${i}`]) !== "") last = i;
2822
+ const slots = Array.from({ length: last }, (_, k) => k + 1);
2823
+ const repsRaw = slots.map((i) => str(ex[`param_1_data_${i}`]));
2824
+ const loadRaw = slots.map((i) => str(ex[`param_2_data_${i}`]));
2825
+ const reps = repsRaw.some((r) => r !== "") ? repsRaw : [];
2826
+ const load = loadRaw.some((w) => w !== "") ? loadRaw : [];
2715
2827
  return {
2716
2828
  order: Number(ex.order),
2717
2829
  title: str(ex.title),
@@ -3266,8 +3378,7 @@ async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
3266
3378
  } catch {
3267
3379
  workouts = [];
3268
3380
  }
3269
- for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
3270
- if (ex.performed.length === 0 || ex.exerciseId === null) continue;
3381
+ for (const ex of performedExercises(workouts)) {
3271
3382
  const family = classifyMainLift(ex.title);
3272
3383
  if (family === null) continue;
3273
3384
  const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
@@ -3512,6 +3623,7 @@ var ExerciseLibrary = class {
3512
3623
  #byId = /* @__PURE__ */ new Map();
3513
3624
  #loaded = false;
3514
3625
  #fetchedAt = 0;
3626
+ #loading = null;
3515
3627
  constructor(client, cache = new MemoryLibraryCache()) {
3516
3628
  this.#client = client;
3517
3629
  this.#cache = cache;
@@ -3539,8 +3651,11 @@ var ExerciseLibrary = class {
3539
3651
  });
3540
3652
  }
3541
3653
  async ensureFresh() {
3542
- if (!this.#loaded) await this.#ensureLoaded();
3543
- else if (Date.now() - this.#fetchedAt > TTL_MS) await this.refresh();
3654
+ if (this.#loaded && Date.now() - this.#fetchedAt <= TTL_MS) return;
3655
+ this.#loading ??= (this.#loaded ? this.refresh() : this.#ensureLoaded()).finally(() => {
3656
+ this.#loading = null;
3657
+ });
3658
+ await this.#loading;
3544
3659
  }
3545
3660
  async refresh() {
3546
3661
  const res = await this.#client.request("GET", LIBRARY_PATH);
@@ -3559,6 +3674,7 @@ var ExerciseLibrary = class {
3559
3674
  return presentExercise(s.raw);
3560
3675
  }
3561
3676
  async defaultsMany(ids) {
3677
+ await this.ensureFresh();
3562
3678
  const result = /* @__PURE__ */ new Map();
3563
3679
  for (const id of ids) {
3564
3680
  const s = this.#byId.get(id);
@@ -3646,27 +3762,6 @@ var ExerciseLibrary = class {
3646
3762
  }
3647
3763
  };
3648
3764
  //#endregion
3649
- //#region ../core/src/history.ts
3650
- /**
3651
- * Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
3652
- * The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
3653
- * first 10 chars so both "YYYY-MM-DD" and "YYYY-MM-DDThh:mm" values filter correctly. Shared by
3654
- * the athlete's own history tool and the coach's per-roster-athlete history tool.
3655
- */
3656
- function historyInRange(presented, since, until) {
3657
- if (since === void 0 && until === void 0) return presented;
3658
- const sessions = presented.sessions.filter((s) => {
3659
- const d = (s.date ?? "").slice(0, 10);
3660
- if (since !== void 0 && d < since) return false;
3661
- if (until !== void 0 && d > until) return false;
3662
- return true;
3663
- });
3664
- return {
3665
- ...presented,
3666
- sessions
3667
- };
3668
- }
3669
- //#endregion
3670
3765
  //#region ../core/src/tools/reads.ts
3671
3766
  const ATHLETE_LIFT_HISTORY_DESC = "A roster athlete's lift history for ONE exercise: the all-time PR board (liftPRs — each entry carries its rep-max label, weight, and the date it was set) plus the dated session series (sets, estimated 1RM). This is the coach-side way to answer 'show me <athlete>'s PRs / how is <athlete>'s squat trending' — pass athleteId from list_athletes and exerciseId from exercise_resolve. There is no cross-exercise PR rollup, so you query one lift at a time, but do NOT guess lift names blindly: first call athlete_training for the month(s) of interest — it lists every exercise the athlete actually performed (with the exact exercise the program used, e.g. 'Clean & Jerk' not 'Clean') — then bring those exerciseIds here. An empty result means that lift was not logged. liftPRs stay all-time; pass since/until (YYYY-MM-DD, inclusive) to window the session series. raw:true returns the untouched API object.";
3672
3767
  const ROSTER_ACTIVITY_DESC = "A coach's roster ranked by actual training recency: for each athleteId you pass (from list_athletes), the all-time sessionsCount, firstLoggedDate, lastLoggedDate, totalReps and totalVolume, sorted most-recently-active first. Use lastLoggedDate — the real training signal — NOT list_athletes' daysSinceLastLogin (app-login, not training) to answer 'who is my most recently active athlete' (the top row) or 'who is falling behind' (a stale or null lastLoggedDate, or low volume). A null lastLoggedDate means the athlete has never logged a session. This fans out one lookup per athlete, so for a large org pass only the athletes you care about. Then drill into a name with athlete_training (their month) or athlete_lift_history.";
@@ -4456,30 +4551,37 @@ function registerExerciseTools(server, ctx) {
4456
4551
  function registerBuild(server, ctx) {
4457
4552
  server.registerTool("workout_build", {
4458
4553
  title: "Build a workout session (draft)",
4459
- description: "Build an UNPUBLISHED session from a spec (program -> session -> blocks -> exercises). Pass programId for a team/group calendar (list_teams → group_program), or athleteId to write on that roster athlete's coach calendar (resolved via /v5/calendars/athletes/{id} — the same calendar the coach web app opens from My Athletes). athleteId requires date. Two exercises in one block become a superset. A block with empty exercises and a non-empty block instruction is a text-only Circuit / Conditioning block (type 1). Add a block 'leaderboard' for a Red-Zone score, or a top-level 'instruction' for the session note (Coach Instructions). Returns the draft ids, a read-back, and unit advisories. Review, then workout_publish.",
4554
+ description: "Build an UNPUBLISHED session from a spec (program -> session -> blocks -> exercises). Pass programId for a team/group calendar (list_teams → group_program), or athleteId to write on that roster athlete's coach calendar (resolved via /v5/calendars/athletes/{id} — the same calendar the coach web app opens from My Athletes). athleteId requires date. Two exercises in one block become a superset. A block with empty exercises and a non-empty block instruction is a text-only Circuit / Conditioning block (type 1). Add a block 'leaderboard' for a Red-Zone score, or a top-level 'instruction' for the session note (Coach Instructions). Returns the draft ids, a read-back, and unit advisories. Exercises above 10 sets are split into consecutive same-titled blocks and require confirmation (elicitation, or confirm:true). Review, then workout_publish.",
4460
4555
  inputSchema: {
4461
4556
  programId: z.number().optional(),
4462
4557
  athleteId: idParam.optional(),
4463
4558
  date: z.string().optional(),
4464
4559
  timelineDay: z.number().optional(),
4465
4560
  blocks: z.array(blockSpecSchema),
4466
- instruction: z.string().optional()
4561
+ instruction: z.string().optional(),
4562
+ confirm: z.boolean().optional()
4467
4563
  },
4468
4564
  outputSchema: toolOutputSchema(workoutBuildOutputSchema),
4469
4565
  annotations: ADDITIVE
4470
- }, ({ programId, athleteId, date, timelineDay, blocks, instruction }) => attempt(async () => {
4566
+ }, ({ programId, athleteId, date, timelineDay, blocks, instruction, confirm }, extra) => attempt(async () => {
4471
4567
  if (date === void 0 && timelineDay === void 0) return errorResult("Provide either date (YYYY-M-D) or timelineDay.");
4568
+ const typed = blocks;
4569
+ const splitSummary = setSplitSummary(typed);
4570
+ if (splitSummary !== null) {
4571
+ const blocked = confirmGate(extra, `${splitSummary} Continue?`, confirm);
4572
+ if (blocked) return blocked;
4573
+ }
4472
4574
  const resolveArgs = {};
4473
4575
  if (programId !== void 0) resolveArgs.programId = programId;
4474
4576
  if (athleteId !== void 0) resolveArgs.athleteId = toId(athleteId);
4475
4577
  if (date !== void 0) resolveArgs.date = date;
4476
4578
  const resolved = await resolveBuildProgramId(ctx.client, resolveArgs);
4477
- const typed = blocks;
4478
4579
  const opts = {
4479
4580
  programId: resolved,
4480
4581
  blocks: typed,
4481
4582
  publish: false
4482
4583
  };
4584
+ if (splitSummary !== null) opts.confirmSetSplit = true;
4483
4585
  if (date !== void 0) opts.date = parseWorkoutDate(date);
4484
4586
  if (timelineDay !== void 0) opts.timelineDay = timelineDay;
4485
4587
  if (instruction !== void 0) opts.instruction = instruction;
@@ -4751,7 +4853,7 @@ var JsonFileLibraryCache = class {
4751
4853
  };
4752
4854
  //#endregion
4753
4855
  //#region package.json
4754
- var version = "3.5.0";
4856
+ var version = "3.5.2";
4755
4857
  //#endregion
4756
4858
  //#region src/server.ts
4757
4859
  function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "3.5.0",
3
+ "version": "3.5.2",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,8 +21,8 @@
21
21
  "dependencies": {
22
22
  "@modelcontextprotocol/server": "2.0.0",
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/core": "3.5.0",
25
- "@trainheroic-unofficial/js": "3.5.0"
24
+ "@trainheroic-unofficial/js": "3.5.2",
25
+ "@trainheroic-unofficial/core": "3.5.2"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.3.0",