@trainheroic-unofficial/coach-mcp 3.5.1 → 3.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/server.mjs +519 -323
  2. package/package.json +3 -3
package/dist/server.mjs CHANGED
@@ -745,15 +745,19 @@ z.object({
745
745
  /**
746
746
  * Parse a `YYYY-M-D` string into the `WorkoutDate` tuple. The single home for this
747
747
  * conversion, shared by the MCP tools and the CLI so they cannot drift on what counts
748
- * 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.
749
751
  */
750
752
  function parseWorkoutDate(s) {
751
- const parts = s.split("-").map((p) => Number(p));
752
- 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}".`);
753
757
  return [
754
- parts[0],
755
- parts[1],
756
- parts[2]
758
+ year,
759
+ month,
760
+ day
757
761
  ];
758
762
  }
759
763
  /** Body for `POST /v5/sessions/template` (library create, not save-from-session). */
@@ -837,12 +841,16 @@ function resultBudget() {
837
841
  function isPlainObject(value) {
838
842
  return typeof value === "object" && value !== null && !Array.isArray(value);
839
843
  }
840
- /** Largest count k such that the JSON of the first k pre-serialized pieces fits. O(n). */
841
- 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) {
842
850
  let used = 2;
843
851
  let k = 0;
844
- for (const piece of pieces) {
845
- 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);
846
854
  if (used + add > charBudget) break;
847
855
  used += add;
848
856
  k += 1;
@@ -857,11 +865,12 @@ function hardCap(text, budget, hint) {
857
865
  return text.slice(0, keep) + note;
858
866
  }
859
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;
860
870
  let best = null;
861
871
  let bestLen = -1;
862
- for (const [key, value] of Object.entries(obj)) {
863
- if (!Array.isArray(value)) continue;
864
- const len = (JSON.stringify(value) ?? "[]").length;
872
+ for (const key of arrayKeys) {
873
+ const len = (JSON.stringify(obj[key]) ?? "[]").length;
865
874
  if (len > bestLen) {
866
875
  best = key;
867
876
  bestLen = len;
@@ -869,9 +878,6 @@ function largestArrayValuedKey(obj) {
869
878
  }
870
879
  return best;
871
880
  }
872
- function jsonValue(data) {
873
- return JSON.parse(JSON.stringify(data) ?? "null");
874
- }
875
881
  function previewEnvelope(source, budget, hint) {
876
882
  const total = source.length;
877
883
  const makeValue = (preview, markerHint) => ({
@@ -898,8 +904,8 @@ function boundedResult(data, budget, hint) {
898
904
  text: data,
899
905
  value: data
900
906
  };
901
- const value = jsonValue(data);
902
- const compact = JSON.stringify(value);
907
+ const compact = JSON.stringify(data) ?? "null";
908
+ const value = JSON.parse(compact);
903
909
  if (compact.length <= budget) {
904
910
  const pretty = JSON.stringify(value, null, 2);
905
911
  return {
@@ -908,7 +914,7 @@ function boundedResult(data, budget, hint) {
908
914
  };
909
915
  }
910
916
  if (Array.isArray(value)) {
911
- 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);
912
918
  const text = JSON.stringify(truncated);
913
919
  if (text.length <= budget) return {
914
920
  text,
@@ -918,7 +924,7 @@ function boundedResult(data, budget, hint) {
918
924
  const key = largestArrayValuedKey(value);
919
925
  if (key !== null) {
920
926
  const array = value[key];
921
- 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);
922
928
  const text = JSON.stringify(truncated);
923
929
  if (text.length <= budget) return {
924
930
  text,
@@ -1027,30 +1033,200 @@ function confirmGate(ctx, message, confirmArg) {
1027
1033
  const SERVER_INSTRUCTIONS = "Speak to the user in plain, everyday language about their training. Describe what you are doing in the TrainHeroic app's own terms (for example, say you are creating a workout rather than naming a tool). Do not surface internal tool names (the snake_case identifiers such as athlete_session_create), raw parameter names, or numeric ids in your replies unless the user explicitly asks for them; they are implementation details. The tool descriptions cross-reference each other by name only so you can chain them correctly. Keep that wiring to yourself.";
1028
1034
  //#endregion
1029
1035
  //#region ../js/src/http-error.ts
1030
- /**
1031
- * A final non-2xx response from TrainHeroic. The error deliberately carries only request
1032
- * metadata that is safe to send to telemetry: never the path, query string, request body,
1033
- * response body, credentials, or session token.
1034
- */
1036
+ const MAX_REQUEST_KEYS = 50;
1037
+ const MAX_RESPONSE_DEPTH = 4;
1038
+ const MAX_RESPONSE_KEYS = 20;
1039
+ const MAX_RESPONSE_ITEMS = 10;
1040
+ const MAX_RESPONSE_NODES = 50;
1041
+ const RESPONSE_DIAGNOSTIC_KEYS = /* @__PURE__ */ new Set([
1042
+ "code",
1043
+ "detail",
1044
+ "details",
1045
+ "error",
1046
+ "error_code",
1047
+ "errors",
1048
+ "message",
1049
+ "reason",
1050
+ "status",
1051
+ "status_code",
1052
+ "success"
1053
+ ]);
1054
+ const RESPONSE_CONTAINER_KEYS = /* @__PURE__ */ new Set([
1055
+ "data",
1056
+ "received",
1057
+ "response",
1058
+ "result"
1059
+ ]);
1060
+ const RESPONSE_STATUS_KEYS = /* @__PURE__ */ new Set(["status", "status_code"]);
1061
+ const RESPONSE_BOOLEAN_KEYS = /* @__PURE__ */ new Set(["success"]);
1062
+ const PARAMETER_TYPES = /* @__PURE__ */ new Set([
1063
+ 0,
1064
+ 1,
1065
+ 2,
1066
+ 3,
1067
+ 4,
1068
+ 5,
1069
+ 6,
1070
+ 7,
1071
+ 10,
1072
+ 11,
1073
+ 12,
1074
+ 13,
1075
+ 14,
1076
+ 18
1077
+ ]);
1078
+ function safeFieldName(key) {
1079
+ if (key === "__proto__" || key === "constructor" || key === "prototype") return "[Redacted key]";
1080
+ if (!/^[A-Za-z_][A-Za-z0-9_.-]{0,79}$/.test(key)) return "[Redacted key]";
1081
+ return key;
1082
+ }
1083
+ function boundedEntries(object, limit) {
1084
+ const entries = [];
1085
+ for (const key of Object.keys(object)) {
1086
+ const descriptor = Object.getOwnPropertyDescriptor(object, key);
1087
+ entries.push([key, descriptor && "value" in descriptor ? descriptor.value : void 0]);
1088
+ if (entries.length >= limit) break;
1089
+ }
1090
+ return entries;
1091
+ }
1092
+ function safeRequestValue(key, value) {
1093
+ if (key === "is_circuit" && typeof value === "boolean") return value;
1094
+ if (["param_1_type", "param_2_type"].includes(key) && typeof value === "number" && PARAMETER_TYPES.has(value)) return value;
1095
+ }
1096
+ function requestBodySummary(body) {
1097
+ if (Array.isArray(body)) return {
1098
+ type: "array",
1099
+ length: body.length
1100
+ };
1101
+ if (body && typeof body === "object") {
1102
+ const entries = boundedEntries(body, MAX_REQUEST_KEYS).sort(([left], [right]) => left.localeCompare(right));
1103
+ const keys = entries.map(([key]) => safeFieldName(key));
1104
+ const values = {};
1105
+ for (const [key, value] of entries) {
1106
+ const safeValue = safeRequestValue(key, value);
1107
+ if (safeValue !== void 0) values[safeFieldName(key)] = safeValue;
1108
+ }
1109
+ return Object.keys(values).length > 0 ? {
1110
+ type: "object",
1111
+ keys,
1112
+ values
1113
+ } : {
1114
+ type: "object",
1115
+ keys
1116
+ };
1117
+ }
1118
+ const primitive = typeof body;
1119
+ return primitive === "boolean" || primitive === "number" || primitive === "string" ? { type: primitive } : { type: "other" };
1120
+ }
1121
+ function sanitizedDiagnosticValue(value, depth, budget, field) {
1122
+ if (budget.nodes <= 0) return "[Truncated]";
1123
+ budget.nodes -= 1;
1124
+ if (value === null) return null;
1125
+ if (typeof value === "boolean") return field && RESPONSE_BOOLEAN_KEYS.has(field) ? value : "[Redacted]";
1126
+ if (typeof value === "number") return field && RESPONSE_STATUS_KEYS.has(field) && Number.isInteger(value) && value >= 100 && value <= 599 ? value : "[Redacted]";
1127
+ if (typeof value === "string") return "[Redacted]";
1128
+ if (depth >= MAX_RESPONSE_DEPTH) return "[Truncated]";
1129
+ if (Array.isArray(value)) {
1130
+ const result = [];
1131
+ for (const item of value.slice(0, MAX_RESPONSE_ITEMS)) {
1132
+ if (budget.nodes <= 0) {
1133
+ result.push("[Truncated]");
1134
+ break;
1135
+ }
1136
+ result.push(sanitizedDiagnosticValue(item, depth + 1, budget));
1137
+ }
1138
+ return result;
1139
+ }
1140
+ if (value && typeof value === "object") {
1141
+ const result = {};
1142
+ for (const [key, item] of boundedEntries(value, MAX_RESPONSE_KEYS)) {
1143
+ if (budget.nodes <= 0) {
1144
+ result.truncated = "[Truncated]";
1145
+ break;
1146
+ }
1147
+ const safeKey = safeFieldName(key);
1148
+ const safeValue = safeRequestValue(key, item);
1149
+ if (RESPONSE_DIAGNOSTIC_KEYS.has(key)) result[safeKey] = sanitizedDiagnosticValue(item, depth + 1, budget, key);
1150
+ else if (RESPONSE_CONTAINER_KEYS.has(key) && item && typeof item === "object") result[safeKey] = sanitizedDiagnosticValue(item, depth + 1, budget);
1151
+ else if (safeValue !== void 0) {
1152
+ budget.nodes -= 1;
1153
+ result[safeKey] = safeValue;
1154
+ }
1155
+ }
1156
+ return result;
1157
+ }
1158
+ return `[${typeof value}]`;
1159
+ }
1160
+ function responseBodyDiagnostics(body, budget, depth = 0) {
1161
+ const activeBudget = budget ?? { nodes: MAX_RESPONSE_NODES };
1162
+ if (activeBudget.nodes <= 0 || depth >= MAX_RESPONSE_DEPTH) return "[Truncated]";
1163
+ if (!body || typeof body !== "object" || Array.isArray(body)) return sanitizedDiagnosticValue(body, depth, activeBudget);
1164
+ const object = body;
1165
+ const result = {};
1166
+ for (const [key, value] of boundedEntries(object, MAX_RESPONSE_KEYS)) {
1167
+ if (activeBudget.nodes <= 0) {
1168
+ result.truncated = "[Truncated]";
1169
+ break;
1170
+ }
1171
+ if (RESPONSE_DIAGNOSTIC_KEYS.has(key)) {
1172
+ result[safeFieldName(key)] = sanitizedDiagnosticValue(value, depth + 1, activeBudget, key);
1173
+ continue;
1174
+ }
1175
+ if (RESPONSE_CONTAINER_KEYS.has(key) && value && typeof value === "object") {
1176
+ activeBudget.nodes -= 1;
1177
+ const nested = responseBodyDiagnostics(value, activeBudget, depth + 1);
1178
+ if (nested === "[Truncated]" || nested && typeof nested === "object" && Object.keys(nested).length > 0) result[safeFieldName(key)] = nested;
1179
+ }
1180
+ }
1181
+ if (Object.keys(result).length > 0) return result;
1182
+ return { type: "object" };
1183
+ }
1184
+ function parseResponseText(text) {
1185
+ if (text.length === 0) return text;
1186
+ try {
1187
+ return JSON.parse(text);
1188
+ } catch {
1189
+ return text;
1190
+ }
1191
+ }
1192
+ function safeRequestBodySummary(body) {
1193
+ try {
1194
+ return requestBodySummary(body);
1195
+ } catch {
1196
+ return { type: "other" };
1197
+ }
1198
+ }
1199
+ function safeResponseBodyDiagnostics(body) {
1200
+ try {
1201
+ return responseBodyDiagnostics(body);
1202
+ } catch {
1203
+ return "[Unavailable]";
1204
+ }
1205
+ }
1206
+ /** A final non-2xx response plus bounded, telemetry-safe request and response diagnostics. */
1035
1207
  var TrainHeroicHttpError = class extends Error {
1036
1208
  name = "TrainHeroicHttpError";
1037
1209
  method;
1038
1210
  status;
1039
1211
  host;
1040
- constructor(method, url, status) {
1212
+ requestBody;
1213
+ responseBody;
1214
+ constructor(method, url, status, diagnostics = {}) {
1041
1215
  const parsed = new URL(url);
1042
1216
  const normalizedMethod = method.toUpperCase();
1043
1217
  super(`TrainHeroic ${normalizedMethod} request failed with HTTP ${status}`);
1044
1218
  this.method = normalizedMethod;
1045
1219
  this.status = status;
1046
1220
  this.host = parsed.host;
1221
+ this.requestBody = diagnostics.requestBody === void 0 ? void 0 : safeRequestBodySummary(diagnostics.requestBody);
1222
+ this.responseBody = diagnostics.responseBody === void 0 ? void 0 : safeResponseBodyDiagnostics(diagnostics.responseBody);
1047
1223
  }
1048
1224
  };
1049
1225
  /** Call observability hooks without allowing them to change SDK behavior. */
1050
- function notifyHttpError(handler, method, url, status) {
1226
+ function notifyHttpError(handler, method, url, status, diagnostics = {}) {
1051
1227
  if (!handler) return;
1052
1228
  try {
1053
- Promise.resolve(handler(new TrainHeroicHttpError(method, url, status))).catch(() => {});
1229
+ Promise.resolve(handler(new TrainHeroicHttpError(method, url, status, diagnostics))).catch(() => {});
1054
1230
  } catch {}
1055
1231
  }
1056
1232
  //#endregion
@@ -1174,14 +1350,19 @@ var TrainHeroicClient = class {
1174
1350
  session = await this.#ensureSession();
1175
1351
  res = await this.#send(method, url, session, options.body);
1176
1352
  }
1177
- if (!res.ok && !options.expectedStatuses?.includes(res.status)) notifyHttpError(this.#onHttpError, method, url, res.status);
1178
- const text = await res.text();
1179
- let data = text;
1180
- if (text.length > 0) try {
1181
- data = JSON.parse(text);
1182
- } catch {
1183
- data = text;
1353
+ const shouldReport = !res.ok && !options.expectedStatuses?.includes(res.status);
1354
+ let text;
1355
+ try {
1356
+ text = await res.text();
1357
+ } catch (error) {
1358
+ if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, { requestBody: options.body });
1359
+ throw error;
1184
1360
  }
1361
+ const data = parseResponseText(text);
1362
+ if (shouldReport) notifyHttpError(this.#onHttpError, method, url, res.status, {
1363
+ requestBody: options.body,
1364
+ responseBody: data
1365
+ });
1185
1366
  return {
1186
1367
  status: res.status,
1187
1368
  ok: res.ok,
@@ -1220,6 +1401,26 @@ function checkResponse(schema, data, label) {
1220
1401
  console.warn(`[trainheroic] response drift in ${label} at ${where}: ${issue?.message ?? "shape mismatch"}`);
1221
1402
  }
1222
1403
  //#endregion
1404
+ //#region ../../node_modules/.pnpm/es-toolkit@1.52.0/node_modules/es-toolkit/dist/array/uniq.mjs
1405
+ /**
1406
+ * Creates a duplicate-free version of an array.
1407
+ *
1408
+ * This function takes an array and returns a new array containing only the unique values
1409
+ * from the original array, preserving the order of first occurrence.
1410
+ *
1411
+ * @template T - The type of elements in the array.
1412
+ * @param arr - The array to process.
1413
+ * @returns A new array with only unique values from the original array.
1414
+ *
1415
+ * @example
1416
+ * const array = [1, 2, 2, 3, 4, 4, 5];
1417
+ * const result = uniq(array);
1418
+ * // result will be [1, 2, 3, 4, 5]
1419
+ */
1420
+ function uniq(arr) {
1421
+ return [...new Set(arr)];
1422
+ }
1423
+ //#endregion
1223
1424
  //#region ../js/src/exercise-util.ts
1224
1425
  /**
1225
1426
  * Display labels for TrainHeroic parameter types. The unit is FIXED PER EXERCISE
@@ -1349,14 +1550,6 @@ function exerciseTitle(ex, fallback = "") {
1349
1550
  return typeof ex.exercise_title === "string" && ex.exercise_title || typeof ex.title === "string" && ex.title || fallback;
1350
1551
  }
1351
1552
  /**
1352
- * True when a program-workout range item is a personal (athlete-created) session rather than a
1353
- * coach-scheduled one. The API marks these with `personal_cal === true`; this is the single
1354
- * definition every consumer (presenter, find-or-create, the remove guard) reads through.
1355
- */
1356
- function isPersonalSession(pw) {
1357
- return isRecord(pw) && pw.personal_cal === true;
1358
- }
1359
- /**
1360
1553
  * The `saved_workout` blob on a program-workout range item, or null if the athlete has no saved
1361
1554
  * copy yet. Session notes, RPE, and set writes all resolve through this.
1362
1555
  */
@@ -1393,18 +1586,76 @@ function rankSearch(rows, query, limit) {
1393
1586
  * on workerd, blowing the subrequest budget.
1394
1587
  */
1395
1588
  async function mapPool(items, limit, fn) {
1589
+ assertPositiveInteger(limit, "Concurrency limit");
1396
1590
  const out = Array.from({ length: items.length });
1397
1591
  let next = 0;
1592
+ const state = { failure: null };
1398
1593
  const worker = async () => {
1399
- while (next < items.length) {
1594
+ while (next < items.length && state.failure === null) {
1400
1595
  const i = next;
1401
1596
  next += 1;
1402
- out[i] = await fn(items[i], i);
1597
+ try {
1598
+ out[i] = await fn(items[i], i);
1599
+ } catch (error) {
1600
+ state.failure ??= { error };
1601
+ }
1403
1602
  }
1404
1603
  };
1405
1604
  await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => worker()));
1605
+ if (state.failure !== null) throw state.failure.error;
1406
1606
  return out;
1407
1607
  }
1608
+ function createLimiter(max) {
1609
+ assertPositiveInteger(max, "Maximum concurrency");
1610
+ let active = 0;
1611
+ let cancelled = null;
1612
+ const waiting = [];
1613
+ const acquire = (finalizer) => new Promise((resolve, reject) => {
1614
+ if (cancelled !== null && !finalizer) reject(cancelled.error);
1615
+ else if (active < max) {
1616
+ active += 1;
1617
+ resolve();
1618
+ } else waiting.push({
1619
+ start: () => {
1620
+ active += 1;
1621
+ resolve();
1622
+ },
1623
+ abort: reject,
1624
+ finalizer
1625
+ });
1626
+ });
1627
+ const release = () => {
1628
+ active -= 1;
1629
+ waiting.shift()?.start();
1630
+ };
1631
+ return {
1632
+ async run(task) {
1633
+ await acquire(false);
1634
+ try {
1635
+ return await task();
1636
+ } finally {
1637
+ release();
1638
+ }
1639
+ },
1640
+ async runFinalizer(task) {
1641
+ await acquire(true);
1642
+ try {
1643
+ return await task();
1644
+ } finally {
1645
+ release();
1646
+ }
1647
+ },
1648
+ cancel(error) {
1649
+ cancelled ??= { error };
1650
+ const queued = waiting.splice(0);
1651
+ for (const entry of queued) if (entry.finalizer) waiting.push(entry);
1652
+ else entry.abort(error);
1653
+ }
1654
+ };
1655
+ }
1656
+ function assertPositiveInteger(value, label) {
1657
+ if (!Number.isInteger(value) || value < 1) throw new RangeError(`${label} must be a positive integer; received ${value}.`);
1658
+ }
1408
1659
  //#endregion
1409
1660
  //#region ../js/src/athlete.ts
1410
1661
  async function getJson(client, path, label) {
@@ -1439,39 +1690,25 @@ function sortRosterByRecency(rows) {
1439
1690
  * summary becomes a null-data row (sorted last), not an error.
1440
1691
  */
1441
1692
  async function fetchRosterActivity(client, athleteIds, useMetric = false) {
1442
- const rows = [];
1443
- const concurrency = 6;
1444
- const uniqueAthleteIds = [...new Set(athleteIds)];
1445
- for (let i = 0; i < uniqueAthleteIds.length; i += concurrency) {
1446
- const chunk = uniqueAthleteIds.slice(i, i + concurrency);
1447
- const settled = await Promise.all(chunk.map(async (id) => {
1448
- try {
1449
- return {
1450
- id,
1451
- summary: await fetchAthleteProfileSummary(client, id, useMetric)
1452
- };
1453
- } catch {
1454
- return {
1455
- id,
1456
- summary: null
1457
- };
1458
- }
1459
- }));
1460
- for (const { id, summary } of settled) {
1461
- const count = summary?.sessions_count ?? null;
1462
- const hasSessions = count !== null && count > 0;
1463
- const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
1464
- rows.push({
1465
- athleteId: id,
1466
- sessionsCount: count,
1467
- firstLoggedDate: normDate(summary?.first_logged_date),
1468
- lastLoggedDate: normDate(summary?.last_logged_date),
1469
- totalReps: summary?.reps_sum ?? null,
1470
- totalVolume: summary?.volume_sum ?? null
1471
- });
1693
+ return sortRosterByRecency(await mapPool(uniq(athleteIds), 6, async (id) => {
1694
+ let summary;
1695
+ try {
1696
+ summary = await fetchAthleteProfileSummary(client, id, useMetric);
1697
+ } catch {
1698
+ summary = null;
1472
1699
  }
1473
- }
1474
- return sortRosterByRecency(rows);
1700
+ const count = summary?.sessions_count ?? null;
1701
+ const hasSessions = count !== null && count > 0;
1702
+ const normDate = (d) => hasSessions && d !== void 0 && d !== "" && !d.startsWith("1970") ? d : null;
1703
+ return {
1704
+ athleteId: id,
1705
+ sessionsCount: count,
1706
+ firstLoggedDate: normDate(summary?.first_logged_date),
1707
+ lastLoggedDate: normDate(summary?.last_logged_date),
1708
+ totalReps: summary?.reps_sum ?? null,
1709
+ totalVolume: summary?.volume_sum ?? null
1710
+ };
1711
+ }));
1475
1712
  }
1476
1713
  function fetchExerciseHistoryDetail(client, exerciseId, userId) {
1477
1714
  return getJson(client, `/v5/exercises/${exerciseId}/history?userId=${userId}`, "athlete exercise history");
@@ -1498,6 +1735,28 @@ function slotValues(ex, requireMade) {
1498
1735
  }
1499
1736
  return map;
1500
1737
  }
1738
+ /**
1739
+ * The slots carrying data that the athlete has NOT marked performed (`param_i_made !== 1`). On a
1740
+ * saved-copy row these are the row's own targets: the pre-filled prescription, an athlete- or
1741
+ * coach-level override written with `made = 0` (`prescribeAthleteSet`), or a personal session's
1742
+ * only prescription, since personal work has no template tree at all.
1743
+ */
1744
+ function unmadeSlotValues(ex) {
1745
+ const map = slotValues(ex, false);
1746
+ for (const i of map.keys()) if (coerceInt(ex[`param_${i}_made`]) === 1) map.delete(i);
1747
+ return map;
1748
+ }
1749
+ /**
1750
+ * The prescription for one exercise: the template row's slots, with any target the saved copy
1751
+ * still holds unperformed taking precedence per set index (that is what the athlete's app shows,
1752
+ * and where a per-athlete override lives). Without a template row the saved copy's unperformed
1753
+ * slots are the whole prescription.
1754
+ */
1755
+ function prescriptionSlots(template, saved) {
1756
+ const map = template ? slotValues(template, false) : /* @__PURE__ */ new Map();
1757
+ if (saved) for (const [i, v] of unmadeSlotValues(saved)) map.set(i, v);
1758
+ return map;
1759
+ }
1501
1760
  /** The joined display for a slot, kept verbatim (`"5 @ 225"`, `"AMRAP"`, `"@ 225"`). */
1502
1761
  function fmtSlot(slot) {
1503
1762
  const has1 = slot.p1 !== null;
@@ -1507,10 +1766,6 @@ function fmtSlot(slot) {
1507
1766
  if (has2) return `@ ${slot.p2}`;
1508
1767
  return "";
1509
1768
  }
1510
- /** Every slot carrying data, joined for display (the prescription reader): `["5 @ 225", "AMRAP"]`. */
1511
- function prescribedStrings(ex) {
1512
- return [...slotValues(ex, false).values()].map(fmtSlot);
1513
- }
1514
1769
  /** The slots the athlete logged (`param_i_made === 1`), joined for display (the performed reader). */
1515
1770
  function performedStrings(ex) {
1516
1771
  return [...slotValues(ex, true).values()].map(fmtSlot);
@@ -1532,179 +1787,45 @@ function savedSets(saved) {
1532
1787
  return out;
1533
1788
  }
1534
1789
  /**
1535
- * Map each prescription exercise id to the slot-indexed values the athlete logged against it. In
1536
- * the saved copy `workout_set_exercise_id` points back at the prescription exercise's `id`, and the
1537
- * entered values live in the same `param_N_data` slots as a prescription.
1790
+ * Every exercise the athlete performed (logged at least one `param_i_made === 1` slot) across a
1791
+ * list of range items, read straight off the saved copies. This is the cheap tally for callers
1792
+ * that only need "which exercises were logged" (the main-lift discovery over a year of sessions)
1793
+ * and skips the prescription merge and string formatting `presentAthleteWorkouts` does per set.
1538
1794
  */
1539
- function performedSlotsByExerciseId(sets) {
1540
- const map = /* @__PURE__ */ new Map();
1541
- for (const { exercises } of sets) for (const ex of exercises) {
1542
- const id = coerceInt(ex.workout_set_exercise_id);
1543
- if (id === null) continue;
1544
- const slots = slotValues(ex, true);
1545
- if (slots.size > 0) map.set(id, slots);
1546
- }
1547
- return map;
1548
- }
1549
- /** Per-exercise athlete notes keyed by the prescription template id (`workout_set_exercise_id`). */
1550
- function notesByTemplateId(sets) {
1551
- const map = /* @__PURE__ */ new Map();
1552
- for (const { exercises } of sets) for (const ex of exercises) {
1553
- const id = coerceInt(ex.workout_set_exercise_id);
1554
- const notes = str$1(ex.notes);
1555
- if (id !== null && notes !== null) map.set(id, notes);
1556
- }
1557
- return map;
1558
- }
1559
- /** Align an exercise's prescribed slots with the slots the athlete logged, per set index. */
1560
- function mergeExercise(prescribed, performed, meta) {
1561
- const indices = [.../* @__PURE__ */ new Set([...prescribed.keys(), ...performed.keys()])].sort((a, b) => a - b);
1562
- return {
1563
- ...meta,
1564
- sets: indices.map((i) => ({
1565
- set: i,
1566
- prescribed: prescribed.get(i) ?? null,
1567
- performed: performed.get(i) ?? null
1568
- }))
1569
- };
1570
- }
1571
- /** A prescription block, each exercise aligned with the slots the athlete logged against it. */
1572
- function mergePrescriptionBlock(set, performedById, notesById) {
1573
- const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
1574
- return {
1575
- order: coerceInt(set.order) ?? 0,
1576
- title: str$1(set.title),
1577
- instruction: str$1(set.instruction),
1578
- isTest: coerceInt(set.is_test) === 1,
1579
- exercises: exercises.filter(isRecord).map((ex) => {
1580
- const id = coerceInt(ex.id);
1581
- const performed = (id !== null ? performedById.get(id) : void 0) ?? /* @__PURE__ */ new Map();
1582
- return mergeExercise(slotValues(ex, false), performed, {
1583
- exerciseId: coerceInt(ex.exercise_id),
1584
- title: typeof ex.title === "string" ? ex.title : "",
1585
- instruction: str$1(ex.instruction),
1586
- notes: id !== null ? notesById.get(id) ?? null : null,
1587
- units: exerciseUnits(ex.param_1_type, ex.param_2_type)
1795
+ function performedExercises(workouts) {
1796
+ const out = [];
1797
+ for (const pw of workouts) {
1798
+ const rec = pw;
1799
+ const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
1800
+ const workout = isRecord(ssw.workout) ? ssw.workout : {};
1801
+ const templates = /* @__PURE__ */ new Map();
1802
+ for (const set of Array.isArray(workout.workoutSets) ? workout.workoutSets : []) {
1803
+ if (!isRecord(set)) continue;
1804
+ const exercises = Array.isArray(set.workoutSetExercises) ? set.workoutSetExercises : [];
1805
+ for (const ex of exercises) {
1806
+ if (!isRecord(ex)) continue;
1807
+ const id = coerceInt(ex.id);
1808
+ if (id !== null) templates.set(id, {
1809
+ exerciseId: coerceInt(ex.exercise_id),
1810
+ title: exerciseTitle(ex)
1811
+ });
1812
+ }
1813
+ }
1814
+ const saved = savedWorkoutOf(pw);
1815
+ if (!saved) continue;
1816
+ for (const { exercises } of savedSets(saved)) for (const ex of exercises) {
1817
+ const templateId = coerceInt(ex.workout_set_exercise_id);
1818
+ const template = templateId === null ? void 0 : templates.get(templateId);
1819
+ const exerciseId = coerceInt(ex.exercise_id) ?? template?.exerciseId ?? null;
1820
+ if (exerciseId === null || slotValues(ex, true).size === 0) continue;
1821
+ out.push({
1822
+ exerciseId,
1823
+ title: exerciseTitle(ex, template?.title)
1588
1824
  });
1589
- })
1590
- };
1591
- }
1592
- /** A logged block straight from the saved copy (athlete-added or personal work; no prescription). */
1593
- function mergeSavedBlock(set, exercises) {
1594
- return {
1595
- order: coerceInt(set.order) ?? 0,
1596
- title: str$1(set.title),
1597
- instruction: str$1(set.instruction),
1598
- isTest: coerceInt(set.is_test) === 1,
1599
- exercises: exercises.map((ex) => mergeExercise(/* @__PURE__ */ new Map(), slotValues(ex, true), {
1600
- exerciseId: coerceInt(ex.exercise_id),
1601
- title: typeof ex.exercise_title === "string" ? ex.exercise_title : "",
1602
- instruction: str$1(ex.instruction),
1603
- notes: str$1(ex.notes),
1604
- units: exerciseUnits(ex.param_1_type, ex.param_2_type)
1605
- }))
1606
- };
1607
- }
1608
- /**
1609
- * Flatten one `/3.0/athlete/programworkout/range` item into the canonical merged form, joining the
1610
- * prescription (`summarizedSavedWorkout.workout`) with what the athlete logged
1611
- * (`summarizedSavedWorkout.saved_workout`). Prescription blocks are enriched with logged slots;
1612
- * athlete-added / personal work with no prescription is appended as its own block.
1613
- */
1614
- function mergeAthleteWorkout(raw) {
1615
- const rec = raw;
1616
- const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
1617
- const workout = isRecord(ssw.workout) ? ssw.workout : {};
1618
- const saved = savedWorkoutOf(rec) ?? {};
1619
- const prescriptionSets = (Array.isArray(workout.workoutSets) ? workout.workoutSets : []).filter(isRecord);
1620
- const logged = savedSets(saved);
1621
- const performedById = performedSlotsByExerciseId(logged);
1622
- const notesById = notesByTemplateId(logged);
1623
- const blocks = prescriptionSets.map((s) => mergePrescriptionBlock(s, performedById, notesById)).sort((a, b) => a.order - b.order);
1624
- const prescribedIds = /* @__PURE__ */ new Set();
1625
- for (const s of prescriptionSets) {
1626
- const exs = Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : [];
1627
- for (const ex of exs) {
1628
- if (!isRecord(ex)) continue;
1629
- const id = coerceInt(ex.id);
1630
- if (id !== null) prescribedIds.add(id);
1631
1825
  }
1632
1826
  }
1633
- for (const { set, exercises } of logged) {
1634
- const extra = exercises.filter((ex) => {
1635
- if (slotValues(ex, true).size === 0) return false;
1636
- const id = coerceInt(ex.workout_set_exercise_id);
1637
- return id === null || !prescribedIds.has(id);
1638
- });
1639
- if (extra.length > 0) blocks.push(mergeSavedBlock(set, extra));
1640
- }
1641
- return {
1642
- id: coerceInt(rec.id),
1643
- date: str$1(rec.date) ?? "",
1644
- title: str$1(rec.workout_title) ?? "",
1645
- program: str$1(rec.program_title),
1646
- team: str$1(rec.team_title),
1647
- instruction: str$1(workout.instruction),
1648
- notes: str$1(saved.notes),
1649
- rpe: coerceInt(saved.rpe),
1650
- logged: blocks.some((b) => b.exercises.some((e) => e.sets.some((s) => s.performed !== null))),
1651
- personal: isPersonalSession(rec),
1652
- blocks
1653
- };
1654
- }
1655
- /** The per-set displays for one side (prescribed or performed), in slot order. */
1656
- function sideStrings(sets, pick) {
1657
- const out = [];
1658
- for (const s of sets) {
1659
- const slot = pick(s);
1660
- if (slot) out.push(fmtSlot(slot));
1661
- }
1662
1827
  return out;
1663
1828
  }
1664
- function toStringExercise(ex) {
1665
- return {
1666
- exerciseId: ex.exerciseId,
1667
- title: ex.title,
1668
- instruction: ex.instruction,
1669
- notes: ex.notes,
1670
- units: ex.units,
1671
- prescribed: sideStrings(ex.sets, (s) => s.prescribed),
1672
- performed: sideStrings(ex.sets, (s) => s.performed)
1673
- };
1674
- }
1675
- function toStringBlock(b) {
1676
- return {
1677
- order: b.order,
1678
- title: b.title,
1679
- instruction: b.instruction,
1680
- isTest: b.isTest,
1681
- exercises: b.exercises.map(toStringExercise)
1682
- };
1683
- }
1684
- /**
1685
- * Flatten one range item into a readable workout: each exercise carries its `prescribed` and
1686
- * `performed` sets as joined `"5 @ 225"` strings; athlete-added/personal work that has no
1687
- * prescription is appended as its own blocks. No `raw` is needed to see logged results.
1688
- */
1689
- function presentAthleteWorkout(raw) {
1690
- const w = mergeAthleteWorkout(raw);
1691
- return {
1692
- id: w.id,
1693
- date: w.date,
1694
- title: w.title,
1695
- program: w.program,
1696
- team: w.team,
1697
- instruction: w.instruction,
1698
- notes: w.notes,
1699
- rpe: w.rpe,
1700
- logged: w.logged,
1701
- personal: w.personal,
1702
- blocks: w.blocks.map(toStringBlock)
1703
- };
1704
- }
1705
- function presentAthleteWorkouts(list) {
1706
- return list.map(presentAthleteWorkout);
1707
- }
1708
1829
  /**
1709
1830
  * Narrow a coach-athlete workout range to a single program or team. The range endpoint returns
1710
1831
  * every program the athlete is enrolled in on a date; for a high-enrollment athlete that is many
@@ -1743,6 +1864,16 @@ function presentLogTargets(list) {
1743
1864
  const ssw = isRecord(rec.summarizedSavedWorkout) ? rec.summarizedSavedWorkout : {};
1744
1865
  const saved = isRecord(ssw.saved_workout) ? ssw.saved_workout : null;
1745
1866
  if (!saved) continue;
1867
+ const workout = isRecord(ssw.workout) ? ssw.workout : {};
1868
+ const templatesById = /* @__PURE__ */ new Map();
1869
+ for (const tSet of Array.isArray(workout.workoutSets) ? workout.workoutSets : []) {
1870
+ if (!isRecord(tSet)) continue;
1871
+ const tExs = Array.isArray(tSet.workoutSetExercises) ? tSet.workoutSetExercises : [];
1872
+ for (const tEx of tExs) {
1873
+ const tId = isRecord(tEx) ? coerceInt(tEx.id) : null;
1874
+ if (tId !== null && isRecord(tEx)) templatesById.set(tId, tEx);
1875
+ }
1876
+ }
1746
1877
  const date = str$1(rec.date) ?? "";
1747
1878
  const workoutTitle = str$1(rec.workout_title) ?? "";
1748
1879
  const program = str$1(rec.program_title);
@@ -1757,12 +1888,14 @@ function presentLogTargets(list) {
1757
1888
  const exercises = (Array.isArray(s.workoutSetExercises) ? s.workoutSetExercises : []).filter(isRecord).map((ex) => {
1758
1889
  const id = coerceInt(ex.id);
1759
1890
  if (id === null) return null;
1891
+ const templateId = coerceInt(ex.workout_set_exercise_id);
1892
+ const template = templateId === null ? void 0 : templatesById.get(templateId);
1760
1893
  return {
1761
1894
  savedWorkoutSetExerciseId: id,
1762
1895
  title: exerciseTitle(ex),
1763
1896
  units: exerciseUnits(ex.param_1_type, ex.param_2_type),
1764
1897
  notes: str$1(ex.notes),
1765
- prescribed: prescribedStrings(ex),
1898
+ prescribed: [...prescriptionSlots(template, ex).values()].map(fmtSlot),
1766
1899
  performed: performedStrings(ex)
1767
1900
  };
1768
1901
  }).filter((e) => e !== null);
@@ -1852,6 +1985,28 @@ function presentExerciseHistory(detail) {
1852
1985
  };
1853
1986
  }
1854
1987
  //#endregion
1988
+ //#region ../js/src/exercise-history.ts
1989
+ /**
1990
+ * Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
1991
+ * The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
1992
+ * first 10 chars so both "YYYY-MM-DD" and "YYYY-MM-DDThh:mm" values filter correctly. The one
1993
+ * window rule shared by the athlete's own history tool, the coach's per-roster-athlete history
1994
+ * tool, and the CLI, so a timestamped session cannot fall out of an inclusive upper bound.
1995
+ */
1996
+ function historyInRange(presented, since, until) {
1997
+ if (since === void 0 && until === void 0) return presented;
1998
+ const sessions = presented.sessions.filter((s) => {
1999
+ const d = (s.date ?? "").slice(0, 10);
2000
+ if (since !== void 0 && d < since) return false;
2001
+ if (until !== void 0 && d > until) return false;
2002
+ return true;
2003
+ });
2004
+ return {
2005
+ ...presented,
2006
+ sessions
2007
+ };
2008
+ }
2009
+ //#endregion
1855
2010
  //#region ../js/src/coach-athlete-calendar.ts
1856
2011
  async function getArray(client, path, label) {
1857
2012
  const res = await client.request("GET", path);
@@ -1986,6 +2141,7 @@ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, w
1986
2141
  }
1987
2142
  //#endregion
1988
2143
  //#region ../js/src/athlete-set-write.ts
2144
+ const WRITE_CONCURRENCY = 4;
1989
2145
  /**
1990
2146
  * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
1991
2147
  * {@link SetResult}[]. The dto schemas validate ids as a number or a numeric string and leave
@@ -2188,6 +2344,41 @@ async function swapAthleteExercise(client, args) {
2188
2344
  originalTeamExerciseId: coerceInt(template.exercise_id)
2189
2345
  };
2190
2346
  }
2347
+ function prepareSetWrite(target, workouts, savedWorkoutSetId, results, mode) {
2348
+ const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
2349
+ assertUniqueExerciseResults(results);
2350
+ const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
2351
+ const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
2352
+ return {
2353
+ savedWorkoutSetId,
2354
+ exercises,
2355
+ rawSet,
2356
+ suffix,
2357
+ extra,
2358
+ writes: results.map((result) => {
2359
+ const ex = exercises.find((candidate) => coerceInt(candidate.id) === result.savedWorkoutSetExerciseId);
2360
+ if (!ex) {
2361
+ const valid = exercises.map((candidate) => {
2362
+ const id = coerceInt(candidate.id);
2363
+ return id === null ? null : `${id} (${exerciseTitle(candidate, "exercise")})`;
2364
+ }).filter((label) => label !== null);
2365
+ throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
2366
+ }
2367
+ const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
2368
+ 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.`);
2369
+ return {
2370
+ id: result.savedWorkoutSetExerciseId,
2371
+ body: {
2372
+ ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
2373
+ ...extra
2374
+ }
2375
+ };
2376
+ })
2377
+ };
2378
+ }
2379
+ function errorMessage(error) {
2380
+ return error instanceof Error ? error.message : String(error);
2381
+ }
2191
2382
  /**
2192
2383
  * Shared set-write behind {@link logAthleteSet}, {@link prescribeAthleteSet},
2193
2384
  * {@link logForAthlete}, and {@link prescribeForAthlete}. `target` selects the surface: `athlete`
@@ -2201,36 +2392,40 @@ async function swapAthleteExercise(client, args) {
2201
2392
  * the written ones); `"prescribe"` writes them as a prescription and skips Step 2, leaving the set
2202
2393
  * open.
2203
2394
  */
2204
- async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode) {
2205
- const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
2206
- assertUniqueExerciseResults(results);
2207
- const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
2208
- const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
2209
- let exercisesWritten = 0;
2210
- const projectedCompletion = /* @__PURE__ */ new Map();
2211
- for (const result of results) {
2212
- const ex = exercises.find((e) => coerceInt(e.id) === result.savedWorkoutSetExerciseId);
2213
- if (!ex) {
2214
- const valid = exercises.map((e) => {
2215
- const id = coerceInt(e.id);
2216
- return id === null ? null : `${id} (${exerciseTitle(e, "exercise")})`;
2217
- }).filter((x) => x !== null);
2218
- throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} not found in saved workout set ${savedWorkoutSetId}. Exercises in this set: ${valid.join(", ") || "none"}.`);
2219
- }
2220
- const workoutSetExerciseId = coerceInt(ex.workout_set_exercise_id);
2221
- 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.`);
2222
- const body = {
2223
- ...buildExerciseSetPayload(result.savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, result.sets, mode, ex),
2224
- ...extra
2395
+ async function executeSetWrite(client, target, prepared, mode, limit, sessionProgress) {
2396
+ const { savedWorkoutSetId, exercises, rawSet, suffix, extra, writes } = prepared;
2397
+ const put = (path, body, failureMessage, finalizer = false) => {
2398
+ const request = async () => {
2399
+ try {
2400
+ const res = await client.request("PUT", path, { body });
2401
+ if (!res.ok) throw new Error(failureMessage(res.status));
2402
+ } catch (error) {
2403
+ limit.cancel(error);
2404
+ throw error;
2405
+ }
2225
2406
  };
2226
- const res = await client.request("PUT", `/1.0/${target.role}/savedworkoutsetexercise/${result.savedWorkoutSetExerciseId}${suffix}`, { body });
2227
- if (!res.ok) {
2228
- 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.` : "";
2229
- throw new Error(`Failed to write exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).${readOnly}`);
2230
- }
2231
- projectedCompletion.set(result.savedWorkoutSetExerciseId, body.completed === 1);
2232
- exercisesWritten += 1;
2407
+ return finalizer ? limit.runFinalizer(request) : limit.run(request);
2408
+ };
2409
+ const confirmed = [];
2410
+ try {
2411
+ await mapPool(writes, WRITE_CONCURRENCY, async ({ id, body }) => {
2412
+ await put(`/1.0/${target.role}/savedworkoutsetexercise/${id}${suffix}`, body, (status) => {
2413
+ 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.` : ""}`;
2414
+ });
2415
+ confirmed.push(id);
2416
+ if (sessionProgress) {
2417
+ const sessionConfirmed = sessionProgress.get(savedWorkoutSetId) ?? [];
2418
+ sessionConfirmed.push(id);
2419
+ sessionProgress.set(savedWorkoutSetId, sessionConfirmed);
2420
+ }
2421
+ });
2422
+ } catch (error) {
2423
+ if (sessionProgress || confirmed.length === 0) throw error;
2424
+ confirmed.sort((a, b) => a - b);
2425
+ 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 });
2233
2426
  }
2427
+ const exercisesWritten = writes.length;
2428
+ const projectedCompletion = new Map(writes.map((w) => [w.id, w.body.completed === 1]));
2234
2429
  let setCompleted = false;
2235
2430
  if (mode === "log") {
2236
2431
  if (isSetFullyLogged(exercises, projectedCompletion)) {
@@ -2238,8 +2433,11 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
2238
2433
  ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
2239
2434
  ...extra
2240
2435
  };
2241
- const setRes = await client.request("PUT", `/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, { body: setBody });
2242
- if (!setRes.ok) throw new Error(`Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${setRes.status}).`);
2436
+ try {
2437
+ await put(`/1.0/${target.role}/savedworkoutset/${savedWorkoutSetId}${suffix}`, setBody, (status) => `Failed to mark workout set ${savedWorkoutSetId} completed (HTTP ${status}).`, true);
2438
+ } catch (error) {
2439
+ throw new Error(`${errorMessage(error)} Exercise values were written successfully; retry the same request to complete the set.`, { cause: error });
2440
+ }
2243
2441
  setCompleted = true;
2244
2442
  }
2245
2443
  }
@@ -2249,6 +2447,9 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
2249
2447
  setCompleted
2250
2448
  };
2251
2449
  }
2450
+ async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode, limit = createLimiter(WRITE_CONCURRENCY)) {
2451
+ return executeSetWrite(client, target, prepareSetWrite(target, workouts, savedWorkoutSetId, results, mode), mode, limit);
2452
+ }
2252
2453
  /**
2253
2454
  * Flatten a day's saved sets into `{ pw, savedWorkoutSetId, ex }` rows (both saved-set keys),
2254
2455
  * carrying the parent program-workout so a caller can read its identity (`personal_cal`, program
@@ -2303,7 +2504,7 @@ function prescribedExerciseLabels(workouts) {
2303
2504
  return labels;
2304
2505
  }
2305
2506
  /** Group resolved exercises by saved set and write each set via the given log target. */
2306
- async function logResolvedExercises(client, target, workouts, resolved) {
2507
+ async function logResolvedExercises(client, target, workouts, resolved, retryGuidance) {
2307
2508
  const bySet = /* @__PURE__ */ new Map();
2308
2509
  for (const r of resolved) {
2309
2510
  const list = bySet.get(r.savedWorkoutSetId) ?? [];
@@ -2313,15 +2514,28 @@ async function logResolvedExercises(client, target, workouts, resolved) {
2313
2514
  });
2314
2515
  bySet.set(r.savedWorkoutSetId, list);
2315
2516
  }
2316
- const out = [];
2317
- for (const [savedWorkoutSetId, results] of bySet) {
2318
- const written = await writeSetResults(client, target, workouts, savedWorkoutSetId, results, "log");
2319
- out.push({
2320
- savedWorkoutSetId: written.savedWorkoutSetId,
2321
- exercisesLogged: written.exercisesWritten
2517
+ const prepared = [...bySet].map(([savedWorkoutSetId, results]) => prepareSetWrite(target, workouts, savedWorkoutSetId, results, "log"));
2518
+ const limit = createLimiter(WRITE_CONCURRENCY);
2519
+ const confirmedBySet = /* @__PURE__ */ new Map();
2520
+ const succeeded = [];
2521
+ try {
2522
+ return await mapPool(prepared, WRITE_CONCURRENCY, async (set) => {
2523
+ const written = await executeSetWrite(client, target, set, "log", limit, confirmedBySet);
2524
+ succeeded.push(written.savedWorkoutSetId);
2525
+ return {
2526
+ savedWorkoutSetId: written.savedWorkoutSetId,
2527
+ exercisesLogged: written.exercisesWritten
2528
+ };
2322
2529
  });
2530
+ } catch (error) {
2531
+ const completed = new Set(succeeded);
2532
+ 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(", ")}`);
2533
+ if (incomplete.length === 0 && succeeded.length === 0) throw error;
2534
+ succeeded.sort((a, b) => a - b);
2535
+ const partial = incomplete.length === 0 ? "" : ` Confirmed exercise writes in incomplete sets before the failure: ${incomplete.join("; ")}.${retryGuidance ? ` ${retryGuidance}` : ""}`;
2536
+ const complete = succeeded.length === 0 ? "" : ` Set writes confirmed before the failure: ${succeeded.join(", ")}.`;
2537
+ throw new Error(`${errorMessage(error)}${partial}${complete}`, { cause: error });
2323
2538
  }
2324
- return out;
2325
2539
  }
2326
2540
  /**
2327
2541
  * Coach "log a session for a roster athlete" by exercise. The API offers no way to put an
@@ -2351,7 +2565,7 @@ async function logSessionForAthlete(client, args) {
2351
2565
  const sets = await logResolvedExercises(client, {
2352
2566
  role: "coach",
2353
2567
  athleteId: args.athleteId
2354
- }, day, resolved);
2568
+ }, day, resolved, "Retry the same request to reconcile them.");
2355
2569
  return {
2356
2570
  date: args.date,
2357
2571
  created: false,
@@ -2758,7 +2972,7 @@ async function readSession(client, programId, date, pwId) {
2758
2972
  const blocks = Object.values(setsObj).sort((a, b) => Number(a.order) - Number(b.order)).map((b) => readBlock(b));
2759
2973
  return {
2760
2974
  pwId,
2761
- date: `${str(pw.year)}-${str(pw.month)}-${str(pw.day)}`,
2975
+ date: `${str(pw.year)}-${str(pw.month).padStart(2, "0")}-${str(pw.day).padStart(2, "0")}`,
2762
2976
  published: pw.published,
2763
2977
  instruction: str(pw.instruction),
2764
2978
  blocks
@@ -2778,14 +2992,13 @@ function readBlock(b) {
2778
2992
  };
2779
2993
  }
2780
2994
  function readExercise(ex) {
2781
- const reps = [];
2782
- const load = [];
2783
- for (let i = 1; i <= 10; i += 1) {
2784
- const r = str(ex[`param_1_data_${i}`]);
2785
- if (r !== "") reps.push(r);
2786
- const w = str(ex[`param_2_data_${i}`]);
2787
- if (w !== "") load.push(w);
2788
- }
2995
+ let last = 0;
2996
+ for (let i = 1; i <= 10; i += 1) if (str(ex[`param_1_data_${i}`]) !== "" || str(ex[`param_2_data_${i}`]) !== "") last = i;
2997
+ const slots = Array.from({ length: last }, (_, k) => k + 1);
2998
+ const repsRaw = slots.map((i) => str(ex[`param_1_data_${i}`]));
2999
+ const loadRaw = slots.map((i) => str(ex[`param_2_data_${i}`]));
3000
+ const reps = repsRaw.some((r) => r !== "") ? repsRaw : [];
3001
+ const load = loadRaw.some((w) => w !== "") ? loadRaw : [];
2789
3002
  return {
2790
3003
  order: Number(ex.order),
2791
3004
  title: str(ex.title),
@@ -3340,8 +3553,7 @@ async function resolveAthleteMainLifts(client, athleteId, opts = {}) {
3340
3553
  } catch {
3341
3554
  workouts = [];
3342
3555
  }
3343
- for (const view of presentAthleteWorkouts(workouts)) for (const block of view.blocks) for (const ex of block.exercises) {
3344
- if (ex.performed.length === 0 || ex.exerciseId === null) continue;
3556
+ for (const ex of performedExercises(workouts)) {
3345
3557
  const family = classifyMainLift(ex.title);
3346
3558
  if (family === null) continue;
3347
3559
  const byId = tally.get(family) ?? /* @__PURE__ */ new Map();
@@ -3586,6 +3798,7 @@ var ExerciseLibrary = class {
3586
3798
  #byId = /* @__PURE__ */ new Map();
3587
3799
  #loaded = false;
3588
3800
  #fetchedAt = 0;
3801
+ #loading = null;
3589
3802
  constructor(client, cache = new MemoryLibraryCache()) {
3590
3803
  this.#client = client;
3591
3804
  this.#cache = cache;
@@ -3613,8 +3826,11 @@ var ExerciseLibrary = class {
3613
3826
  });
3614
3827
  }
3615
3828
  async ensureFresh() {
3616
- if (!this.#loaded) await this.#ensureLoaded();
3617
- else if (Date.now() - this.#fetchedAt > TTL_MS) await this.refresh();
3829
+ if (this.#loaded && Date.now() - this.#fetchedAt <= TTL_MS) return;
3830
+ this.#loading ??= (this.#loaded ? this.refresh() : this.#ensureLoaded()).finally(() => {
3831
+ this.#loading = null;
3832
+ });
3833
+ await this.#loading;
3618
3834
  }
3619
3835
  async refresh() {
3620
3836
  const res = await this.#client.request("GET", LIBRARY_PATH);
@@ -3633,6 +3849,7 @@ var ExerciseLibrary = class {
3633
3849
  return presentExercise(s.raw);
3634
3850
  }
3635
3851
  async defaultsMany(ids) {
3852
+ await this.ensureFresh();
3636
3853
  const result = /* @__PURE__ */ new Map();
3637
3854
  for (const id of ids) {
3638
3855
  const s = this.#byId.get(id);
@@ -3720,27 +3937,6 @@ var ExerciseLibrary = class {
3720
3937
  }
3721
3938
  };
3722
3939
  //#endregion
3723
- //#region ../core/src/history.ts
3724
- /**
3725
- * Trim a presented exercise history's session time-series to an inclusive YYYY-MM-DD window.
3726
- * The `liftPRs` board stays all-time (PRs are not a windowed concept). Dates compare as their
3727
- * first 10 chars so both "YYYY-MM-DD" and "YYYY-MM-DDThh:mm" values filter correctly. Shared by
3728
- * the athlete's own history tool and the coach's per-roster-athlete history tool.
3729
- */
3730
- function historyInRange(presented, since, until) {
3731
- if (since === void 0 && until === void 0) return presented;
3732
- const sessions = presented.sessions.filter((s) => {
3733
- const d = (s.date ?? "").slice(0, 10);
3734
- if (since !== void 0 && d < since) return false;
3735
- if (until !== void 0 && d > until) return false;
3736
- return true;
3737
- });
3738
- return {
3739
- ...presented,
3740
- sessions
3741
- };
3742
- }
3743
- //#endregion
3744
3940
  //#region ../core/src/tools/reads.ts
3745
3941
  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.";
3746
3942
  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.";
@@ -4832,7 +5028,7 @@ var JsonFileLibraryCache = class {
4832
5028
  };
4833
5029
  //#endregion
4834
5030
  //#region package.json
4835
- var version = "3.5.1";
5031
+ var version = "3.6.0";
4836
5032
  //#endregion
4837
5033
  //#region src/server.ts
4838
5034
  function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "3.5.1",
3
+ "version": "3.6.0",
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.1",
25
- "@trainheroic-unofficial/js": "3.5.1"
24
+ "@trainheroic-unofficial/core": "3.6.0",
25
+ "@trainheroic-unofficial/js": "3.6.0"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.3.0",