@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
package/dist/index.js CHANGED
@@ -1,171 +1,215 @@
1
- import { execFile } from "node:child_process";
2
- import { promisify } from "node:util";
3
1
  import { Type } from "typebox";
4
2
  import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
5
- const execFileAsync = promisify(execFile);
6
- const DEFAULT_GC_BINARY = "gc";
7
- const GC_TIMEOUT_MS = 20_000;
8
- /**
9
- * Runs one `gc <args...> --format json` call. Each call is independent and
10
- * failure-isolated: a down Garmin session, a rate limit, or one unsupported
11
- * subcommand must not blank out the rest of the digest.
12
- */
13
- async function fetchGarminJson(gcBinary, args) {
14
- try {
15
- const { stdout } = await execFileAsync(gcBinary, [...args, "--format", "json"], {
16
- timeout: GC_TIMEOUT_MS,
17
- maxBuffer: 8 * 1024 * 1024,
18
- });
19
- return { ok: true, data: JSON.parse(stdout) };
20
- }
21
- catch (error) {
22
- return { ok: false, error: error instanceof Error ? error.message : String(error) };
23
- }
24
- }
25
- /** Runs several failure-isolated gc fetches concurrently and splits results from errors. */
26
- async function fetchGarminBatch(fetches) {
27
- const resolved = await Promise.all(Object.entries(fetches).map(async ([key, pending]) => [key, await pending]));
28
- const data = {};
29
- const errors = {};
30
- for (const [key, result] of resolved) {
31
- if (result.ok) {
32
- data[key] = result.data;
33
- }
34
- else {
35
- data[key] = null;
36
- errors[key] = result.error;
37
- }
38
- }
39
- return { data, errors };
40
- }
41
- function isoDate(date) {
42
- return date.toISOString().slice(0, 10);
43
- }
44
- const UnknownJson = Type.Unknown();
3
+ import { parseConfig } from "./config.js";
4
+ import { createGcRunner } from "./garmin/gc.js";
5
+ import { ToolInputError, activityDeepDive, briefingCharts, briefingEmail, CHART_IDS, dailyBriefing, dataStatus, journalInsights, journalLog, strengthAnalysis, trainingLoad, trends, workoutPush, zonesAndPaces, } from "./tools.js";
6
+ const DateParam = Type.Optional(Type.String({ description: "YYYY-MM-DD, 'today' or 'yesterday'. Default: today in the configured timezone." }));
7
+ const SyncParam = Type.Optional(Type.Boolean({ description: "Fetch new data from Garmin first (default true). Pass false to reuse the local store." }));
8
+ const ActivityIdParam = Type.String({ pattern: "^[0-9]{1,20}$", description: "Garmin activity id, as listed by coach_daily_briefing or coach_training_load." });
9
+ const Rating = (label) => Type.Optional(Type.Integer({ minimum: 1, maximum: 5, description: `${label}: 1 = worst, 5 = best.` }));
10
+ const TOOLS = [
11
+ {
12
+ name: "coach_daily_briefing",
13
+ label: "Coach Daily Briefing",
14
+ description: "Daily physiological assessment from Garmin data, computed with documented models against the athlete's own baselines: " +
15
+ "training ceiling for the day (rest/easy/moderate/hard) with its reasons, recovery index, HRV trend versus personal normal range, " +
16
+ "sleep sufficiency/debt/regularity, early-warning flags (possible illness or strain), training load (fitness, fatigue, form) and " +
17
+ "yesterday's sessions. Start every check-in with this tool. Every block carries a status (ready/calibrating/insufficient_data).",
18
+ parameters: Type.Object({ date: DateParam, sync: SyncParam }),
19
+ run: dailyBriefing,
20
+ summary: (r) => `Briefing ${r.date}: ceiling "${r.readiness.ceiling}" (confidence ${r.readiness.confidence}), recovery ${r.recovery.score ?? "n/a"}/100.`,
21
+ },
22
+ {
23
+ name: "coach_trends",
24
+ label: "Coach Trends",
25
+ description: "Multi-week view for weekly reviews and plan adjustments: weekly aggregates (HRV, resting heart rate, sleep, load, volume, " +
26
+ "elevation, intensity distribution, fitness and form), HRV and sleep analysis, training-load indicators, and long-term health " +
27
+ "markers compared with published thresholds. Set includeDaily for the day-by-day series.",
28
+ parameters: Type.Object({
29
+ days: Type.Optional(Type.Integer({ minimum: 14, maximum: 365, default: 28, description: "Window in days (limited by the stored history)." })),
30
+ includeDaily: Type.Optional(Type.Boolean({ description: "Also return one row per day (larger output)." })),
31
+ sync: SyncParam,
32
+ }),
33
+ run: trends,
34
+ summary: (r) => `Trends over ${r.windowDays} days (${r.weekly.length} weeks).`,
35
+ },
36
+ {
37
+ name: "coach_training_load",
38
+ label: "Coach Training Load",
39
+ description: "Training-load model: per-session load (Banister TRIMP), fitness (42-day), fatigue (7-day), form, weekly change, monotony and " +
40
+ "strain, intensity distribution. Pass `plan` (future sessions as a load, or as duration and heart-rate zone) to project " +
41
+ "fitness, fatigue and form over the plan before proposing it: use this to check a build or a taper.",
42
+ parameters: Type.Object({
43
+ plan: Type.Optional(Type.Array(Type.Object({
44
+ date: Type.String({ description: "YYYY-MM-DD, after today." }),
45
+ load: Type.Optional(Type.Number({ minimum: 0, description: "Session load in TRIMP, if already known." })),
46
+ durationMin: Type.Optional(Type.Number({ minimum: 1, maximum: 1440 })),
47
+ zone: Type.Optional(Type.Integer({ minimum: 1, maximum: 5, description: "Mean heart-rate zone of the session." })),
48
+ }), { maxItems: 200 })),
49
+ sync: SyncParam,
50
+ }),
51
+ run: trainingLoad,
52
+ summary: (r) => r.load.today ? `Load: fitness ${r.load.today.ctl}, fatigue ${r.load.today.atl}, form ${r.load.today.tsb}.` : "Load: no history yet.",
53
+ },
54
+ {
55
+ name: "coach_activity_deep_dive",
56
+ label: "Coach Activity Deep Dive",
57
+ description: "Analysis of one activity: load, time in heart-rate zones, per-lap pace and grade-adjusted pace, aerobic decoupling " +
58
+ "(heart-rate drift for the same output), efficiency, weather and heat flags. Use it on key sessions, long runs, races and " +
59
+ "any session whose heart rate or pace looks unusual.",
60
+ parameters: Type.Object({ activityId: ActivityIdParam }),
61
+ run: activityDeepDive,
62
+ summary: (r) => `Activity ${r.activityId}: ${r.flags?.length ?? 0} flag(s).`,
63
+ },
64
+ {
65
+ name: "coach_zones_and_paces",
66
+ label: "Coach Zones And Paces",
67
+ description: "Heart-rate zone tables from the athlete's anchors (lactate-threshold heart rate, heart-rate reserve, maximum heart rate). " +
68
+ "With a recent race result (raceDistanceM, raceTimeS) also returns VDOT, training paces and equivalent times for other flat distances.",
69
+ parameters: Type.Object({
70
+ raceDistanceM: Type.Optional(Type.Number({ minimum: 800, maximum: 100000 })),
71
+ raceTimeS: Type.Optional(Type.Number({ minimum: 120, maximum: 86400 })),
72
+ targetDistanceM: Type.Optional(Type.Number({ minimum: 800, maximum: 100000 })),
73
+ }),
74
+ run: zonesAndPaces,
75
+ summary: () => "Zones and paces computed.",
76
+ },
77
+ {
78
+ name: "coach_strength_analysis",
79
+ label: "Coach Strength Analysis",
80
+ description: "Summary of one strength session recorded on the watch: sets, repetitions, volume load, top set and estimated one-repetition " +
81
+ "maximum per exercise, sets per muscle group. Descriptive only.",
82
+ parameters: Type.Object({ activityId: ActivityIdParam }),
83
+ run: strengthAnalysis,
84
+ summary: (r) => `Strength session ${r.activityId}: ${r.totalSets ?? 0} sets.`,
85
+ },
86
+ {
87
+ name: "coach_journal_log",
88
+ label: "Coach Journal Log",
89
+ description: "Saves the athlete's subjective check-in and habits for a day in the local journal: wellness ratings, session RPE, symptoms, " +
90
+ "and habit tags (e.g. alcohol: 2, late_caffeine: true, sauna: true). Log tags as false on days without the habit, so that " +
91
+ "coach_journal_insights can compare. Only record what the athlete actually said.",
92
+ parameters: Type.Object({
93
+ date: DateParam,
94
+ tags: Type.Optional(Type.Record(Type.String(), Type.Union([Type.Boolean(), Type.Number({ minimum: 0 })]))),
95
+ rpe: Type.Optional(Type.Number({ minimum: 0, maximum: 10, description: "Session rating of perceived exertion (CR-10)." })),
96
+ fatigue: Rating("Fatigue"),
97
+ soreness: Rating("Muscle soreness"),
98
+ mood: Rating("Mood"),
99
+ sleepQuality: Rating("Perceived sleep quality"),
100
+ stress: Rating("Life stress"),
101
+ symptoms: Type.Optional(Type.Array(Type.String({ maxLength: 80 }), { maxItems: 10, description: "Symptoms reported today (sore throat, fever, pain...)." })),
102
+ notes: Type.Optional(Type.String({ maxLength: 500 })),
103
+ }),
104
+ run: journalLog,
105
+ summary: (r) => `Journal saved for ${r.saved.date}.`,
106
+ },
107
+ {
108
+ name: "coach_journal_insights",
109
+ label: "Coach Journal Insights",
110
+ description: "Compares the nights that follow days with a logged habit to the nights that follow days without it (HRV, resting heart rate, " +
111
+ "sleep). Returns group sizes, difference with a confidence interval, effect size and adjusted p-value. These are observed " +
112
+ "associations in personal data, never proof of cause: present them that way.",
113
+ parameters: Type.Object({ days: Type.Optional(Type.Integer({ minimum: 30, maximum: 730, default: 120 })) }),
114
+ run: journalInsights,
115
+ summary: (r) => `Journal: ${r.journalDays} days, ${r.associations.length} comparison(s).`,
116
+ },
117
+ {
118
+ name: "coach_workout_push",
119
+ label: "Coach Workout Push",
120
+ description: "Creates a structured workout in Garmin Connect. Without confirm it only returns a preview (duration, estimated load): show it " +
121
+ "to the athlete, and call again with confirm: true only after they explicitly agree. Disabled unless allowWorkoutPush is set.",
122
+ parameters: Type.Object({
123
+ name: Type.String({ minLength: 1, maxLength: 80 }),
124
+ sport: Type.Union(["running", "cycling", "swimming", "strength_training", "walking", "hiking"].map((sport) => Type.Literal(sport))),
125
+ steps: Type.Array(Type.Object({
126
+ type: Type.Union(["warmup", "interval", "recovery", "cooldown", "rest"].map((type) => Type.Literal(type))),
127
+ durationS: Type.Integer({ minimum: 10, maximum: 21600 }),
128
+ target: Type.Optional(Type.String({ description: "hr_zone:2, pace_zone:3, power_zone:4, heart_rate:150, power:220-240 or no_target." })),
129
+ }), { minItems: 1, maxItems: 60, description: "Flat list of steps: write out each repetition of an interval block." }),
130
+ confirm: Type.Optional(Type.Boolean({ description: "true only after the athlete has approved the preview." })),
131
+ }),
132
+ run: workoutPush,
133
+ summary: (r) => (r.created ? "Workout created." : r.message),
134
+ },
135
+ {
136
+ name: "coach_briefing_charts",
137
+ label: "Coach Briefing Charts",
138
+ description: "Renders the day's key figures as PNG images for an email or report: recovery gauge, today's ceiling, overnight signals against " +
139
+ "the personal baseline, HRV trend with normal range, fitness/fatigue/form curve, sleep of the last 14 nights. Numbers come from " +
140
+ "the same models as coach_daily_briefing. Returns file paths, content ids and alt texts; pass them to send_email as inlineImages. " +
141
+ "Writes files under the coach data directory only. A chart without enough data is skipped with the reason.",
142
+ parameters: Type.Object({
143
+ date: DateParam,
144
+ sync: SyncParam,
145
+ charts: Type.Optional(Type.Array(Type.Union(CHART_IDS.map((id) => Type.Literal(id))), { minItems: 1, maxItems: 6, description: "Subset of charts. Default: all six." })),
146
+ lang: Type.Optional(Type.Union([Type.Literal("en"), Type.Literal("fr")], { description: "Label language. Default: the plugin's `language` setting." })),
147
+ theme: Type.Optional(Type.Union([Type.Literal("light"), Type.Literal("dark")], { description: "Default light (best for email: the card keeps its own background)." })),
148
+ }),
149
+ run: briefingCharts,
150
+ summary: (r) => `${r.charts.length} chart(s) rendered, ${r.skipped.length} skipped.`,
151
+ },
152
+ {
153
+ name: "coach_briefing_email",
154
+ label: "Coach Briefing Email",
155
+ description: "Builds the complete daily briefing e-mail in code: subject, HTML (centred column, ceiling banner, recovery gauge, signals, HRV, sleep, " +
156
+ "text summary table), plain-text version and inline-image list. Pass subject, bodyHtml, bodyText and inlineImages to a mail tool " +
157
+ "(send_email) without rewriting them. Optionally supply headline, why and watch in the athlete's language to personalise the three " +
158
+ "sentences that need judgement. The load curve is added on Sundays. It does not send anything.",
159
+ parameters: Type.Object({
160
+ date: DateParam,
161
+ sync: SyncParam,
162
+ lang: Type.Optional(Type.Union([Type.Literal("en"), Type.Literal("fr")], { description: "Language of labels and default texts. Default: the plugin's `language` setting." })),
163
+ headline: Type.Optional(Type.String({ maxLength: 240, description: "One sentence: what to do today, taking ATHLETE.md and PLAN.md into account. Default: the meaning of the ceiling." })),
164
+ why: Type.Optional(Type.Array(Type.String({ maxLength: 240 }), { maxItems: 3, description: "Up to 3 bullets, main cause first, with figures and their personal reference. Default: the rules that set the ceiling, for English only; omitted for French when not supplied." })),
165
+ watch: Type.Optional(Type.Array(Type.String({ maxLength: 240 }), { maxItems: 4, description: "Cautions only (early warning, symptoms, sleep debt, load, missing data). Default: the briefing's caveats, for English only; omitted for French when not supplied. Pass [] when there is nothing to watch." })),
166
+ weekly: Type.Optional(Type.Boolean({ description: "Add the fitness/fatigue/form curve. Default: only on Sundays." })),
167
+ }),
168
+ run: briefingEmail,
169
+ summary: (r) => `E-mail built: "${r.subject}", ${r.inlineImages.length} inline image(s).`,
170
+ },
171
+ {
172
+ name: "coach_data_status",
173
+ label: "Coach Data Status",
174
+ description: "State of the coach's data: history coverage per signal, last sync and its errors, physiological anchors in use and where they " +
175
+ "come from, and what to configure. Use it when a briefing reports calibrating or insufficient_data, or to backfill (sync: true).",
176
+ parameters: Type.Object({ sync: Type.Optional(Type.Boolean({ description: "Fetch missing history from Garmin now (default false)." })) }),
177
+ run: dataStatus,
178
+ summary: (r) => `Data status: ${r.advice.length} point(s) to address.`,
179
+ },
180
+ ];
45
181
  export default definePluginEntry({
46
182
  id: "coach",
47
183
  name: "AI Coach",
48
- description: "Endurance coaching skill backed by Garmin Connect training-signal tools.",
184
+ description: "Endurance and recovery coach: documented physiological models computed on Garmin data, with a coaching skill.",
49
185
  register(api) {
50
- const gcBinary = typeof api.pluginConfig?.gcBinary === "string" && api.pluginConfig.gcBinary.trim()
51
- ? api.pluginConfig.gcBinary.trim()
52
- : DEFAULT_GC_BINARY;
53
- api.registerTool({
54
- name: "coach_garmin_digest",
55
- label: "Coach Garmin Digest",
56
- description: "Fetches a compact Garmin Connect training-signal digest for the coach: recent " +
57
- "activities, training readiness/status, HRV, body battery, sleep, weight trend, and " +
58
- "race predictions. One call replaces several separate `gc` invocations. Use " +
59
- "coach_activity_deep_dive afterwards for a specific activity's splits/HR-zones/weather. " +
60
- "Requires the gc CLI (garmin-cli) to already be authenticated in this environment.",
61
- parameters: Type.Object({
62
- days: Type.Optional(Type.Integer({
63
- minimum: 1,
64
- maximum: 90,
65
- default: 7,
66
- description: "Lookback window in days for activities and weigh-ins (default 7).",
67
- })),
68
- }),
69
- outputSchema: Type.Object({
70
- rangeStart: Type.String(),
71
- rangeEnd: Type.String(),
72
- activities: UnknownJson,
73
- trainingReadiness: UnknownJson,
74
- trainingStatus: UnknownJson,
75
- hrv: UnknownJson,
76
- bodyBattery: UnknownJson,
77
- sleep: UnknownJson,
78
- weighIns: UnknownJson,
79
- racePredictions: UnknownJson,
80
- errors: Type.Record(Type.String(), Type.String()),
81
- }, { additionalProperties: false }),
82
- async execute(_id, rawParams) {
83
- const { days = 7 } = rawParams;
84
- const end = new Date();
85
- const start = new Date(end.getTime() - days * 24 * 60 * 60 * 1000);
86
- const rangeStart = isoDate(start);
87
- const rangeEnd = isoDate(end);
88
- const { data, errors } = await fetchGarminBatch({
89
- activities: fetchGarminJson(gcBinary, [
90
- "activities",
91
- "--start",
92
- rangeStart,
93
- "--end",
94
- rangeEnd,
95
- ]),
96
- trainingReadiness: fetchGarminJson(gcBinary, ["metrics", "training-readiness", "today"]),
97
- trainingStatus: fetchGarminJson(gcBinary, ["metrics", "training-status", "today"]),
98
- hrv: fetchGarminJson(gcBinary, ["metrics", "hrv", "today"]),
99
- bodyBattery: fetchGarminJson(gcBinary, ["battery", "today"]),
100
- sleep: fetchGarminJson(gcBinary, ["sleep", "yesterday"]),
101
- weighIns: fetchGarminJson(gcBinary, [
102
- "body",
103
- "weighins",
104
- "--start",
105
- rangeStart,
106
- "--end",
107
- rangeEnd,
108
- ]),
109
- racePredictions: fetchGarminJson(gcBinary, ["metrics", "race-predictions"]),
110
- });
111
- const digest = { rangeStart, rangeEnd, ...data, errors };
112
- const totalCalls = Object.keys(data).length;
113
- const failedCount = Object.keys(errors).length;
114
- const summaryText = failedCount === 0
115
- ? `Garmin digest for ${rangeStart} to ${rangeEnd}: all ${totalCalls} signals fetched.`
116
- : `Garmin digest for ${rangeStart} to ${rangeEnd}: ${failedCount} of ${totalCalls} signals unavailable (${Object.keys(errors).join(", ")}).`;
117
- return {
118
- content: [
119
- { type: "text", text: summaryText },
120
- { type: "text", text: JSON.stringify(digest, null, 2) },
121
- ],
122
- details: digest,
123
- };
124
- },
125
- });
126
- api.registerTool({
127
- name: "coach_activity_deep_dive",
128
- label: "Coach Activity Deep Dive",
129
- description: "Fetches a fine-grained analysis bundle for one Garmin activity: summary, elevation- " +
130
- "and grade-segmented splits, HR zones, and weather (temperature/conditions) at the " +
131
- "time of the activity. Use this after coach_garmin_digest identifies an activity worth " +
132
- "a closer look (a key long run, a race, an unusually hard or easy session).",
133
- parameters: Type.Object({
134
- activityId: Type.String({
135
- description: "Garmin activity id, as returned in coach_garmin_digest's activities list.",
136
- }),
137
- }),
138
- outputSchema: Type.Object({
139
- activityId: Type.String(),
140
- summary: UnknownJson,
141
- typedSplits: UnknownJson,
142
- hrZones: UnknownJson,
143
- weather: UnknownJson,
144
- errors: Type.Record(Type.String(), Type.String()),
145
- }, { additionalProperties: false }),
146
- async execute(_id, rawParams) {
147
- const { activityId } = rawParams;
148
- const { data, errors } = await fetchGarminBatch({
149
- summary: fetchGarminJson(gcBinary, ["activities", "get", activityId]),
150
- // Typed splits carry per-segment elevation/grade, the basis for grade-adjusted
151
- // pace analysis; plain splits are a strict subset without that detail.
152
- typedSplits: fetchGarminJson(gcBinary, ["activities", "typed-splits", activityId]),
153
- hrZones: fetchGarminJson(gcBinary, ["activities", "hr-zones", activityId]),
154
- weather: fetchGarminJson(gcBinary, ["activities", "weather", activityId]),
155
- });
156
- const digest = { activityId, ...data, errors };
157
- const failedCount = Object.keys(errors).length;
158
- const summaryText = failedCount === 0
159
- ? `Activity ${activityId}: summary, splits, HR zones, and weather all fetched.`
160
- : `Activity ${activityId}: ${failedCount} of ${Object.keys(data).length} signals unavailable (${Object.keys(errors).join(", ")}).`;
161
- return {
162
- content: [
163
- { type: "text", text: summaryText },
164
- { type: "text", text: JSON.stringify(digest, null, 2) },
165
- ],
166
- details: digest,
167
- };
168
- },
169
- });
186
+ const config = parseConfig(api.pluginConfig);
187
+ const deps = { config, gc: createGcRunner(config.gcBinary) };
188
+ for (const tool of TOOLS) {
189
+ api.registerTool({
190
+ name: tool.name,
191
+ label: tool.label,
192
+ description: tool.description,
193
+ parameters: tool.parameters,
194
+ async execute(_id, rawParams) {
195
+ try {
196
+ const result = await tool.run(deps, (rawParams ?? {}));
197
+ return {
198
+ content: [
199
+ { type: "text", text: tool.summary(result) },
200
+ { type: "text", text: JSON.stringify(result) },
201
+ ],
202
+ details: result,
203
+ };
204
+ }
205
+ catch (error) {
206
+ // Input errors are explained to the model; anything else is reported without internals.
207
+ const message = error instanceof ToolInputError ? error.message : `The coach tool failed: ${error instanceof Error ? error.message : "unknown error"}.`;
208
+ const failure = { error: error instanceof ToolInputError ? "invalid_input" : "internal_error", message };
209
+ return { content: [{ type: "text", text: JSON.stringify(failure) }], details: failure };
210
+ }
211
+ },
212
+ });
213
+ }
170
214
  },
171
215
  });
@@ -0,0 +1,4 @@
1
+ /** Resolves the athlete's physiological anchors: configuration first, then data, then formulas. */
2
+ import type { CoachConfig } from "./config.ts";
3
+ import type { Activity, DayRecord, Profile } from "./types.ts";
4
+ export declare function resolveProfile(config: CoachConfig, days: readonly DayRecord[], activities: readonly Activity[], storedLthr: number | null, today: string): Profile;
@@ -0,0 +1,43 @@
1
+ /** Resolves the athlete's physiological anchors: configuration first, then data, then formulas. */
2
+ import { hrMaxFromAge, observedHrMax } from "./science/performance.js";
3
+ import { median, valid } from "./science/stats.js";
4
+ const DEFAULT_SLEEP_NEED_H = 8;
5
+ export function resolveProfile(config, days, activities, storedLthr, today) {
6
+ let hrMax = config.hrMax;
7
+ let hrMaxSource = hrMax !== null ? "config" : null;
8
+ if (hrMax === null) {
9
+ const observed = observedHrMax(activities);
10
+ if (observed !== null) {
11
+ hrMax = observed;
12
+ hrMaxSource = "observed";
13
+ }
14
+ else if (config.birthYear !== null) {
15
+ hrMax = hrMaxFromAge(Number(today.slice(0, 4)) - config.birthYear);
16
+ hrMaxSource = "age-formula";
17
+ }
18
+ }
19
+ let hrRest = config.hrRest;
20
+ let hrRestSource = hrRest !== null ? "config" : null;
21
+ if (hrRest === null) {
22
+ const recent = valid(days.slice(-60).map((day) => day.restingHr));
23
+ const baseline = recent.length >= 7 ? median(recent) : null;
24
+ if (baseline !== null) {
25
+ hrRest = Math.round(baseline);
26
+ hrRestSource = "baseline";
27
+ }
28
+ }
29
+ const lthr = config.lthr ?? storedLthr;
30
+ return {
31
+ sex: config.sex,
32
+ birthYear: config.birthYear,
33
+ hrMax,
34
+ hrMaxSource,
35
+ hrRest,
36
+ hrRestSource,
37
+ lthr,
38
+ lthrSource: lthr === null ? null : config.lthr !== null ? "config" : "garmin",
39
+ sleepNeedS: (config.sleepNeedHours ?? DEFAULT_SLEEP_NEED_H) * 3600,
40
+ sleepNeedSource: config.sleepNeedHours !== null ? "config" : "default",
41
+ hrZoneFloorsPctMax: config.hrZoneFloorsPctMax,
42
+ };
43
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Habit journal: does a logged habit go with a different night afterwards?
3
+ *
4
+ * For each habit tag, the nights following days with the habit are compared with
5
+ * the nights following days without it. The output is an observed association
6
+ * in one person's uncontrolled data, never a causal effect: habits cluster
7
+ * (alcohol on weekends, late nights with hard sessions), and the athlete knows
8
+ * which nights were which. Each comparison reports group sizes, the difference
9
+ * with a bootstrap confidence interval, a standardized effect size (Hedges' g),
10
+ * a permutation p-value, and a false-discovery-rate adjustment across all the
11
+ * comparisons made in the same call (Benjamini & Hochberg 1995).
12
+ */
13
+ import type { AlgorithmTag, DayRecord, JournalEntry } from "../types.ts";
14
+ export declare const ASSOCIATION_ALGORITHM: AlgorithmTag;
15
+ /** Nights needed in each group before a comparison is reported. */
16
+ export declare const MIN_GROUP_SIZE = 5;
17
+ type Outcome = {
18
+ key: string;
19
+ label: string;
20
+ unit: string;
21
+ get: (day: DayRecord) => number | null;
22
+ asPercent?: boolean;
23
+ };
24
+ export declare const OUTCOMES: Outcome[];
25
+ export type Association = {
26
+ tag: string;
27
+ outcome: string;
28
+ unit: string;
29
+ nightsWith: number;
30
+ nightsWithout: number;
31
+ /** Mean after days with the habit minus mean after days without (HRV: percent). */
32
+ difference: number;
33
+ ci95: [number, number] | null;
34
+ effectSize: number | null;
35
+ pValue: number | null;
36
+ /** p-value adjusted for the number of comparisons in this call. */
37
+ pAdjusted: number | null;
38
+ reading: "no clear difference" | "possible difference" | "consistent difference";
39
+ };
40
+ export type AssociationReport = {
41
+ algorithm: AlgorithmTag;
42
+ associations: Association[];
43
+ /** Tags logged too rarely (or too often) to compare. */
44
+ insufficient: Array<{
45
+ tag: string;
46
+ daysWith: number;
47
+ daysWithout: number;
48
+ }>;
49
+ caveats: string[];
50
+ };
51
+ /**
52
+ * @param days Day records by ascending date. The night that follows journal day D
53
+ * is stored on record D + 1 (records are dated by wake-up day).
54
+ */
55
+ export declare function habitAssociations(days: readonly DayRecord[], journal: readonly JournalEntry[]): AssociationReport;
56
+ export {};
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Habit journal: does a logged habit go with a different night afterwards?
3
+ *
4
+ * For each habit tag, the nights following days with the habit are compared with
5
+ * the nights following days without it. The output is an observed association
6
+ * in one person's uncontrolled data, never a causal effect: habits cluster
7
+ * (alcohol on weekends, late nights with hard sessions), and the athlete knows
8
+ * which nights were which. Each comparison reports group sizes, the difference
9
+ * with a bootstrap confidence interval, a standardized effect size (Hedges' g),
10
+ * a permutation p-value, and a false-discovery-rate adjustment across all the
11
+ * comparisons made in the same call (Benjamini & Hochberg 1995).
12
+ */
13
+ import { addDays } from "../dates.js";
14
+ import { lnRmssd } from "./hrv.js";
15
+ import { benjaminiHochberg, bootstrapDiffCi, hedgesG, isNum, mean, permutationP, round } from "./stats.js";
16
+ export const ASSOCIATION_ALGORITHM = {
17
+ id: "habit-associations",
18
+ version: "1.0.0",
19
+ refs: ["benjamini1995", "efron1993", "hedges1981"],
20
+ };
21
+ /** Nights needed in each group before a comparison is reported. */
22
+ export const MIN_GROUP_SIZE = 5;
23
+ export const OUTCOMES = [
24
+ { key: "hrv", label: "overnight HRV", unit: "%", get: (day) => lnRmssd(day), asPercent: true },
25
+ { key: "restingHr", label: "resting heart rate", unit: "bpm", get: (day) => day.restingHr },
26
+ { key: "sleepDuration", label: "sleep duration", unit: "min", get: (day) => (isNum(day.sleep?.durationS) ? day.sleep.durationS / 60 : null) },
27
+ { key: "deepSleep", label: "deep sleep", unit: "min", get: (day) => (isNum(day.sleep?.deepS) ? day.sleep.deepS / 60 : null) },
28
+ { key: "sleepScore", label: "Garmin sleep score", unit: "points", get: (day) => day.sleep?.score ?? null },
29
+ { key: "respiration", label: "sleep respiratory rate", unit: "breaths/min", get: (day) => day.respiration?.sleepAvg ?? null },
30
+ ];
31
+ function isOn(value) {
32
+ return value === true || (typeof value === "number" && value > 0);
33
+ }
34
+ /**
35
+ * @param days Day records by ascending date. The night that follows journal day D
36
+ * is stored on record D + 1 (records are dated by wake-up day).
37
+ */
38
+ export function habitAssociations(days, journal) {
39
+ const byDate = new Map(days.map((day) => [day.date, day]));
40
+ const logged = journal.filter((entry) => byDate.has(addDays(entry.date, 1)));
41
+ const tags = [...new Set(logged.flatMap((entry) => Object.keys(entry.tags)))].sort();
42
+ const associations = [];
43
+ const insufficient = [];
44
+ for (const tag of tags) {
45
+ // A day counts as "without" only if the journal was filled that day: an
46
+ // absent entry is unknown, not "no".
47
+ const withDays = logged.filter((entry) => isOn(entry.tags[tag]));
48
+ const withoutDays = logged.filter((entry) => !isOn(entry.tags[tag]));
49
+ if (withDays.length < MIN_GROUP_SIZE || withoutDays.length < MIN_GROUP_SIZE) {
50
+ insufficient.push({ tag, daysWith: withDays.length, daysWithout: withoutDays.length });
51
+ continue;
52
+ }
53
+ for (const outcome of OUTCOMES) {
54
+ const values = (entries) => entries.map((entry) => outcome.get(byDate.get(addDays(entry.date, 1)))).filter(isNum);
55
+ const a = values(withDays);
56
+ const b = values(withoutDays);
57
+ if (a.length < MIN_GROUP_SIZE || b.length < MIN_GROUP_SIZE)
58
+ continue;
59
+ const raw = mean(a) - mean(b);
60
+ const ci = bootstrapDiffCi(a, b);
61
+ // HRV is compared on the log scale; the difference is reported as a percent change.
62
+ const show = (x) => (outcome.asPercent ? round((Math.exp(x) - 1) * 100, 1) : round(x, 1));
63
+ associations.push({
64
+ tag,
65
+ outcome: outcome.label,
66
+ unit: outcome.unit,
67
+ nightsWith: a.length,
68
+ nightsWithout: b.length,
69
+ difference: show(raw),
70
+ ci95: ci ? [show(ci[0]), show(ci[1])] : null,
71
+ effectSize: (() => {
72
+ const g = hedgesG(a, b);
73
+ return g === null ? null : round(g, 2);
74
+ })(),
75
+ pValue: permutationP(a, b),
76
+ pAdjusted: null,
77
+ reading: "no clear difference",
78
+ });
79
+ }
80
+ }
81
+ const tested = associations.filter((item) => item.pValue !== null);
82
+ const adjusted = benjaminiHochberg(tested.map((item) => item.pValue));
83
+ tested.forEach((item, index) => {
84
+ item.pValue = round(item.pValue, 3);
85
+ item.pAdjusted = round(adjusted[index], 3);
86
+ const excludesZero = item.ci95 !== null && (item.ci95[0] > 0 || item.ci95[1] < 0);
87
+ if (item.pAdjusted < 0.05 && excludesZero)
88
+ item.reading = "consistent difference";
89
+ else if (excludesZero && Math.abs(item.effectSize ?? 0) >= 0.5)
90
+ item.reading = "possible difference";
91
+ });
92
+ return {
93
+ algorithm: ASSOCIATION_ALGORITHM,
94
+ associations,
95
+ insufficient,
96
+ caveats: [
97
+ "Observed association in uncontrolled personal data: it does not show that the habit causes the difference.",
98
+ "Habits cluster with weekdays, training and each other; a difference can come from what accompanies the habit.",
99
+ `Comparisons need at least ${MIN_GROUP_SIZE} nights in each group; more nights give narrower intervals.`,
100
+ ],
101
+ };
102
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Long-term health markers that a watch can follow, compared with published
3
+ * thresholds. No "biological age": each marker is shown as it is, with its
4
+ * evidence, because a composite age needs blood biomarkers and a validated
5
+ * model (Levine 2018) that wearable data cannot replace.
6
+ */
7
+ import type { Activity, AlgorithmTag, DayRecord } from "../types.ts";
8
+ import type { Profile } from "../types.ts";
9
+ export declare const HEALTHSPAN_ALGORITHM: AlgorithmTag;
10
+ export type Marker = {
11
+ marker: string;
12
+ value: number | null;
13
+ unit: string;
14
+ /** Published reference the value is compared with. */
15
+ reference: string;
16
+ met: boolean | null;
17
+ trend?: string | null;
18
+ refs: string[];
19
+ };
20
+ export declare function healthspanMarkers(days: readonly DayRecord[], activities: readonly Activity[], profile: Profile): {
21
+ algorithm: AlgorithmTag;
22
+ windowDays: number;
23
+ markers: Marker[];
24
+ caveat: string;
25
+ };