@trainheroic-unofficial/coach-mcp 1.7.2 → 1.7.3

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 +110 -106
  2. package/package.json +6 -6
package/dist/server.mjs CHANGED
@@ -172,6 +172,26 @@ const loggedSetSchema = z.object({
172
172
  * always sequential).
173
173
  */
174
174
  const loggedSetWithSlotSchema = loggedSetSchema.extend({ slot: z.number().int().min(1).max(10).optional() });
175
+ function requireUniqueExerciseIds(results, ctx) {
176
+ const seen = /* @__PURE__ */ new Set();
177
+ results.forEach((result, index) => {
178
+ const id = String(result.savedWorkoutSetExerciseId).replace(/^0+(?=\d)/u, "");
179
+ if (seen.has(id)) ctx.addIssue({
180
+ code: "custom",
181
+ message: `savedWorkoutSetExerciseId ${id} appears more than once; combine its sets into one result.`,
182
+ path: [index, "savedWorkoutSetExerciseId"]
183
+ });
184
+ seen.add(id);
185
+ });
186
+ }
187
+ const loggedExerciseResultsSchema = z.array(z.object({
188
+ savedWorkoutSetExerciseId: idArgSchema,
189
+ sets: z.array(loggedSetWithSlotSchema).min(1)
190
+ })).min(1).superRefine(requireUniqueExerciseIds);
191
+ const prescribedExerciseResultsSchema = z.array(z.object({
192
+ savedWorkoutSetExerciseId: idArgSchema,
193
+ sets: z.array(loggedSetSchema).min(1)
194
+ })).min(1).superRefine(requireUniqueExerciseIds);
175
195
  /**
176
196
  * Args for the coach "log for athlete" write — the same shape as logSetArgsSchema plus the
177
197
  * roster `athleteId` whose set is being logged on their behalf.
@@ -179,10 +199,7 @@ const loggedSetWithSlotSchema = loggedSetSchema.extend({ slot: z.number().int().
179
199
  const coachLogSetArgsSchema = z.object({
180
200
  date: dateString,
181
201
  savedWorkoutSetId: idArgSchema,
182
- results: z.array(z.object({
183
- savedWorkoutSetExerciseId: idArgSchema,
184
- sets: z.array(loggedSetWithSlotSchema).min(1)
185
- })).min(1)
202
+ results: loggedExerciseResultsSchema
186
203
  }).extend({ athleteId: idArgSchema });
187
204
  /**
188
205
  * Args for the coach prescription-override write. Like {@link coachLogSetArgsSchema}
@@ -197,10 +214,7 @@ const coachPrescribeSetArgsSchema = z.object({
197
214
  date: dateString,
198
215
  savedWorkoutSetId: idArgSchema,
199
216
  athleteId: idArgSchema,
200
- results: z.array(z.object({
201
- savedWorkoutSetExerciseId: idArgSchema,
202
- sets: z.array(loggedSetSchema).min(1)
203
- })).min(1)
217
+ results: prescribedExerciseResultsSchema
204
218
  });
205
219
  /**
206
220
  * Args for the coach per-athlete exercise swap: replace the exercise prescribed in one of a
@@ -1314,6 +1328,75 @@ function presentExerciseHistory(detail) {
1314
1328
  };
1315
1329
  }
1316
1330
  //#endregion
1331
+ //#region ../js/src/exercise-set-payload.ts
1332
+ function slotData(exercise, key) {
1333
+ const value = exercise?.[key];
1334
+ return value === void 0 || value === null ? "" : String(value);
1335
+ }
1336
+ function slotIsActive(exercise, slot, targeted = false) {
1337
+ return targeted || slotData(exercise, `param_1_data_${slot}`) !== "" || slotData(exercise, `param_2_data_${slot}`) !== "" || coerceInt(exercise?.[`param_${slot}_made`]) === 1;
1338
+ }
1339
+ /** True when an existing saved-copy exercise has at least one active slot and all are performed. */
1340
+ function exerciseIsFullyLogged(exercise) {
1341
+ let anyActive = false;
1342
+ for (let slot = 1; slot <= 10; slot += 1) {
1343
+ if (!slotIsActive(exercise, slot)) continue;
1344
+ anyActive = true;
1345
+ if (coerceInt(exercise[`param_${slot}_made`]) !== 1) return false;
1346
+ }
1347
+ return anyActive;
1348
+ }
1349
+ /**
1350
+ * Build the typed body for `PUT /1.0/{role}/savedworkoutsetexercise/{id}`.
1351
+ *
1352
+ * A log marks only slots carrying reps as performed. The exercise completes only when every active
1353
+ * slot is performed; active slots are prescribed values, prior performed values, or slots targeted
1354
+ * by this write. Untargeted performed slots carry over, while untouched prescription values are
1355
+ * blanked so TrainHeroic cannot fabricate performed results from them. A prescription replaces the
1356
+ * full payload and never marks slots or the exercise complete.
1357
+ */
1358
+ function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode, existing) {
1359
+ if (results.length > 10) throw new Error(`At most 10 sets are supported per exercise; got ${results.length}.`);
1360
+ const bySlot = /* @__PURE__ */ new Map();
1361
+ results.forEach((set, index) => {
1362
+ const slot = set.slot ?? index + 1;
1363
+ if (slot < 1 || slot > 10) throw new Error(`Set slot ${slot} is out of range; slots are 1–10.`);
1364
+ if (bySlot.has(slot)) throw new Error(`Two sets target slot ${slot}; each slot can be written once.`);
1365
+ bySlot.set(slot, set);
1366
+ });
1367
+ const logging = mode === "log";
1368
+ const body = {
1369
+ id: savedWorkoutSetExerciseId,
1370
+ saved_workout_set_id: savedWorkoutSetId,
1371
+ workout_set_exercise_id: workoutSetExerciseId,
1372
+ completed: 0
1373
+ };
1374
+ let anyMade = false;
1375
+ let allActiveSlotsMade = true;
1376
+ for (let slot = 1; slot <= 10; slot += 1) {
1377
+ const target = bySlot.get(slot);
1378
+ let param1 = "";
1379
+ let param2 = "";
1380
+ let made = 0;
1381
+ if (target) {
1382
+ param1 = target.param1 === void 0 ? "" : String(target.param1);
1383
+ param2 = target.param2 === void 0 ? "" : String(target.param2);
1384
+ made = logging && param1 !== "" ? 1 : 0;
1385
+ } else if (logging && coerceInt(existing?.[`param_${slot}_made`]) === 1) {
1386
+ param1 = slotData(existing, `param_1_data_${slot}`);
1387
+ param2 = slotData(existing, `param_2_data_${slot}`);
1388
+ made = 1;
1389
+ }
1390
+ anyMade ||= made === 1;
1391
+ if (slotIsActive(existing, slot, target !== void 0) && made !== 1) allActiveSlotsMade = false;
1392
+ body[`param_${slot}_made`] = made;
1393
+ body[`param_1_data_${slot}`] = param1;
1394
+ body[`param_2_data_${slot}`] = param2;
1395
+ }
1396
+ body.completed = logging && anyMade && allActiveSlotsMade ? 1 : 0;
1397
+ return body;
1398
+ }
1399
+ //#endregion
1317
1400
  //#region ../js/src/athlete-set-write.ts
1318
1401
  /**
1319
1402
  * Coerce the loosely-typed `results` from a validated log/prescribe args object into the SDK's
@@ -1339,107 +1422,25 @@ function toSetResults(results) {
1339
1422
  });
1340
1423
  }
1341
1424
  /**
1342
- * Build the body for `PUT /1.0/{role}/savedworkoutsetexercise/{id}`. The body uses snake_case
1343
- * keys matching the live API response shape. Each set slot (1-10) carries `param_1_data_N` /
1344
- * `param_2_data_N` string values plus a `param_N_made` flag.
1345
- *
1346
- * `mode` selects which write this is — the same endpoint serves both:
1347
- * - `"log"`: the values ARE a performed result, so `param_N_made` is 1 where the slot has reps
1348
- * entered (`param1`) and the exercise `completed` flag is 1 when any set is performed. A slot
1349
- * carrying only a weight (`param2`) with no reps is a target, not a performed set, so it stays
1350
- * un-made — matching the app, which shows no completion checkmark until reps are logged.
1351
- * - `"prescribe"`: the values are prescribed targets, written with every `param_N_made` and
1352
- * `completed` left at 0 so the set is not marked done. This matches what the app sends when a
1353
- * coach edits an athlete's prescribed reps/weight.
1354
- *
1355
- * Each set fills a 1-based slot: its explicit `slot`, or its sequential position in `results`
1356
- * when `slot` is omitted. A `log` carrying the live exercise record in `existing` keeps the slots
1357
- * it does not write that were ALREADY performed (`param_N_made === 1`), so logging a second part of
1358
- * a set does not wipe the earlier-logged sets. A slot holding only un-logged prescription pre-fill
1359
- * (`param_N_made === 0`) is left blank rather than carried over: marking the set completed makes
1360
- * the server flag every data-bearing slot performed, so preserving that pre-fill would fabricate
1361
- * sets the athlete never did. The prescription is unaffected (it lives in the separate `workout`
1362
- * copy, not this saved copy). A `prescribe` ignores `existing` and replaces the whole prescription.
1363
- *
1364
- * Only `savedWorkoutSetExerciseId`, `savedWorkoutSetId`, and `workoutSetExerciseId` are
1365
- * required from the live exercise record; everything else is derived from `results` and the
1366
- * preserved slots of `existing`.
1367
- *
1368
- * Exported for unit testing — callers should use `logAthleteSet` / `prescribeForAthlete` instead.
1425
+ * Whether every exercise in a saved workout set is fully logged — either completed by its projected
1426
+ * payload in this call (`projectedCompletion`) or already carrying made flags for every active slot.
1427
+ * This gates the set-completion PUT so a partial exercise cannot close a superset/circuit and cause
1428
+ * TrainHeroic to backfill its omitted slots or untouched siblings.
1369
1429
  */
1370
- function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode, existing) {
1371
- if (results.length > 10) throw new Error(`At most 10 sets are supported per exercise; got ${results.length}.`);
1372
- const bySlot = /* @__PURE__ */ new Map();
1373
- results.forEach((set, i) => {
1374
- const slot = set.slot ?? i + 1;
1375
- if (slot < 1 || slot > 10) throw new Error(`Set slot ${slot} is out of range; slots are 1–10.`);
1376
- if (bySlot.has(slot)) throw new Error(`Two sets target slot ${slot}; each slot can be written once.`);
1377
- bySlot.set(slot, set);
1378
- });
1379
- const performed = mode === "log";
1380
- const carryOver = performed && existing !== void 0;
1381
- const body = {
1382
- id: savedWorkoutSetExerciseId,
1383
- saved_workout_set_id: savedWorkoutSetId,
1384
- workout_set_exercise_id: workoutSetExerciseId
1385
- };
1386
- let anyMade = false;
1387
- for (let i = 1; i <= 10; i += 1) {
1388
- const target = bySlot.get(i);
1389
- let p1;
1390
- let p2;
1391
- let made;
1392
- if (target) {
1393
- p1 = target.param1 !== void 0 ? String(target.param1) : "";
1394
- p2 = target.param2 !== void 0 ? String(target.param2) : "";
1395
- made = performed && p1 !== "" ? 1 : 0;
1396
- } else if (carryOver && coerceInt(existing?.[`param_${i}_made`]) === 1) {
1397
- p1 = existingSlotData(existing, `param_1_data_${i}`);
1398
- p2 = existingSlotData(existing, `param_2_data_${i}`);
1399
- made = 1;
1400
- } else {
1401
- p1 = "";
1402
- p2 = "";
1403
- made = 0;
1404
- }
1405
- if (made === 1) anyMade = true;
1406
- body[`param_${i}_made`] = made;
1407
- body[`param_1_data_${i}`] = p1;
1408
- body[`param_2_data_${i}`] = p2;
1409
- }
1410
- body.completed = performed && anyMade ? 1 : 0;
1411
- return body;
1412
- }
1413
- /** Read a saved-copy slot value (`param_1_data_N` / `param_2_data_N`) as the string the body uses. */
1414
- function existingSlotData(existing, key) {
1415
- const v = existing?.[key];
1416
- return v === void 0 || v === null ? "" : String(v);
1417
- }
1418
- /** True when a saved-copy exercise already carries a performed slot (any `param_N_made` === 1). */
1419
- function exerciseHasLoggedData(ex) {
1420
- for (let i = 1; i <= 10; i += 1) if (coerceInt(ex[`param_${i}_made`]) === 1) return true;
1421
- return false;
1422
- }
1423
- /** True when a result carries at least one set with reps entered (so it produces a performed slot).
1424
- * A weight-only set (`param2` set, `param1` blank) is a target, not a performed result, and so does
1425
- * not count — mirroring the `made` rule in {@link buildExerciseSetPayload}. */
1426
- function resultHasPerformedSet(result) {
1427
- return result.sets.some((s) => s.param1 !== void 0 && String(s.param1) !== "");
1428
- }
1429
- /**
1430
- * Whether every exercise in a saved workout set now has logged data — either written with data in
1431
- * this call (`loggedIds`) or already carrying a performed slot. Gates the set-completion PUT: a
1432
- * superset/circuit stays open until the last exercise is logged, so completing it on a partial log
1433
- * does not flip its still-empty siblings to "done". An exercise written with no reps — empty values,
1434
- * or a weight (`param2`) with no reps (`param1`) — does not count (it would not be marked performed),
1435
- * so a no-reps log never completes the set.
1436
- */
1437
- function isSetFullyLogged(exercises, loggedIds) {
1430
+ function isSetFullyLogged(exercises, projectedCompletion) {
1438
1431
  return exercises.every((ex) => {
1439
1432
  const id = coerceInt(ex.id);
1440
- return id !== null && loggedIds.has(id) || exerciseHasLoggedData(ex);
1433
+ if (id !== null && projectedCompletion.has(id)) return projectedCompletion.get(id) === true;
1434
+ return exerciseIsFullyLogged(ex);
1441
1435
  });
1442
1436
  }
1437
+ function assertUniqueExerciseResults(results) {
1438
+ const seen = /* @__PURE__ */ new Set();
1439
+ for (const result of results) {
1440
+ if (seen.has(result.savedWorkoutSetExerciseId)) throw new Error(`savedWorkoutSetExerciseId ${result.savedWorkoutSetExerciseId} appears more than once; combine its sets into one result.`);
1441
+ seen.add(result.savedWorkoutSetExerciseId);
1442
+ }
1443
+ }
1443
1444
  /**
1444
1445
  * Locate the target saved workout set across all program workouts on the given day.
1445
1446
  * Returns the `savedWorkoutId`, the matching set's `workoutSetExercises` array so callers
@@ -1639,9 +1640,11 @@ async function swapAthleteExercise(client, args) {
1639
1640
  */
1640
1641
  async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode) {
1641
1642
  const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
1643
+ assertUniqueExerciseResults(results);
1642
1644
  const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
1643
1645
  const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
1644
1646
  let exercisesWritten = 0;
1647
+ const projectedCompletion = /* @__PURE__ */ new Map();
1645
1648
  for (const result of results) {
1646
1649
  const ex = exercises.find((e) => coerceInt(e.id) === result.savedWorkoutSetExerciseId);
1647
1650
  if (!ex) {
@@ -1662,11 +1665,12 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1662
1665
  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.` : "";
1663
1666
  throw new Error(`Failed to write exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).${readOnly}`);
1664
1667
  }
1668
+ projectedCompletion.set(result.savedWorkoutSetExerciseId, body.completed === 1);
1665
1669
  exercisesWritten += 1;
1666
1670
  }
1667
1671
  let setCompleted = false;
1668
1672
  if (mode === "log") {
1669
- if (isSetFullyLogged(exercises, new Set(results.filter(resultHasPerformedSet).map((r) => r.savedWorkoutSetExerciseId)))) {
1673
+ if (isSetFullyLogged(exercises, projectedCompletion)) {
1670
1674
  const setBody = {
1671
1675
  ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
1672
1676
  ...extra
@@ -3742,7 +3746,7 @@ var JsonFileLibraryCache = class {
3742
3746
  };
3743
3747
  //#endregion
3744
3748
  //#region package.json
3745
- var version = "1.7.2";
3749
+ var version = "1.7.3";
3746
3750
  //#endregion
3747
3751
  //#region src/server.ts
3748
3752
  async function main() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trainheroic-unofficial/coach-mcp",
3
- "version": "1.7.2",
3
+ "version": "1.7.3",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,15 +21,15 @@
21
21
  "dependencies": {
22
22
  "@modelcontextprotocol/sdk": "^1.29.0",
23
23
  "zod": "^4.4.3",
24
- "@trainheroic-unofficial/core": "1.7.2",
25
- "@trainheroic-unofficial/js": "1.7.2"
24
+ "@trainheroic-unofficial/core": "1.7.3",
25
+ "@trainheroic-unofficial/js": "1.7.3"
26
26
  },
27
27
  "devDependencies": {
28
- "@types/node": "^26.0.1",
28
+ "@types/node": "^26.1.0",
29
29
  "tsdown": "^0.22.3",
30
- "tsx": "^4.22.4",
30
+ "tsx": "^4.23.0",
31
31
  "typescript": "^6.0.3",
32
- "vitest": "^4.1.9"
32
+ "vitest": "^4.1.10"
33
33
  },
34
34
  "scripts": {
35
35
  "start": "tsx src/server.ts",