@sctg/openclaw-coach 0.1.0 → 2.1.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 (64) hide show
  1. package/README.md +323 -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/icon.png +0 -0
  6. package/assets/logo.png +0 -0
  7. package/assets/logo.svg +62 -0
  8. package/dist/charts/build.d.ts +71 -0
  9. package/dist/charts/build.js +276 -0
  10. package/dist/charts/labels.d.ts +38 -0
  11. package/dist/charts/labels.js +73 -0
  12. package/dist/charts/render.d.ts +10 -0
  13. package/dist/charts/render.js +26 -0
  14. package/dist/charts/svg.d.ts +47 -0
  15. package/dist/charts/svg.js +92 -0
  16. package/dist/config.d.ts +25 -0
  17. package/dist/config.js +38 -0
  18. package/dist/dates.d.ts +22 -0
  19. package/dist/dates.js +71 -0
  20. package/dist/email.d.ts +58 -0
  21. package/dist/email.js +188 -0
  22. package/dist/garmin/gc.d.ts +25 -0
  23. package/dist/garmin/gc.js +81 -0
  24. package/dist/garmin/normalize.d.ts +20 -0
  25. package/dist/garmin/normalize.js +132 -0
  26. package/dist/index.js +207 -163
  27. package/dist/profile.d.ts +4 -0
  28. package/dist/profile.js +43 -0
  29. package/dist/science/associations.d.ts +56 -0
  30. package/dist/science/associations.js +102 -0
  31. package/dist/science/healthspan.d.ts +25 -0
  32. package/dist/science/healthspan.js +89 -0
  33. package/dist/science/hrv.d.ts +61 -0
  34. package/dist/science/hrv.js +119 -0
  35. package/dist/science/load.d.ts +107 -0
  36. package/dist/science/load.js +228 -0
  37. package/dist/science/performance.d.ts +93 -0
  38. package/dist/science/performance.js +191 -0
  39. package/dist/science/readiness.d.ts +47 -0
  40. package/dist/science/readiness.js +97 -0
  41. package/dist/science/recovery.d.ts +74 -0
  42. package/dist/science/recovery.js +173 -0
  43. package/dist/science/sleep.d.ts +79 -0
  44. package/dist/science/sleep.js +165 -0
  45. package/dist/science/stats.d.ts +50 -0
  46. package/dist/science/stats.js +201 -0
  47. package/dist/science/strength.d.ts +47 -0
  48. package/dist/science/strength.js +120 -0
  49. package/dist/store.d.ts +36 -0
  50. package/dist/store.js +78 -0
  51. package/dist/sync.d.ts +36 -0
  52. package/dist/sync.js +145 -0
  53. package/dist/tools.d.ts +463 -0
  54. package/dist/tools.js +792 -0
  55. package/dist/types.d.ts +143 -0
  56. package/dist/types.js +2 -0
  57. package/docs/SCIENCE.md +721 -0
  58. package/examples/ATHLETE-fr.md +72 -0
  59. package/examples/ATHLETE.md +74 -0
  60. package/examples/PLAN-fr.md +55 -0
  61. package/examples/PLAN.md +55 -0
  62. package/openclaw.plugin.json +158 -5
  63. package/package.json +14 -3
  64. package/skills/coach/SKILL.md +291 -208
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Performance anchors: maximum heart rate, training zones, race equivalence,
3
+ * grade-adjusted pace and aerobic decoupling.
4
+ */
5
+ import type { Activity, AlgorithmTag, Profile } from "../types.ts";
6
+ export declare const ZONES_ALGORITHM: AlgorithmTag;
7
+ export declare const ACTIVITY_ALGORITHM: AlgorithmTag;
8
+ /** Age-predicted maximum heart rate (Tanaka 2001): 208 - 0.7 x age. SD about 10 bpm. */
9
+ export declare function hrMaxFromAge(age: number): number;
10
+ /**
11
+ * Highest heart rate reached in recorded activities. The 98th percentile of
12
+ * session maxima is used rather than the single highest value, which is often
13
+ * an optical-sensor spike. Needs at least 10 sessions.
14
+ */
15
+ export declare function observedHrMax(activities: readonly Activity[]): number | null;
16
+ export type Zone = {
17
+ zone: number;
18
+ name: string;
19
+ lowBpm: number;
20
+ highBpm: number;
21
+ };
22
+ /** Zones as fractions of heart-rate reserve (Karvonen 1957): 50-60-70-80-90-100 %. */
23
+ export declare function zonesFromReserve(hrMax: number, hrRest: number): Zone[];
24
+ /**
25
+ * Zones anchored on the lactate-threshold heart rate (LTHR), which follows the
26
+ * athlete's current fitness better than a percentage of maximum heart rate.
27
+ * Bounds for running, in percent of LTHR: <85, 85-89, 90-94, 95-99, >=100
28
+ * (Friel's field system, a practitioner convention; the physiological rationale
29
+ * for threshold-anchored zones is in Seiler 2010).
30
+ */
31
+ export declare function zonesFromLthr(lthr: number, hrMax: number | null): Zone[];
32
+ export declare function zonesFromMax(hrMax: number, floorsPct: readonly number[]): Zone[];
33
+ /** VDOT: the VO2max that the Daniels-Gilbert model associates with a race result. */
34
+ export declare function vdot(distanceM: number, timeS: number): number | null;
35
+ export type TrainingPaces = {
36
+ vdot: number;
37
+ /** Seconds per kilometre. */
38
+ easy: {
39
+ slow: number;
40
+ fast: number;
41
+ };
42
+ marathon: number;
43
+ threshold: number;
44
+ interval: number;
45
+ repetition: number;
46
+ };
47
+ /** Training paces at fixed fractions of VDOT (Daniels' intensity classes). */
48
+ export declare function trainingPaces(vdotValue: number): TrainingPaces;
49
+ /** Time predicted by the VDOT model for another distance (bisection on the race time). */
50
+ export declare function predictTimeFromVdot(vdotValue: number, distanceM: number): number | null;
51
+ /** Riegel's endurance equation (1981): T2 = T1 x (D2 / D1)^1.06. Flat races, 3.5 min to ~4 h. */
52
+ export declare function riegel(timeS: number, fromM: number, toM: number, exponent?: number): number;
53
+ /**
54
+ * Energy cost of running on a gradient, J/kg/m (Minetti 2002), valid from -0.45 to +0.45.
55
+ * `gradient` is rise over run (0.10 = 10 %).
56
+ */
57
+ export declare function minettiCost(gradient: number): number;
58
+ /** Flat-equivalent speed of a segment run at `speed` on mean gradient `gradient`. */
59
+ export declare function gradeAdjustedSpeed(speed: number, gradient: number): number;
60
+ export type Split = {
61
+ durationS: number;
62
+ distanceM: number;
63
+ avgHr: number | null;
64
+ elevGainM: number | null;
65
+ elevLossM: number | null;
66
+ /** Grade-adjusted speed from Garmin when present (m/s). */
67
+ gapSpeedMs: number | null;
68
+ };
69
+ export type Decoupling = {
70
+ /** Efficiency = flat-equivalent speed (m/min) per heartbeat-per-minute. */
71
+ firstHalfEfficiency: number;
72
+ secondHalfEfficiency: number;
73
+ /** Loss of efficiency from the first to the second half, in percent. */
74
+ decouplingPct: number;
75
+ firstHalfHr: number;
76
+ secondHalfHr: number;
77
+ gradeAdjusted: boolean;
78
+ splitsUsed: number;
79
+ };
80
+ /**
81
+ * Aerobic decoupling: change of the speed-to-heart-rate ratio between the two
82
+ * halves of a steady effort. A rising heart rate for the same output
83
+ * (cardiovascular drift) reflects heat, dehydration, glycogen depletion or
84
+ * insufficient aerobic durability (Maunder 2021). Below about 5 % is the usual
85
+ * practitioner benchmark for a well-tolerated duration; it is a field heuristic.
86
+ * Only meaningful for continuous efforts of 40 min or more.
87
+ */
88
+ export declare function aerobicDecoupling(splits: readonly Split[]): Decoupling | null;
89
+ /** Zone tables available for this profile, most specific anchor first. */
90
+ export declare function zoneTables(profile: Profile): Array<{
91
+ anchor: string;
92
+ zones: Zone[];
93
+ }>;
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Performance anchors: maximum heart rate, training zones, race equivalence,
3
+ * grade-adjusted pace and aerobic decoupling.
4
+ */
5
+ import { clamp, isNum, quantile, round } from "./stats.js";
6
+ export const ZONES_ALGORITHM = {
7
+ id: "zones-and-paces",
8
+ version: "1.0.0",
9
+ refs: ["tanaka2001", "karvonen1957", "seiler2010", "friel2009", "daniels2014", "riegel1981"],
10
+ };
11
+ export const ACTIVITY_ALGORITHM = {
12
+ id: "activity-analysis",
13
+ version: "1.0.0",
14
+ refs: ["minetti2002", "maunder2021", "periard2015"],
15
+ };
16
+ /** Age-predicted maximum heart rate (Tanaka 2001): 208 - 0.7 x age. SD about 10 bpm. */
17
+ export function hrMaxFromAge(age) {
18
+ return Math.round(208 - 0.7 * age);
19
+ }
20
+ /**
21
+ * Highest heart rate reached in recorded activities. The 98th percentile of
22
+ * session maxima is used rather than the single highest value, which is often
23
+ * an optical-sensor spike. Needs at least 10 sessions.
24
+ */
25
+ export function observedHrMax(activities) {
26
+ const maxima = activities.map((activity) => activity.maxHr).filter((value) => isNum(value) && value > 100 && value < 230);
27
+ if (maxima.length < 10)
28
+ return null;
29
+ return Math.round(quantile(maxima, 0.98));
30
+ }
31
+ const ZONE_NAMES = ["Recovery", "Aerobic endurance", "Tempo", "Threshold", "VO2max"];
32
+ /** Zones as fractions of heart-rate reserve (Karvonen 1957): 50-60-70-80-90-100 %. */
33
+ export function zonesFromReserve(hrMax, hrRest) {
34
+ const at = (fraction) => Math.round(hrRest + fraction * (hrMax - hrRest));
35
+ return ZONE_NAMES.map((name, index) => ({ zone: index + 1, name, lowBpm: at(0.5 + index * 0.1), highBpm: at(0.6 + index * 0.1) }));
36
+ }
37
+ /**
38
+ * Zones anchored on the lactate-threshold heart rate (LTHR), which follows the
39
+ * athlete's current fitness better than a percentage of maximum heart rate.
40
+ * Bounds for running, in percent of LTHR: <85, 85-89, 90-94, 95-99, >=100
41
+ * (Friel's field system, a practitioner convention; the physiological rationale
42
+ * for threshold-anchored zones is in Seiler 2010).
43
+ */
44
+ export function zonesFromLthr(lthr, hrMax) {
45
+ const bounds = [0.7, 0.85, 0.9, 0.95, 1];
46
+ const top = hrMax ?? Math.round(lthr * 1.1);
47
+ return ZONE_NAMES.map((name, index) => ({
48
+ zone: index + 1,
49
+ name,
50
+ lowBpm: Math.round(lthr * bounds[index]),
51
+ highBpm: index === 4 ? top : Math.round(lthr * bounds[index + 1]) - 1,
52
+ }));
53
+ }
54
+ export function zonesFromMax(hrMax, floorsPct) {
55
+ return ZONE_NAMES.map((name, index) => ({
56
+ zone: index + 1,
57
+ name,
58
+ lowBpm: Math.round((hrMax * floorsPct[index]) / 100),
59
+ highBpm: Math.round((hrMax * (floorsPct[index + 1] ?? 100)) / 100),
60
+ }));
61
+ }
62
+ /** Oxygen cost of running at `speed` (m/min) on the flat (Daniels & Gilbert 1979). */
63
+ function vo2AtSpeed(speed) {
64
+ return -4.6 + 0.182258 * speed + 0.000104 * speed ** 2;
65
+ }
66
+ /** Fraction of VO2max that can be sustained for `minutes` (Daniels & Gilbert 1979). */
67
+ function sustainableFraction(minutes) {
68
+ return 0.8 + 0.1894393 * Math.exp(-0.012778 * minutes) + 0.2989558 * Math.exp(-0.1932605 * minutes);
69
+ }
70
+ /** VDOT: the VO2max that the Daniels-Gilbert model associates with a race result. */
71
+ export function vdot(distanceM, timeS) {
72
+ const minutes = timeS / 60;
73
+ // The model was fitted on races from about 3.5 min to 4 h.
74
+ if (!(distanceM > 0) || minutes < 3.5 || minutes > 300)
75
+ return null;
76
+ return round(vo2AtSpeed(distanceM / minutes) / sustainableFraction(minutes), 1);
77
+ }
78
+ /** Running speed (m/min) whose flat oxygen cost is `vo2`. */
79
+ function speedAtVo2(vo2) {
80
+ return (-0.182258 + Math.sqrt(0.182258 ** 2 + 4 * 0.000104 * (vo2 + 4.6))) / (2 * 0.000104);
81
+ }
82
+ function paceSecPerKm(speedMPerMin) {
83
+ return Math.round(60_000 / speedMPerMin);
84
+ }
85
+ /** Training paces at fixed fractions of VDOT (Daniels' intensity classes). */
86
+ export function trainingPaces(vdotValue) {
87
+ const pace = (fraction) => paceSecPerKm(speedAtVo2(vdotValue * fraction));
88
+ return {
89
+ vdot: vdotValue,
90
+ easy: { slow: pace(0.59), fast: pace(0.74) },
91
+ marathon: pace(0.8),
92
+ threshold: pace(0.88),
93
+ interval: pace(0.98),
94
+ repetition: pace(1.05),
95
+ };
96
+ }
97
+ /** Time predicted by the VDOT model for another distance (bisection on the race time). */
98
+ export function predictTimeFromVdot(vdotValue, distanceM) {
99
+ let low = 3.5 * 60;
100
+ let high = 300 * 60;
101
+ const estimate = (seconds) => vdot(distanceM, seconds) ?? 0;
102
+ if (estimate(low) < vdotValue || estimate(high) > vdotValue)
103
+ return null;
104
+ for (let i = 0; i < 60; i += 1) {
105
+ const mid = (low + high) / 2;
106
+ if (estimate(mid) > vdotValue)
107
+ low = mid;
108
+ else
109
+ high = mid;
110
+ }
111
+ return Math.round((low + high) / 2);
112
+ }
113
+ /** Riegel's endurance equation (1981): T2 = T1 x (D2 / D1)^1.06. Flat races, 3.5 min to ~4 h. */
114
+ export function riegel(timeS, fromM, toM, exponent = 1.06) {
115
+ return Math.round(timeS * (toM / fromM) ** exponent);
116
+ }
117
+ /**
118
+ * Energy cost of running on a gradient, J/kg/m (Minetti 2002), valid from -0.45 to +0.45.
119
+ * `gradient` is rise over run (0.10 = 10 %).
120
+ */
121
+ export function minettiCost(gradient) {
122
+ const i = clamp(gradient, -0.45, 0.45);
123
+ return 155.4 * i ** 5 - 30.4 * i ** 4 - 43.3 * i ** 3 + 46.3 * i ** 2 + 19.5 * i + 3.6;
124
+ }
125
+ /** Flat-equivalent speed of a segment run at `speed` on mean gradient `gradient`. */
126
+ export function gradeAdjustedSpeed(speed, gradient) {
127
+ return (speed * minettiCost(gradient)) / minettiCost(0);
128
+ }
129
+ function splitFlatSpeed(split) {
130
+ if (isNum(split.gapSpeedMs) && split.gapSpeedMs > 0)
131
+ return { speed: split.gapSpeedMs, adjusted: true };
132
+ const speed = split.distanceM / split.durationS;
133
+ if (isNum(split.elevGainM) || isNum(split.elevLossM)) {
134
+ const gradient = ((split.elevGainM ?? 0) - (split.elevLossM ?? 0)) / split.distanceM;
135
+ return { speed: gradeAdjustedSpeed(speed, gradient), adjusted: true };
136
+ }
137
+ return { speed, adjusted: false };
138
+ }
139
+ /**
140
+ * Aerobic decoupling: change of the speed-to-heart-rate ratio between the two
141
+ * halves of a steady effort. A rising heart rate for the same output
142
+ * (cardiovascular drift) reflects heat, dehydration, glycogen depletion or
143
+ * insufficient aerobic durability (Maunder 2021). Below about 5 % is the usual
144
+ * practitioner benchmark for a well-tolerated duration; it is a field heuristic.
145
+ * Only meaningful for continuous efforts of 40 min or more.
146
+ */
147
+ export function aerobicDecoupling(splits) {
148
+ const usable = splits.filter((split) => split.durationS > 0 && split.distanceM > 0 && isNum(split.avgHr) && split.avgHr > 60);
149
+ const total = usable.reduce((seconds, split) => seconds + split.durationS, 0);
150
+ if (usable.length < 4 || total < 40 * 60)
151
+ return null;
152
+ const halves = [
153
+ { seconds: 0, flatMeters: 0, beats: 0 },
154
+ { seconds: 0, flatMeters: 0, beats: 0 },
155
+ ];
156
+ let elapsed = 0;
157
+ let adjusted = true;
158
+ for (const split of usable) {
159
+ const half = halves[elapsed + split.durationS / 2 < total / 2 ? 0 : 1];
160
+ const flat = splitFlatSpeed(split);
161
+ adjusted &&= flat.adjusted;
162
+ half.seconds += split.durationS;
163
+ half.flatMeters += flat.speed * split.durationS;
164
+ half.beats += split.avgHr * split.durationS;
165
+ elapsed += split.durationS;
166
+ }
167
+ if (!halves[0].seconds || !halves[1].seconds)
168
+ return null;
169
+ const efficiency = halves.map((half) => ((half.flatMeters / half.seconds) * 60) / (half.beats / half.seconds));
170
+ return {
171
+ firstHalfEfficiency: round(efficiency[0], 3),
172
+ secondHalfEfficiency: round(efficiency[1], 3),
173
+ decouplingPct: round(((efficiency[0] - efficiency[1]) / efficiency[0]) * 100, 1),
174
+ firstHalfHr: round(halves[0].beats / halves[0].seconds, 0),
175
+ secondHalfHr: round(halves[1].beats / halves[1].seconds, 0),
176
+ gradeAdjusted: adjusted,
177
+ splitsUsed: usable.length,
178
+ };
179
+ }
180
+ /** Zone tables available for this profile, most specific anchor first. */
181
+ export function zoneTables(profile) {
182
+ const tables = [];
183
+ if (isNum(profile.lthr))
184
+ tables.push({ anchor: `lactate-threshold heart rate ${profile.lthr} bpm (${profile.lthrSource})`, zones: zonesFromLthr(profile.lthr, profile.hrMax) });
185
+ if (isNum(profile.hrMax) && isNum(profile.hrRest)) {
186
+ tables.push({ anchor: `heart-rate reserve (max ${profile.hrMax}, rest ${profile.hrRest})`, zones: zonesFromReserve(profile.hrMax, profile.hrRest) });
187
+ }
188
+ if (isNum(profile.hrMax))
189
+ tables.push({ anchor: `percent of maximum heart rate ${profile.hrMax} bpm (${profile.hrMaxSource})`, zones: zonesFromMax(profile.hrMax, profile.hrZoneFloorsPctMax) });
190
+ return tables;
191
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Daily training decision: the highest intensity that today's signals support.
3
+ *
4
+ * The core rule is HRV-guided training, the only wearable-based daily rule
5
+ * tested in randomized trials: do high-intensity work when the 7-day HRV trend
6
+ * is inside the personal normal range, otherwise train easy or rest (Kiviniemi
7
+ * 2007, Vesterinen 2016, Javaloyes 2019; meta-analysis Düking 2021). The other
8
+ * rules only lower the ceiling: a possible illness, a short night, a load spike.
9
+ *
10
+ * The result is a ceiling, not a prescription: the plan, the athlete's symptoms
11
+ * and the constraints of ATHLETE.md come first, and subjective state is at least
12
+ * as informative as any device signal (Saw 2016).
13
+ */
14
+ import type { AlgorithmTag, JournalEntry } from "../types.ts";
15
+ import type { HrvAnalysis } from "./hrv.ts";
16
+ import type { LoadAnalysis } from "./load.ts";
17
+ import type { RecoveryAnalysis, WarningAnalysis } from "./recovery.ts";
18
+ import type { SleepAnalysis } from "./sleep.ts";
19
+ export declare const READINESS_ALGORITHM: AlgorithmTag;
20
+ export type Ceiling = "rest" | "easy" | "moderate" | "hard";
21
+ export type ReadinessDecision = {
22
+ algorithm: AlgorithmTag;
23
+ /** Highest intensity supported today. */
24
+ ceiling: Ceiling;
25
+ /** What each ceiling means in practice. */
26
+ meaning: string;
27
+ reasons: Array<{
28
+ rule: string;
29
+ caps: Ceiling;
30
+ detail: string;
31
+ }>;
32
+ /** Suggested load range for today, in the load unit, relative to current fitness (heuristic). */
33
+ suggestedLoad: {
34
+ min: number;
35
+ max: number;
36
+ } | null;
37
+ confidence: "high" | "medium" | "low";
38
+ caveats: string[];
39
+ };
40
+ export declare function decideReadiness(input: {
41
+ hrv: HrvAnalysis;
42
+ recovery: RecoveryAnalysis;
43
+ warning: WarningAnalysis;
44
+ sleep: SleepAnalysis;
45
+ load: LoadAnalysis;
46
+ journal?: JournalEntry | null;
47
+ }): ReadinessDecision;
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Daily training decision: the highest intensity that today's signals support.
3
+ *
4
+ * The core rule is HRV-guided training, the only wearable-based daily rule
5
+ * tested in randomized trials: do high-intensity work when the 7-day HRV trend
6
+ * is inside the personal normal range, otherwise train easy or rest (Kiviniemi
7
+ * 2007, Vesterinen 2016, Javaloyes 2019; meta-analysis Düking 2021). The other
8
+ * rules only lower the ceiling: a possible illness, a short night, a load spike.
9
+ *
10
+ * The result is a ceiling, not a prescription: the plan, the athlete's symptoms
11
+ * and the constraints of ATHLETE.md come first, and subjective state is at least
12
+ * as informative as any device signal (Saw 2016).
13
+ */
14
+ import { isNum, round } from "./stats.js";
15
+ export const READINESS_ALGORITHM = {
16
+ id: "readiness-decision",
17
+ version: "1.0.0",
18
+ refs: ["kiviniemi2007", "vesterinen2016", "javaloyes2019", "duking2021", "saw2016", "fullagar2015", "schwellnus2016", "foster1998"],
19
+ };
20
+ const ORDER = ["rest", "easy", "moderate", "hard"];
21
+ const MEANING = {
22
+ rest: "Rest or very light movement only.",
23
+ easy: "Easy aerobic work only (zones 1-2), no intensity.",
24
+ moderate: "Steady aerobic or tempo work is fine; postpone maximal or very long sessions.",
25
+ hard: "No signal argues against a planned hard or long session.",
26
+ };
27
+ /** Share of current fitness (CTL) suggested as today's load for each ceiling. */
28
+ const LOAD_SHARE = {
29
+ rest: [0, 0.3],
30
+ easy: [0.3, 0.8],
31
+ moderate: [0.8, 1.3],
32
+ hard: [1.2, 2],
33
+ };
34
+ export function decideReadiness(input) {
35
+ const { hrv, recovery, warning, sleep, load, journal } = input;
36
+ const reasons = [];
37
+ const cap = (rule, caps, detail) => reasons.push({ rule, caps, detail });
38
+ if (warning.level === "elevated") {
39
+ cap("early-warning", warning.persistent ? "rest" : "easy", `Several signals are outside the personal range (${warning.signals.join("; ")})${warning.persistent ? ", for the second day" : ""}. Check for symptoms before training.`);
40
+ }
41
+ if (hrv.trend === "below") {
42
+ cap("hrv-guided", "easy", `7-day HRV (${hrv.rolling7Ms} ms) is below the personal normal range (${hrv.baseline?.lowMs}-${hrv.baseline?.highMs} ms) for ${hrv.daysBelow} day(s).`);
43
+ }
44
+ else if (hrv.trend === "above" && isNum(recovery.deviations.restingHr.z) && recovery.deviations.restingHr.z > 1) {
45
+ cap("hrv-guided", "moderate", "7-day HRV is above the normal range while resting heart rate is also raised: an unusual pattern, treat with caution.");
46
+ }
47
+ if (recovery.band === "low") {
48
+ cap("recovery-index", "easy", `Recovery index ${recovery.score}/100: last night is clearly below this athlete's usual.`);
49
+ }
50
+ const night = sleep.lastNight;
51
+ if (night && isNum(night.durationH) && (night.durationH < 5 || (isNum(night.sufficiency) && night.sufficiency < 0.6))) {
52
+ cap("sleep", "easy", `Very short night (${night.durationH} h).`);
53
+ }
54
+ else if (night && isNum(night.durationH) && (night.durationH < 6 || (isNum(night.sufficiency) && night.sufficiency < 0.75))) {
55
+ cap("sleep", "moderate", `Short night (${night.durationH} h for a need of ${night.needH} h).`);
56
+ }
57
+ if (isNum(sleep.debtH) && sleep.debtH >= 8) {
58
+ cap("sleep-debt", "moderate", `Sleep debt of ${sleep.debtH} h over ${sleep.debtNights} nights.`);
59
+ }
60
+ if (load.flags.includes("load_spike")) {
61
+ cap("load", "moderate", `The last 7 days carry ${load.acuteChronicRatio} times the load of the previous three weeks.`);
62
+ }
63
+ if (load.flags.includes("high_monotony")) {
64
+ cap("load", "moderate", `Training monotony ${load.monotony} (> 2): the week lacks easy days.`);
65
+ }
66
+ if (journal) {
67
+ if (journal.symptoms?.length) {
68
+ cap("symptoms", "rest", `Reported symptoms: ${journal.symptoms.join(", ")}. Symptoms come before any device signal.`);
69
+ }
70
+ const poor = [journal.fatigue, journal.soreness, journal.mood, journal.sleepQuality, journal.stress].filter((value) => isNum(value) && value <= 2).length;
71
+ if (poor >= 2)
72
+ cap("wellness", "easy", `${poor} wellness ratings at 2/5 or below today.`);
73
+ }
74
+ const ceiling = reasons.reduce((lowest, reason) => (ORDER.indexOf(reason.caps) < ORDER.indexOf(lowest) ? reason.caps : lowest), "hard");
75
+ const ready = [hrv.status, recovery.status, sleep.status].filter((status) => status === "ready").length;
76
+ const confidence = ready === 3 && hrv.nightsInTrend >= 5 ? "high" : ready >= 2 ? "medium" : "low";
77
+ const caveats = [];
78
+ if (hrv.status !== "ready")
79
+ caveats.push("HRV baseline not established yet: the HRV-guided rule is inactive.");
80
+ // A single deviating signal happens by chance on several days a month: it is
81
+ // reported, but it does not lower the ceiling on its own.
82
+ if (warning.level === "watch")
83
+ caveats.push(`One signal is outside the personal range (${warning.signals[0]}): worth a second look tomorrow.`);
84
+ if (!journal)
85
+ caveats.push("No subjective check-in for today: ask how the athlete feels before applying this ceiling.");
86
+ const ctl = load.today?.ctl;
87
+ const share = LOAD_SHARE[ceiling];
88
+ return {
89
+ algorithm: READINESS_ALGORITHM,
90
+ ceiling,
91
+ meaning: MEANING[ceiling],
92
+ reasons,
93
+ suggestedLoad: isNum(ctl) && ctl > 0 ? { min: round(ctl * share[0], 0), max: round(ctl * share[1], 0) } : null,
94
+ confidence,
95
+ caveats,
96
+ };
97
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Daily recovery index and physiological early-warning flags.
3
+ *
4
+ * Both compare last night's signals with the athlete's own baseline (median and
5
+ * robust SD of the 60 preceding days): absolute values differ too much between
6
+ * people to be read against population norms.
7
+ *
8
+ * Recovery index (0-100): weighted mean of signed z-scores, mapped through the
9
+ * normal distribution, so 50 is a typical night for this athlete and the bands
10
+ * are roughly the thirds of the personal distribution. The weights are a
11
+ * documented design choice (HRV first, as the best-studied marker: Bellenger
12
+ * 2016, Buchheit 2014), not a validated clinical score.
13
+ *
14
+ * Early warning: several signals deviating together (resting heart rate up, HRV
15
+ * down, respiratory rate up, skin temperature up) often precede or accompany an
16
+ * infection (Mishra 2020, Radin 2020, Natarajan 2020, Miller 2020, Smarr 2020).
17
+ * The same pattern is produced by alcohol, heat, altitude, a late hard session,
18
+ * travel or the luteal phase: it is a prompt to check symptoms, not a diagnosis.
19
+ */
20
+ import type { AlgorithmTag, DataStatus, DayRecord, Profile } from "../types.ts";
21
+ export declare const RECOVERY_ALGORITHM: AlgorithmTag;
22
+ export declare const WARNING_ALGORITHM: AlgorithmTag;
23
+ export declare const BASELINE_DAYS = 60;
24
+ export declare const BASELINE_MIN_NIGHTS = 14;
25
+ export declare const RECOVERY_WEIGHTS: {
26
+ hrv: number;
27
+ restingHr: number;
28
+ sleep: number;
29
+ respiration: number;
30
+ skinTemp: number;
31
+ };
32
+ type SignalKey = "hrv" | "restingHr" | "respiration" | "skinTemp" | "spo2";
33
+ export type SignalDeviation = {
34
+ value: number | null;
35
+ baseline: number | null;
36
+ /** Value minus baseline, in the signal's unit (HRV: percent of rMSSD). */
37
+ delta: number | null;
38
+ z: number | null;
39
+ nights: number;
40
+ };
41
+ /** Last night's value of each signal against the personal baseline. */
42
+ export declare function signalDeviations(days: readonly DayRecord[]): Record<SignalKey, SignalDeviation>;
43
+ export type RecoveryBand = "low" | "moderate" | "high";
44
+ export type RecoveryAnalysis = {
45
+ status: DataStatus;
46
+ algorithm: AlgorithmTag;
47
+ /** 0-100; 50 is a typical night for this athlete. */
48
+ score: number | null;
49
+ band: RecoveryBand | null;
50
+ /** Signed contribution of each component, in z units (positive = better than usual). */
51
+ components: Record<string, {
52
+ z: number;
53
+ weight: number;
54
+ }>;
55
+ /** Share of the full weight that had data (1 = all five components). */
56
+ coverage: number;
57
+ deviations: Record<SignalKey, SignalDeviation>;
58
+ notes: string[];
59
+ };
60
+ export declare function analyzeRecovery(days: readonly DayRecord[], profile: Profile): RecoveryAnalysis;
61
+ export type WarningLevel = "none" | "watch" | "elevated";
62
+ export type WarningAnalysis = {
63
+ status: DataStatus;
64
+ algorithm: AlgorithmTag;
65
+ level: WarningLevel;
66
+ /** Signals outside the personal range last night. */
67
+ signals: string[];
68
+ /** True when at least two signals were also deviating the night before. */
69
+ persistent: boolean;
70
+ spo2Note: string | null;
71
+ confounders: string[];
72
+ };
73
+ export declare function analyzeWarning(days: readonly DayRecord[]): WarningAnalysis;
74
+ export {};
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Daily recovery index and physiological early-warning flags.
3
+ *
4
+ * Both compare last night's signals with the athlete's own baseline (median and
5
+ * robust SD of the 60 preceding days): absolute values differ too much between
6
+ * people to be read against population norms.
7
+ *
8
+ * Recovery index (0-100): weighted mean of signed z-scores, mapped through the
9
+ * normal distribution, so 50 is a typical night for this athlete and the bands
10
+ * are roughly the thirds of the personal distribution. The weights are a
11
+ * documented design choice (HRV first, as the best-studied marker: Bellenger
12
+ * 2016, Buchheit 2014), not a validated clinical score.
13
+ *
14
+ * Early warning: several signals deviating together (resting heart rate up, HRV
15
+ * down, respiratory rate up, skin temperature up) often precede or accompany an
16
+ * infection (Mishra 2020, Radin 2020, Natarajan 2020, Miller 2020, Smarr 2020).
17
+ * The same pattern is produced by alcohol, heat, altitude, a late hard session,
18
+ * travel or the luteal phase: it is a prompt to check symptoms, not a diagnosis.
19
+ */
20
+ import { lnRmssd } from "./hrv.js";
21
+ import { describeNight } from "./sleep.js";
22
+ import { clamp, isNum, normalCdf, robustBaseline, round, roundOrNull, zScore } from "./stats.js";
23
+ export const RECOVERY_ALGORITHM = {
24
+ id: "recovery-index",
25
+ version: "1.0.0",
26
+ refs: ["bellenger2016", "buchheit2014", "plews2013", "fullagar2015"],
27
+ };
28
+ export const WARNING_ALGORITHM = {
29
+ id: "early-warning",
30
+ version: "1.0.0",
31
+ refs: ["mishra2020", "radin2020", "natarajan2020", "miller2020", "smarr2020", "quer2021"],
32
+ };
33
+ export const BASELINE_DAYS = 60;
34
+ export const BASELINE_MIN_NIGHTS = 14;
35
+ /** Smallest SD accepted for each signal (measurement resolution). */
36
+ const FLOORS = { hrv: 0.05, rhr: 1, respiration: 0.3, skinTemp: 0.2, spo2: 0.7 };
37
+ export const RECOVERY_WEIGHTS = { hrv: 0.4, restingHr: 0.2, sleep: 0.25, respiration: 0.075, skinTemp: 0.075 };
38
+ const GETTERS = {
39
+ hrv: (day) => lnRmssd(day),
40
+ restingHr: (day) => day.restingHr,
41
+ respiration: (day) => day.respiration?.sleepAvg,
42
+ skinTemp: (day) => day.skinTempDeviationC,
43
+ spo2: (day) => day.spo2?.sleepAvg,
44
+ };
45
+ const SCALE_FLOOR = {
46
+ hrv: FLOORS.hrv,
47
+ restingHr: FLOORS.rhr,
48
+ respiration: FLOORS.respiration,
49
+ skinTemp: FLOORS.skinTemp,
50
+ spo2: FLOORS.spo2,
51
+ };
52
+ function baselineOf(days, key) {
53
+ const previous = days.slice(Math.max(0, days.length - 1 - BASELINE_DAYS), Math.max(0, days.length - 1));
54
+ return robustBaseline(previous.map(GETTERS[key]), SCALE_FLOOR[key], BASELINE_MIN_NIGHTS);
55
+ }
56
+ /** Last night's value of each signal against the personal baseline. */
57
+ export function signalDeviations(days) {
58
+ const today = days[days.length - 1];
59
+ const out = {};
60
+ for (const key of Object.keys(GETTERS)) {
61
+ const raw = today ? GETTERS[key](today) : null;
62
+ const value = isNum(raw) ? raw : null;
63
+ const baseline = baselineOf(days, key);
64
+ const z = zScore(value, baseline);
65
+ let delta = null;
66
+ if (value !== null && baseline) {
67
+ delta = key === "hrv" ? (Math.exp(value - baseline.center) - 1) * 100 : value - baseline.center;
68
+ }
69
+ const display = (x) => (x === null ? null : key === "hrv" ? round(Math.exp(x), 0) : round(x, 1));
70
+ out[key] = {
71
+ value: display(value),
72
+ baseline: baseline ? display(baseline.center) : null,
73
+ delta: roundOrNull(delta, 1),
74
+ z: roundOrNull(z, 2),
75
+ nights: baseline?.n ?? 0,
76
+ };
77
+ }
78
+ return out;
79
+ }
80
+ export function analyzeRecovery(days, profile) {
81
+ const deviations = signalDeviations(days);
82
+ const components = {};
83
+ const notes = [];
84
+ const add = (name, z) => {
85
+ if (z !== null)
86
+ components[name] = { z: round(z, 2), weight: RECOVERY_WEIGHTS[name] };
87
+ };
88
+ // More HRV than usual is not "more recovered" without limit: the benefit is capped.
89
+ if (deviations.hrv.z !== null)
90
+ add("hrv", clamp(deviations.hrv.z, -3, 1.5));
91
+ if (deviations.restingHr.z !== null)
92
+ add("restingHr", clamp(-deviations.restingHr.z, -3, 1.5));
93
+ // Respiration and skin temperature only count against recovery when elevated.
94
+ if (deviations.respiration.z !== null)
95
+ add("respiration", clamp(-deviations.respiration.z, -3, 0.5));
96
+ if (deviations.skinTemp.z !== null)
97
+ add("skinTemp", clamp(-deviations.skinTemp.z, -3, 0.5));
98
+ const night = describeNight(days[days.length - 1], profile);
99
+ if (night && isNum(night.sufficiency)) {
100
+ // 15 % of the need (about 70 min for 8 h) is taken as one "SD" of sleep sufficiency.
101
+ add("sleep", clamp((night.sufficiency - 1) / 0.15, -3, 1));
102
+ }
103
+ const weight = Object.values(components).reduce((total, part) => total + part.weight, 0);
104
+ const hasCardiac = "hrv" in components || "restingHr" in components;
105
+ let score = null;
106
+ if (hasCardiac && weight >= 0.5) {
107
+ const z = Object.values(components).reduce((total, part) => total + part.z * part.weight, 0) / weight;
108
+ score = Math.round(100 * normalCdf(z));
109
+ }
110
+ if (!("hrv" in components))
111
+ notes.push("No HRV for last night: the index relies on resting heart rate and sleep.");
112
+ if (!night)
113
+ notes.push("No sleep recorded for last night.");
114
+ const calibrating = deviations.hrv.nights < BASELINE_MIN_NIGHTS && deviations.restingHr.nights < BASELINE_MIN_NIGHTS;
115
+ return {
116
+ status: score === null ? (calibrating ? "calibrating" : "insufficient_data") : "ready",
117
+ algorithm: RECOVERY_ALGORITHM,
118
+ score,
119
+ band: score === null ? null : score >= 67 ? "high" : score >= 34 ? "moderate" : "low",
120
+ components,
121
+ coverage: round(weight, 2),
122
+ deviations,
123
+ notes,
124
+ };
125
+ }
126
+ const CONFOUNDERS = [
127
+ "alcohol the evening before",
128
+ "hard or late training session",
129
+ "heat, dehydration",
130
+ "altitude or travel across time zones",
131
+ "short or fragmented night",
132
+ "luteal phase of the menstrual cycle (higher temperature and heart rate)",
133
+ ];
134
+ function deviatingSignals(days) {
135
+ const d = signalDeviations(days);
136
+ const out = [];
137
+ if (isNum(d.restingHr.z) && isNum(d.restingHr.delta) && d.restingHr.z >= 2 && d.restingHr.delta >= 3) {
138
+ out.push(`resting heart rate +${d.restingHr.delta} bpm`);
139
+ }
140
+ if (isNum(d.hrv.z) && d.hrv.z <= -2)
141
+ out.push(`HRV ${d.hrv.delta} % vs baseline`);
142
+ if (isNum(d.respiration.z) && isNum(d.respiration.delta) && d.respiration.z >= 2 && d.respiration.delta >= 0.8) {
143
+ out.push(`respiratory rate +${d.respiration.delta} breaths/min`);
144
+ }
145
+ const temp = d.skinTemp;
146
+ if (isNum(temp.value) && ((isNum(temp.z) && temp.z >= 2 && temp.value >= 0.5) || (temp.z === null && temp.value >= 1))) {
147
+ out.push(`skin temperature +${temp.value} °C vs personal norm`);
148
+ }
149
+ if (isNum(d.spo2.z) && isNum(d.spo2.delta) && d.spo2.z <= -2 && d.spo2.delta <= -2) {
150
+ out.push(`sleep SpO2 ${d.spo2.delta} points`);
151
+ }
152
+ return out;
153
+ }
154
+ export function analyzeWarning(days) {
155
+ const signals = deviatingSignals(days);
156
+ const before = days.length > 1 ? deviatingSignals(days.slice(0, -1)) : [];
157
+ const deviations = signalDeviations(days);
158
+ const usable = ["hrv", "restingHr", "respiration", "skinTemp"].filter((key) => deviations[key].z !== null).length;
159
+ const low = days[days.length - 1]?.spo2?.sleepLow;
160
+ const spo2Note = isNum(low) && low < 85
161
+ ? `Lowest sleep SpO2 ${low} %: wrist oximetry is imprecise; if this repeats at low altitude with snoring or daytime sleepiness, it is worth mentioning to a doctor.`
162
+ : null;
163
+ const level = signals.length >= 2 ? "elevated" : signals.length === 1 ? "watch" : "none";
164
+ return {
165
+ status: usable >= 2 ? "ready" : usable === 1 ? "calibrating" : "insufficient_data",
166
+ algorithm: WARNING_ALGORITHM,
167
+ level,
168
+ signals,
169
+ persistent: signals.length >= 2 && before.length >= 2,
170
+ spo2Note,
171
+ confounders: level === "none" ? [] : CONFOUNDERS,
172
+ };
173
+ }