@sctg/openclaw-coach 0.1.0 → 2.0.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 (61) hide show
  1. package/README.md +296 -66
  2. package/assets/fonts/Inter_400Regular.ttf +0 -0
  3. package/assets/fonts/Inter_600SemiBold.ttf +0 -0
  4. package/assets/fonts/LICENSE.txt +93 -0
  5. package/assets/logo.png +0 -0
  6. package/assets/logo.svg +62 -0
  7. package/dist/charts/build.d.ts +71 -0
  8. package/dist/charts/build.js +276 -0
  9. package/dist/charts/labels.d.ts +38 -0
  10. package/dist/charts/labels.js +73 -0
  11. package/dist/charts/render.d.ts +10 -0
  12. package/dist/charts/render.js +26 -0
  13. package/dist/charts/svg.d.ts +47 -0
  14. package/dist/charts/svg.js +92 -0
  15. package/dist/config.d.ts +25 -0
  16. package/dist/config.js +38 -0
  17. package/dist/dates.d.ts +22 -0
  18. package/dist/dates.js +71 -0
  19. package/dist/garmin/gc.d.ts +25 -0
  20. package/dist/garmin/gc.js +81 -0
  21. package/dist/garmin/normalize.d.ts +20 -0
  22. package/dist/garmin/normalize.js +132 -0
  23. package/dist/index.js +188 -163
  24. package/dist/profile.d.ts +4 -0
  25. package/dist/profile.js +43 -0
  26. package/dist/science/associations.d.ts +56 -0
  27. package/dist/science/associations.js +102 -0
  28. package/dist/science/healthspan.d.ts +25 -0
  29. package/dist/science/healthspan.js +89 -0
  30. package/dist/science/hrv.d.ts +61 -0
  31. package/dist/science/hrv.js +119 -0
  32. package/dist/science/load.d.ts +107 -0
  33. package/dist/science/load.js +228 -0
  34. package/dist/science/performance.d.ts +93 -0
  35. package/dist/science/performance.js +191 -0
  36. package/dist/science/readiness.d.ts +47 -0
  37. package/dist/science/readiness.js +97 -0
  38. package/dist/science/recovery.d.ts +74 -0
  39. package/dist/science/recovery.js +173 -0
  40. package/dist/science/sleep.d.ts +79 -0
  41. package/dist/science/sleep.js +165 -0
  42. package/dist/science/stats.d.ts +50 -0
  43. package/dist/science/stats.js +201 -0
  44. package/dist/science/strength.d.ts +47 -0
  45. package/dist/science/strength.js +120 -0
  46. package/dist/store.d.ts +36 -0
  47. package/dist/store.js +78 -0
  48. package/dist/sync.d.ts +36 -0
  49. package/dist/sync.js +145 -0
  50. package/dist/tools.d.ts +427 -0
  51. package/dist/tools.js +721 -0
  52. package/dist/types.d.ts +143 -0
  53. package/dist/types.js +2 -0
  54. package/docs/SCIENCE.md +717 -0
  55. package/examples/ATHLETE-fr.md +72 -0
  56. package/examples/ATHLETE.md +74 -0
  57. package/examples/PLAN-fr.md +55 -0
  58. package/examples/PLAN.md +55 -0
  59. package/openclaw.plugin.json +152 -5
  60. package/package.json +14 -3
  61. package/skills/coach/SKILL.md +283 -208
package/dist/tools.js ADDED
@@ -0,0 +1,721 @@
1
+ /**
2
+ * Tool handlers. Each one loads the local store, syncs it with Garmin when
3
+ * asked, runs the models and returns a compact JSON result. Handlers take their
4
+ * dependencies as arguments so that tests can inject a fake `gc` and clock.
5
+ */
6
+ import fs from "node:fs/promises";
7
+ import path from "node:path";
8
+ import { ceilingLadder, hrvChart, loadChart, recoveryGauge, signalsChart, sleepChart } from "./charts/build.js";
9
+ import { renderPng } from "./charts/render.js";
10
+ import { THEMES } from "./charts/svg.js";
11
+ import { addDays, dateRange, isIsoDate, todayIn, weekStart } from "./dates.js";
12
+ import { garminDaySignals, normalizeActivity, normalizeSplits } from "./garmin/normalize.js";
13
+ import { resolveProfile } from "./profile.js";
14
+ import { habitAssociations } from "./science/associations.js";
15
+ import { healthspanMarkers } from "./science/healthspan.js";
16
+ import { analyzeHrv, lnRmssd } from "./science/hrv.js";
17
+ import { analyzeLoad, dailyLoads, fitnessFatigue, intensityDistribution, plannedSessionLoad, projectLoads, sessionLoad, } from "./science/load.js";
18
+ import { ACTIVITY_ALGORITHM, ZONES_ALGORITHM, aerobicDecoupling, gradeAdjustedSpeed, predictTimeFromVdot, riegel, trainingPaces, vdot, zoneTables, } from "./science/performance.js";
19
+ import { decideReadiness } from "./science/readiness.js";
20
+ import { analyzeRecovery, analyzeWarning } from "./science/recovery.js";
21
+ import { analyzeSleep, describeNight } from "./science/sleep.js";
22
+ import { isNum, mean, round, roundOrNull, sum, valid } from "./science/stats.js";
23
+ import { STRENGTH_ALGORITHM, parseExerciseSets, summarizeStrength } from "./science/strength.js";
24
+ import { activitiesFrom, daysBetweenDates, loadStore, saveStore } from "./store.js";
25
+ import { coverage, syncStore } from "./sync.js";
26
+ export class ToolInputError extends Error {
27
+ }
28
+ /** One store operation at a time: two tool calls must not interleave a load and a save. */
29
+ let queue = Promise.resolve();
30
+ function exclusive(task) {
31
+ const run = queue.then(task, task);
32
+ queue = run.catch(() => undefined);
33
+ return run;
34
+ }
35
+ function resolveDate(value, today) {
36
+ if (value === undefined || value === null || value === "today")
37
+ return today;
38
+ if (value === "yesterday")
39
+ return addDays(today, -1);
40
+ if (!isIsoDate(value))
41
+ throw new ToolInputError("date must be YYYY-MM-DD, 'today' or 'yesterday'.");
42
+ if (value > today)
43
+ throw new ToolInputError("date is in the future.");
44
+ return value;
45
+ }
46
+ async function loadContext(deps, options) {
47
+ const { config } = deps;
48
+ const now = deps.now?.() ?? new Date();
49
+ const today = todayIn(config.timezone, now);
50
+ const date = resolveDate(options.date, today);
51
+ return exclusive(async () => {
52
+ const store = await loadStore(config.dataDir);
53
+ let sync = null;
54
+ if (options.sync !== false) {
55
+ sync = await syncStore(store, deps.gc, config, today, now);
56
+ await saveStore(config.dataDir, store);
57
+ }
58
+ const days = daysBetweenDates(store, dateRange(addDays(date, -(config.historyDays - 1)), date));
59
+ // The load series starts where the activity list is known to be complete: days
60
+ // before that are unknown, not rest days.
61
+ const wanted = addDays(date, -(config.loadHistoryDays - 1));
62
+ const loadStart = store.activitiesFrom && store.activitiesFrom > wanted ? store.activitiesFrom : wanted;
63
+ const activities = activitiesFrom(store, loadStart, date);
64
+ const profile = resolveProfile(config, days, activities, store.lthr?.value ?? null, date);
65
+ const loads = loadStart <= date && store.activitiesFrom ? dailyLoads(activities, profile, loadStart, date) : [];
66
+ return { today, date, store, sync, days, activities, loads, profile };
67
+ });
68
+ }
69
+ function profileSummary(profile) {
70
+ return {
71
+ sex: profile.sex,
72
+ hrMax: profile.hrMax,
73
+ hrMaxSource: profile.hrMaxSource,
74
+ hrRest: profile.hrRest,
75
+ hrRestSource: profile.hrRestSource,
76
+ lthr: profile.lthr,
77
+ lthrSource: profile.lthrSource,
78
+ sleepNeedH: round(profile.sleepNeedS / 3600, 1),
79
+ sleepNeedSource: profile.sleepNeedSource,
80
+ };
81
+ }
82
+ function paceText(speedMs) {
83
+ if (!isNum(speedMs) || speedMs <= 0)
84
+ return null;
85
+ const seconds = Math.round(1000 / speedMs);
86
+ return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}/km`;
87
+ }
88
+ function clock(seconds) {
89
+ const total = Math.round(seconds);
90
+ const h = Math.floor(total / 3600);
91
+ const m = Math.floor((total % 3600) / 60);
92
+ const s = total % 60;
93
+ return h ? `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}` : `${m}:${String(s).padStart(2, "0")}`;
94
+ }
95
+ function activityLine(activity, profile) {
96
+ const load = sessionLoad(activity, profile);
97
+ return {
98
+ id: activity.id,
99
+ date: activity.date,
100
+ start: activity.startLocal?.slice(11, 16) ?? null,
101
+ type: activity.type,
102
+ name: activity.name,
103
+ durationMin: roundOrNull(isNum(activity.durationS) ? activity.durationS / 60 : null, 0),
104
+ distanceKm: roundOrNull(isNum(activity.distanceM) ? activity.distanceM / 1000 : null, 2),
105
+ elevGainM: roundOrNull(activity.elevGainM, 0),
106
+ avgHr: activity.avgHr,
107
+ maxHr: activity.maxHr,
108
+ pace: paceText(activity.avgSpeedMs),
109
+ gradeAdjustedPace: paceText(activity.gapSpeedMs),
110
+ load: load.trimp,
111
+ loadMethod: load.method,
112
+ garminLoad: load.garmin,
113
+ aerobicTE: activity.aerobicTE,
114
+ anaerobicTE: activity.anaerobicTE,
115
+ };
116
+ }
117
+ function syncSummary(context) {
118
+ return {
119
+ assessedDate: context.date,
120
+ isToday: context.date === context.today,
121
+ sync: context.sync ? { fetchedDays: context.sync.fetchedDays, fetchedActivities: context.sync.fetchedActivities, errors: context.sync.errors } : "not requested",
122
+ dayErrors: context.days[context.days.length - 1]?.errors ?? {},
123
+ };
124
+ }
125
+ // --- coach_daily_briefing -------------------------------------------------------------------------
126
+ export async function dailyBriefing(deps, params) {
127
+ const context = await loadContext(deps, params);
128
+ const { days, activities, loads, profile, date, store } = context;
129
+ const today = days[days.length - 1];
130
+ const journal = store.journal[date] ?? null;
131
+ const hrv = analyzeHrv(days);
132
+ const sleep = analyzeSleep(days, profile);
133
+ const recovery = analyzeRecovery(days, profile);
134
+ const warning = analyzeWarning(days);
135
+ const load = analyzeLoad(loads, activities, profile);
136
+ const readiness = decideReadiness({ hrv, recovery, warning, sleep, load, journal });
137
+ const [readinessResult, statusResult] = await Promise.all([
138
+ deps.gc(["metrics", "training-readiness", date]),
139
+ deps.gc(["metrics", "training-status", date]),
140
+ ]);
141
+ const garmin = garminDaySignals(readinessResult.ok ? readinessResult.data : null, statusResult.ok ? statusResult.data : null);
142
+ const yesterday = addDays(date, -1);
143
+ return {
144
+ date,
145
+ data: { ...syncSummary(context), coverage: coverage(store, date, deps.config.historyDays) },
146
+ readiness,
147
+ recovery: { status: recovery.status, score: recovery.score, band: recovery.band, components: recovery.components, coverage: recovery.coverage, notes: recovery.notes, algorithm: recovery.algorithm },
148
+ signals: recovery.deviations,
149
+ hrv,
150
+ sleep,
151
+ earlyWarning: warning,
152
+ load: { ...load, intensity28: load.intensity28 },
153
+ garmin: {
154
+ ...garmin,
155
+ hrvStatus: today?.hrv?.status ?? null,
156
+ bodyBattery: today?.bodyBattery ?? null,
157
+ stress: today?.stress ? { avg: today.stress.avg, max: today.stress.max } : null,
158
+ note: "Garmin's own scores, reported as such: proprietary models, shown for comparison.",
159
+ },
160
+ activities: {
161
+ today: activities.filter((activity) => activity.date === date).map((activity) => activityLine(activity, profile)),
162
+ yesterday: activities.filter((activity) => activity.date === yesterday).map((activity) => activityLine(activity, profile)),
163
+ },
164
+ journal,
165
+ profile: profileSummary(profile),
166
+ };
167
+ }
168
+ // --- coach_trends ---------------------------------------------------------------------------------
169
+ export async function trends(deps, params) {
170
+ const context = await loadContext(deps, { sync: params.sync });
171
+ const { days, activities, loads, profile, date } = context;
172
+ const span = Math.min(Math.max(Math.round(params.days ?? 28), 14), deps.config.historyDays);
173
+ const window = days.slice(-span);
174
+ const curve = fitnessFatigue(loads);
175
+ const curveByDate = new Map(curve.map((point) => [point.date, point]));
176
+ const weeks = new Map();
177
+ for (const day of window) {
178
+ const key = weekStart(day.date);
179
+ if (!weeks.has(key))
180
+ weeks.set(key, { days: [], activities: [] });
181
+ weeks.get(key)?.days.push(day);
182
+ }
183
+ for (const activity of activities)
184
+ weeks.get(weekStart(activity.date))?.activities.push(activity);
185
+ const weekly = [...weeks.entries()].map(([start, week]) => {
186
+ const inWindow = week.activities.filter((activity) => activity.date >= window[0].date);
187
+ const ln = valid(week.days.map(lnRmssd));
188
+ const lastDay = week.days[week.days.length - 1].date;
189
+ return {
190
+ weekStart: start,
191
+ daysInWindow: week.days.length,
192
+ hrvMs: ln.length ? round(Math.exp(mean(ln)), 0) : null,
193
+ restingHr: roundOrNull(mean(valid(week.days.map((day) => day.restingHr))), 0),
194
+ sleepH: roundOrNull(mean(valid(week.days.map((day) => (isNum(day.sleep?.durationS) ? day.sleep.durationS / 3600 : null)))), 2),
195
+ respiration: roundOrNull(mean(valid(week.days.map((day) => day.respiration?.sleepAvg))), 1),
196
+ load: round(sum(inWindow.map((activity) => sessionLoad(activity, profile).trimp ?? 0)), 0),
197
+ sessions: inWindow.length,
198
+ hours: round(sum(inWindow.map((activity) => activity.durationS ?? 0)) / 3600, 1),
199
+ distanceKm: round(sum(inWindow.map((activity) => activity.distanceM ?? 0)) / 1000, 1),
200
+ elevGainM: round(sum(inWindow.map((activity) => activity.elevGainM ?? 0)), 0),
201
+ fitnessAtEnd: curveByDate.get(lastDay)?.ctl ?? null,
202
+ formAtEnd: curveByDate.get(lastDay)?.tsb ?? null,
203
+ intensity: intensityDistribution(inWindow),
204
+ };
205
+ });
206
+ const result = {
207
+ date,
208
+ windowDays: span,
209
+ data: syncSummary(context),
210
+ weekly,
211
+ hrv: analyzeHrv(days),
212
+ sleep: analyzeSleep(days, profile),
213
+ load: analyzeLoad(loads, activities, profile),
214
+ healthspan: healthspanMarkers(days, activities, profile),
215
+ profile: profileSummary(profile),
216
+ };
217
+ if (params.includeDaily) {
218
+ result.daily = window.map((day) => ({
219
+ date: day.date,
220
+ hrvMs: day.hrv?.lastNightAvgMs ?? null,
221
+ restingHr: day.restingHr,
222
+ sleepH: roundOrNull(isNum(day.sleep?.durationS) ? day.sleep.durationS / 3600 : null, 1),
223
+ respiration: day.respiration?.sleepAvg ?? null,
224
+ spo2: day.spo2?.sleepAvg ?? null,
225
+ skinTempC: day.skinTempDeviationC,
226
+ load: curveByDate.get(day.date)?.load ?? null,
227
+ fitness: curveByDate.get(day.date)?.ctl ?? null,
228
+ fatigue: curveByDate.get(day.date)?.atl ?? null,
229
+ form: curveByDate.get(day.date)?.tsb ?? null,
230
+ }));
231
+ }
232
+ return result;
233
+ }
234
+ export async function trainingLoad(deps, params) {
235
+ const context = await loadContext(deps, { sync: params.sync });
236
+ const { activities, loads, profile, date } = context;
237
+ const analysis = analyzeLoad(loads, activities, profile);
238
+ const curve = fitnessFatigue(loads);
239
+ const result = {
240
+ date,
241
+ data: syncSummary(context),
242
+ load: analysis,
243
+ recentSessions: activities.filter((activity) => activity.date >= addDays(date, -13)).map((activity) => activityLine(activity, profile)),
244
+ weeklyCurve: curve.filter((_, index) => (curve.length - 1 - index) % 7 === 0).slice(-12),
245
+ profile: profileSummary(profile),
246
+ };
247
+ if (params.plan?.length) {
248
+ if (!analysis.today)
249
+ throw new ToolInputError("No load history yet: a plan cannot be projected.");
250
+ const byDate = new Map();
251
+ const rejected = [];
252
+ for (const session of params.plan) {
253
+ if (!isIsoDate(session.date) || session.date <= date || session.date > addDays(date, 120)) {
254
+ rejected.push(`${String(session.date)}: date must be within the next 120 days`);
255
+ continue;
256
+ }
257
+ const load = isNum(session.load) && session.load >= 0
258
+ ? session.load
259
+ : isNum(session.durationMin) && isNum(session.zone)
260
+ ? plannedSessionLoad(session.durationMin, session.zone, profile)
261
+ : null;
262
+ if (load === null) {
263
+ rejected.push(`${session.date}: give either load, or durationMin and zone (needs hrMax and hrRest)`);
264
+ continue;
265
+ }
266
+ byDate.set(session.date, (byDate.get(session.date) ?? 0) + load);
267
+ }
268
+ const lastDate = [...byDate.keys()].sort().pop();
269
+ if (lastDate) {
270
+ // Days of the plan without a session are rest days: load 0.
271
+ const planned = dateRange(addDays(date, 1), lastDate).map((day) => ({ date: day, load: byDate.get(day) ?? 0 }));
272
+ const projection = projectLoads(analysis.today, planned);
273
+ const end = projection[projection.length - 1];
274
+ result.projection = {
275
+ note: "Fitness-fatigue projection of the planned loads. Form (TSB) is fitness minus fatigue on the morning of each day.",
276
+ points: projection.filter((point, index) => byDate.has(point.date) || index === projection.length - 1),
277
+ atEnd: { date: end.date, fitness: end.ctl, fatigue: end.atl, formNextMorning: round(end.ctl - end.atl, 1) },
278
+ fitnessChange: round(end.ctl - analysis.today.ctl, 1),
279
+ peakFatigue: Math.max(...projection.map((point) => point.atl)),
280
+ lowestForm: Math.min(...projection.map((point) => point.tsb)),
281
+ rejected,
282
+ };
283
+ }
284
+ else {
285
+ result.projection = { rejected };
286
+ }
287
+ }
288
+ return result;
289
+ }
290
+ // --- coach_activity_deep_dive ---------------------------------------------------------------------
291
+ const ACTIVITY_ID = /^\d{1,20}$/;
292
+ function requireActivityId(value) {
293
+ const id = typeof value === "number" ? String(value) : value;
294
+ if (typeof id !== "string" || !ACTIVITY_ID.test(id))
295
+ throw new ToolInputError("activityId must be a numeric Garmin activity id.");
296
+ return id;
297
+ }
298
+ /** `gc activities get` nests the figures under summaryDTO; flatten it to the list shape. */
299
+ function flattenActivityDetail(payload) {
300
+ const root = payload;
301
+ if (!root || typeof root !== "object")
302
+ return null;
303
+ const summary = (root.summaryDTO ?? {});
304
+ const start = typeof summary.startTimeLocal === "string" ? summary.startTimeLocal.replace("T", " ") : undefined;
305
+ return {
306
+ ...summary,
307
+ activityId: root.activityId,
308
+ activityName: root.activityName,
309
+ activityType: root.activityTypeDTO ?? root.activityType,
310
+ startTimeLocal: start,
311
+ aerobicTrainingEffect: summary.trainingEffect ?? summary.aerobicTrainingEffect,
312
+ };
313
+ }
314
+ function zonesFromPayload(payload) {
315
+ if (!Array.isArray(payload))
316
+ return null;
317
+ const seconds = [0, 0, 0, 0, 0];
318
+ const floorsBpm = [0, 0, 0, 0, 0];
319
+ let found = false;
320
+ for (const raw of payload) {
321
+ const zone = raw?.zoneNumber;
322
+ if (!isNum(zone) || zone < 1 || zone > 5)
323
+ continue;
324
+ if (isNum(raw.secsInZone))
325
+ seconds[zone - 1] = raw.secsInZone;
326
+ if (isNum(raw.zoneLowBoundary))
327
+ floorsBpm[zone - 1] = raw.zoneLowBoundary;
328
+ found = true;
329
+ }
330
+ return found ? { seconds, floorsBpm } : null;
331
+ }
332
+ export async function activityDeepDive(deps, params) {
333
+ const id = requireActivityId(params.activityId);
334
+ const context = await loadContext(deps, { sync: false });
335
+ const [summary, splits, zones, weather] = await Promise.all([
336
+ deps.gc(["activities", "get", id]),
337
+ deps.gc(["activities", "splits", id]),
338
+ deps.gc(["activities", "hr-zones", id]),
339
+ deps.gc(["activities", "weather", id]),
340
+ ]);
341
+ const errors = {};
342
+ for (const [name, result] of Object.entries({ summary, splits, zones, weather }))
343
+ if (!result.ok)
344
+ errors[name] = result.code;
345
+ const stored = context.store.activities[id] ?? null;
346
+ const activity = (summary.ok ? normalizeActivity(flattenActivityDetail(summary.data)) : null) ?? stored;
347
+ if (!activity)
348
+ return { activityId: id, errors, note: "Activity not found." };
349
+ const zoneData = zones.ok ? zonesFromPayload(zones.data) : null;
350
+ let profile = context.profile;
351
+ if (zoneData) {
352
+ activity.hrZonesS = zoneData.seconds;
353
+ // The activity's own zone boundaries are more exact than the configured percentages.
354
+ if (isNum(profile.hrMax) && zoneData.floorsBpm.every((value) => value > 0)) {
355
+ profile = { ...profile, hrZoneFloorsPctMax: zoneData.floorsBpm.map((bpm) => (bpm / profile.hrMax) * 100) };
356
+ }
357
+ }
358
+ const laps = splits.ok ? normalizeSplits(splits.data) : [];
359
+ const decoupling = aerobicDecoupling(laps);
360
+ const zoneTotal = activity.hrZonesS ? sum(activity.hrZonesS) : 0;
361
+ const w = weather.ok ? weather.data : null;
362
+ // Garmin's activity weather service reports degrees Fahrenheit.
363
+ const weatherC = isNum(w?.temp) ? round((w.temp - 32) * (5 / 9), 0) : null;
364
+ const flags = [];
365
+ if (isNum(weatherC) && weatherC >= 25)
366
+ flags.push(`heat (${weatherC} °C): heart rate is higher at a given pace, do not read it as lost fitness`);
367
+ if (decoupling && decoupling.decouplingPct > 5)
368
+ flags.push(`aerobic decoupling ${decoupling.decouplingPct} %: heart rate drifted upwards for the same output`);
369
+ if (isNum(activity.elevGainM) && isNum(activity.distanceM) && activity.elevGainM / activity.distanceM > 0.03) {
370
+ flags.push("hilly course: compare efforts with grade-adjusted pace or heart rate, not raw pace");
371
+ }
372
+ return {
373
+ activityId: id,
374
+ algorithm: ACTIVITY_ALGORITHM,
375
+ summary: activityLine(activity, profile),
376
+ load: sessionLoad(activity, profile),
377
+ hrZones: activity.hrZonesS && zoneTotal > 0
378
+ ? { minutes: activity.hrZonesS.map((seconds) => round(seconds / 60, 0)), pct: activity.hrZonesS.map((seconds) => round((seconds / zoneTotal) * 100, 0)), floorsBpm: zoneData?.floorsBpm ?? null }
379
+ : null,
380
+ decoupling,
381
+ efficiency: isNum(activity.avgHr) && isNum(activity.gapSpeedMs ?? activity.avgSpeedMs)
382
+ ? { value: round(((activity.gapSpeedMs ?? activity.avgSpeedMs) * 60) / activity.avgHr, 3), unit: "m/min per bpm", note: "Compare only between similar efforts (same sport, duration, terrain, temperature)." }
383
+ : null,
384
+ splits: laps.slice(0, 60).map((lap, index) => {
385
+ const speed = lap.distanceM / lap.durationS;
386
+ const gradient = isNum(lap.elevGainM) || isNum(lap.elevLossM) ? ((lap.elevGainM ?? 0) - (lap.elevLossM ?? 0)) / lap.distanceM : null;
387
+ const flat = lap.gapSpeedMs ?? (gradient !== null ? gradeAdjustedSpeed(speed, gradient) : null);
388
+ return {
389
+ n: index + 1,
390
+ km: round(lap.distanceM / 1000, 2),
391
+ pace: paceText(speed),
392
+ gradeAdjustedPace: paceText(flat),
393
+ avgHr: lap.avgHr,
394
+ gainM: roundOrNull(lap.elevGainM, 0),
395
+ lossM: roundOrNull(lap.elevLossM, 0),
396
+ gradePct: gradient === null ? null : round(gradient * 100, 1),
397
+ };
398
+ }),
399
+ weather: w
400
+ ? { temperatureC: weatherC, humidityPct: isNum(w.relativeHumidity) ? w.relativeHumidity : null, conditions: w.weatherTypeDTO?.desc ?? null, unitAssumption: "Garmin weather temperature converted from °F" }
401
+ : null,
402
+ deviceTemperatureC: { min: activity.tempMinC, max: activity.tempMaxC },
403
+ flags,
404
+ errors,
405
+ };
406
+ }
407
+ // --- coach_zones_and_paces ------------------------------------------------------------------------
408
+ const STANDARD_DISTANCES = [
409
+ ["5 km", 5000],
410
+ ["10 km", 10000],
411
+ ["half marathon", 21097.5],
412
+ ["marathon", 42195],
413
+ ];
414
+ export async function zonesAndPaces(deps, params) {
415
+ const context = await loadContext(deps, { sync: false });
416
+ const result = {
417
+ algorithm: ZONES_ALGORITHM,
418
+ profile: profileSummary(context.profile),
419
+ heartRateZones: zoneTables(context.profile),
420
+ zoneNote: "Prefer the threshold-anchored table when a recent lactate-threshold estimate exists. Zones from an age-predicted maximum are approximate (SD about 10 bpm). On steep or technical terrain use heart rate or perceived effort, not pace.",
421
+ };
422
+ if (isNum(params.raceDistanceM) && isNum(params.raceTimeS)) {
423
+ const value = vdot(params.raceDistanceM, params.raceTimeS);
424
+ if (value === null)
425
+ throw new ToolInputError("The race must last between 3.5 minutes and 5 hours.");
426
+ const paces = trainingPaces(value);
427
+ const text = (seconds) => `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}/km`;
428
+ const targets = isNum(params.targetDistanceM) ? [[`${params.targetDistanceM} m`, params.targetDistanceM]] : STANDARD_DISTANCES;
429
+ result.race = {
430
+ input: { distanceM: params.raceDistanceM, time: clock(params.raceTimeS) },
431
+ vdot: value,
432
+ trainingPaces: {
433
+ easy: `${text(paces.easy.slow)} to ${text(paces.easy.fast)}`,
434
+ marathon: text(paces.marathon),
435
+ threshold: text(paces.threshold),
436
+ interval: text(paces.interval),
437
+ repetition: text(paces.repetition),
438
+ },
439
+ predictions: targets.map(([label, meters]) => {
440
+ const byVdot = predictTimeFromVdot(value, meters);
441
+ return { distance: label, vdotModel: byVdot === null ? null : clock(byVdot), riegel: clock(riegel(params.raceTimeS, params.raceDistanceM, meters)) };
442
+ }),
443
+ note: "Flat-road equivalences from one race result. They assume training specific to the target distance and do not apply to trail or mountain races.",
444
+ };
445
+ }
446
+ return result;
447
+ }
448
+ // --- coach_strength_analysis ----------------------------------------------------------------------
449
+ export async function strengthAnalysis(deps, params) {
450
+ const id = requireActivityId(params.activityId);
451
+ const result = await deps.gc(["activities", "exercise-sets", id]);
452
+ if (!result.ok)
453
+ return { activityId: id, error: result.code, message: result.message };
454
+ const sets = parseExerciseSets(result.data);
455
+ return {
456
+ activityId: id,
457
+ algorithm: STRENGTH_ALGORITHM,
458
+ ...summarizeStrength(sets),
459
+ notes: [
460
+ "Exercise names come from the watch's automatic recognition and can be wrong: confirm them with the athlete.",
461
+ "Estimated 1RM is computed only for sets of 1 to 10 repetitions, and assumes the set was taken close to failure.",
462
+ "No muscle-recovery score is computed: the watch records neither proximity to failure nor technique.",
463
+ ],
464
+ };
465
+ }
466
+ // --- coach_journal_log / coach_journal_insights ---------------------------------------------------
467
+ const TAG = /^[a-z0-9][a-z0-9_]{0,39}$/;
468
+ export async function journalLog(deps, params) {
469
+ const now = deps.now?.() ?? new Date();
470
+ const today = todayIn(deps.config.timezone, now);
471
+ const date = resolveDate(params.date, today);
472
+ const tags = {};
473
+ for (const [rawKey, value] of Object.entries(params.tags ?? {})) {
474
+ const key = rawKey.trim().toLowerCase().replace(/[\s-]+/g, "_");
475
+ if (!TAG.test(key))
476
+ throw new ToolInputError(`Invalid tag name "${rawKey}": use letters, digits and underscores.`);
477
+ if (typeof value === "boolean" || (isNum(value) && value >= 0))
478
+ tags[key] = value;
479
+ else
480
+ throw new ToolInputError(`Tag "${rawKey}" must be true, false or a non-negative number.`);
481
+ }
482
+ const rating = (value, low, high, name) => {
483
+ if (value === undefined)
484
+ return undefined;
485
+ if (!isNum(value) || value < low || value > high)
486
+ throw new ToolInputError(`${name} must be between ${low} and ${high}.`);
487
+ return value;
488
+ };
489
+ const symptoms = Array.isArray(params.symptoms) ? params.symptoms.filter((item) => typeof item === "string").map((item) => item.slice(0, 80)).slice(0, 10) : undefined;
490
+ return exclusive(async () => {
491
+ const store = await loadStore(deps.config.dataDir);
492
+ const previous = store.journal[date];
493
+ const entry = {
494
+ ...previous,
495
+ date,
496
+ tags: { ...previous?.tags, ...tags },
497
+ updatedAt: now.toISOString(),
498
+ };
499
+ const set = (key, value) => {
500
+ if (value !== undefined)
501
+ entry[key] = value;
502
+ };
503
+ set("rpe", rating(params.rpe, 0, 10, "rpe"));
504
+ set("fatigue", rating(params.fatigue, 1, 5, "fatigue"));
505
+ set("soreness", rating(params.soreness, 1, 5, "soreness"));
506
+ set("mood", rating(params.mood, 1, 5, "mood"));
507
+ set("sleepQuality", rating(params.sleepQuality, 1, 5, "sleepQuality"));
508
+ set("stress", rating(params.stress, 1, 5, "stress"));
509
+ set("symptoms", symptoms);
510
+ if (typeof params.notes === "string")
511
+ entry.notes = params.notes.slice(0, 500);
512
+ store.journal[date] = entry;
513
+ await saveStore(deps.config.dataDir, store);
514
+ return { saved: entry, entries: Object.keys(store.journal).length };
515
+ });
516
+ }
517
+ export async function journalInsights(deps, params) {
518
+ const context = await loadContext(deps, { sync: false });
519
+ const span = Math.min(Math.max(Math.round(params.days ?? 120), 30), deps.config.retentionDays);
520
+ const start = addDays(context.date, -(span - 1));
521
+ const days = Object.values(context.store.days).filter((day) => day.date >= start).sort((a, b) => a.date.localeCompare(b.date));
522
+ const journal = Object.values(context.store.journal).filter((entry) => entry.date >= start).sort((a, b) => a.date.localeCompare(b.date));
523
+ const ratings = (key) => roundOrNull(mean(valid(journal.slice(-7).map((entry) => entry[key]))), 1);
524
+ return {
525
+ windowDays: span,
526
+ journalDays: journal.length,
527
+ wellness7: { fatigue: ratings("fatigue"), soreness: ratings("soreness"), mood: ratings("mood"), sleepQuality: ratings("sleepQuality"), stress: ratings("stress"), scale: "1 = worst, 5 = best" },
528
+ ...habitAssociations(days, journal),
529
+ };
530
+ }
531
+ // --- coach_workout_push ---------------------------------------------------------------------------
532
+ const SPORTS = ["running", "cycling", "swimming", "strength_training", "walking", "hiking"];
533
+ const STEP_TYPES = ["warmup", "interval", "recovery", "cooldown", "rest"];
534
+ const TARGET = /^(?:no_target|(?:hr_zone|power_zone|pace_zone):[1-7]|(?:heart_rate|power|cadence):\d{2,4}(?:-\d{2,4})?)$/;
535
+ export async function workoutPush(deps, params) {
536
+ const name = typeof params.name === "string" ? params.name.trim() : "";
537
+ if (!name || name.length > 80)
538
+ throw new ToolInputError("name is required (80 characters at most).");
539
+ if (typeof params.sport !== "string" || !SPORTS.includes(params.sport))
540
+ throw new ToolInputError(`sport must be one of: ${SPORTS.join(", ")}.`);
541
+ if (!Array.isArray(params.steps) || !params.steps.length || params.steps.length > 60)
542
+ throw new ToolInputError("steps must hold 1 to 60 steps.");
543
+ const steps = [];
544
+ for (const raw of params.steps) {
545
+ if (!STEP_TYPES.includes(raw?.type))
546
+ throw new ToolInputError(`step type must be one of: ${STEP_TYPES.join(", ")}.`);
547
+ if (!isNum(raw.durationS) || raw.durationS < 10 || raw.durationS > 6 * 3600)
548
+ throw new ToolInputError("step durationS must be between 10 seconds and 6 hours.");
549
+ if (raw.target !== undefined && !TARGET.test(raw.target))
550
+ throw new ToolInputError(`invalid target "${raw.target}": use hr_zone:2, pace_zone:3, power_zone:4, heart_rate:150 or no_target.`);
551
+ steps.push({ type: raw.type, duration: Math.round(raw.durationS), ...(raw.target ? { target: raw.target } : {}) });
552
+ }
553
+ const context = await loadContext(deps, { sync: false });
554
+ let load = 0;
555
+ for (const step of steps) {
556
+ const zone = /^hr_zone:(\d)$/.exec(step.target ?? "");
557
+ // Steps without a heart-rate zone are assumed easy (zone 1 for rest/recovery, 2 otherwise).
558
+ const assumed = zone ? Number(zone[1]) : step.type === "rest" || step.type === "recovery" ? 1 : 2;
559
+ const part = plannedSessionLoad(step.duration / 60, Math.min(assumed, 5), context.profile);
560
+ load = part === null || load === null ? null : load + part;
561
+ }
562
+ const preview = {
563
+ name,
564
+ sport: params.sport,
565
+ totalMin: round(sum(steps.map((step) => step.duration)) / 60, 0),
566
+ steps,
567
+ estimatedLoad: load === null ? null : round(load, 0),
568
+ currentFitness: analyzeLoad(context.loads, context.activities, context.profile).today?.ctl ?? null,
569
+ };
570
+ if (!deps.config.allowWorkoutPush) {
571
+ return { created: false, preview, message: "Writing to Garmin Connect is disabled. Set allowWorkoutPush: true in the plugin config to enable it." };
572
+ }
573
+ if (params.confirm !== true) {
574
+ return { created: false, preview, message: "Preview only. Show it to the athlete; call again with confirm: true once they agree." };
575
+ }
576
+ const result = await deps.gc(["workouts", "create", "--name", name, "--sport", params.sport, "--steps", JSON.stringify(steps)], { timeoutMs: 60_000 });
577
+ if (result.ok) {
578
+ const data = result.data;
579
+ return { created: true, workoutId: data?.workoutId ?? null, preview, message: "Workout created in Garmin Connect. It reaches the watch at the next sync; it is not scheduled on a date." };
580
+ }
581
+ // gc prints a plain confirmation instead of JSON when Garmin returns no body.
582
+ if (result.code === "parse_error")
583
+ return { created: true, workoutId: null, preview, message: "Workout created (Garmin returned no identifier)." };
584
+ return { created: false, preview, error: result.code, message: result.message };
585
+ }
586
+ // --- coach_data_status ----------------------------------------------------------------------------
587
+ export async function dataStatus(deps, params) {
588
+ const context = await loadContext(deps, { sync: params.sync === true });
589
+ const cover = coverage(context.store, context.date, deps.config.historyDays);
590
+ const advice = [];
591
+ if (context.sync?.errors.daily === "unsupported" || context.sync?.errors.recent === "unsupported")
592
+ advice.push("Update garmin-cli to 0.4.0 or later: the `gc daily` command is missing.");
593
+ if (Object.values(context.sync?.errors ?? {}).includes("not_configured"))
594
+ advice.push("The gc binary was not found: install garmin-cli or set gcBinary in the plugin config.");
595
+ if (Object.values(context.sync?.errors ?? {}).includes("auth"))
596
+ advice.push("Run `gc login` in the Gateway environment.");
597
+ if (cover.daysWithHrv < 14)
598
+ advice.push(`HRV baseline needs 14 nights; ${cover.daysWithHrv} available.`);
599
+ if (!isNum(context.profile.hrMax))
600
+ advice.push("Set hrMax (measured maximum heart rate) in the plugin config: training load cannot be computed without it.");
601
+ if (context.profile.hrMaxSource === "age-formula")
602
+ advice.push("hrMax comes from an age formula: replace it with a measured value when possible.");
603
+ if (!context.profile.sex)
604
+ advice.push("Set sex in the plugin config for the correct training-load coefficients.");
605
+ return {
606
+ date: context.date,
607
+ timezone: deps.config.timezone,
608
+ dataDir: deps.config.dataDir,
609
+ sync: context.sync ?? "not requested (pass sync: true)",
610
+ coverage: cover,
611
+ profile: profileSummary(context.profile),
612
+ retentionDays: deps.config.retentionDays,
613
+ advice,
614
+ };
615
+ }
616
+ // --- coach_briefing_charts ------------------------------------------------------------------------
617
+ export const CHART_IDS = ["recovery_gauge", "ceiling", "signals", "hrv_trend", "load_curve", "sleep_nights"];
618
+ const CHART_KEEP_DAYS = 14;
619
+ /** Deletes chart folders (YYYY-MM-DD) older than the retention, never anything else. */
620
+ async function pruneCharts(root, today) {
621
+ let names;
622
+ try {
623
+ names = await fs.readdir(root);
624
+ }
625
+ catch {
626
+ return;
627
+ }
628
+ const limit = addDays(today, -CHART_KEEP_DAYS);
629
+ for (const name of names) {
630
+ if (isIsoDate(name) && name < limit)
631
+ await fs.rm(path.join(root, name), { recursive: true, force: true });
632
+ }
633
+ }
634
+ export async function briefingCharts(deps, params) {
635
+ const requested = params.charts?.length ? params.charts : [...CHART_IDS];
636
+ for (const id of requested) {
637
+ if (!CHART_IDS.includes(id))
638
+ throw new ToolInputError(`Unknown chart '${id}'. Available: ${CHART_IDS.join(", ")}.`);
639
+ }
640
+ if (params.theme !== undefined && params.theme !== "light" && params.theme !== "dark")
641
+ throw new ToolInputError("theme must be 'light' or 'dark'.");
642
+ if (params.lang !== undefined && params.lang !== "en" && params.lang !== "fr")
643
+ throw new ToolInputError("lang must be 'en' or 'fr'.");
644
+ const lang = params.lang ?? deps.config.language;
645
+ const theme = THEMES[params.theme ?? "light"];
646
+ const context = await loadContext(deps, params);
647
+ const { days, activities, loads, profile, date, store } = context;
648
+ const hrv = analyzeHrv(days);
649
+ const sleep = analyzeSleep(days, profile);
650
+ const recovery = analyzeRecovery(days, profile);
651
+ const warning = analyzeWarning(days);
652
+ const load = analyzeLoad(loads, activities, profile);
653
+ const readiness = decideReadiness({ hrv, recovery, warning, sleep, load, journal: store.journal[date] ?? null });
654
+ const common = { theme, lang };
655
+ const builders = {
656
+ recovery_gauge: () => recoveryGauge({ ...common, score: recovery.score, band: recovery.band }),
657
+ ceiling: () => ceilingLadder({ ...common, ceiling: readiness.ceiling, suggestedLoad: readiness.suggestedLoad }),
658
+ signals: () => {
659
+ const rows = recovery.deviations;
660
+ if (!Object.values(rows).some((row) => row.z !== null))
661
+ return "No overnight signal has a personal baseline yet (about 14 nights are needed).";
662
+ return signalsChart({ ...common, rows });
663
+ },
664
+ hrv_trend: () => {
665
+ const window = days.slice(-28);
666
+ const series = days.map(lnRmssd);
667
+ const points = window.map((day, index) => {
668
+ const end = days.length - window.length + index;
669
+ const trend = valid(series.slice(Math.max(0, end - 6), end + 1));
670
+ const ln = series[end];
671
+ return { date: day.date, ms: ln === null ? null : Math.exp(ln), trendMs: trend.length >= 3 ? Math.exp(mean(trend)) : null };
672
+ });
673
+ if (!points.some((point) => point.ms !== null))
674
+ return "No HRV value in the last 28 days.";
675
+ return hrvChart({ ...common, points, range: hrv.baseline ? { lowMs: hrv.baseline.lowMs, highMs: hrv.baseline.highMs } : null });
676
+ },
677
+ load_curve: () => {
678
+ const curve = fitnessFatigue(loads).slice(-56);
679
+ if (curve.length < 14)
680
+ return "Fewer than 14 days of load history.";
681
+ return loadChart({ ...common, points: curve });
682
+ },
683
+ sleep_nights: () => {
684
+ const nights = days.slice(-14).map((day) => {
685
+ const night = describeNight(day, profile);
686
+ const s = day.sleep;
687
+ const hours = (seconds) => (isNum(seconds) ? seconds / 3600 : null);
688
+ return { date: day.date, hours: night?.durationH ?? null, deepH: hours(s?.deepS), lightH: hours(s?.lightS), remH: hours(s?.remS), needH: night?.needH ?? profile.sleepNeedS / 3600 };
689
+ });
690
+ if (!nights.some((night) => night.hours !== null))
691
+ return "No sleep recorded in the last 14 nights.";
692
+ return sleepChart({ ...common, nights });
693
+ },
694
+ };
695
+ const folder = path.join(deps.config.dataDir, "charts");
696
+ const directory = path.join(folder, date);
697
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 });
698
+ const charts = [];
699
+ const skipped = [];
700
+ for (const id of requested) {
701
+ const built = builders[id]();
702
+ if (typeof built === "string") {
703
+ skipped.push({ id, reason: built });
704
+ continue;
705
+ }
706
+ const rendered = await renderPng(built.svg);
707
+ const file = path.join(directory, `${id}.png`);
708
+ await fs.writeFile(file, rendered.png, { mode: 0o600 });
709
+ charts.push({ id, path: file, cid: `coach-${id}`, displayWidth: built.width, displayHeight: built.height, pixelWidth: rendered.width, pixelHeight: rendered.height, bytes: rendered.png.length, alt: built.alt });
710
+ }
711
+ await pruneCharts(folder, context.today);
712
+ return {
713
+ date,
714
+ lang,
715
+ theme: theme.name,
716
+ charts,
717
+ skipped,
718
+ usage: "Each chart is a PNG file. To embed it in an email, pass { cid, path } in send_email's inlineImages and reference it in the HTML as " +
719
+ '<img src="cid:CID" width="displayWidth" alt="alt" style="display:block;max-width:100%;height:auto">. Gauge and ceiling are 280 px wide: place them side by side in a two-cell table.',
720
+ };
721
+ }