@trainheroic-unofficial/coach-mcp 1.7.1 → 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 -101
  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,102 +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 data
1348
- * and the exercise `completed` flag is 1 when any set has logged data.
1349
- * - `"prescribe"`: the values are prescribed targets, written with every `param_N_made` and
1350
- * `completed` left at 0 so the set is not marked done. This matches what the app sends when a
1351
- * coach edits an athlete's prescribed reps/weight.
1352
- *
1353
- * Each set fills a 1-based slot: its explicit `slot`, or its sequential position in `results`
1354
- * when `slot` is omitted. A `log` carrying the live exercise record in `existing` keeps the slots
1355
- * it does not write that were ALREADY performed (`param_N_made === 1`), so logging a second part of
1356
- * a set does not wipe the earlier-logged sets. A slot holding only un-logged prescription pre-fill
1357
- * (`param_N_made === 0`) is left blank rather than carried over: marking the set completed makes
1358
- * the server flag every data-bearing slot performed, so preserving that pre-fill would fabricate
1359
- * sets the athlete never did. The prescription is unaffected (it lives in the separate `workout`
1360
- * copy, not this saved copy). A `prescribe` ignores `existing` and replaces the whole prescription.
1361
- *
1362
- * Only `savedWorkoutSetExerciseId`, `savedWorkoutSetId`, and `workoutSetExerciseId` are
1363
- * required from the live exercise record; everything else is derived from `results` and the
1364
- * preserved slots of `existing`.
1365
- *
1366
- * 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.
1367
1429
  */
1368
- function buildExerciseSetPayload(savedWorkoutSetExerciseId, savedWorkoutSetId, workoutSetExerciseId, results, mode, existing) {
1369
- if (results.length > 10) throw new Error(`At most 10 sets are supported per exercise; got ${results.length}.`);
1370
- const bySlot = /* @__PURE__ */ new Map();
1371
- results.forEach((set, i) => {
1372
- const slot = set.slot ?? i + 1;
1373
- if (slot < 1 || slot > 10) throw new Error(`Set slot ${slot} is out of range; slots are 1–10.`);
1374
- if (bySlot.has(slot)) throw new Error(`Two sets target slot ${slot}; each slot can be written once.`);
1375
- bySlot.set(slot, set);
1376
- });
1377
- const performed = mode === "log";
1378
- const carryOver = performed && existing !== void 0;
1379
- const body = {
1380
- id: savedWorkoutSetExerciseId,
1381
- saved_workout_set_id: savedWorkoutSetId,
1382
- workout_set_exercise_id: workoutSetExerciseId
1383
- };
1384
- let anyMade = false;
1385
- for (let i = 1; i <= 10; i += 1) {
1386
- const target = bySlot.get(i);
1387
- let p1;
1388
- let p2;
1389
- let made;
1390
- if (target) {
1391
- p1 = target.param1 !== void 0 ? String(target.param1) : "";
1392
- p2 = target.param2 !== void 0 ? String(target.param2) : "";
1393
- made = performed && (p1 !== "" || p2 !== "") ? 1 : 0;
1394
- } else if (carryOver && coerceInt(existing?.[`param_${i}_made`]) === 1) {
1395
- p1 = existingSlotData(existing, `param_1_data_${i}`);
1396
- p2 = existingSlotData(existing, `param_2_data_${i}`);
1397
- made = 1;
1398
- } else {
1399
- p1 = "";
1400
- p2 = "";
1401
- made = 0;
1402
- }
1403
- if (made === 1) anyMade = true;
1404
- body[`param_${i}_made`] = made;
1405
- body[`param_1_data_${i}`] = p1;
1406
- body[`param_2_data_${i}`] = p2;
1407
- }
1408
- body.completed = performed && anyMade ? 1 : 0;
1409
- return body;
1410
- }
1411
- /** Read a saved-copy slot value (`param_1_data_N` / `param_2_data_N`) as the string the body uses. */
1412
- function existingSlotData(existing, key) {
1413
- const v = existing?.[key];
1414
- return v === void 0 || v === null ? "" : String(v);
1415
- }
1416
- /** True when a saved-copy exercise already carries a performed slot (any `param_N_made` === 1). */
1417
- function exerciseHasLoggedData(ex) {
1418
- for (let i = 1; i <= 10; i += 1) if (coerceInt(ex[`param_${i}_made`]) === 1) return true;
1419
- return false;
1420
- }
1421
- /** True when a result carries at least one non-empty param value (so it produces a performed slot). */
1422
- function resultHasData(result) {
1423
- return result.sets.some((s) => s.param1 !== void 0 && String(s.param1) !== "" || s.param2 !== void 0 && String(s.param2) !== "");
1424
- }
1425
- /**
1426
- * Whether every exercise in a saved workout set now has logged data — either written with data in
1427
- * this call (`loggedIds`) or already carrying a performed slot. Gates the set-completion PUT: a
1428
- * superset/circuit stays open until the last exercise is logged, so completing it on a partial log
1429
- * does not flip its still-empty siblings to "done". An exercise written with only empty values does
1430
- * not count (it would not be marked performed), so an all-empty log never completes the set.
1431
- */
1432
- function isSetFullyLogged(exercises, loggedIds) {
1430
+ function isSetFullyLogged(exercises, projectedCompletion) {
1433
1431
  return exercises.every((ex) => {
1434
1432
  const id = coerceInt(ex.id);
1435
- return id !== null && loggedIds.has(id) || exerciseHasLoggedData(ex);
1433
+ if (id !== null && projectedCompletion.has(id)) return projectedCompletion.get(id) === true;
1434
+ return exerciseIsFullyLogged(ex);
1436
1435
  });
1437
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
+ }
1438
1444
  /**
1439
1445
  * Locate the target saved workout set across all program workouts on the given day.
1440
1446
  * Returns the `savedWorkoutId`, the matching set's `workoutSetExercises` array so callers
@@ -1634,9 +1640,11 @@ async function swapAthleteExercise(client, args) {
1634
1640
  */
1635
1641
  async function writeSetResults(client, target, workouts, savedWorkoutSetId, results, mode) {
1636
1642
  const { exercises, rawSet } = findSavedWorkoutSet(workouts, savedWorkoutSetId);
1643
+ assertUniqueExerciseResults(results);
1637
1644
  const suffix = target.role === "coach" ? `/${target.athleteId}` : "";
1638
1645
  const extra = target.role === "coach" ? { athleteId: target.athleteId } : {};
1639
1646
  let exercisesWritten = 0;
1647
+ const projectedCompletion = /* @__PURE__ */ new Map();
1640
1648
  for (const result of results) {
1641
1649
  const ex = exercises.find((e) => coerceInt(e.id) === result.savedWorkoutSetExerciseId);
1642
1650
  if (!ex) {
@@ -1657,11 +1665,12 @@ async function writeSetResults(client, target, workouts, savedWorkoutSetId, resu
1657
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.` : "";
1658
1666
  throw new Error(`Failed to write exercise ${result.savedWorkoutSetExerciseId} (HTTP ${res.status}).${readOnly}`);
1659
1667
  }
1668
+ projectedCompletion.set(result.savedWorkoutSetExerciseId, body.completed === 1);
1660
1669
  exercisesWritten += 1;
1661
1670
  }
1662
1671
  let setCompleted = false;
1663
1672
  if (mode === "log") {
1664
- if (isSetFullyLogged(exercises, new Set(results.filter(resultHasData).map((r) => r.savedWorkoutSetExerciseId)))) {
1673
+ if (isSetFullyLogged(exercises, projectedCompletion)) {
1665
1674
  const setBody = {
1666
1675
  ...buildSetCompletePayload(rawSet, exercises.map((e) => coerceInt(e.id)).filter((n) => n !== null), true),
1667
1676
  ...extra
@@ -3737,7 +3746,7 @@ var JsonFileLibraryCache = class {
3737
3746
  };
3738
3747
  //#endregion
3739
3748
  //#region package.json
3740
- var version = "1.7.1";
3749
+ var version = "1.7.3";
3741
3750
  //#endregion
3742
3751
  //#region src/server.ts
3743
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.1",
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.1",
25
- "@trainheroic-unofficial/js": "1.7.1"
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",