From de6f057c955f995e9b2f67aafd0a50a9916cce47 Mon Sep 17 00:00:00 2001 From: Dariusz Tyszka Date: Wed, 21 Oct 2026 10:39:51 +0200 Subject: [PATCH 01/19] =?UTF-8?q?fix(cli):=20naprawy=200.3.1=20=E2=80=94?= =?UTF-8?q?=20review,=20why,=20log,=20komunikaty=20i=20dokumentacja=20zgod?= =?UTF-8?q?na=20z=20kodem?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Usterki zauważone przy uruchomieniu wszystkich komend na świeżym katalogu (docs/PLAN-v0.4.md, etap A): - review w niedzielę pokazuje pozostałe km obok celu tygodnia zamiast objętości całego tygodnia przy liczbie pozostałych sesji; - katalog bez trainctl.yaml odsyła do init, nie do plan; - why bez „0 minut" w dzień wolny, bez dublowania celu, jedna lista reguł z treścią i pochodzeniem; - log odbija plan obok zapisu i zwraca dane strukturalne; - ścieżki w komunikatach w formie POSIX na każdym systemie; - informacja o planie z innego minora silnika, odmowa nowszego schematu; - FOUNDATIONS jako link przypięty do tagu wydania (pliku nie ma w paczce npm). Dokumentacja: tabela komend z shorten, listy narzędzi bez liczby, przykłady CI na opublikowanej paczce, CLAUDE.md, krok GitHub Release w procedurze wydania. docs.test.ts pilnuje zgodności README z bin.ts i server.ts. Port sync rozdzielony na ActivitySource i SyncProvider (pod adapter plikowy). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 29 + CLAUDE.md | 30 + README.md | 13 +- README.pl.md | 13 +- docs/PLAN-v0.4.md | 942 +++++++++++++++++++++++++ docs/PUBLISHING.md | 5 + docs/examples/ci-check.md | 22 +- docs/examples/github-actions-review.md | 17 +- packages/cli/src/agents-md.ts | 3 +- packages/cli/src/check.test.ts | 8 +- packages/cli/src/commands.ts | 106 ++- packages/cli/src/docs.test.ts | 49 ++ packages/cli/src/fixes-031.test.ts | 168 +++++ packages/cli/src/i18n/cli-en.ts | 27 +- packages/cli/src/i18n/cli-i18n.test.ts | 4 +- packages/cli/src/i18n/cli-pl.ts | 28 +- packages/cli/src/i18n/improve-en.ts | 1 - packages/cli/src/i18n/improve-pl.ts | 1 - packages/cli/src/i18n/no-leaks.test.ts | 2 +- packages/cli/src/planfile.ts | 19 +- packages/cli/src/rules-explain.ts | 11 + packages/core/src/ports/sync.ts | 15 +- packages/mcp/README.md | 2 +- 23 files changed, 1410 insertions(+), 105 deletions(-) create mode 100644 CLAUDE.md create mode 100644 docs/PLAN-v0.4.md create mode 100644 packages/cli/src/docs.test.ts create mode 100644 packages/cli/src/fixes-031.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index a299838..a47da53 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,35 @@ change between minor versions — a regenerated plan can differ. ## [Unreleased] +### Fixed — found by running every command on a fresh directory + +- `review` on a Sunday no longer reports the whole week's volume next to the + number of *remaining* sessions ("52 km across 1 sessions"); it shows what is + left of the week's target. +- A directory without `trainctl.yaml` now points to `trainctl init` instead of + `trainctl plan`, which would only have pointed back to `init`. +- `why` no longer prints "About 0 minutes" for a rest day, no longer states the + session's purpose twice, and lists each rule once with its text and + provenance instead of in two separate sections. +- `log` answers with what the plan had for that day next to what was recorded, + says when an entry falls on a rest day, and returns structured `data` for MCP. +- Messages print `plan/plan.yaml` on every system (Windows printed `plan\plan.yaml`). +- A plan generated by another minor version of the engine is reported in + `today`, `week`, `why`, `review` and `check` (informational; never fails + `--strict`). A plan file with a newer schema is refused with a clear message. +- Rule sources link to `docs/science/FOUNDATIONS.md` on GitHub, pinned to the + release tag — the file is not part of the npm package, so the relative path + in `why`, `desk` and `AGENTS.md` led nowhere after installation. + +### Docs + +- README command tables list `shorten` and the missing flags; tool lists no + longer carry a count that drifts. `docs.test.ts` keeps both READMEs and the + MCP README in step with `bin.ts` and `server.ts`. +- CI examples install the published package (`npx trainctl@`) instead + of cloning the engine and running Node 23. +- `CLAUDE.md` for coding agents working on this repository. + ## [0.3.0] — 2026-09-06 ### Added — everyday coaching workflows diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..f0b98aa --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,30 @@ +# trainctl — notes for coding agents + +Read [CONTRIBUTING.md](CONTRIBUTING.md) first; decisions live in the ADR table +of [SPEC.md](SPEC.md) §10–§11, rule IDs in +[docs/science/FOUNDATIONS.md](docs/science/FOUNDATIONS.md) §10. The current +work plan is [docs/PLAN-v0.4.md](docs/PLAN-v0.4.md). + +Gate before every commit: `pnpm check` (typecheck of all packages + vitest). + +Rules that break things when ignored: + +1. **Native type stripping (Node ≥ 22.18).** Relative imports end in `.ts`; + no parameter properties, enums or namespaces. The repo has no build step; + `pnpm build` only emits `dist/` for publishing (ADR-026). +2. **Handlers return blocks, not colours.** Command handlers in + `packages/cli/src/commands.ts` return semantic blocks (`ui/blocks.ts`) and + `data`; only `bin.ts` renders ANSI. MCP must never receive `\x1b[`. +3. **Both languages, always.** User-facing text goes to the catalogues + (`packages/cli/src/i18n/cli-en.ts` is the type source, `cli-pl.ts` follows; + domain text in `packages/core/src/i18n/`). `cli-i18n.test.ts` and + `no-leaks.test.ts` enforce it. +4. **Every engine constant cites a FOUNDATIONS rule ID** or is commented as an + engineering choice. The engine proposes, it never silently rewrites a plan + (ADR-011, ADR-029). +5. **Secrets and personal data never enter the repo**: no API keys, no corpus + files, no real activity files or `init --from-intervals` output in fixtures. + Remote deletes only touch entries prefixed `trainctl-` (ADR-016). + +Comments and commit messages are written in Polish (Conventional Commits); +README and package descriptions in English, with `README.pl.md` kept in step. diff --git a/README.md b/README.md index 69cd31c..e02a48e 100644 --- a/README.md +++ b/README.md @@ -242,14 +242,15 @@ a key is configured). `trainctl adapt` compares execution with the plan and | `today` | the session for today | `--date` | | `week` | the week, with journal status | `--date`, `-i` (arrow-key browsing) | | `why` | purpose + research rules behind a session | `--date` | -| `log` | record a completed session | `--status`, `--km`, `--time`, `--rpe`, `--note` | +| `log` | record a completed session | `--status`, `--km`, `--time`, `--test-time`, `--rpe`, `--note` | | `shift` | swap two sessions inside a week | `--from`, `--to` (or pick from a list) | | `reschedule` | re-solve the week around busy days | `--block`, `--time`, `--pin`, `--preparation`, `--strategy`, `--apply` | | `adapt` | analyse execution, propose corrections | `--date`, `--prepare`, `--apply ` | -| `review` | pull + adapt + week in one call | `--days` | +| `shorten` | fit one session into the time you have, as a proposal | `--minutes`, `--date`, `--apply ` | +| `review` | pull + adapt + week in one call | `--days`, `--date`, `--prepare` | | `desk` | training windows around office hours | `--heavy` | | `push` | send planned sessions to intervals.icu | `--days`, `--from`, `--to` | -| `pull` | fetch activities and wellness, compare | `--days` | +| `pull` | fetch activities and wellness, compare | `--days`, `--date` | | `export` | `.fit`, `.ics`, printout, race pack | `--what`, `--date` | | `diff` | what a regeneration would change | `--plan ` | | `check` | lint the plan; fails the exit code | `--strict` | @@ -396,12 +397,12 @@ Any MCP client works — the generic form: } ``` -Sixteen tools over the same handlers the CLI uses, so the agent and your +The tools run over the same handlers the CLI uses, so the agent and your terminal can never disagree: `trainctl_plan`, `trainctl_today`, `trainctl_week`, `trainctl_log`, `trainctl_shift`, `trainctl_why`, `trainctl_diff`, `trainctl_check`, `trainctl_init`, `trainctl_push`, `trainctl_pull`, -`trainctl_adapt`, `trainctl_desk`, `trainctl_reschedule`, `trainctl_export`, -`trainctl_review`. +`trainctl_adapt`, `trainctl_shorten`, `trainctl_desk`, `trainctl_reschedule`, +`trainctl_export`, `trainctl_review`. The `AGENTS.md` written by `trainctl init` turns the agent into a coach rather than a command runner: ask before regenerating a plan, ask for context when a diff --git a/README.pl.md b/README.pl.md index 06d5963..83634b9 100644 --- a/README.pl.md +++ b/README.pl.md @@ -245,14 +245,15 @@ Twoimi plecami. | `today` | trening na dziś | `--date` | | `week` | tydzień ze statusem z dziennika | `--date`, `-i` (przeglądanie strzałkami) | | `why` | cel jednostki + reguły z badań | `--date` | -| `log` | zapis wykonania | `--status`, `--km`, `--time`, `--rpe`, `--note` | +| `log` | zapis wykonania | `--status`, `--km`, `--time`, `--test-time`, `--rpe`, `--note` | | `shift` | zamiana dwóch jednostek w tygodniu | `--from`, `--to` (albo wybór z listy) | | `reschedule` | przestawia tydzień wokół zajętych dni | `--block`, `--time`, `--pin`, `--preparation`, `--strategy`, `--apply` | | `adapt` | analiza wykonania → propozycje korekt | `--date`, `--prepare`, `--apply ` | -| `review` | pull + adapt + week w jednym | `--days` | +| `shorten` | dopasowuje jednostkę do dostępnego czasu, jako propozycja | `--minutes`, `--date`, `--apply ` | +| `review` | pull + adapt + week w jednym | `--days`, `--date`, `--prepare` | | `desk` | okna treningowe wokół godzin pracy | `--heavy` | | `push` | wysyła treningi do intervals.icu | `--days`, `--from`, `--to` | -| `pull` | pobiera aktywności i wellness, porównuje | `--days` | +| `pull` | pobiera aktywności i wellness, porównuje | `--days`, `--date` | | `export` | `.fit`, `.ics`, rozpiska, pakiet startowy | `--what`, `--date` | | `diff` | co zmieniłaby regeneracja planu | `--plan ` | | `check` | lint planu; psuje kod wyjścia | `--strict` | @@ -401,12 +402,12 @@ Dowolny klient MCP — postać ogólna: } ``` -Szesnaście narzędzi nad tymi samymi handlerami, z których korzysta CLI, więc +Narzędzia działają nad tymi samymi handlerami, z których korzysta CLI, więc agent i terminal nie mogą się rozjechać: `trainctl_plan`, `trainctl_today`, `trainctl_week`, `trainctl_log`, `trainctl_shift`, `trainctl_why`, `trainctl_diff`, `trainctl_check`, `trainctl_init`, `trainctl_push`, -`trainctl_pull`, `trainctl_adapt`, `trainctl_desk`, `trainctl_reschedule`, -`trainctl_export`, `trainctl_review`. +`trainctl_pull`, `trainctl_adapt`, `trainctl_shorten`, `trainctl_desk`, +`trainctl_reschedule`, `trainctl_export`, `trainctl_review`. `AGENTS.md`, który zostawia `trainctl init`, robi z agenta trenera, a nie wykonawcę komend: pyta przed regeneracją planu, dopytuje o kontekst przy diff --git a/docs/PLAN-v0.4.md b/docs/PLAN-v0.4.md new file mode 100644 index 0000000..bf89e6d --- /dev/null +++ b/docs/PLAN-v0.4.md @@ -0,0 +1,942 @@ +# Plan rozwoju 0.3.1 → 0.6.0 — naprawy i uzupełnienia + +Samowystarczalny plan dla sesji Claude Code, w konwencji [PLAN-v1.1.md](PLAN-v1.1.md). +Kontekst produktu: [SPEC.md](../SPEC.md) (wizja, architektura, ADR-y). Warstwa +naukowa: [docs/science/FOUNDATIONS.md](science/FOUNDATIONS.md). Granice adaptacji +i budżetów czasu: [REVIEWED-ADAPTATION.md](REVIEWED-ADAPTATION.md). + +**Stan wyjściowy (2026-10-21):** wydanie 0.3.0 we wszystkich pięciu paczkach +(npm `latest` = 0.3.0), 641 testów w 46 plikach, typecheck czysty, 17 komend CLI, +17 narzędzi MCP. Wszystkie komendy uruchomione na świeżym katalogu z +`trainctl init --template` (NO_COLOR, Windows, Node 24): żadna nie wywaliła +wyjątku, ale ujawniły usterki opisane w etapie A. + +**Źródła planu:** + +- przegląd kodu i uruchomień z 2026-10-21 (ten dokument jest jego zapisem); +- audyt [2026-09-05](audits/2026-09-05-code-audit.md) — tabela „Funkcje, które + warto rozważyć po naprawach": punkty 3–7 nadal otwarte (powrót po przerwie + i po starcie, repertuar zależny od celu, aktualność kalibracji, tryb bez + zawodów, dziennik siły i kontekst regeneracji); +- SPEC §8 „znane uproszczenia silnika v1" i §9 „ryzyka" (import FIT/GPX jako + mitygacja zależności od intervals.icu — zapowiedziany, nie zrobiony); +- weryfikacja dokumentacji pluginów Claude Code i Codex z 2026-10-21 (linki + w etapie C). + +**Zasada doboru zakresu.** Nie dokładamy „inteligencji planu". Domykamy to, co +czyni „plan jako kod" i „trenera w agencie" wiarygodnymi, w tej kolejności: +stan planu, który nie przepada (B1); CLI, które da się skryptować (B2–B5); +agent, który instaluje się jednym poleceniem (C); dane wykonania bez +pojedynczego punktu zależności (D); a dopiero na końcu silnik — wyłącznie +z dowodem w FOUNDATIONS albo jawną etykietą wartości inżynierskiej (E). + +--- + +## 0. Reguły wykonania (obowiązują w każdym etapie) + +**Higiena sesji** — każdy etap kończy się, w tej kolejności: + +1. `pnpm test` — zielone we wszystkich paczkach; licznik testów rośnie, nigdy + nie maleje (dziś 641). +2. `pnpm typecheck` — czysto w pięciu paczkach. +3. `pnpm build` + lokalna próba instalacji z tarballi (wzorzec joba `dist` + w `.github/workflows/ci.yml`): `npx trainctl --version` w pustym katalogu + jest częścią wydania, nie sprzątaniem po nim (lekcja 0.1.0, ADR-026). +4. `CHANGELOG.md` — sekcja `[Unreleased]` uzupełniona na bieżąco, nie przed + tagiem. +5. `SPEC.md` — tabela etapów §8 i nowe ADR-y w §10/§11; `README.md` + i `README.pl.md` razem (jeden PR, oba pliki). +6. Jeden commit na etap albo na spójny podetap (Conventional Commits, + po polsku, jak w historii repo). + +**Twarde ograniczenia kodu (bez zmian wobec PLAN-v1.1, zaktualizowane progi):** + +- Node ≥ 22.18, natywny type-stripping: importy z rozszerzeniem `.ts`, + **zakaz parameter properties** w klasach, zero kroku budowania w repo; + build (`dist/`) wyłącznie do publikacji (ADR-026). `bin.test.ts` odpala + prawdziwe binarki i ma przechodzić po każdym podetapie. +- `exactOptionalPropertyTypes` + `noUncheckedIndexedAccess`: opcjonalne wejścia + handlerów typować `x?: T | undefined`. +- Warstwa prezentacji (ADR-013): handlery w `packages/cli/src/commands.ts` + zwracają **bloki semantyczne** (`ui/blocks.ts`) i **dane** (`CmdResult.data`); + ANSI dokłada wyłącznie `bin.ts` przez `renderAnsi`. Test braku `\x1b[` + w wyjściu MCP obowiązuje nowe komendy. +- **Oba języki zawsze** (faza 12): każdy nowy tekst trafia do katalogów + `packages/cli/src/i18n/cli-en.ts` (źródło typu) i `cli-pl.ts`, teksty + domenowe do `packages/core/src/i18n/`. Strażnicy: `cli-i18n.test.ts` + (komplet kluczy i arność), `no-leaks.test.ts` (polskie słowa w angielskim + wyjściu), `i18n.test.ts`. +- Każda stała silnika cytuje ID reguły z FOUNDATIONS §10 albo jest jawnie + oznaczona komentarzem jako wartość inżynierska. +- Adaptacja **proponuje, nie przepisuje** (ADR-011); propozycje przez + `prepare` → `apply ` (ADR-029). Nic w tym planie tego nie zmienia — + B1 rozszerza tę ochronę na `plan`. +- Sekrety (ADR-009/009a): klucz wyłącznie z env `TRAINCTL_INTERVALS_API_KEY`, + `.env` albo `.trainctl-secret`; **nigdy w repo, testach ani fixture'ach**. + Testy e2e na żywym koncie tylko lokalnie, z posprzątaniem konta. +- Kasowanie zdalne tylko z prefiksem `trainctl-` (ADR-016). +- Dane osobowe: żadnych realnych plików aktywności, wyników `--from-intervals` + ani fragmentów korpusu w fixture'ach (D1 używa wyłącznie syntetycznych FIT/TCX). + +**Kolejność etapów:** A → B → C → D → E. B1 (chroniona regeneracja) blokuje +E2/E3, bo bez niej każda zmiana celu kasuje historię. C zależy od B2 (`--json`) +tylko w hookach — można je zrównoleglić. D i E są od siebie niezależne. + +--- + +## 1. Mapa etapów + +| Etap | Wydanie | Zakres | Rozmiar | +|---|---|---|---| +| **A** | 0.3.1 (patch) | usterki zaobserwowane na żywo, dokumentacja odjechana od kodu, higiena wydań | S–M, jedna sesja | +| **B** | 0.4.0 | chroniona regeneracja planu; `--json`, `-C`, `TRAINCTL_TODAY`, daty względne, interaktywny `log`, `status`, `--commit`, drobiazgi UX | L, dwie–trzy sesje | +| **C** | 0.4.0 | plugin Claude Code + Codex z jednego katalogu; MCP: zasoby, prompty, narzędzie reguł; `init --agent` | M, jedna–dwie sesje | +| **D** | 0.5.0 | import plików aktywności (FIT/TCX/GPX) jako drugi adapter; intervals.icu głębiej; wellness i RPE z huba cytowane w przeglądzie | L, dwie–trzy sesje | +| **E** | 0.6.0 | budżet czasu tygodnia w generatorze; blok po starcie; plan bez zawodów; siła: dziennik i warianty; `terrain` w kalibracji | XL, każdy podetap z krokiem „najpierw nauka" | + +Rozmiar jest orientacyjny (S = pół sesji, M = sesja, L = dwie–trzy, XL = etap +dzielony na niezależne wydania 0.6.x). + +--- + +## 2. Etap A — naprawy i dokumentacja (0.3.1) + +Każdy punkt: objaw → miejsce → zmiana → test. Żaden nie zmienia zachowania +silnika; wszystkie dotyczą prezentacji, komunikatów i dokumentów. + +### A1. `review` — „przed nami" miesza objętość tygodnia z liczbą pozostałych sesji + +- **Objaw:** `trainctl review --date ` pokazuje „Volume 52 km across + 1 sessions": km z całego tygodnia, sesje tylko pozostałe. +- **Miejsce:** `cmdReview` w `commands.ts`, wywołanie + `ui().review.volumeAhead(week.totalKm, upcoming.length)` (okolice linii 1210). +- **Zmiana:** policzyć `remainingKm` z `upcoming` (suma `workout.distanceKm`, + dla startu `raceDistanceKm`) i pokazać „pozostało X z Y km w N sesjach"; + gdy `upcoming` jest puste, przełączyć się na następny tydzień (ta gałąź już + istnieje — `hasFuture`). Klucz `volumeAhead` dostaje trzeci argument w obu + językach. +- **Test:** `review.test.ts` — data niedzieli z wykonaną częścią tygodnia: + liczba km w sekcji „Ahead" równa sumie pozostałych sesji; data poniedziałku + bez zmian wobec dziś. + +### A2. Katalog bez `trainctl.yaml` odsyła do `plan` zamiast do `init` + +- **Objaw:** w pustym katalogu `today`, `push` itd. mówią „No plan yet — run: + trainctl plan"; `plan` dopiero odpowie „No trainctl.yaml — run: trainctl init". +- **Miejsce:** `loadPlan`/`readPlanDocument` w `planfile.ts` rzuca + `common.noPlan` nie sprawdzając configu. +- **Zmiana:** wspólny `requireWorkspace(cwd)` (nowa funkcja w `planfile.ts` + albo `config.ts`): brak `trainctl.yaml` → `common.missingConfig`; jest config, + brak planu → `common.noPlan`. Wołany z `loadPlan`. +- **Test:** `bin.test.ts` smoke w pustym katalogu (`today`, `week`, `push`) + → komunikat o `init`, kod 1, bez stack trace; `commands.test.ts` dla + katalogu z configiem bez planu → komunikat o `plan`. + +### A3. `why` — dzień wolny „About 0 minutes" i zdublowany cel sesji + +- **Objaw:** dla dnia bez treningu linia „About 0 minutes, including + preparation"; dla treningu zdanie o celu jednostki pojawia się w sekcji + „How this session fits your plan" i ponownie w panelu pod „Origin of the + decision". +- **Miejsce:** `explain-session.ts` (nowe bloki z 0.3.0) + końcówka `cmdWhy` + (panel `kindPurpose` + sekcja „Rules" z 0.1.0). +- **Zmiana:** linia czasu tylko gdy `day.workout` istnieje; panel celu usunąć + (zostaje zdanie w sekcji kontekstu), sekcja „Rules" zostaje jako jedyne + miejsce pełnych treści reguł, a „Origin of the decision" pokazuje tylko + klasyfikację (research / heurystyka) bez powtarzania ID z „Rules" — + albo scalić obie w jedną tabelę `ID · klasa · treść`. +- **Test:** `coach-flows.test.ts` — dzień wolny: brak frazy o minutach; + dzień treningowy: zdanie celu występuje raz (policzyć wystąpienia + `kindPurpose(kind)` w `renderPlain`). + +### A4. `log` jest niemy wobec planu + +- **Objaw:** `log --date --km 5` → „Logged …: done" i nic więcej; + `log` dla treningu też nie odbija planu. +- **Miejsce:** `cmdLog` zwraca `ok(ui().log.saved(date, status))` bez bloków + i bez `data`. +- **Zmiana:** zwracać `okDoc` z blokami: plan (rodzaj, km, szacowany czas) vs + zapis (km, czas, RPE, notatka); gdy dzień w planie jest wolny — + `b.info` „w planie odpoczynek; zapis liczy się jako bieg poza planem"; + gdy brak RPE — `b.hint` z podpowiedzią (`--rpe`). `data`: `{ entry, planned }` + (potrzebne B2 i MCP). +- **Test:** `commands.test.ts` — trzy przypadki (trening, dzień wolny, + `skipped`); `server.test.ts` — `trainctl_log` zwraca `structuredContent.data.entry`. + +### A5. Ścieżki w wyjściu z backslashem na Windows + +- **Objaw:** `plan` drukuje `Saved plan\plan.yaml + plan\PLAN.md`; podpowiedzi + obok mówią `plan/plan.yaml`. +- **Miejsce:** `PLAN_YAML`/`PLAN_MD` w `planfile.ts` (prawdopodobnie `join`) + używane zarówno do I/O, jak i do wyświetlania. +- **Zmiana:** stałe wyświetlane (`PLAN_YAML_DISPLAY = 'plan/plan.yaml'`) osobno + od ścieżek I/O; przejrzeć `export.ts` (tam ścieżki bezwzględne są + zamierzone — zostają). +- **Test:** `bin.test.ts` — wyjście `plan` nie zawiera `\` (CI już biega na + `windows-latest`, więc test jest realny, nie teoretyczny). + +### A6. Plan z innej wersji silnika przechodzi bez słowa + +- **Objaw:** `plan.yaml` niesie `engineVersion` i `schemaVersion`, ale nic ich + nie czyta; CHANGELOG zapowiada zmiany wyjścia między minorami poniżej 1.0. +- **Miejsce:** `StoredPlan.engineVersion?` w `planfile.ts`; zapis w `computePlan`. +- **Zmiana:** `planCompatibility(plan): Block[]` w `planfile.ts`: różny minor + (`0.2.x` vs `0.3.x`) → `b.info` „plan wygenerowany silnikiem 0.2.0, działa + 0.3.1 — `trainctl diff` pokaże, co zmieniłaby regeneracja"; brak pola → + „plan sprzed 0.2.0". Dokładane w `today`, `week`, `why`, `review`, a w `check` + jako ustalenie klasy „file" (warn, bez ID reguły — to nie jest reguła + metodyczna). `schemaVersion` ≠ 1 → błąd z prośbą o regenerację. +- **Test:** `check.test.ts` i `commands.test.ts` z planem o podmienionym + `engineVersion`. + +### A7. README nie zgadza się z kodem + +- Tabela „Commands" bez wiersza `shorten` (flagi: `--minutes`, `--date`, + `--apply `); sekcja „Agent (MCP)": „Sixteen tools" i lista bez + `trainctl_shorten` → siedemnaście, pełna lista (jak w `packages/mcp/README.md`). +- Oba README (`README.md`, `README.pl.md`) w jednym commicie; `CONTRIBUTING.md` + już mówi „17 tools". +- **Test:** rozszerzyć `packaging.test.ts` albo dodać `docs.test.ts`: liczba + narzędzi zarejestrowanych w `server.ts` (regex `registerTool\(\s*'trainctl_`) + równa liczbie `trainctl_*` w obu README i w `packages/mcp/README.md`; każda + komenda z `bin.ts` ma wiersz w tabeli README. + +### A8. Przykłady Actions klonują silnik i używają Node 23 + +- `docs/examples/ci-check.md` i `github-actions-review.md` powstały przed + publikacją na npm: `actions/checkout` silnika do `.trainctl-engine`, + `node-version: '23'`, `corepack enable`. +- **Zmiana:** `actions/setup-node@v5` z `node-version: '22.18'`, + `npx --yes trainctl@0.3.1 check` / `… review --days 7`; usunąć checkout + silnika; zostawić `NO_COLOR=1` i zastrzeżenia o kluczu w sekretach. + Wersję pisać jawnie (pin), z komentarzem, że to ta sama zasada co + „pin the version in your training repo" z README. +- **Test:** `docs.test.ts` — żaden plik w `docs/examples/` nie zawiera + `.trainctl-engine` ani `node-version: '23'`. + +### A9. `why` i `desk` odsyłają do pliku, którego użytkownik npm nie ma + +- **Objaw:** podpowiedzi `sources and parameters: docs/science/FOUNDATIONS.md §10` + (`cli-en.ts` ~213, `rulesHint` ~284, opis narzędzia MCP ~779, `agentsMd`). + Pole `files` paczek nie zawiera `docs/`. +- **Zmiana:** `FOUNDATIONS_URL = https://github.com/dithiothreitol/trainctl/blob/v${packageVersion()}/docs/science/FOUNDATIONS.md` + (pin do tagu wydania, więc link nie dryfuje) w `rules-explain.ts`; + katalogi i18n dostają URL przez argument. Wewnątrz repo (`pnpm trainctl`) + może zostać ścieżka względna — wykryć po istnieniu pliku obok `bin.ts`? + Prościej: zawsze URL. `AGENTS.md` (szablon w `agentsMd`) — ta sama zmiana. +- **Test:** `no-leaks.test.ts` bez zmian (URL nie ma polskich słów); + `bin.test.ts` — `why` zawiera `https://github.com/`. + +### A10. Wydania na GitHubie zatrzymały się na 0.1.1 (działanie właściciela) + +- Tagi `v0.2.0` i `v0.3.0` istnieją, Release tylko dla `v0.1.0` i `v0.1.1`. +- **Zmiana:** `gh release create v0.2.0 --notes-from-tag` (albo treść z + CHANGELOG) i to samo dla `v0.3.0`; `docs/PUBLISHING.md` — do sekwencji + wydania dopisać krok „GitHub Release z sekcji CHANGELOG" zaraz po + `npx @ --version`. + +### A11. `docs/karuzela` — nieskomitowana i z nieaktualnymi liczbami (decyzja właściciela) + +- Katalog jest `untracked`, a `FAKTY.md` podaje 557 testów, 16 komend, + 16 narzędzi (dziś 641 / 17 / 17). README karuzeli deklaruje, że źródła są + w repo, a `out/` nie. +- **Decyzja do podjęcia:** (a) skomitować źródła (`out/` i `node_modules/` + wyklucza lokalny `.gitignore`) i odświeżyć FAKTY przed każdą publikacją; + (b) przenieść do osobnego repo materiałów. Rekomendacja: (a), bo README + karuzeli już tę decyzję opisuje — tylko nie została wykonana. +- Jeśli (a): dodać do `docs.test.ts` kontrolę, że liczby w `FAKTY.md` + (testy, komendy, narzędzia) zgadzają się z kodem — inaczej plik będzie + kłamać przy następnym wydaniu tak samo jak dziś. + +### A12. `CLAUDE.md` dla repozytorium silnika + +- Repo powstaje z agentem, ma `.claude/settings.local.json`, ale nie ma + `CLAUDE.md`. Krótki plik (≤ 40 linii): wskaźniki do `CONTRIBUTING.md`, + `SPEC.md` §10, FOUNDATIONS; pięć reguł z §0 tego planu (type-stripping, + bloki, oba języki, ID reguł, sekrety); `pnpm check` jako bramka. + Bez powielania treści, które już są w CONTRIBUTING. + +### A13. Zamknięcie etapu + +`CHANGELOG` sekcja 0.3.1 („Fixed", „Docs"); SPEC — linia statusu i tabela §8 +(wiersz „A"); tag `v0.3.1`, publikacja pięciu paczek (wersja wspólna — +`packaging.test.ts` tego pilnuje), Release na GitHubie (A10 obowiązuje od razu). + +**DoD etapu A:** wszystkie objawy z A1–A6 mają test, który bez poprawki nie +przechodzi; `docs.test.ts` pilnuje A7, A8 i (jeśli skomitowana) A11; README +w obu językach zgodne z `bin.ts` i `server.ts`; Releases 0.2.0–0.3.1 na GitHubie. + +--- + +## 3. Etap B — CLI, które da się skryptować, i stan, który nie przepada (0.4.0) + +### B1. Chroniona regeneracja planu (`plan` na istniejącym planie) + +**Problem.** `cmdPlan` liczy `computePlan(config, today)` i woła `writePlan` +bez czytania poprzedniego planu. Przepadają: `loadState` (zatwierdzona baza +objętości po `adapt --apply`), `timeBudgets`, dni `pinned`, `timeAdjustment` +po `shorten --apply`, historia `changes`, a także dni przeszłe i zalogowane. +Dokumentacja każe przy nowym wyniku robić „edycja `trainctl.yaml` → `diff` → +`plan`", czyli dokładnie tę ścieżkę. To jedyny punkt planu, który może kogoś +realnie zaskoczyć — stąd pierwsze miejsce w etapie B. + +**Decyzja (kandydat ADR-033).** `trainctl plan` na istniejącym planie wykonuje +**regenerację chronioną**: dni przeszłe (względem zegara, nie `--date`), +zalogowane i przypięte zostają jak były; przyszłość liczy się z `trainctl.yaml` +**i** `loadState` (baza efektywna od `effectiveFrom`), z przeniesieniem +`timeBudgets` i `timeAdjustment` dla dat, które nadal istnieją w planie; +`changes` dostaje wpis `regenerate`. Komenda pokazuje podsumowanie różnic +(wspólny `diffWeeks` z `cmdDiff`) i wynik lintu. Pełne nadpisanie od zera +wymaga jawnego `--fresh` i drukuje, co zostaje porzucone. Nowy katalog bez +planu zachowuje się jak dziś. + +**Implementacja.** + +- `proposals.ts` ma już budowę planu zakotwiczoną w `loadState` i listę + `protectedDates` (poprawka A02/A05 z 0.3.0). Wyciągnąć z niej czystą funkcję + `rebuildPlan(existing: StoredPlan, config, today): { plan, protectedDates, carried, dropped }` + do `planfile.ts` i użyć w trzech miejscach: `prepareProposal`, `cmdPlan`, + `cmdDiff` (dry-run ma pokazywać **tę samą** regenerację, którą wykona `plan` — + inaczej diff i plan się rozjadą). +- `cmdPlan(cwd, { date?, fresh? })`: bez planu → jak dziś; z planem i bez + `--fresh` → `rebuildPlan`, bloki: sekcja „Co się zmieniło" (diff), `b.info` + o liczbie dni chronionych i przeniesionych budżetów, lint; `--fresh` → + `computePlan` + `b.warn` z listą porzuconego stanu. +- MCP `trainctl_plan`: parametr `fresh: z.boolean().optional()`; opis narzędzia + przestaje mówić „OVERWRITES" — mówi „regeneruje przyszłość, chroni przeszłość + i zatwierdzone decyzje; `fresh=true` nadpisuje wszystko". +- `AGENTS.md` (szablon): zasada 1 („nie regeneruj bez pytania") zostaje — + regeneracja dalej zmienia przyszłe tygodnie — ale opis skutków aktualny. + +**Testy** (`commands.test.ts`, `audit-fixes.test.ts`): + +- sekwencja: redukcja → `adapt --apply` → nowy wynik w configu → `plan` → + tygodnie przyszłe trzymają zredukowaną bazę, tempa nowe; +- piny i `timeBudgets` przyszłych dat przeżywają; dni przeszłe i zalogowane + bajt w bajt identyczne; +- `--fresh` kasuje stan i ostrzega; `diff` i `plan` dają ten sam zestaw zmian + (porównać `changes`); +- `bin.test.ts`: smoke `plan` dwa razy pod rząd → drugi raz „bez zmian". + +### B2. `--json` — dane zamiast tekstu + +- `bin.ts`: globalna opcja `--json`; `print()` wtedy drukuje + `JSON.stringify({ code, data, output: renderPlain(blocks) })`, kod wyjścia + jak dotąd. Bez ANSI, bez spinnera (spinner na stderr już nie przeszkadza, + ale w trybie `--json` wyłączyć). +- Przegląd handlerów: każdy zwraca `data` (dziś część zwraca `ok(text)` — + `cmdLog` z A4, `cmdInit`, `cmdShift`). Schemat `data` jest **kontraktem** + tylko w zakresie pól już używanych przez MCP (`structuredContent.data`); + resztę oznaczyć w README jako „kształt może się zmienić do 1.0". +- **Test:** `bin.test.ts` — `today --json`, `week --json`, `check --json` + parsują się, nie zawierają `\x1b[`, `code` zgodny z kodem procesu; + `no-leaks.test.ts` obejmuje tryb `--json`. + +### B3. `-C ` i `TRAINCTL_DIR` w CLI + +- Dziś CLI działa wyłącznie na `process.cwd()`; MCP ma `TRAINCTL_DIR`. +- `bin.ts`: katalog roboczy = `-C`/`--dir` > `TRAINCTL_DIR` > cwd, ustalany + **przed** `loadEnvFile` i `readConfigLanguage` (tak jak `--lang` jest dziś + czytany z `argv` przed zbudowaniem drzewa komend). Ścieżki względne w + `-C` liczone od cwd procesu. +- Przykłady cron/Actions w docs przestają potrzebować `cd`. +- **Test:** `bin.test.ts` — uruchomienie z innego katalogu z `-C` + i z `TRAINCTL_DIR`; `.env` czytany z katalogu docelowego, nie z cwd. + +### B4. Jawny zegar symulacji `TRAINCTL_TODAY` (kandydat ADR-034) + +- **Problem.** Po poprawce A05 ochrona przeszłości idzie po prawdziwej dacie + (`localToday()`), a `--date` jest tylko selektorem. To słuszne — ale na + katalogu demo z planem w przeszłości `shorten` i `reschedule` odmawiają, + więc nie da się odtworzyć bloków z `docs/karuzela/FAKTY.md`, screenshotów + do README ani ręcznie przetestować scenariusza „za trzy tygodnie". +- **Decyzja.** `localToday()` honoruje `TRAINCTL_TODAY=YYYY-MM-DD` (walidacja + `parseIso`, błąd przy złym formacie). Gdy zmienna jest ustawiona, **każde** + wyjście zaczyna się blokiem `b.warn` „data symulowana: 2026-08-16" + (CLI i MCP — w MCP dodatkowo linia na stderr przy starcie). Symulacja nigdy + nie jest cicha; propozycje zapisane pod symulowaną datą noszą ją w pliku + (`createdFor`), żeby `apply` pod prawdziwą datą je odrzucił tak samo jak + dziś odrzuca zmianę dnia. +- Testy mogą od tej pory używać zmiennej zamiast podmieniać zegar — tam, + gdzie dziś mockują `Date`, zostawić jak jest; nowe testy używają env. +- **Test:** `bin.test.ts` — z `TRAINCTL_TODAY` ustawionym na dzień z planu + `shorten --minutes 40` przechodzi i drukuje ostrzeżenie o symulacji; + propozycja przygotowana pod symulacją nie aplikuje się bez tej samej + wartości zmiennej. + +### B5. Daty względne w CLI + +- `packages/core/src/util/dates.ts`: `resolveDate(input, today, locale)`: + ISO; `today|tomorrow|yesterday`; `+N|-N` (dni); nazwy dni `mon…sun` + (najbliższy w przód dla `--to`/`--block`, w tył dla `log --date`? — nie: + **zawsze najbliższy w przyszłości**, poza `log`, gdzie najbliższy w + przeszłości; zasada opisana w `help`); aliasy polskie `dziś|jutro|wczoraj`, + `pn wt śr czw pt sob nd` (z `wizard.dayCodes`, z normalizacją diakrytyków jak + w `parseDaysInput`). +- Zastosować w `bin.ts` do wszystkich `--date`, `--from`, `--to`, `--block`, + `--pin`, `--time YYYY-MM-DD=min`. **MCP zostaje przy ISO** (agent liczy + daty sam; `isoDate()` bez zmian) — unikamy dwuznaczności w narzędziu. +- **Test:** `dates.test.ts` — macierz wejść × `today`; `bin.test.ts` — + `log --date yesterday`, `reschedule --block thu`. + +### B6. Interaktywny `log` w TTY + +- Najczęstsza komenda dnia jest jedyną codzienną bez trybu bez flag + (ADR-015: interaktywność jako dodatek). `trainctl log` bez argumentów + w TTY: `select` daty z ostatnich 7 dni (etykieta: data · rodzaj · km · + status z dziennika), potem pytania `readline/promises` jak w `ui/wizard.ts`: + status (done/skipped/modified, Enter = done), km (domyślnie planowane), + czas (`MM:SS`, Enter = pomiń), RPE 1–10, notatka. Na końcu `cmdLog` + i jego bloki (A4). Poza TTY — jak dziś (komunikat, jak podać flagi). +- Kod w `interactive.ts` (`runLogPrompt`), parsery współdzielone z wizardem + (`parseTimeInput`), teksty w `ui().log.prompt*` w obu językach. +- **Test:** `interactive.test.ts` — parsowanie odpowiedzi i domyślne wartości + bez TTY (wzorzec `renderChoices` z `select.test.ts`); `bin.test.ts` — + poza TTY `log` bez flag daje czytelną instrukcję, kod 1. + +### B7. `trainctl status` — jeden ekran stanu katalogu + +- `cmdStatus(cwd)`, read-only, zwraca bloki i `data`: + - **config:** istnieje? waliduje się? (lista błędów `loadConfig` zamiast + wyjątku), język; + - **plan:** `generatedAt`, `engineVersion` vs `packageVersion()` (A6), + tygodnie/sesje, cel i dni do startu, `loadState` jeśli jest; + - **kalibracja:** wybrany wynik, wiek w dniach, liczba wykluczonych; + - **klucz:** źródło (`env` / `.env` / `.trainctl-secret` / brak) i czy `.env` + jest ignorowany przez gita (wynik `loadEnvFile`); + - **sync:** `pulledAt`, zakres, liczba aktywności z `dataWithheld`; + - **dziennik:** liczba wpisów, ostatni wpis, dni bez potwierdzenia + w bieżącym tygodniu (`buildExecution` → `unknown`); + - **propozycje:** lista `plan/proposals/*.json` — id, rodzaj (adapt / + shorten), data utworzenia, **ważna dziś / wygasła** (reguła „następny + lokalny dzień kalendarzowy"), jedno zdanie zmian; dziś nic tego nie + listuje i zgubiony ID trzeba szukać w plikach; + - **git:** w repozytorium? zmiany niezacommitowane w `trainctl.yaml`, + `plan/`, `log.jsonl` (`spawnSync('git', ['status','--porcelain', …])`, + cicho pomijane bez gita). +- MCP: `trainctl_status` (readOnlyHint: true) — agent zaczyna od niego + zamiast od trzech wywołań. Licznik narzędzi: 18 (`server.test.ts`). +- Opcjonalnie `adapt --discard ` / `shorten --discard ` do sprzątania + wygasłych propozycji; bez tego `status` tylko je pokazuje. +- **Test:** `commands.test.ts` — katalog pusty, z configiem, z planem + i propozycją ważną oraz wygasłą (z `TRAINCTL_TODAY`); `bin.test.ts` smoke. + +### B8. `--commit` na operacjach piszących (kandydat ADR-040) + +- AGENTS.md każe „commit after every change to the plan"; narzędzie może to + domknąć bez stawania się klientem gita. Flaga `--commit [wiadomość]` na: + `plan`, `log`, `shift`, `reschedule --apply`, `adapt --apply`, + `shorten --apply`, `init`. Po udanym zapisie: `git add` **tylko plików, + które komenda zmieniła** (`trainctl.yaml`, `plan/**`, `log.jsonl`, + `AGENTS.md`, `.gitignore`), potem `git commit -m` z wiadomością domyślną + w języku katalogu (np. `trainctl shift: 2026-08-13 ↔ 2026-08-15`). + Nigdy `.env`, `.trainctl-secret`, `sync.json`. +- Bez gita w katalogu → `b.info` i kod 0 (operacja się udała, commit nie). + Brak tożsamości gita → komunikat gita przepuszczony, kod 0. +- MCP: parametr `commit: z.boolean().optional()` na tych samych narzędziach; + opis mówi wprost, że to zapis do historii użytkownika. +- **Test:** `commands.test.ts` z tymczasowym repo (`git init`, + `-c user.name/email` w `spawnSync`): commit zawiera tylko oczekiwane + pliki; katalog bez gita → informacja, kod 0; Windows — `EBUSY` retry jak + w istniejących testach sprzątania. + +### B9. `today`: czas i „jutro" + +- Panel treningu dostaje linię szacowanego czasu (ten sam + `estimateWorkoutMinutes` + siła, który już zasila `data.estimatedMinutes` + i `why`) oraz linię „następna sesja: data · rodzaj · km" (szukana w przód + przez `findDay`). Dla biegacza zza biurka to dwie najważniejsze liczby dnia. +- **Test:** `commands.test.ts` — obecność linii i poprawność następnej sesji + przez dzień wolny i przez granicę tygodnia. + +### B10. Uzupełnienia powłoki: `completion` + +- `trainctl completion bash|zsh|fish|pwsh` — generator statycznych skryptów + z drzewa `program.commands` (nazwy komend i opcji), zero zależności. + Instrukcja w `help completion` i README („Install"). +- **Test:** snapshot każdej powłoki zawiera wszystkie komendy z `bin.ts` + (porównanie z listą w czasie testu, nie z zamrożoną). + +### B11. Przykłady w `help ` + +- `addHelpText('after', ui().examples.)` dla komend z nietrywialnymi + flagami: `log`, `reschedule`, `shorten`, `adapt`, `review`, `export`, + `diff`, `push`/`pull`. Dwa–trzy przykłady, oba języki. +- **Test:** `no-leaks.test.ts` obejmuje `help ` dla każdej komendy. + +### B12. Kody wyjścia (opcjonalne, małe) + +- Dziś wszystko niezerowe to 1. Rozróżnić: 1 błąd danych/konfiguracji, + 2 błąd użycia (commander `exitOverride`), 3 odmowa ochronna (przeszłość, + dzień startu, pin, wygasła propozycja). Zmiana widoczna dla skryptów + i hooków z etapu C (hook `check` może odróżnić „plan niespójny" od „brak + planu"). Udokumentować w README „Commands". Jeśli nie wejdzie w 0.4.0 — + nie blokuje nic innego. + +### B13. Zamknięcie etapu + +CHANGELOG 0.4.0 („Added", „Changed" — B1 to zmiana zachowania, opisać wprost); +SPEC: ADR-033, 034, 040 w §11, tabela §8; README „Commands" (flagi globalne +`--json`, `-C`, `--lang`; `status`; `completion`), sekcja „Plan as code" +(regeneracja chroniona, `--fresh`, `--commit`); `REVIEWED-ADAPTATION.md` +(interakcja `plan` z `loadState`); `AGENTS.md` szablon (zasada 1). + +**DoD etapu B:** sekwencja z B1 ma test; `--json` na każdej komendzie bez ANSI; +`TRAINCTL_TODAY` widoczny w wyjściu i respektowany przez propozycje; `status` +listuje propozycje z terminem; 18 narzędzi MCP; `bin.test.ts` zielony na +Windows i Linux. + +--- + +## 4. Etap C — plugin Claude Code i Codex, MCP poza narzędziami (0.4.0) + +**Cel.** „Trener w agencie" instaluje się jednym poleceniem zamiast ręcznego +`claude mcp add` i kopiowania AGENTS.md. Jeden katalog pluginu obsługuje oba +agenty: Codex czyta także starsze `.claude-plugin/marketplace.json` i podaje +hookom `CLAUDE_PLUGIN_ROOT` dla zgodności, więc format Claude Code jest +wspólnym mianownikiem. + +**Fakty zweryfikowane 2026-10-21** (do ponownego sprawdzenia przed wydaniem — +oba ekosystemy zmieniają się co miesiąc): + +| | Claude Code | Codex | +|---|---|---| +| manifest | `.claude-plugin/plugin.json`, opcjonalny, wymagane tylko `name` | `.codex-plugin/plugin.json` (CLI ≥ 0.117, III 2026) albo przenośny `plugin.json` w korzeniu z `extensions.com.openai` | +| skille | `skills//SKILL.md` → `/trainctl:`; `commands/*.md` to format starszy | `skills//SKILL.md`, wskazane w manifeście polem `skills` | +| MCP | `.mcp.json` w korzeniu pluginu; podstawianie `${CLAUDE_PLUGIN_ROOT}`, `${CLAUDE_PROJECT_DIR}`, `${VAR}`/`${VAR:-default}`; serwer startuje z każdą sesją z włączonym pluginem | manifest `mcpServers: "./"`; `.mcp.json` z `command/args/env` i `${VAR}` (opis społeczności — **do weryfikacji**); przenośny `mcp.json` dokumentuje transport HTTP z polem `type` | +| hooki | `hooks/hooks.json` (`SessionStart`, `PostToolUse` …); `CLAUDE.md` z korzenia pluginu **nie** jest ładowany | `hooks/hooks.json` tylko dla ręcznie instalowanych pluginów desktopowych; pluginy z hookami nie wchodzą do publicznego katalogu | +| marketplace | `.claude-plugin/marketplace.json` w repo; repo może być jednocześnie marketplace i pluginem (`"source": "./…"`) | `.agents/plugins/marketplace.json` w repo albo `~/.agents/plugins/`; czyta też `.claude-plugin/marketplace.json` | +| instalacja | `/plugin marketplace add dithiothreitol/trainctl` + `/plugin install trainctl@trainctl`; jednym krokiem `/plugin install trainctl --marketplace dithiothreitol/trainctl`; źródło pluginu może być też `npm` | `codex plugin marketplace add dithiothreitol/trainctl`, potem `/plugins` w sesji | +| włączenie per repo | `.claude/settings.json` z `extraKnownMarketplaces` + `enabledPlugins` | `.codex/config.toml`: `[plugins."trainctl@trainctl"] enabled = true` (tylko zaufane projekty) | +| aktywacja warunkowa „tylko gdy jest trainctl.yaml" | **brak** — plugin jest włączony globalnie albo per scope | brak | +| katalog oficjalny | marketplace Anthropic nie przyjmuje zgłoszeń; katalog claude.ai wymaga płatnego planu; własny marketplace darmowy | portal zgłoszeń; pluginy z hookami wykluczone | + +Źródła: dokumentacja Claude Code (plugins: overview, components, +manifest-reference, marketplace-reference, install, loading, publish; mcp; +hooks-guide), dokumentacja Codex (`developers.openai.com/codex/plugins`, +strona „Package your plugin"), opisy społeczności Codex (plugin system, +marketplace) — linki w CHANGELOG przy wydaniu. + +### C1. Struktura: `plugin/` w korzeniu repo + +``` +plugin/ + .claude-plugin/plugin.json # name, version (= wersja paczek), description, author, homepage, repository, license, keywords + .codex-plugin/plugin.json # name, version, description, skills: "./skills/", mcpServers: "./codex.mcp.json" + .mcp.json # Claude Code + codex.mcp.json # Codex (bez ${CLAUDE_PROJECT_DIR}; serwer używa cwd) + skills/ + coach/SKILL.md # persona = treść AGENTS.md (EN), opis wyzwalający przy tematach biegowych + review/SKILL.md # /trainctl:review — rytuał poniedziałkowy + debrief/SKILL.md # /trainctl:debrief — odprawa po treningu (RPE, notatka, jedno pytanie o kontekst) + shorten/SKILL.md # /trainctl:shorten — „mam dziś tylko N minut" + what-if/SKILL.md # /trainctl:what-if — scenariusz na gałęzi + diff + hooks/hooks.json + scripts/ + session-start.mjs # drukuje AGENTS.md katalogu (albo krótką personę), milczy bez trainctl.yaml + check-plan.mjs # PostToolUse Edit|Write: gdy file_path kończy się na plan/plan.yaml → trainctl check + README.md +``` + +`.mcp.json` (Claude Code): + +```json +{ + "mcpServers": { + "trainctl": { + "command": "npx", + "args": ["-y", "trainctl-mcp@0.4.0"], + "env": { "TRAINCTL_DIR": "${CLAUDE_PROJECT_DIR}" } + } + } +} +``` + +`codex.mcp.json` — to samo bez `env`: `trainctl-mcp` już dziś używa +`process.cwd()`, gdy `TRAINCTL_DIR` nie jest ustawione (`packages/mcp/src/bin.ts`). +**Do weryfikacji w implementacji:** czy Codex uruchamia serwer MCP pluginu +z katalogu projektu; jeśli nie — udokumentować `codex mcp add` z jawnym +`TRAINCTL_DIR` jako ścieżkę zapasową. + +Skrypty hooków w Node, nie w sh — Node jest gwarantowany (wymaganie +`trainctl`), a hooki muszą działać także na Windows: + +```json +{ + "hooks": { + "SessionStart": [{ "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/session-start.mjs\"" }] }], + "PostToolUse": [{ "matcher": "Edit|Write", "hooks": [{ "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/check-plan.mjs\"" }] }] + } +} +``` + +`session-start.mjs`: jeśli w `CLAUDE_PROJECT_DIR` (albo cwd) nie ma +`trainctl.yaml` — `exit 0` bez wyjścia (jedyna dostępna namiastka aktywacji +warunkowej); jeśli jest — drukuje `AGENTS.md` z katalogu (gdy istnieje), +inaczej skróconą personę z pluginu. `check-plan.mjs`: czyta JSON ze stdin, +`tool_input.file_path`; gdy ścieżka kończy się na `plan/plan.yaml` — +`npx -y trainctl@ check --json` i przekazuje wynik; `code` 1 +→ komunikat do agenta („plik niespójny — pokaż ustalenia użytkownikowi"), +ostrzeżenia → relacja z ID reguł. Bez `--json` z B2 hook parsowałby tekst — +stąd zależność C od B2. + +### C2. Skille — cienkie, odsyłające do narzędzi, bez własnej logiki treningowej + +Każdy `SKILL.md`: frontmatter `name`, `description` (kiedy się włączać), +treść: które narzędzie wywołać, czego **nie** robić (propose-don't-apply, +nie wymyślać liczb, nie regenerować bez pytania), co pokazać użytkownikowi. +Treść pochodzi z rytuałów `agentsMd` (`cli-en.ts`) — **nie kopiować ręcznie**: +skrypt `tools/plugin/render-skills.mjs` generuje `skills/*/SKILL.md` z katalogu +i18n, a test porównuje wynik z plikami w repo (dryf = czerwony test). Język +skilli: angielski; wyjście narzędzi i tak idzie w języku katalogu +treningowego, więc polski użytkownik dostaje polskie treści z MCP. + +### C3. Marketplace: repo jest marketplace'em + +`/.claude-plugin/marketplace.json` (korzeń repo): + +```json +{ + "name": "trainctl", + "owner": { "name": "Dariusz Tyszka" }, + "plugins": [{ "name": "trainctl", "source": "./plugin", "description": "Running coach: plan as code, coach as your agent’s tool", "category": "productivity" }] +} +``` + +`/.agents/plugins/marketplace.json` dla Codex — ten sam wpis w jego schemacie +(`source: { "source": "local", "path": "./plugin" }`, `policy`, `category`). +Publikacja = tag w repo (plugin ciągnie `trainctl-mcp@` z npm). +Alternatywa (źródło `npm` w marketplace Claude Code) zostaje w zapasie — +wymagałaby szóstej paczki. + +### C4. `trainctl init --agent claude|codex|all` (kandydat ADR-036) + +- `init` dopisuje do katalogu treningowego pliki integracji **tylko na jawną + flagę** (nic po cichu — ta sama zasada co ADR-019): + - `claude`: `.claude/settings.json` z `extraKnownMarketplaces` (github + `dithiothreitol/trainctl`) i `enabledPlugins: { "trainctl@trainctl": true }` + oraz `.mcp.json` katalogu jako ścieżka zapasowa bez pluginu + (`claude mcp add` w jednym pliku); + - `codex`: `.codex/config.toml` z `[plugins."trainctl@trainctl"] enabled = true` + i `[mcp_servers.trainctl]` jako zapas; + - istniejące pliki nie są nadpisywane (jak `AGENTS.md`); `.gitignore` bez + zmian — te pliki **mają** być w repo treningowym. +- Kreator (`ui/wizard.ts`) dostaje ostatnie pytanie „Którego agenta używasz?" + z opcją „żadnego". +- Bez flagi `init` drukuje jedną podpowiedź: `trainctl init --agent claude`. +- **Test:** `init-*.test.ts` — zawartość plików, idempotencja, brak nadpisania; + `no-leaks.test.ts` — pliki konfiguracyjne agentów bez polskich słów + (to pliki techniczne). + +### C5. MCP: zasoby, prompty, narzędzie reguł + +- **Zasoby** (`server.registerResource`): `trainctl://plan/PLAN.md`, + `trainctl://config` (`trainctl.yaml`), `trainctl://agents` (`AGENTS.md`), + `trainctl://rules/{id}` (template). Klient pokazuje plan bez wywołania + narzędzia; zasoby są read-only z definicji. +- **Prompty** (`server.registerPrompt`): `weekly-review` (argument `date?`), + `debrief` (argument `date?`) — treść z tych samych rytuałów co skille. +- **Narzędzie** `trainctl_rule(id)`: `ruleExplain` + `ruleEvidence` + z `rules-explain.ts` + URL FOUNDATIONS (A9) + klasyfikacja (research / + heurystyka). Agent nie ma FOUNDATIONS na dysku — dziś `why` odsyła do pliku, + którego nie widzi. Licznik narzędzi: 19 (`server.test.ts`). +- **Test:** `server.test.ts` — klient in-memory listuje zasoby i prompty, + czyta `trainctl://plan/PLAN.md` równy plikowi, `trainctl_rule('I-7')` + zwraca tekst i URL; brak ANSI (istniejący strażnik obejmuje nowe wyjścia). + +### C6. Testy i CI pluginu + +- `plugin.test.ts` (w `packages/cli` albo nowy `tests/plugin/`): oba manifesty + parsują się; `version` równa wersji paczek (rozszerzyć `packaging.test.ts`); + `.mcp.json`/`codex.mcp.json` wskazują `trainctl-mcp@`; + każdy `SKILL.md` ma frontmatter `name` i `description`; `hooks.json` wskazuje + istniejące skrypty; skille zgodne z generatorem (C2); skrypty hooków + przechodzą próbę z fałszywym stdin (`check-plan.mjs` na pliku spoza planu → + cisza, kod 0; na `plan/plan.yaml` → wywołanie `check`). +- CI: job `plugin` — `node tools/plugin/render-skills.mjs --check` + i `plugin.test.ts`; `claude plugin validate ./plugin` jako krok lokalny + w `CONTRIBUTING.md` (CLI Claude nie ma w runnerze). +- Wersja w `.mcp.json` i manifestach podnoszona razem z paczkami — + dopisać do sekwencji wydania w `docs/PUBLISHING.md`. + +### C7. Dokumentacja + +- README (oba): sekcja „Agent (MCP)" zaczyna się od pluginu (dwa polecenia), + ręczne `claude mcp add` schodzi do akapitu „bez pluginu"; sekcja dla Codex + (`codex plugin marketplace add`, `/plugins`, AGENTS.md czytany natywnie). +- `docs/integrations/agents.md`: instalacja, co robi hook, jak wyłączyć, + ograniczenia (brak aktywacji warunkowej, hooki a katalog publiczny OpenAI), + wersjonowanie. +- `plugin/README.md` dla przeglądających repo marketplace'u. + +**DoD etapu C:** `/plugin install trainctl --marketplace dithiothreitol/trainctl` +w czystym katalogu treningowym daje działające narzędzia `trainctl_*`, +skille `/trainctl:*` i hook `check` (próba ręczna, zapisana w +`docs/integrations/agents.md` z datą); Codex: `codex plugin marketplace add` ++ `/plugins` — próba ręczna z datą i listą tego, co nie zadziałało; +`init --agent` z testami; 19 narzędzi MCP, zasoby i prompty z testami; +ADR-036 w SPEC. + +--- + +## 5. Etap D — integracje (0.5.0) + +### D1. Import plików aktywności: FIT / TCX / GPX (kandydat ADR-037) + +**Cel.** Drugi adapter portu — bez konta w serwisie. SPEC §9 nazywa to +mitygacją zależności od intervals.icu; dodatkowo obchodzi ograniczenie +Stravy (Garmin Connect, Coros i Polar eksportują pliki lokalnie). + +**Port.** `SyncProvider` łączy odczyt (`listActivities`, `listWellness`) +z zapisem (`pushWorkouts`, `listPlannedWorkouts`, `deleteWorkout`). Adapter +plikowy jest pull-only. Dwie opcje: (a) rozdzielić port na `ActivitySource` +i `WorkoutSink`, `SyncProvider = oba`; (b) `FileProvider implements SyncProvider` +z metodami zapisu rzucającymi jawny błąd „ten adapter nie wysyła". Rekomendacja: +(a) — `review` i `pull` potrzebują tylko źródła, `push` tylko ujścia; typy +powiedzą kompilatorem, która komenda czego wymaga. Zmiana w +`packages/core/src/ports/sync.ts`, adapter intervals.icu implementuje oba. + +**Paczka.** `trainctl-sync-files` (szósta paczka, ten sam szablon manifestu +co `trainctl-sync-intervalsicu`): + +- `fit.ts`: dekoder **plików aktywności** FIT (dziś mamy tylko koder + treningów w `trainctl-export/fit.ts`): nagłówek, rekordy definicji + i danych, little/big endian, CRC; interesują nas komunikaty `session` + (sport, sub_sport, start_time, total_distance, total_timer_time, + total_elapsed_time, avg_heart_rate, total_ascent) i `file_id`; `record` + tylko gdy brak `session` (suma z punktów). Bez SDK Garmina (ADR-017 — + ta sama logika co przy koderze). +- `tcx.ts`: XML bez zależności — minimalny parser elementów `Activity Sport`, + `Lap StartTime`, `TotalTimeSeconds`, `DistanceMeters`, `AverageHeartRateBpm`. +- `gpx.ts`: `trkpt lat/lon/time`; dystans z haversine, czas z pierwszego + i ostatniego punktu; sport z `type` albo heurystyka tempa (jawnie oznaczona + jako wartość inżynierska, bez wpływu na kalibrację). +- `provider.ts`: `FileActivitySource({ dir })` czyta katalog (rekurencyjnie, + `.fit/.FIT/.tcx/.gpx`), normalizuje do `SyncedActivity` (`externalId` = + hash zawartości, `source: 'file'`), filtruje po `oldest/newest`. + +**CLI/MCP.** `trainctl.yaml`: sekcja `sync: { files: ./activities }` +(opcjonalna). `pull --from ` jednorazowo; `review` i `adapt` +czytają z `sync.json` jak dotąd — `writeSnapshot` scala po `externalId`, +więc źródła mogą współistnieć (klucz + katalog). `status` (B7) pokazuje +źródła. + +**Testy.** Fixture'y **syntetyczne**: generator testowy FIT (session + file_id) +w `fit.test.ts`, ręcznie napisane TCX/GPX; weryfikacja dekodera FIT na +pliku z niezależnego kodera (np. zapisany trening z `trainctl-export` jako +kontrola CRC/nagłówka) — bez realnych aktywności użytkownika w repo. +`execution.ts` bez zmian (`isRunningActivity` po `type`) — test, że FIT z +`sport=running` wpada, `cycling` nie, a plik bez dystansu daje `dataWithheld`. + +**Docs.** `docs/integrations/files.md`: skąd wziąć pliki (Garmin Connect +eksport aktywności, Coros, Polar Flow), ograniczenia (brak wellness, brak +RPE), prywatność (pliki zostają lokalnie; `activities/` do `.gitignore` +przez `init`? — **tak**, pliki aktywności zawierają trasy GPS). + +### D2. intervals.icu głębiej + +- **Starty jako zdarzenia startowe.** Cel A i `tuneUpRaces` wysyłane + z `category: RACE_A | RACE_B | RACE_C` zamiast `WORKOUT` (intervals.icu + rozpoznaje je w kalendarzu i wykresie formy). Wymaga weryfikacji na żywym + koncie: czy `events/bulk?upsert=true` przyjmuje te kategorie i czy + `external_id` działa tak samo (prefiks `trainctl-` i kasowanie — ADR-016 + bez zmian). Wynik do `docs/integrations/intervalsicu.md` §2c. +- **Siła jako osobne zdarzenie** (`type: WeightTraining`, opis sesji, + `moving_time` = `durationMin`), nadal nie jako trening biegowy (ADR-023). + `toPushableWorkout` dostaje drugą funkcję `toPushableStrength`; + `PushableWorkout.sport` rozszerzony o `'strength'`. +- **Cel czasu** obok `distance_target`: `moving_time` z `estimateWorkoutMinutes` + (pole do zweryfikowania w Swaggerze). +- **Test:** `provider.test.ts` na nagranych odpowiedziach; `workout-syntax.test.ts` + dla siły; e2e lokalnie z posprzątaniem konta. + +### D3. Wellness i RPE z huba cytowane w przeglądzie (zgodnie z ADR-027) + +- `sync.json` ma `wellness` (tętno spoczynkowe, HRV, sen, masa, CTL/ATL) + i `activities[].rpe` (`icu_rpe`) — nic ich nie pokazuje. +- `review`: sekcja „Kontekst z zegarka" — per dzień okna: tętno spoczynkowe, + sen (h:mm), masa jeśli jest; **bez progów, średnich i wniosków**, dokładnie + jak sekcja „Jak się biegało". RPE z huba w „Jak się biegało" tylko gdy + dziennik nie ma RPE dla tej daty, z etykietą źródła („RPE 6 · intervals.icu"). + CTL/ATL **nie** pokazujemy (P-4: deskryptory, nie guardraile — a pokazane + obok planu zaczną sterować decyzjami). +- **Test:** `review.test.ts` — snapshot z wellness → sekcja; bez → brak sekcji; + RPE z dziennika wygrywa nad hubem. + +### D4. Zamknięcie etapu + +CHANGELOG 0.5.0; SPEC: ADR-037 (port rozdzielony, adapter plikowy), §7 +„Integracje" (druga ścieżka), §9 (ryzyko zależności — zmitygowane); +`packaging.test.ts` i job `dist` obejmują szóstą paczkę; `SECURITY.md` +(„jeden host wyjściowy" nadal prawdziwe — pliki nie wychodzą). + +**DoD etapu D:** `pull --from ./activities` na syntetycznych FIT/TCX/GPX daje +`sync.json` zgodny z tym z intervals.icu dla tych samych danych; `review` +działa bez klucza na plikach; starty i siła widoczne w kalendarzu intervals.icu +(próba e2e z datą w docs); wellness w przeglądzie wyłącznie cytowane. + +--- + +## 6. Etap E — silnik: najpierw nauka, potem kod (0.6.x) + +Każdy podetap zaczyna się od FOUNDATIONS (nowe reguły albo jawne „wartość +inżynierska") i, gdzie to możliwe, od pomiaru w korpusie (`tools/corpus/`). +Podetapy są niezależne — mogą wyjść jako 0.6.0, 0.6.1 … w kolejności +gotowości. Backtest (`backtest.test.ts`) ma zostać Δ0 dla akcentów i sesji. + +### E1. Budżet czasu tygodnia w generatorze + +- **Dziś:** budżety minut tylko per data w `reschedule --time` i `shorten`; + generator planuje w km, a biegacz zza biurka ma ograniczenie w minutach. +- **Nauka:** reguła E-1 (odcięcia inżynierskie skracania) już istnieje; + dodać E-2 „plan mieści się w zadeklarowanym czasie" jako wartość inżynierską + (konwersja km → min po tempie easy z `estimateWorkoutMinutes`, z zapasem + przygotowania 15 min jak w `shorten`). +- **Config:** `athlete.time: { weeklyMinutes?, weekday?: minutes, weekend?: minutes }` + (walidacja w `config.ts`). +- **Silnik:** `macrocycle.ts` — `targetKm` ograniczone przez czas (sufit + obok `peakWeeklyKm`), z `feasibilityWarnings` gdy rekomendowana objętość + dla dystansu (P-7/P-8) nie mieści się w czasie; `microcycle.ts` — rozkład + dni z limitem minut per dzień używa istniejących wariantów z `shorten.ts` + zamiast nowych konstrukcji. +- **Testy:** `time-budgets.test.ts` — profil 45 km z 4 h tygodniowo → plan + mieści się w czasie, lint I-5 trzyma ≥ 75 % easy, ostrzeżenie o niewykonalnej + objętości rekomendowanej; backtest Δ0 bez sekcji `time`. + +### E2. Życie po starcie: blok przejściowy i następny cel (kandydat ADR-038) + +- **Dziś:** makrocykl kończy się tygodniem celu; dzień po starcie `today` + mówi „poza planem", `adapt` odmawia propozycji przy `post-race-recovery`. +- **Nauka:** FOUNDATIONS R-1/R-2 (protokół po starcie) istnieją; zmierzyć + w korpusie, jak trener planował 2–3 tygodnie po startach A (`tools/corpus/` + — nowy skrypt `post_race_profile.py` w stylu `long_run_profile.py`): + objętość względem ostatniego tygodnia budowania, liczba sesji, kiedy wraca + pierwszy akcent. Wynik → reguły R-3…R-5 albo jawnie inżynierskie. +- **Silnik:** `macrocycle.ts` dokłada `transition` (nowa `MacroPhase`) — + 2–3 tygodnie po starcie: tylko easy, objętość wg korpusu/R-x, zero akcentów, + siła wraca od drugiego tygodnia (F-13 analogicznie do taperu). Kompilator + wskaże wszystkie switche po `MacroPhase` (lint, PLAN.md, eksport, i18n). +- **CLI:** `today` w bloku przejściowym pokazuje cel bloku i podpowiedź + „następny cel: edytuj `goal` w trainctl.yaml → `trainctl plan`" (B1 + zachowa historię); `plan` z nowym celem i datą startu w przeszłości + zaczyna progresję od `loadState`/ostatnich tygodni, nie od `recentWeeklyKm` + z configu (jawny wybór w `why`). +- **Testy:** `macrocycle.test.ts` (długość i kształt bloku, brak akcentów), + `validate.test.ts` (nowe stany dozwolone), `commands.test.ts` (sekwencja + start → log → `plan` z nowym celem → historia nietknięta), backtest Δ0. + +### E3. Plan bez zawodów: tryb bazowy (kandydat ADR-039) + +- **Dziś:** `loadConfig` wymaga `goal` z datą i dystansem; predykcja, pakiet + startowy, taper i „dni do startu" zakładają start. +- **Config:** `goal: { kind: base, weeks: 12 }` albo `{ kind: base, until: "2027-03-01" }` + (jedno z dwóch); `distanceKm` i `date` niewymagane; `tuneUpRaces` dozwolone. +- **Silnik:** `macrocycle.ts` — wyłącznie faza `base` z deloadem co czwarty + tydzień (P-1), bez taperu, bez tygodnia startowego; progresja do + `peakWeeklyKm` albo plateau po jego osiągnięciu; sprawdzian jako fallback + kalibracji (W-11…W-13) co ~6 tyg. zostaje, bo bez startów nie ma innego + źródła VDOT. Reguły T-* nieaktywne — lint musi to wiedzieć + (`validate.ts`: zestaw kontroli zależny od `goal.kind`). +- **Interfejsy:** `plan` bez sekcji „Predicted finish"; `today`/`week`/`review` + bez „dni do startu" (w zamian „tydzień N z M bazy"); `export --what race` + odmawia z czytelnym komunikatem; `PLAN.md` i oba README z przykładem. +- **Testy:** macierz w `macrocycle.test.ts`; `check.test.ts` (brak fałszywych + ostrzeżeń T-*); `export.test.ts` (odmowa pakietu startowego); + `no-leaks.test.ts`. + +### E4. Siła: dziennik i warianty + +- **Dziś:** `strengthSession()` zwraca stałe 35 min i jeden opis; brak + logowania; `review` nie liczy wykonania siły. +- **Nauka:** F-1…F-4 (dawkowanie 2×/tydz., ciężko, niska liczba powtórzeń) + wystarczają na 2–3 warianty treści per faza (base: nauka wzorców; build/peak: + ciężko 3–5 powtórzeń; bez taperu — F-13). Warianty to **house choice** + oznaczony jako inżynierski — korpus nie zawiera siły. +- **Dziennik:** `LogEntry.strength?: { status: 'done'|'skipped', minutes?, note? }`; + `log --strength done --minutes 30` (CLI), `strength: {...}` (MCP). + `buildExecution` zostaje biegowe; `review` dostaje linię „siła: 1/2 sesji" + — liczba, bez wniosków. +- **Testy:** `strength.test.ts` (warianty per faza, S-5/F-13 nienaruszone), + `commands.test.ts` (log siły w dzień bez biegu i w dzień z biegiem), + `review.test.ts`. + +### E5. `terrain` w kalibracji + +- **Dziś:** `RaceResult.terrain` i `RaceGoal.terrain` istnieją, `inspectCalibration` + ich nie widzi; wynik z trailu podnosi/zaniża VDOT do stref szosowych. +- **Decyzja minimalna i uczciwa:** wyniki `terrain: trail` **nie kalibrują** + stref szosowych (polityka `best-vdot-540-days` dostaje powód `terrain`), + chyba że nie ma innych — wtedy używane z ostrzeżeniem w `why`. Bez + przeliczników (brak dowodu w FOUNDATIONS — dopisać do §11 „unverified"). +- **Testy:** `daniels.test.ts`/`calibration` — wybór wyniku z mieszanej listy; + `coach-flows.test.ts` — `why` pokazuje powód. + +### E6. Zamknięcie etapu + +CHANGELOG per wydanie 0.6.x; FOUNDATIONS §10 (nowe reguły E-2, R-3…R-5, +oznaczenia inżynierskie), §11; SPEC: ADR-038, 039, tabela §8, „znane +uproszczenia" (skreślić: brak życia po starcie, brak trybu bez zawodów); +README „Configuration" (sekcje `time`, `goal.kind`, `log --strength`). + +**DoD etapu E (całości):** profil bez startu generuje plan bazowy, który +przechodzi `check`; plan z celem kończy się blokiem przejściowym, a zmiana +celu zachowuje historię (B1); budżet czasu ogranicza objętość z jawnym +ostrzeżeniem; siła ma dziennik; backtest Δ0; każda nowa stała ma ID albo +etykietę inżynierską. + +--- + +## 7. Kandydaci ADR (następny wolny numer: 033) + +| # | Decyzja (skrót) | Sedno uzasadnienia | +|---|---|---| +| 033 | `plan` na istniejącym planie = **regeneracja chroniona**: przeszłość, dziennik, piny i `loadState` zostają; pełne nadpisanie tylko z `--fresh`; `diff` pokazuje tę samą regenerację | dokumentowana ścieżka „nowy wynik → plan" kasowała zatwierdzone decyzje; ochrona z ADR-029 obowiązywała propozycje, nie regenerację — to była luka, nie wybór | +| 034 | Zegar symulacji `TRAINCTL_TODAY` jest **jawny i widoczny** w każdym wyjściu; propozycje noszą datę, pod którą powstały | A05 słusznie oddzielił selekcję tygodnia od zegara, ale bez sankcjonowanej symulacji dokumentacja i próby ręczne stały się niemożliwe; cicha symulacja byłaby powtórką problemu A05 | +| 035 | `--json` zwraca `CmdResult.data` — ten sam kształt, który dostaje MCP (`structuredContent.data`); stabilność kontraktu ograniczona do pól używanych przez MCP do 1.0 | jedno źródło danych dla agenta i skryptów; drugi format wyjścia bez drugiej logiki (ADR-013) | +| 036 | Plugin Claude Code/Codex jest **kanałem dystrybucji**, nie nową logiką: skille generowane z tych samych rytuałów co `AGENTS.md`; `init` zapisuje pliki agenta tylko na jawną flagę | dryf między AGENTS.md a skillami zrobiłby dwie persony; cicha konfiguracja agenta w repo użytkownika łamie zasadę „nic bez pytania" (ADR-019) | +| 037 | Port sync rozdzielony na źródło aktywności i ujście treningów; adapter plikowy FIT/TCX/GPX jako druga implementacja źródła | zapowiedziana mitygacja ryzyka §9; pull-only adapter w porcie z metodami push to kłamstwo typów | +| 038 | Makrocykl kończy się **blokiem przejściowym**, nie tygodniem startu; kształt bloku z korpusu albo jawnie inżynierski | narzędzie, które milczy dzień po starcie, zostawia biegacza w najgorszym momencie; R-1/R-2 już opisują protokół — brakowało miejsca w planie | +| 039 | `goal.kind: base` — plan bez zawodów na N tygodni; reguły T-* nieaktywne, sprawdzian jako jedyne źródło kalibracji | większość tygodni roku nie ma celu; wymuszanie fikcyjnego startu produkowałoby fikcyjny taper | +| 040 | `--commit` to opcjonalne domknięcie historii gita po udanym zapisie; narzędzie nigdy nie commituje samo i nigdy sekretów | AGENTS.md każe commitować po każdej zmianie — flaga robi to, co i tak jest zalecane, bez stawania się klientem gita | + +--- + +## 8. Backlog — świadomie POZA zakresem (nie zaczynać bez decyzji) + +- **Repertuar zależny od celu i doświadczenia** (5 km vs maraton poza + objętością i taperem; długie z członami tempa — korpus: 29 % to **krótszy** + wzorzec, nie „długie z dodatkiem"). Warunek wstępny: pomiar w korpusie + i reguły w FOUNDATIONS; bez tego to dokładanie konstrukcji „bo tak się robi". +- **Kalibracja VDOT w backteście** z wyników użytkownika zamiast wartości + inżynierskiej 51 (znane uproszczenie). +- **Subskrybowany kalendarz** (ICS pod URL-em) — wymaga hostingu, sprzeczne + z local-first; zostaje eksport pliku, ewentualnie regeneracja `export/` + po każdym `--apply`. +- **Szósta paczka pluginu na npm** jako alternatywne źródło marketplace — + tylko jeśli marketplace z repo okaże się niewystarczający. +- **REST API / hosting / inne sporty** — jak w SPEC §8 „dalej". +- **Odrzucone na stałe** (analiza 2026-08-05, bez zmian): autopilot HRV / + gotowość (H-1, §11), streaki i gamifikacja, pogoda z sieci (ręczne + `--temp` dla pakietu startowego już jest), przebieg butów, metryki + ryzyka urazu (N-1…N-3), zamiana odczuć na liczby (ADR-027). + +--- + +## 9. Ryzyka tego planu + +- **Ekosystemy pluginów zmieniają się szybko.** Fakty z etapu C są z + 2026-10-21; przed implementacją powtórzyć weryfikację (szczególnie Codex: + format `.mcp.json` ze stdio i cwd serwera). Mitygacja: testy pluginu + sprawdzają strukturę plików, nie zachowanie agentów; próby ręczne + zapisane z datą. +- **B1 zmienia zachowanie komendy, którą użytkownicy znają.** Mitygacja: + wpis „Changed" w CHANGELOG, komunikat w wyjściu `plan` przez jedno wydanie + („od 0.4.0 `plan` chroni przeszłość; `--fresh` przywraca stare zachowanie"). +- **Dekoder FIT to nowa powierzchnia błędów** na plikach z dziesiątek + urządzeń. Mitygacja: `session` jako jedyne źródło prawdy, `record` tylko + jako fallback; plik niezrozumiały → `dataWithheld` z nazwą pliku, nigdy + zgadywanie dystansu. +- **Etap E rośnie.** Każdy podetap ma własne DoD i może wyjść osobno; + żaden nie blokuje A–D. +- **Dokumentacja znów odjedzie.** Mitygacja: `docs.test.ts` (A7/A8/A11) + i generator skilli (C2) zamieniają uzgodnienie w test, nie w pamięć. diff --git a/docs/PUBLISHING.md b/docs/PUBLISHING.md index de9c4ef..0563cb2 100644 --- a/docs/PUBLISHING.md +++ b/docs/PUBLISHING.md @@ -109,8 +109,13 @@ npm config set //registry.npmjs.org/:_authToken pnpm build && pnpm release:dry # przeczytaj listę plików KAŻDEJ paczki pnpm publish -r --access public npx @ --version # z rejestru, w pustym katalogu +gh release create v --title "v — " --notes-file ``` +**GitHub Release jest częścią wydania**, nie dodatkiem: tagi `v0.2.0` i `v0.3.0` +powstały bez Release'ów, więc strona repozytorium pokazywała 0.1.1 jako +najnowsze wydanie, choć npm miał już 0.3.0. + **Build jest od 0.1.1 obowiązkowy** (ADR-026): `pnpm build` → `dist/` z JS, deklaracjami i mapami źródeł; `publishConfig` przestawia wejścia paczki na `dist/*.js`, a w repozytorium nic się nie zmienia — dalej jedziemy na natywnym diff --git a/docs/examples/ci-check.md b/docs/examples/ci-check.md index c747b00..7b4d412 100644 --- a/docs/examples/ci-check.md +++ b/docs/examples/ci-check.md @@ -40,27 +40,23 @@ jobs: check: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - - name: trainctl (silnik) - uses: actions/checkout@v4 + - uses: actions/setup-node@v5 with: - repository: /trainctl - path: .trainctl-engine - - - uses: actions/setup-node@v4 - with: - node-version: '23' - - - run: corepack enable && pnpm install --frozen-lockfile - working-directory: .trainctl-engine + node-version: '22.18' # minimum z `engines` paczki trainctl + # Wersja przypięta jak w README („pin the version in your training repo"): + # ten sam plan i ta sama wersja silnika dają ten sam wynik lintu. - name: trainctl check env: NO_COLOR: '1' - run: node .trainctl-engine/packages/cli/src/bin.ts check + run: npx --yes trainctl@0.3.0 check ``` +Zamiast `trainctl@0.3.0` wpisz wersję, której używasz lokalnie +(`trainctl --version`) — i podnoś ją świadomie, razem z regeneracją planu. + `check` niczego nie zapisuje i nie potrzebuje klucza API — czyta wyłącznie `plan/plan.yaml`, więc workflow działa też na publicznym repo bez sekretów. Kto chce, żeby ostrzeżenia również blokowały merge, dodaje `--strict`. diff --git a/docs/examples/github-actions-review.md b/docs/examples/github-actions-review.md index 31441ec..6cd4bf7 100644 --- a/docs/examples/github-actions-review.md +++ b/docs/examples/github-actions-review.md @@ -43,20 +43,11 @@ jobs: review: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v5 - - name: trainctl (silnik) - uses: actions/checkout@v4 + - uses: actions/setup-node@v5 with: - repository: /trainctl - path: .trainctl-engine - - - uses: actions/setup-node@v4 - with: - node-version: '23' # natywny type-stripping: bez kroku budowania - - - run: corepack enable && pnpm install --frozen-lockfile - working-directory: .trainctl-engine + node-version: '22.18' # minimum z `engines` paczki trainctl - name: Przegląd id: review @@ -64,7 +55,7 @@ jobs: TRAINCTL_INTERVALS_API_KEY: ${{ secrets.TRAINCTL_INTERVALS_API_KEY }} NO_COLOR: '1' # czysty tekst do komentarza run: | - node .trainctl-engine/packages/cli/src/bin.ts review --days 7 > review.txt + npx --yes trainctl@0.3.0 review --days 7 > review.txt # wersja jak lokalnie { echo 'body< ui().agentsMd() +export const agentsTemplate = (): string => ui().agentsMd(foundationsUrl()) diff --git a/packages/cli/src/check.test.ts b/packages/cli/src/check.test.ts index 3398320..c931890 100644 --- a/packages/cli/src/check.test.ts +++ b/packages/cli/src/check.test.ts @@ -51,12 +51,16 @@ describe('trainctl check', () => { expect(r.output).toContain('2026-11-23') }) - it('brak planu: czytelny błąd', () => { + it('brak planu: czytelny błąd — pusty katalog odsyła do init, katalog z profilem do plan', () => { const empty = mkdtempSync(join(tmpdir(), 'trainctl-check-empty-')) try { const r = cmdCheck(empty) expect(r.code).toBe(1) - expect(r.output).toContain('Brak planu') + expect(r.output).toContain('trainctl init') + writeFileSync(join(empty, 'trainctl.yaml'), 'athlete: {}\n', 'utf-8') + const withConfig = cmdCheck(empty) + expect(withConfig.code).toBe(1) + expect(withConfig.output).toContain('Brak planu') } finally { rmSync(empty, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }) } diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index 8435ca5..73dc917 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -8,6 +8,7 @@ import { getLocale, inferProfile, estimateWorkoutMinutes, + formatNumber, messages, mondayOf, parseIso, @@ -43,7 +44,8 @@ import { PLAN_YAML, type StoredPlan, } from './planfile.ts' -import { kindPurpose, ruleExplain, ruleEvidence } from './rules-explain.ts' +import { foundationsUrl, kindPurpose, ruleExplain, ruleEvidence } from './rules-explain.ts' +import { packageVersion } from './version.ts' import { runExport, EXPORT_DIR, type ExportWhat } from './export.ts' import { b, renderPlain, type Block } from './ui/blocks.ts' import type { ColorName } from './ui/theme.ts' @@ -110,6 +112,17 @@ const fail = (e: unknown): CmdResult => { return { output: message, code: 1, blocks: [b.error(message)] } } +/** + * Plan z innego minora silnika nadal działa, ale poniżej 1.0 regeneracja może dać + * inne tygodnie (CHANGELOG). Mówimy o tym przy czytaniu planu — nie blokujemy. + */ +export function compatibilityNotes(plan: StoredPlan): Block[] { + const current = packageVersion() + if (!plan.engineVersion) return [b.info(ui().common.planFromOldEngine(current))] + const minor = (v: string) => v.split('.').slice(0, 2).join('.') + return minor(plan.engineVersion) === minor(current) ? [] : [b.info(ui().common.planFromOtherEngine(plan.engineVersion, current))] +} + export function localToday(): string { const d = new Date() const p = (n: number) => String(n).padStart(2, '0') @@ -354,6 +367,7 @@ export function cmdToday(cwd: string, opts: { date?: string | undefined } = {}): `${ui().today.weekOf(sk.index + 1, plan.weeks.length)} · ${phaseLabel(sk.phase)}` + `${sk.deload ? ` · ${ui().today.deload}` : ''} · ${ui().today.daysToRace(toRace)}`, ), + ...compatibilityNotes(plan), ] if (!day.workout) { @@ -433,6 +447,7 @@ export function cmdWeek(cwd: string, opts: { date?: string | undefined } = {}): ui().week.subtitle(phaseLabel(sk.phase), model, sk.targetKm, week.totalKm) + (sk.deload ? ` · ${ui().week.deloadUpper}` : ''), ), + ...compatibilityNotes(plan), b.table([ui().week.columns.day, ui().week.columns.date, ui().week.columns.km, ui().week.columns.workout], rows, accents), ] if (sk.raceDate) blocks.push(b.info(ui().week.raceThisWeek(sk.raceDate))) @@ -476,7 +491,7 @@ export function cmdLog( if (testTimeSec !== undefined && (status === 'skipped' || !['test', 'race'].includes(findDay(plan, date)?.day.workout?.kind ?? ''))) throw new Error(ui().improve.testTimeOnly) if (status === 'skipped' && ((Number(opts.km) || 0) > 0 || opts.time !== undefined)) throw new Error(ui().improve.skippedMetrics) if (testTimeSec !== undefined && opts.time && testTimeSec > parseTime(opts.time)) throw new Error(ui().improve.testTimeOnly) - appendLog(cwd, { + const entry: LogEntry = { date, status, ...(opts.km ? { km: Number(opts.km) } : {}), @@ -485,8 +500,34 @@ export function cmdLog( ...(rpe !== undefined ? { rpe } : {}), ...(opts.note ? { note: opts.note } : {}), loggedAt: new Date().toISOString(), + } + appendLog(cwd, entry) + // Odpowiedź odbija plan obok zapisu: samo „zalogowano" nie mówi, że w planie + // był odpoczynek albo że zapis dotyczy innej jednostki niż zaplanowana. + const workout = findDay(plan, date)!.day.workout + const minutes = workout ? estimateWorkoutMinutes(workout, plan.preparationMinutes ?? 15) : undefined + const knownMinutes = minutes !== undefined && Number.isFinite(minutes) ? minutes : null + const planned = workout + ? [kindLabel(workout.kind), `${formatNumber(getLocale(), workout.raceDistanceKm ?? workout.distanceKm)} km`, ...(knownMinutes !== null ? [`~${knownMinutes} min`] : [])].join(' · ') + : ui().week.rest + const recorded = [ + entry.status, + ...(entry.km !== undefined ? [`${formatNumber(getLocale(), entry.km)} km`] : []), + ...(entry.timeSec !== undefined ? [fmtTime(entry.timeSec)] : []), + ...(entry.testTimeSec !== undefined ? [ui().log.testTime(fmtTime(entry.testTimeSec))] : []), + ...(entry.rpe !== undefined ? [`RPE ${entry.rpe}`] : []), + ...(entry.note ? [`“${entry.note}”`] : []), + ].join(' · ') + const blocks: Block[] = [ + b.success(ui().log.saved(date, status)), + b.kv([[ui().log.planned, planned], [ui().log.recorded, recorded]]), + ] + if (!workout && status !== 'skipped') blocks.push(b.info(ui().log.unplanned)) + blocks.push(b.hint(ui().shift.weekHint(date))) + return okDoc(blocks, { + entry, + planned: workout ? { kind: workout.kind, distanceKm: workout.raceDistanceKm ?? workout.distanceKm, estimatedMinutes: knownMinutes } : null, }) - return ok(ui().log.saved(date, status)) } catch (e) { return fail(e) } @@ -536,45 +577,32 @@ export function cmdWhy(cwd: string, opts: { date?: string | undefined } = {}): C (sk.deload ? ` · ${ui().why.deloadWeek}` : ''), ), ] + blocks.push(...compatibilityNotes(plan)) blocks.push(b.section(ui().coach.context), b.text(explanation.purpose), b.bullets(explanation.context)) if (explanation.dose.length) blocks.push(b.section(ui().coach.dose), b.bullets(explanation.dose)) - blocks.push(Number.isFinite(explanation.estimatedMinutes) && explanation.estimatedMinutes !== null - ? b.info(ui().improve.minuteEstimate(explanation.estimatedMinutes)) : b.info(ui().improve.unknownDuration)) + // Szacunek czasu ma sens tylko wtedy, gdy jest co szacować — dzień wolny to nie „0 minut". + if (day.workout || day.strength) { + blocks.push(Number.isFinite(explanation.estimatedMinutes) && explanation.estimatedMinutes !== null + ? b.info(ui().improve.minuteEstimate(explanation.estimatedMinutes)) : b.info(ui().improve.unknownDuration)) + } + if (day.strength) { + blocks.push(b.panel(ui().today.strengthTitle(day.strength.durationMin), [day.strength.description], 'accent')) + // Gdy siła jest jedyną aktywnością dnia, jej cel stoi już na górze jako cel dnia. + if (day.workout) blocks.push(b.section(ui().why.strengthPurposeTitle), b.text(ui().why.strengthPurpose)) + } + if (!day.workout && !day.strength) blocks.push(b.text(ui().why.restDay)) blocks.push(b.section(ui().improve.calibration)) if (plan.calibration) { blocks.push(b.text(ui().improve.calibrationPolicy), b.bullets(plan.calibration.candidates.map((c) => [c.result.date, c.result.name ?? String(c.result.distanceKm) + ' km', 'VDOT ' + c.vdot.toFixed(1), ui().improve[c.reason], ui().improve.age(c.ageDays), c.result.exclusionReason ?? ''].filter(Boolean).join(' · ')))) } else blocks.push(b.info(ui().improve.calibrationMissing)) const evidence = [...new Set([...(day.workout?.ruleRefs ?? []), ...sk.ruleRefs, ...(day.strength?.ruleRefs ?? [])])].map((id) => ({ id, origin: ruleEvidence(id), explanation: ruleExplain(id) ?? id })) - blocks.push(b.section(ui().improve.evidence), b.bullets(evidence.map((e) => e.id + ': ' + ui().improve[e.origin]))) - if (!day.workout && !day.strength) { - blocks.push(b.text(ui().why.restDay)) - return okDoc(blocks, { day, explanation, calibration: plan.calibration ?? null, evidence }) + // Jedna lista reguł: ID, treść i pochodzenie razem. Wcześniej te same ID stały + // w dwóch sekcjach — raz z klasyfikacją, raz z treścią — a cel jednostki dwa razy. + if (evidence.length) { + blocks.push(b.section(ui().why.rules), b.bullets(evidence.map((e) => ui().why.ruleLine(e.id, ruleExplain(e.id), ui().improve[e.origin])))) } - if (day.strength) { - blocks.push( - b.panel(ui().today.strengthTitle(day.strength.durationMin), [day.strength.description], 'accent'), - b.section(ui().why.strengthPurposeTitle), - b.text(ui().why.strengthPurpose), - ) - const refs = day.strength.ruleRefs.filter(ruleExplain).map((r) => `${r} — ${ruleExplain(r)}`) - if (refs.length) blocks.push(b.section(ui().why.strengthRules), b.bullets(refs)) - if (!day.workout) { - blocks.push(b.blank(), b.hint(ui().why.sourcesHint('§10.8'))) - return okDoc(blocks, { day, explanation, calibration: plan.calibration ?? null, evidence }) - } - blocks.push(b.blank()) - } - const workout = day.workout - if (!workout) return okDoc(blocks, { day, explanation, calibration: plan.calibration ?? null, evidence }) - blocks.push( - b.panel(kindLabel(workout.kind), [kindPurpose(workout.kind)], - KIND_COLOR[workout.kind] ?? 'accent'), - ) - const refs = [...new Set([...workout.ruleRefs, ...sk.ruleRefs])].sort() - const explained = refs.filter(ruleExplain).map((r) => `${r} — ${ruleExplain(r)}`) - if (explained.length) blocks.push(b.section(ui().why.rules), b.bullets(explained)) - blocks.push(b.blank(), b.hint(ui().why.sourcesHint('§10'))) + blocks.push(b.blank(), b.hint(ui().why.sourcesHint(foundationsUrl(), day.workout || !day.strength ? '§10' : '§10.8'))) return okDoc(blocks, { day, explanation, calibration: plan.calibration ?? null, evidence }) } catch (e) { return fail(e) @@ -906,7 +934,7 @@ export function cmdDesk( blocks.push(opts.heavy === true && isPaceRule ? b.warn(g) : b.text(g)) blocks.push(b.blank()) } - blocks.push(b.hint(ui().desk.rulesHint(day.ruleRefs.join(', ')))) + blocks.push(b.hint(ui().desk.rulesHint(day.ruleRefs.join(', '), foundationsUrl()))) return okDoc(blocks, { day }) } catch (e) { return fail(e) @@ -1133,6 +1161,7 @@ export async function cmdReview( ), ] for (const n of notes) blocks.push(b.info(n)) + blocks.push(...compatibilityNotes(plan)) blocks.push(b.info(ui().coach.reviewWindow(from, today, days))) // 2) co się wydarzyło — te same porównania co w trainctl pull @@ -1207,7 +1236,8 @@ export async function cmdReview( ui().review.phase, `${phaseLabel(sk.phase)}${sk.deload ? ` · ${ui().today.deload}` : ''}`, ], - [ui().review.volume, ui().review.volumeAhead(week.totalKm, upcoming.length)], + // pozostałe km liczone tą samą miarą co totalKm (objętość treningowa, bez dystansu startu) + [ui().review.volume, ui().review.volumeAhead(Math.round(upcoming.reduce((s, d) => s + (d.workout?.distanceKm ?? 0), 0) * 10) / 10, week.totalKm, upcoming.length)], [ui().review.toRace, ui().review.toRaceValue(diffDays(today, plan.goal.date))], ]), ) @@ -1377,14 +1407,16 @@ export function cmdCheck(cwd: string, opts: { strict?: boolean | undefined } = { const errors = issues.filter((i) => i.severity === 'error') const warns = issues.filter((i) => i.severity === 'warn') const t = ui().check + // Wersja silnika to informacja, nie ustalenie lintu: nie liczy się do --strict. + const versionNotes = plan.goal && Array.isArray(plan.weeks) ? compatibilityNotes(plan as StoredPlan) : [] if (issues.length === 0) { const weeks = plan.weeks ?? [] const sessions = weeks.reduce((sum, w) => sum + w.days.filter((d) => d.workout).length, 0) - return okDoc([b.success(t.passed(weeks.length, sessions))]) + return okDoc([b.success(t.passed(weeks.length, sessions)), ...versionNotes]) } - const blocks: Block[] = [b.title(t.title, t.subtitle(PLAN_YAML))] + const blocks: Block[] = [b.title(t.title, t.subtitle(PLAN_YAML)), ...versionNotes] if (errors.length) { blocks.push(b.section(t.errorsSection)) for (const issue of errors) blocks.push(b.error(describeIssue(issue))) diff --git a/packages/cli/src/docs.test.ts b/packages/cli/src/docs.test.ts new file mode 100644 index 0000000..f2db570 --- /dev/null +++ b/packages/cli/src/docs.test.ts @@ -0,0 +1,49 @@ +/** + * Dokumentacja zgodna z kodem — uzgodnienie jako test, nie jako pamięć. + * + * Powód istnienia: 0.3.0 wyszło z README, które liczyło szesnaście narzędzi MCP + * przy siedemnastu w kodzie i bez wiersza `shorten` w tabeli komend, a przykłady + * CI nadal klonowały silnik sprzed publikacji na npm. + */ +import { readdirSync, readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { describe, expect, it } from 'vitest' + +const ROOT = join(dirname(fileURLToPath(import.meta.url)), '../../..') +const read = (path: string) => readFileSync(join(ROOT, path), 'utf-8') + +const tools = [...read('packages/mcp/src/server.ts').matchAll(/registerTool\(\s*'(trainctl_[a-z_]+)'/g)].map((m) => m[1]!) +const commands = [...read('packages/cli/src/bin.ts').matchAll(/\.command\('([a-z]+)/g)].map((m) => m[1]!) + +describe('README zna wszystkie narzędzia i komendy', () => { + it('kod rejestruje narzędzia i komendy (sanity check wyrażeń)', () => { + expect(tools.length).toBeGreaterThan(10) + expect(commands).toContain('shorten') + }) + + for (const file of ['README.md', 'README.pl.md', 'packages/mcp/README.md']) { + it(`${file}: każde narzędzie MCP jest wymienione`, () => { + const text = read(file) + expect(tools.filter((t) => !text.includes(`\`${t}\``))).toEqual([]) + }) + } + + for (const file of ['README.md', 'README.pl.md']) { + it(`${file}: każda komenda ma wiersz w tabeli komend`, () => { + const text = read(file) + expect(commands.filter((c) => !text.includes(`| \`${c}\``))).toEqual([]) + }) + } +}) + +describe('przykłady w docs/examples używają opublikowanej paczki', () => { + const files = readdirSync(join(ROOT, 'docs/examples')).filter((f) => f.endsWith('.md')) + for (const file of files) { + it(`${file}: bez klonowania silnika i bez Node 23`, () => { + const text = read(`docs/examples/${file}`) + expect(text).not.toContain('.trainctl-engine') + expect(text).not.toMatch(/node-version:\s*'23'/) + }) + } +}) diff --git a/packages/cli/src/fixes-031.test.ts b/packages/cli/src/fixes-031.test.ts new file mode 100644 index 0000000..812a10f --- /dev/null +++ b/packages/cli/src/fixes-031.test.ts @@ -0,0 +1,168 @@ +/** + * Regresje 0.3.1 — usterki zauważone przy uruchomieniu wszystkich komend na + * świeżym katalogu (docs/PLAN-v0.4.md, etap A). Każdy test pada bez poprawki. + */ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { parse, stringify } from 'yaml' +import { setLocale } from 'trainctl-core' +import { cmdCheck, cmdInit, cmdLog, cmdPlan, cmdReview, cmdToday, cmdWeek, cmdWhy } from './commands.ts' +import { kindPurpose } from './rules-explain.ts' +import { loadPlan, PLAN_YAML, type StoredPlan } from './planfile.ts' + +setLocale('en') + +const CONFIG = `athlete: + recentWeeklyKm: 45 + peakWeeklyKm: 65 + daysAvailable: [tue, wed, thu, sat, sun] + longRunDay: sat + results: + - { date: "2026-03-29", distanceKm: 10, timeSec: 2580 } +goal: + name: "Half marathon" + date: "2026-11-29" + distanceKm: 21.0975 + priority: A +` + +let dir: string +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'trainctl-031-')) +}) +afterEach(() => rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })) + +const withPlan = (): StoredPlan => { + writeFileSync(join(dir, 'trainctl.yaml'), CONFIG, 'utf-8') + expect(cmdPlan(dir, { date: '2026-08-08' }).code).toBe(0) + return loadPlan(dir) +} +const editPlan = (edit: (doc: Record) => void) => { + const path = join(dir, PLAN_YAML) + const doc = parse(readFileSync(path, 'utf-8')) as Record + edit(doc) + writeFileSync(path, stringify(doc), 'utf-8') +} + +describe('A1 · review: „przed nami" nie miesza objętości tygodnia z liczbą pozostałych sesji', () => { + it('w niedzielę pokazuje pozostałe km obok celu tygodnia', () => { + const plan = withPlan() + const week = plan.weeks.find((w) => w.weekStart === '2026-08-10')! + const sunday = '2026-08-16' + const remaining = week.days.filter((d) => d.workout && d.date >= sunday).reduce((s, d) => s + d.workout!.distanceKm, 0) + expect(remaining).toBeLessThan(week.totalKm) + const r = cmdReview(dir, { date: sunday }) + return r.then((res) => { + expect(res.output).toContain(`${remaining} of ${week.totalKm} km left across 1 session`) + }) + }) +}) + +describe('A2 · pusty katalog odsyła do init, nie do plan', () => { + it('bez trainctl.yaml: komunikat o init', () => { + const r = cmdToday(dir, { date: '2026-08-11' }) + expect(r.code).toBe(1) + expect(r.output).toContain('trainctl init') + }) + it('z trainctl.yaml, bez planu: komunikat o plan', () => { + writeFileSync(join(dir, 'trainctl.yaml'), CONFIG, 'utf-8') + const r = cmdWeek(dir, { date: '2026-08-11' }) + expect(r.code).toBe(1) + expect(r.output).toContain('trainctl plan') + }) +}) + +describe('A3 · why bez „0 minut" i bez dublowania celu', () => { + it('dzień wolny nie dostaje szacunku czasu', () => { + withPlan() + const out = cmdWhy(dir, { date: '2026-08-10' }).output + expect(out).not.toMatch(/About \d+ minutes/) + expect(out).toContain('Rest day') + }) + it('cel jednostki pojawia się raz, a reguły jedną listą z pochodzeniem', () => { + const plan = withPlan() + const day = plan.weeks[1]!.days.find((d) => d.workout?.kind === 'quality_intervals')! + const out = cmdWhy(dir, { date: day.date }).output + const purpose = kindPurpose('quality_intervals') + expect(out.split(purpose).length - 1).toBe(1) + expect(out).not.toContain('Origin of the decision') + expect(out).toMatch(/I-7 — .+ · Interpretation of published research/) + }) +}) + +describe('A4 · log odbija plan obok zapisu', () => { + it('wpis w dzień wolny mówi, że to bieg poza planem', () => { + withPlan() + const r = cmdLog(dir, { date: '2026-08-10', km: '5' }) + expect(r.code).toBe(0) + expect(r.output).toContain('unplanned run') + expect(r.data).toMatchObject({ entry: { date: '2026-08-10', km: 5 }, planned: null }) + }) + it('wpis treningu pokazuje rodzaj, km i szacunek czasu z planu', () => { + const plan = withPlan() + const day = plan.weeks[1]!.days.find((d) => d.workout?.kind === 'quality_intervals')! + const r = cmdLog(dir, { date: day.date, km: '8', time: '41:20', rpe: '4', note: 'ok' }) + expect(r.output).toMatch(/Planned: intervals · \d+ km · ~\d+ min/) + expect(r.output).toContain('Recorded: done · 8 km · 41:20 · RPE 4 · “ok”') + expect(r.data).toMatchObject({ planned: { kind: 'quality_intervals' } }) + }) +}) + +describe('A5 · ścieżki w komunikatach są takie same na każdym systemie', () => { + it('plan drukuje plan/plan.yaml, nie plan\\plan.yaml', () => { + writeFileSync(join(dir, 'trainctl.yaml'), CONFIG, 'utf-8') + const out = cmdPlan(dir, { date: '2026-08-08' }).output + expect(out).toContain('plan/plan.yaml + plan/PLAN.md') + expect(out).not.toContain('plan\\') + }) +}) + +describe('A6 · plan z innej wersji silnika', () => { + it('inny minor: informacja w today, week i why — bez blokowania', () => { + withPlan() + editPlan((doc) => { doc['engineVersion'] = '0.1.1' }) + for (const r of [cmdToday(dir, { date: '2026-08-11' }), cmdWeek(dir, { date: '2026-08-11' }), cmdWhy(dir, { date: '2026-08-11' })]) { + expect(r.code).toBe(0) + expect(r.output).toContain('generated by engine 0.1.1') + } + }) + it('plan bez wersji silnika: plan sprzed 0.2.0', () => { + withPlan() + editPlan((doc) => { delete doc['engineVersion'] }) + expect(cmdToday(dir, { date: '2026-08-11' }).output).toContain('predates engine 0.2.0') + }) + it('ten sam minor: cisza', () => { + withPlan() + expect(cmdToday(dir, { date: '2026-08-11' }).output).not.toContain('engine') + }) + it('nowszy schemat pliku: czytelny błąd zamiast cichego złego odczytu', () => { + withPlan() + editPlan((doc) => { doc['schemaVersion'] = 2 }) + const r = cmdToday(dir, { date: '2026-08-11' }) + expect(r.code).toBe(1) + expect(r.output).toContain('plan schema 2') + }) + it('check informuje, ale nie liczy tego jako ostrzeżenia w --strict', () => { + withPlan() + editPlan((doc) => { doc['engineVersion'] = '0.1.1' }) + const r = cmdCheck(dir, { strict: true }) + expect(r.output).toContain('generated by engine 0.1.1') + expect(r.code).toBe(0) + }) +}) + +describe('A9 · źródła reguł jako link, który działa po instalacji z npm', () => { + it('why i AGENTS.md wskazują FOUNDATIONS na GitHubie, przypięte do wersji', () => { + withPlan() + expect(cmdWhy(dir, { date: '2026-08-11' }).output).toMatch(/https:\/\/github\.com\/dithiothreitol\/trainctl\/blob\/v\d+\.\d+\.\d+\/docs\/science\/FOUNDATIONS\.md/) + const other = mkdtempSync(join(tmpdir(), 'trainctl-031-init-')) + try { + cmdInit(other) + expect(readFileSync(join(other, 'AGENTS.md'), 'utf-8')).toMatch(/\]\(https:\/\/github\.com\/dithiothreitol\/trainctl\/blob\/v/) + } finally { + rmSync(other, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) + } + }) +}) diff --git a/packages/cli/src/i18n/cli-en.ts b/packages/cli/src/i18n/cli-en.ts index 9dc5c25..f1d86a1 100644 --- a/packages/cli/src/i18n/cli-en.ts +++ b/packages/cli/src/i18n/cli-en.ts @@ -81,6 +81,13 @@ export const cliEn = { `${file} is not a usable plan (no goal/weeks) — run trainctl check to see what is broken, ` + 'or trainctl plan to regenerate it', missingConfig: (file: string) => `No ${file} — run: trainctl init`, + planFromOldEngine: (current: string) => + `This plan predates engine 0.2.0; running ${current}. trainctl diff shows what a regeneration would change.`, + planFromOtherEngine: (planVersion: string, current: string) => + `This plan was generated by engine ${planVersion}; running ${current}. Before 1.0 a regeneration ` + + 'may produce different weeks — trainctl diff shows the differences.', + planSchemaNewer: (file: string, version: number) => + `${file} uses plan schema ${version}, newer than this trainctl understands (1) — upgrade trainctl.`, configErrors: (file: string, errors: string) => `Errors in ${file}:\n - ${errors}`, cancelled: 'cancelled', interrupted: 'interrupted', @@ -174,6 +181,10 @@ export const cliEn = { badRpe: (rpe: string) => `RPE "${rpe}" is off the scale — use a whole number 1–10 (10 = maximal effort).`, saved: (date: string, status: string) => `Logged ${date}: ${status}.`, + planned: 'Planned', + recorded: 'Recorded', + testTime: (time: string) => `test segment ${time}`, + unplanned: 'The plan had a rest day here — the entry counts as an unplanned run.', }, shift: { @@ -202,7 +213,8 @@ export const cliEn = { 'Rest day. Adaptation happens in recovery — the coach’s plans assumed ' + '2–3 rest days a week (corpus: Mon 94%, Fri 92%).', rules: 'Rules', - strengthRules: 'Strength rules', + ruleLine: (id: string, text: string | undefined, origin: string) => + text ? `${id} — ${text} · ${origin}` : `${id} · ${origin}`, strengthPurposeTitle: 'What strength is for', strengthPurpose: 'The point is running economy — a lower oxygen cost at the same speed (F-8, and the effect ' + @@ -210,7 +222,7 @@ export const cliEn = { 'meta-analysis on runners came out non-significant (F-9). Honestly: for runners aged 34–45 ' + 'the effect on economy is also non-significant (F-15), and the evidence for performance ' + 'stops at 1.5–10 km in a laboratory (F-17). Strength disappears from the plan in the taper (F-13).', - sourcesHint: (section: string) => `sources and parameters: docs/science/FOUNDATIONS.md ${section}`, + sourcesHint: (url: string, section: string) => `sources and parameters: ${url} ${section}`, }, push: { @@ -281,7 +293,7 @@ export const cliEn = { breaksStay: 'The sitting breaks stay — they are not training.', breaksCount: (count: number) => `Sitting breaks (${count})`, notes: 'Notes', - rulesHint: (rules: string) => `rules: ${rules} — docs/science/FOUNDATIONS.md §10.10`, + rulesHint: (rules: string, url: string) => `rules: ${rules} — ${url} §10.10`, }, reschedule: { @@ -472,7 +484,10 @@ export const cliEn = { ahead: (weekStart: string) => `Ahead of you · week of ${weekStart}`, todo: 'To do', phase: 'Phase', - volumeAhead: (km: number, sessions: number) => `${n(km)} km across ${sessions} sessions`, + volumeAhead: (remainingKm: number, totalKm: number, sessions: number) => { + const across = `across ${sessions} ${pluralEn(sessions, { one: 'session', other: 'sessions' })}` + return remainingKm === totalKm ? `${n(totalKm)} km ${across}` : `${n(remainingKm)} of ${n(totalKm)} km left ${across}` + }, toRace: 'To race day', toRaceValue: (days: number) => `${days} days`, raceThisWeek: (date: string) => @@ -838,7 +853,7 @@ export const cliEn = { }, /** AGENTS.md — the coach persona dropped into the training directory by `trainctl init`. */ - agentsMd: (): string => `# Coach — instructions for the agent + agentsMd: (foundationsUrl: string): string => `# Coach — instructions for the agent This directory is a training plan as code. You have the \`trainctl_*\` MCP tools (or the \`trainctl\` CLI) and you act as a coach, not just a command runner. @@ -880,7 +895,7 @@ This directory is a training plan as code. You have the \`trainctl_*\` MCP tools 5. **Do not invent numbers.** Paces, volumes and rules come from the engine; if something is not in a tool’s output, say “I don’t know” rather than estimate. 6. **Cite reasons, not just commands.** \`trainctl_why\` gives the purpose of a session - and the rules behind it (IDs from \`docs/science/FOUNDATIONS.md\`) — that is the + and the rules behind it (IDs from [docs/science/FOUNDATIONS.md](${foundationsUrl})) — that is the value a coach adds over a list of workouts. 7. **A what-if question gets a scenario, not an overwrite.** “What if the race moves three weeks?” → git branch or a copied directory, change \`trainctl.yaml\` diff --git a/packages/cli/src/i18n/cli-i18n.test.ts b/packages/cli/src/i18n/cli-i18n.test.ts index cecaed4..fcfa226 100644 --- a/packages/cli/src/i18n/cli-i18n.test.ts +++ b/packages/cli/src/i18n/cli-i18n.test.ts @@ -155,8 +155,8 @@ describe('reguły i cele jednostek', () => { }) describe('instrukcja dla agenta (AGENTS.md)', () => { - const en = cliEn.agentsMd() - const pl = cliPl.agentsMd() + const en = cliEn.agentsMd('https://example.test/FOUNDATIONS.md') + const pl = cliPl.agentsMd('https://example.test/FOUNDATIONS.md') it('to dwa różne teksty, nie jeden skopiowany', () => { expect(en).not.toBe(pl) diff --git a/packages/cli/src/i18n/cli-pl.ts b/packages/cli/src/i18n/cli-pl.ts index 5fd5572..69c6d15 100644 --- a/packages/cli/src/i18n/cli-pl.ts +++ b/packages/cli/src/i18n/cli-pl.ts @@ -95,6 +95,13 @@ export const cliPl: CliMessages = { `${file} to nie jest kompletny plan (brak goal/weeks) — uruchom trainctl check, ` + 'żeby zobaczyć co jest połamane, albo trainctl plan, żeby przegenerować', missingConfig: (file: string) => `Brak ${file} — uruchom najpierw: trainctl init`, + planFromOldEngine: (current: string) => + `Plan powstał silnikiem sprzed 0.2.0, działa ${current}. trainctl diff pokaże, co zmieniłaby regeneracja.`, + planFromOtherEngine: (planVersion: string, current: string) => + `Plan wygenerował silnik ${planVersion}, działa ${current}. Przed 1.0 regeneracja może dać inne ` + + 'tygodnie — trainctl diff pokaże różnice.', + planSchemaNewer: (file: string, version: number) => + `${file} ma schemat planu ${version}, nowszy niż obsługiwany przez tę wersję (1) — zaktualizuj trainctl.`, configErrors: (file: string, errors: string) => `Błędy w ${file}:\n - ${errors}`, cancelled: 'anulowano', interrupted: 'przerwano', @@ -187,6 +194,10 @@ export const cliPl: CliMessages = { badRpe: (rpe: string) => `RPE „${rpe}” wypada poza skalę — podaj liczbę całkowitą 1–10 (10 = wysiłek maksymalny).`, saved: (date: string, status: string) => `Zalogowano ${date}: ${status}.`, + planned: 'W planie', + recorded: 'Zapis', + testTime: (time: string) => `odcinek pomiarowy ${time}`, + unplanned: 'W planie był tu dzień wolny — wpis liczy się jako bieg poza planem.', }, shift: { @@ -215,7 +226,8 @@ export const cliPl: CliMessages = { 'Dzień wolny. Adaptacja zachodzi w regeneracji — plan trenera zakładał ' + '2–3 dni wolne tygodniowo (korpus: PN 94%, PT 92%).', rules: 'Reguły', - strengthRules: 'Reguły siły', + ruleLine: (id: string, text: string | undefined, origin: string) => + text ? `${id} — ${text} · ${origin}` : `${id} · ${origin}`, strengthPurposeTitle: 'Po co siła biegaczowi', strengthPurpose: 'Cel: ekonomia biegu — mniejszy koszt tlenowy tej samej prędkości (F-8, efekt mały: ' + @@ -223,7 +235,7 @@ export const cliPl: CliMessages = { 'metaanaliza na biegaczach dała wynik nieistotny (F-9). Uczciwie: u biegaczy 34–45 lat ' + 'efekt na ekonomię też wychodzi nieistotny (F-15), a dowody na wynik kończą się na ' + '1,5–10 km w laboratorium (F-17). W taperze siła znika z planu (F-13).', - sourcesHint: (section: string) => `źródła i parametry: docs/science/FOUNDATIONS.md ${section}`, + sourcesHint: (url: string, section: string) => `źródła i parametry: ${url} ${section}`, }, push: { @@ -296,7 +308,7 @@ export const cliPl: CliMessages = { breaksStay: 'Przerwy w siedzeniu zostają — to nie jest trening.', breaksCount: (count: number) => `Przerwy w siedzeniu (${przerwy(count)})`, notes: 'Uwagi', - rulesHint: (rules: string) => `reguły: ${rules} — docs/science/FOUNDATIONS.md §10.10`, + rulesHint: (rules: string, url: string) => `reguły: ${rules} — ${url} §10.10`, }, reschedule: { @@ -492,8 +504,10 @@ export const cliPl: CliMessages = { ahead: (weekStart: string) => `Przed nami · tydzień od ${weekStart}`, todo: 'Do zrobienia', phase: 'Faza', - volumeAhead: (km: number, sessions: number) => - `${n(km)} km w ${sessions} ${pluralPl(sessions, { one: 'sesji', few: 'sesjach', other: 'sesjach' })}`, + volumeAhead: (remainingKm: number, totalKm: number, sessions: number) => { + const w = `w ${sessions} ${pluralPl(sessions, { one: 'sesji', few: 'sesjach', other: 'sesjach' })}` + return remainingKm === totalKm ? `${n(totalKm)} km ${w}` : `zostało ${n(remainingKm)} z ${n(totalKm)} km ${w}` + }, toRace: 'Do startu', toRaceValue: (days: number) => `${days} ${pluralPl(days, { one: 'dzień', few: 'dni', other: 'dni' })}`, @@ -861,7 +875,7 @@ export const cliPl: CliMessages = { checkStrict: 'true = ostrzeżenia też liczą się jak błędy', }, - agentsMd: (): string => `# Trener — instrukcja dla agenta + agentsMd: (foundationsUrl: string): string => `# Trener — instrukcja dla agenta Ten katalog to plan treningowy jako kod. Masz narzędzia MCP \`trainctl_*\` (albo CLI \`trainctl\`) i pełnisz rolę trenera, nie tylko wykonawcy komend. @@ -905,7 +919,7 @@ Ten katalog to plan treningowy jako kod. Masz narzędzia MCP \`trainctl_*\` 5. **Nie wymyślaj liczb.** Tempa, objętości i reguły pochodzą z silnika; jeśli czegoś nie ma w wyniku narzędzia, powiedz „nie wiem”, zamiast oszacować. 6. **Cytuj powody, nie tylko polecenia.** \`trainctl_why\` podaje cel jednostki i - reguły z badań (ID z \`docs/science/FOUNDATIONS.md\`) — to jest wartość, którą + reguły z badań (ID z [docs/science/FOUNDATIONS.md](${foundationsUrl})) — to jest wartość, którą trener wnosi ponad listę treningów. 7. **Pytanie „co jeśli” dostaje scenariusz, nie nadpisanie.** „Co jeśli przełożę start o trzy tygodnie?” → gałąź gita albo skopiowany katalog, zmiana diff --git a/packages/cli/src/i18n/improve-en.ts b/packages/cli/src/i18n/improve-en.ts index 0813f04..c293fc4 100644 --- a/packages/cli/src/i18n/improve-en.ts +++ b/packages/cli/src/i18n/improve-en.ts @@ -32,7 +32,6 @@ export const improveEn = { selected: 'Used for zones', 'lower-vdot': 'Lower VDOT', excluded: 'Excluded by you', future: 'Future result', stale: 'Older than 540 days', age: (days: number) => `${days} days old`, unclassified: 'See the source rule; provenance not classified', - evidence: 'Origin of the decision', research: 'Interpretation of published research', corpus: 'Coaching corpus', engineering: 'Engineering heuristic', minuteEstimate: (minutes: number) => `About ${minutes} minutes, including preparation; an estimate, not a guarantee.`, mobile: 'Workout for your phone', mobileExport: 'Export a standalone mobile workout page', diff --git a/packages/cli/src/i18n/improve-pl.ts b/packages/cli/src/i18n/improve-pl.ts index 78c3a8e..5c698c0 100644 --- a/packages/cli/src/i18n/improve-pl.ts +++ b/packages/cli/src/i18n/improve-pl.ts @@ -33,7 +33,6 @@ export const improvePl: typeof improveEn = { selected: 'Użyty do stref', 'lower-vdot': 'Niższy VDOT', excluded: 'Wykluczony przez Ciebie', future: 'Wynik z przyszłości', stale: 'Starszy niż 540 dni', age: (days: number) => `sprzed ${days} dni`, unclassified: 'Sprawdź regułę źródłową; pochodzenie niesklasyfikowane', - evidence: 'Pochodzenie decyzji', research: 'Interpretacja opublikowanych badań', corpus: 'Korpus trenerski', engineering: 'Heurystyka inżynierska', minuteEstimate: (minutes: number) => `Około ${minutes} minut z przygotowaniem; to szacunek, nie gwarancja.`, mobile: 'Trening na telefon', mobileExport: 'Eksport samodzielnej strony treningu na telefon', diff --git a/packages/cli/src/i18n/no-leaks.test.ts b/packages/cli/src/i18n/no-leaks.test.ts index d61a862..5515db9 100644 --- a/packages/cli/src/i18n/no-leaks.test.ts +++ b/packages/cli/src/i18n/no-leaks.test.ts @@ -196,6 +196,6 @@ describe('interfejs agenta nie przecieka polskim', () => { } } walk(cliEn) - expectEnglish('agentsMd', cliEn.agentsMd()) + expectEnglish('agentsMd', cliEn.agentsMd('https://example.test/FOUNDATIONS.md')) }) }) diff --git a/packages/cli/src/planfile.ts b/packages/cli/src/planfile.ts index ed71eba..222a925 100644 --- a/packages/cli/src/planfile.ts +++ b/packages/cli/src/planfile.ts @@ -20,14 +20,18 @@ import { type RaceGoal, type RacePrediction, } from 'trainctl-core' -import type { StrengthConfig, TrainctlConfig } from './config.ts' +import { CONFIG_FILE, type StrengthConfig, type TrainctlConfig } from './config.ts' import { ui } from './i18n/index.ts' import { inspectCalibration, type Calibration } from './calibration.ts' import { packageVersion } from './version.ts' export const PLAN_DIR = 'plan' -export const PLAN_YAML = join(PLAN_DIR, 'plan.yaml') -export const PLAN_MD = join(PLAN_DIR, 'PLAN.md') +// Ścieżki jako napisy POSIX: służą i do zapisu (`join(cwd, PLAN_YAML)` normalizuje +// separator), i do komunikatów — a te mają wyglądać tak samo na każdym systemie. +export const PLAN_YAML = `${PLAN_DIR}/plan.yaml` +export const PLAN_MD = `${PLAN_DIR}/PLAN.md` +/** Najnowsza wersja schematu `plan.yaml`, którą ten kod umie czytać. */ +export const PLAN_SCHEMA_VERSION = 1 export const dayFingerprint = (day: PlannedDay): string => createHash('sha256').update(JSON.stringify(day)).digest('hex') @@ -87,7 +91,7 @@ export function computePlan(config: TrainctlConfig, today: string, calibrationDa }) if (config.strength?.enabled) applyStrength(weeks, config.strength) const plan: StoredPlan = { - schemaVersion: 1, + schemaVersion: PLAN_SCHEMA_VERSION, engineVersion: packageVersion(), calibration: inspectCalibration(athlete.results, calibrationDate), generatedAt: today, @@ -170,7 +174,9 @@ function looksLikePlan(value: unknown): value is StoredPlan { export function readPlanDocument(cwd: string): unknown { const path = join(cwd, PLAN_YAML) if (!existsSync(path)) { - throw new Error(ui().common.noPlan) + // Pusty katalog to krok `init`, nie `plan` — inaczej `today` odsyła do `plan`, + // a `plan` dopiero powie, że brakuje profilu. + throw new Error(existsSync(join(cwd, CONFIG_FILE)) ? ui().common.noPlan : ui().common.missingConfig(CONFIG_FILE)) } return parse(readFileSync(path, 'utf-8')) } @@ -180,6 +186,9 @@ export function loadPlan(cwd: string): StoredPlan { if (!looksLikePlan(doc)) { throw new Error(ui().common.planMalformed(PLAN_YAML)) } + if (typeof doc.schemaVersion === 'number' && doc.schemaVersion > PLAN_SCHEMA_VERSION) { + throw new Error(ui().common.planSchemaNewer(PLAN_YAML, doc.schemaVersion)) + } return doc } diff --git a/packages/cli/src/rules-explain.ts b/packages/cli/src/rules-explain.ts index a5b4e47..84ec5c9 100644 --- a/packages/cli/src/rules-explain.ts +++ b/packages/cli/src/rules-explain.ts @@ -5,6 +5,17 @@ */ import type { WorkoutKind } from 'trainctl-core' import { ui } from './i18n/index.ts' +import { packageVersion } from './version.ts' + +export const FOUNDATIONS_PATH = 'docs/science/FOUNDATIONS.md' + +/** + * FOUNDATIONS nie jedzie w paczce npm, więc ścieżka względna w podpowiedzi + * prowadziła donikąd. Link przypięty do tagu wydania nie dryfuje: reguły, + * które cytuje ten silnik, są tymi z jego własnej wersji. + */ +export const foundationsUrl = (): string => + `https://github.com/dithiothreitol/trainctl/blob/v${packageVersion()}/${FOUNDATIONS_PATH}` /** Objaśnienie reguły po jej ID (np. `I-7`); undefined, gdy reguły nie opisano. */ export const ruleExplain = (id: string): string | undefined => diff --git a/packages/core/src/ports/sync.ts b/packages/core/src/ports/sync.ts index 29ddf8d..938e32e 100644 --- a/packages/core/src/ports/sync.ts +++ b/packages/core/src/ports/sync.ts @@ -63,12 +63,21 @@ export interface RemotePlannedWorkout { externalId?: string } -export interface SyncProvider { +/** + * Źródło wykonania (pull): hub online albo lokalny katalog plików aktywności. + * `review`, `pull` i `adapt` potrzebują wyłącznie tego — dlatego adapter + * plikowy (pull-only) nie musi udawać, że umie wysyłać treningi (ADR-037). + */ +export interface ActivitySource { readonly name: string - /** Sprawdzenie poświadczeń — zwraca identyfikator konta. */ - verify(): Promise<{ athleteId: string; name?: string }> listActivities(oldest: string, newest: string): Promise listWellness(oldest: string, newest: string): Promise +} + +/** Pełny hub: źródło wykonania + ujście zaplanowanych treningów (push). */ +export interface SyncProvider extends ActivitySource { + /** Sprawdzenie poświadczeń — zwraca identyfikator konta. */ + verify(): Promise<{ athleteId: string; name?: string }> pushWorkouts(workouts: PushableWorkout[]): Promise /** Treningi wcześniej wypchnięte przez nas (po prefiksie `external_id`). */ listPlannedWorkouts(oldest: string, newest: string): Promise diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 03f4359..9cb8f44 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -13,7 +13,7 @@ claude mcp add trainctl --env TRAINCTL_DIR="/path/to/my-training" \ `trainctl.yaml`, `plan/`, `log.jsonl`); without it the server uses the current working directory. -Seventeen tools over the same handlers the CLI uses, so the agent and your +Tools over the same handlers the CLI uses, so the agent and your terminal can never disagree: `trainctl_plan`, `trainctl_today`, `trainctl_week`, `trainctl_log`, `trainctl_shift`, `trainctl_why`, `trainctl_diff`, `trainctl_check`, `trainctl_init`, `trainctl_push`, `trainctl_pull`, From 38bba4cc9583f52760ca594ab1b6da1b7f30d28c Mon Sep 17 00:00:00 2001 From: Dariusz Tyszka Date: Wed, 21 Oct 2026 11:30:14 +0200 Subject: [PATCH 02/19] =?UTF-8?q?feat(cli):=20chroniona=20regeneracja=20pl?= =?UTF-8?q?anu=20i=20CLI,=20kt=C3=B3re=20da=20si=C4=99=20skryptowa=C4=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Etap B z docs/PLAN-v0.4.md. Regeneracja (ADR-033): `trainctl plan` na istniejącym planie zmienia tylko przyszłość. Dni przeszłe, zalogowane, przypięte, ręcznie edytowane, zatwierdzone skrócenia i przekraczające budżet czasu zostają; zatwierdzona baza z adapt obowiązuje, dopóki profil nie zmieni recentWeeklyKm. Ten sam cykl trzyma granice faz, inny dystans albo cel po starcie otwiera nowy cykl z historią w pliku. diff pokazuje tę samą regenerację, --fresh zaczyna od zera. Silnik: wynik wpisany w horyzoncie planu zeruje rytm kalibracji (W-12) — wcześniej regeneracja potrafiła wstawić sprawdzian tydzień po świeżym wyniku. CLI: --json, -C/TRAINCTL_DIR, jawny zegar TRAINCTL_TODAY (ADR-034), daty względne, interaktywny log, status (+ trainctl_status w MCP), --commit wyłącznie na plikach zmienionych przez komendę (ADR-040), czas i następna sesja w today, completion dla czterech powłok, przykłady w help, kod 2 dla błędów użycia. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 39 ++ README.md | 47 +- README.pl.md | 50 ++- SPEC.md | 4 + docs/REVIEWED-ADAPTATION.md | 6 + packages/cli/src/bin.test.ts | 3 +- packages/cli/src/bin.ts | 451 +++++++++++++------- packages/cli/src/cli-040.test.ts | 238 +++++++++++ packages/cli/src/clock.ts | 45 ++ packages/cli/src/commands.ts | 229 ++++++++-- packages/cli/src/completion.ts | 92 ++++ packages/cli/src/date-input.ts | 53 +++ packages/cli/src/env-file.ts | 16 + packages/cli/src/export.ts | 12 +- packages/cli/src/git.ts | 57 +++ packages/cli/src/i18n/cli-en.ts | 213 ++++++++- packages/cli/src/i18n/cli-i18n.test.ts | 5 + packages/cli/src/i18n/cli-pl.ts | 213 ++++++++- packages/cli/src/interactive.ts | 92 +++- packages/cli/src/planfile.ts | 35 +- packages/cli/src/proposals.ts | 44 +- packages/cli/src/regenerate.test.ts | 150 +++++++ packages/cli/src/regenerate.ts | 224 ++++++++++ packages/cli/src/status.ts | 151 +++++++ packages/cli/src/ui/wizard.ts | 2 +- packages/core/src/engine/macrocycle.test.ts | 18 + packages/core/src/engine/macrocycle.ts | 18 +- packages/mcp/README.md | 2 +- packages/mcp/src/server.test.ts | 24 +- packages/mcp/src/server.ts | 32 +- 30 files changed, 2299 insertions(+), 266 deletions(-) create mode 100644 packages/cli/src/cli-040.test.ts create mode 100644 packages/cli/src/clock.ts create mode 100644 packages/cli/src/completion.ts create mode 100644 packages/cli/src/date-input.ts create mode 100644 packages/cli/src/git.ts create mode 100644 packages/cli/src/regenerate.test.ts create mode 100644 packages/cli/src/regenerate.ts create mode 100644 packages/cli/src/status.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index a47da53..634932e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,45 @@ change between minor versions — a regenerated plan can differ. release tag — the file is not part of the npm package, so the relative path in `why`, `desk` and `AGENTS.md` led nowhere after installation. +### Changed — `trainctl plan` keeps what you decided (ADR-033) + +- On an existing plan, `plan` regenerates **only the future**. Past and logged + days, pinned days, hand edits, approved shortenings and days whose new session + would exceed a saved time budget stay as they are. An approved volume baseline + from `adapt --apply` is kept until you change `athlete.recentWeeklyKm`. + Previously every regeneration silently discarded all of that — including on + the documented path "add a race result → `trainctl plan`". +- The same training cycle keeps its phase boundaries; a different goal distance, + or a new goal after the race, starts a new cycle and keeps the earlier weeks + as history ("week 2/12" counts the current cycle). +- `trainctl diff` shows exactly the regeneration `plan` would perform. + `plan --fresh` (MCP `fresh`) starts over and lists what it discards. +- Fixed: a race result recorded inside the plan's horizon did not reset the + calibration rhythm (W-12), so a regeneration could schedule a time trial a + week after a fresh 10 km result. + +### Added — a CLI you can script + +- `--json` on every command prints `{ code, data, output }` — the same data the + MCP tools return (ADR-035). +- `-C ` / `TRAINCTL_DIR` for the CLI, as the MCP server already had. +- `TRAINCTL_TODAY=YYYY-MM-DD` simulates the date; every CLI and MCP output + announces it, and past-day protection and proposal expiry follow it (ADR-034). +- Relative dates in the CLI: `today`, `tomorrow`, `yesterday`, `+N`/`-N`, + weekday names in English and Polish. MCP tools stay ISO-only. +- `trainctl log` without flags in a terminal asks: pick a session from the last + week, then status, distance, time, RPE and a note. +- `trainctl status` / `trainctl_status`: profile validity, engine version, + calibration, key source (never its value), `.env` protection, last pull, + journal, saved proposals with their validity today, uncommitted files. +- `--commit [message]` on `init`, `plan`, `log`, `shift`, `reschedule --apply`, + `adapt --apply` and `shorten --apply` (MCP `commit`) commits exactly the files + the command changed — never secrets, `sync.json` or other staged changes + (ADR-040). +- `today` shows the estimated duration and the next session. +- `trainctl completion bash|zsh|fish|pwsh`, examples under `trainctl help `. +- Usage errors (unknown command or flag, a date that is not a date) exit with 2. + ### Docs - README command tables list `shorten` and the missing flags; tool lists no diff --git a/README.md b/README.md index e02a48e..d299ae2 100644 --- a/README.md +++ b/README.md @@ -186,10 +186,15 @@ Rules **Record what actually happened.** ```bash +trainctl log # in a terminal: pick the session, answer a few questions trainctl log --km 8 --time 41:20 --rpe 4 --note "felt good" -trainctl log --date 2026-08-06 --status skipped --note "work" +trainctl log --date yesterday --status skipped --note "work" ``` +Dates accept `YYYY-MM-DD`, `today`/`tomorrow`/`yesterday`, `+N`/`-N` and weekday +names (`thu`). `log`, `review`, `adapt` and `pull` look back; everything else +looks ahead. + `--rpe` is the session effort on the 1–10 scale. The engine stores it and the weekly review quotes it back verbatim — it never turns feelings into zones, paces or volume (that refusal is deliberate; see [Where it refuses](#where-it-refuses)). @@ -237,16 +242,16 @@ a key is configured). `trainctl adapt` compares execution with the plan and | command | what it does | key flags | |---|---|---| -| `init` | profile wizard | `--template`, `--from-intervals` | -| `plan` | generate the plan from `trainctl.yaml` | `--date` | +| `init` | profile wizard | `--template`, `--from-intervals`, `--commit` | +| `plan` | generate the plan; on an existing plan regenerate only the future | `--date`, `--fresh`, `--commit` | | `today` | the session for today | `--date` | | `week` | the week, with journal status | `--date`, `-i` (arrow-key browsing) | | `why` | purpose + research rules behind a session | `--date` | -| `log` | record a completed session | `--status`, `--km`, `--time`, `--test-time`, `--rpe`, `--note` | -| `shift` | swap two sessions inside a week | `--from`, `--to` (or pick from a list) | -| `reschedule` | re-solve the week around busy days | `--block`, `--time`, `--pin`, `--preparation`, `--strategy`, `--apply` | -| `adapt` | analyse execution, propose corrections | `--date`, `--prepare`, `--apply ` | -| `shorten` | fit one session into the time you have, as a proposal | `--minutes`, `--date`, `--apply ` | +| `log` | record a completed session (no flags in a terminal: asks) | `--status`, `--km`, `--time`, `--test-time`, `--rpe`, `--note`, `--commit` | +| `shift` | swap two sessions inside a week | `--from`, `--to` (or pick from a list), `--commit` | +| `reschedule` | re-solve the week around busy days | `--block`, `--time`, `--pin`, `--preparation`, `--strategy`, `--apply`, `--commit` | +| `adapt` | analyse execution, propose corrections | `--date`, `--prepare`, `--apply `, `--commit` | +| `shorten` | fit one session into the time you have, as a proposal | `--minutes`, `--date`, `--apply `, `--commit` | | `review` | pull + adapt + week in one call | `--days`, `--date`, `--prepare` | | `desk` | training windows around office hours | `--heavy` | | `push` | send planned sessions to intervals.icu | `--days`, `--from`, `--to` | @@ -254,9 +259,20 @@ a key is configured). `trainctl adapt` compares execution with the plan and | `export` | `.fit`, `.ics`, printout, race pack | `--what`, `--date` | | `diff` | what a regeneration would change | `--plan ` | | `check` | lint the plan; fails the exit code | `--strict` | +| `status` | the directory at a glance: profile, plan, key, data, proposals, git | | +| `completion` | shell completion script | `bash`, `zsh`, `fish`, `pwsh` | + +Every command takes `--lang en|pl`, `--json` (prints `{ code, data, output }` — +the same data the MCP tools return) and `-C ` (or `TRAINCTL_DIR`) to work +on a training directory elsewhere. `trainctl help ` prints the full +flag list with examples. Exit codes: 0 success, 1 error or refusal, 2 usage +error (unknown command or flag, a date that is not a date). -`--lang en|pl` works on every command. `trainctl help ` prints the full -flag list. +`--commit` commits exactly the files the command changed — never `.env`, +`.trainctl-secret` or `sync.json`, and never other changes you have staged. +`TRAINCTL_TODAY=YYYY-MM-DD` simulates the date for trying a scenario; every +output then starts by saying so, and past-day protection follows the simulated +date. ## Configuration @@ -402,7 +418,7 @@ terminal can never disagree: `trainctl_plan`, `trainctl_today`, `trainctl_week`, `trainctl_log`, `trainctl_shift`, `trainctl_why`, `trainctl_diff`, `trainctl_check`, `trainctl_init`, `trainctl_push`, `trainctl_pull`, `trainctl_adapt`, `trainctl_shorten`, `trainctl_desk`, `trainctl_reschedule`, -`trainctl_export`, `trainctl_review`. +`trainctl_export`, `trainctl_review`, `trainctl_status`. The `AGENTS.md` written by `trainctl init` turns the agent into a coach rather than a command runner: ask before regenerating a plan, ask for context when a @@ -504,6 +520,15 @@ result it will not calibrate zones from watch readings. manners: it explains, warns and negotiates, but it never applies a change to your plan without you. +**What happens to my plan when I run `trainctl plan` again?** Only the future +changes. Past and logged days, pinned days, hand edits, approved shortenings and +days whose new session would not fit a saved time budget stay as they are; an +approved volume baseline from `adapt` stays until you change +`athlete.recentWeeklyKm` yourself. A different goal distance, or a new goal after +the race, starts a new cycle and keeps the earlier weeks as history. +`trainctl diff` shows exactly the same changes without saving; `--fresh` starts +over (the old plan is in git). + **Can I edit `plan/plan.yaml` by hand?** Yes — that is the point of plan-as-code. Run `trainctl check` afterwards; it verifies the invariants the generator guarantees and tells you what a hand edit broke. diff --git a/README.pl.md b/README.pl.md index 83634b9..2f832e4 100644 --- a/README.pl.md +++ b/README.pl.md @@ -188,10 +188,15 @@ Reguły **Zapisz, co naprawdę się wydarzyło.** ```bash +trainctl log # w terminalu: wybierz trening, odpowiedz na kilka pytań trainctl log --km 8 --time 41:20 --rpe 4 --note "dobre czucie" -trainctl log --date 2026-08-06 --status skipped --note "praca" +trainctl log --date wczoraj --status skipped --note "praca" ``` +Daty przyjmują `RRRR-MM-DD`, `dziś`/`jutro`/`wczoraj` (także po angielsku), +`+N`/`-N` i dni tygodnia (`czw`, `thu`). `log`, `review`, `adapt` i `pull` +patrzą wstecz; pozostałe komendy — w przód. + `--rpe` to wysiłek sesji w skali 1–10. Silnik go zapisuje, a tygodniowy przegląd cytuje dosłownie — nigdy nie przelicza odczuć na strefy, tempa ani objętość (ta odmowa jest celowa; patrz [Gdzie silnik odmawia](#gdzie-silnik-odmawia)). @@ -240,16 +245,16 @@ Twoimi plecami. | komenda | co robi | ważniejsze flagi | |---|---|---| -| `init` | kreator profilu | `--template`, `--from-intervals` | -| `plan` | generuje plan z `trainctl.yaml` | `--date` | +| `init` | kreator profilu | `--template`, `--from-intervals`, `--commit` | +| `plan` | generuje plan; na istniejącym regeneruje tylko przyszłość | `--date`, `--fresh`, `--commit` | | `today` | trening na dziś | `--date` | | `week` | tydzień ze statusem z dziennika | `--date`, `-i` (przeglądanie strzałkami) | | `why` | cel jednostki + reguły z badań | `--date` | -| `log` | zapis wykonania | `--status`, `--km`, `--time`, `--test-time`, `--rpe`, `--note` | -| `shift` | zamiana dwóch jednostek w tygodniu | `--from`, `--to` (albo wybór z listy) | -| `reschedule` | przestawia tydzień wokół zajętych dni | `--block`, `--time`, `--pin`, `--preparation`, `--strategy`, `--apply` | -| `adapt` | analiza wykonania → propozycje korekt | `--date`, `--prepare`, `--apply ` | -| `shorten` | dopasowuje jednostkę do dostępnego czasu, jako propozycja | `--minutes`, `--date`, `--apply ` | +| `log` | zapis wykonania (bez flag w terminalu: pyta) | `--status`, `--km`, `--time`, `--test-time`, `--rpe`, `--note`, `--commit` | +| `shift` | zamiana dwóch jednostek w tygodniu | `--from`, `--to` (albo wybór z listy), `--commit` | +| `reschedule` | przestawia tydzień wokół zajętych dni | `--block`, `--time`, `--pin`, `--preparation`, `--strategy`, `--apply`, `--commit` | +| `adapt` | analiza wykonania → propozycje korekt | `--date`, `--prepare`, `--apply `, `--commit` | +| `shorten` | dopasowuje jednostkę do dostępnego czasu, jako propozycja | `--minutes`, `--date`, `--apply `, `--commit` | | `review` | pull + adapt + week w jednym | `--days`, `--date`, `--prepare` | | `desk` | okna treningowe wokół godzin pracy | `--heavy` | | `push` | wysyła treningi do intervals.icu | `--days`, `--from`, `--to` | @@ -257,9 +262,21 @@ Twoimi plecami. | `export` | `.fit`, `.ics`, rozpiska, pakiet startowy | `--what`, `--date` | | `diff` | co zmieniłaby regeneracja planu | `--plan ` | | `check` | lint planu; psuje kod wyjścia | `--strict` | - -`--lang en|pl` działa na każdej komendzie. `trainctl help ` wypisuje -pełną listę flag. +| `status` | stan katalogu na jednym ekranie: profil, plan, klucz, dane, propozycje, git | | +| `completion` | skrypt uzupełniania dla powłoki | `bash`, `zsh`, `fish`, `pwsh` | + +Każda komenda przyjmuje `--lang en|pl`, `--json` (wypisuje `{ code, data, +output }` — te same dane, które zwracają narzędzia MCP) i `-C ` (albo +`TRAINCTL_DIR`), żeby pracować na katalogu treningowym w innym miejscu. +`trainctl help ` wypisuje pełną listę flag z przykładami. Kody wyjścia: +0 sukces, 1 błąd albo odmowa, 2 błąd użycia (nieznana komenda lub flaga, data, +która nie jest datą). + +`--commit` commituje dokładnie pliki zmienione przez komendę — nigdy `.env`, +`.trainctl-secret` ani `sync.json` i nigdy innych zmian, które masz w indeksie. +`TRAINCTL_TODAY=RRRR-MM-DD` symuluje datę, żeby przećwiczyć scenariusz; każde +wyjście zaczyna się wtedy od tej informacji, a ochrona przeszłości idzie za +datą symulowaną. ## Konfiguracja @@ -407,7 +424,7 @@ agent i terminal nie mogą się rozjechać: `trainctl_plan`, `trainctl_today`, `trainctl_week`, `trainctl_log`, `trainctl_shift`, `trainctl_why`, `trainctl_diff`, `trainctl_check`, `trainctl_init`, `trainctl_push`, `trainctl_pull`, `trainctl_adapt`, `trainctl_shorten`, `trainctl_desk`, -`trainctl_reschedule`, `trainctl_export`, `trainctl_review`. +`trainctl_reschedule`, `trainctl_export`, `trainctl_review`, `trainctl_status`. `AGENTS.md`, który zostawia `trainctl init`, robi z agenta trenera, a nie wykonawcę komend: pyta przed regeneracją planu, dopytuje o kontekst przy @@ -511,6 +528,15 @@ skalibruje stref z odczytów zegarka. **To generator planów czy trener?** Generator z manierami trenera: tłumaczy, ostrzega i negocjuje, ale nigdy nie zastosuje zmiany w planie bez Ciebie. +**Co się dzieje z planem, gdy znowu uruchomię `trainctl plan`?** Zmienia się +tylko przyszłość. Dni przeszłe i zalogowane, przypięte, ręcznie edytowane, +zatwierdzone skrócenia i dni, w których nowa jednostka nie zmieściłaby się +w zapisanym budżecie czasu, zostają bez zmian; zatwierdzona baza objętości +z `adapt` obowiązuje, dopóki sam nie zmienisz `athlete.recentWeeklyKm`. Inny +dystans celu albo nowy cel po starcie otwiera nowy cykl, a wcześniejsze tygodnie +zostają jako historia. `trainctl diff` pokazuje dokładnie te same zmiany bez +zapisu; `--fresh` zaczyna od zera (stary plan jest w gicie). + **Mogę edytować `plan/plan.yaml` ręcznie?** Tak — o to chodzi w plan-as-code. Uruchom potem `trainctl check`: sprawdza inwarianty, które gwarantuje generator, i mówi, co ręczna edycja zepsuła. diff --git a/SPEC.md b/SPEC.md index 49d92e6..0f4e5fc 100644 --- a/SPEC.md +++ b/SPEC.md @@ -326,3 +326,7 @@ dane strukturalne MCP i samodzielny eksport mobilny. Opis poleceń i granic: | 030 | 2026-09-05 | Budżety minut i przypięcia są ograniczeniami solvera; czas zawiera przerwy, przygotowanie i siłę. | Dostępny dzień nie oznacza nieograniczonego czasu. Solver pokazuje odpuszczone jednostki i alternatywne priorytety, bez automatycznego ścieśniania treningu. | | 031 | 2026-09-05 | Plan przechowuje kalibrację, wersję schematu/silnika i odciski wygenerowanych dni. Wyniki można jawnie wykluczać. | Nowe wyniki porównujemy z rzeczywiście zapisaną historią; uzasadnienie ujawnia heurystykę wyboru i nie udaje liczbowej pewności. | | 032 | 2026-09-05 | MCP zwraca dane strukturalne obok tekstu; mobile jest eksportem HTML offline. | Agent operuje na faktach i propozycjach, a użytkownik może odczytać trening na telefonie bez konta ani nowego backendu. | +| 033 | 2026-10-21 | `trainctl plan` na istniejącym planie = **regeneracja chroniona**: dni przeszłe, zalogowane, przypięte, ręcznie edytowane, zatwierdzone skrócenia i przekraczające budżet zostają; zatwierdzona baza `loadState` obowiązuje, dopóki profil nie zmieni `recentWeeklyKm`; ten sam cykl liczony od pierwotnej daty startu planu (granice faz), inny dystans albo cel po starcie = nowy cykl z historią w pliku; `--fresh` zaczyna od zera; `diff` pokazuje tę samą regenerację | dokumentowana ścieżka „nowy wynik → trainctl.yaml → plan" kasowała zatwierdzone decyzje — ochrona z ADR-029 obejmowała propozycje, nie regenerację. To była luka, nie wybór | +| 034 | 2026-10-21 | Zegar symulacji `TRAINCTL_TODAY` jest **jawny**: każde wyjście CLI i MCP zaczyna się od informacji o nim, ochrona przeszłości i ważność propozycji idą za datą symulowaną | A05 słusznie oddzielił wybór tygodnia od zegara, ale bez sankcjonowanej symulacji dokumentacja i próby ręczne stały się niemożliwe; cicha symulacja byłaby powtórką A05 | +| 035 | 2026-10-21 | `--json` zwraca `CmdResult.data` — te same dane, które dostaje MCP; stabilność kształtu do 1.0 tylko w polach używanych przez MCP | jedno źródło danych dla agenta i skryptów, bez drugiej logiki wyjścia (ADR-013) | +| 040 | 2026-10-21 | `--commit` commituje wyłącznie pliki zmienione przez komendę (pathspec przy `git commit`), nigdy sekretów ani `sync.json`; brak gita to informacja, nie błąd | AGENTS.md każe commitować po każdej zmianie planu — flaga robi to, co i tak jest zalecane, bez stawania się klientem gita i bez zabierania cudzych zmian z indeksu | diff --git a/docs/REVIEWED-ADAPTATION.md b/docs/REVIEWED-ADAPTATION.md index 65b5e6b..c1be927 100644 --- a/docs/REVIEWED-ADAPTATION.md +++ b/docs/REVIEWED-ADAPTATION.md @@ -1,5 +1,11 @@ # Reviewed adaptation and time budgets +> **Since 0.4.0, `trainctl plan` keeps what you approved here.** Regenerating an +> existing plan changes only future days that are not logged, pinned, hand-edited, +> shortened by an approved proposal or over a saved time budget, and it keeps the +> approved volume baseline until you change `athlete.recentWeeklyKm` (ADR-033). +> `trainctl diff` shows the same regeneration without saving. + The CLI and MCP use the same operations. The examples below use a training directory containing `trainctl.yaml` and a generated plan. diff --git a/packages/cli/src/bin.test.ts b/packages/cli/src/bin.test.ts index f8a7194..30ba229 100644 --- a/packages/cli/src/bin.test.ts +++ b/packages/cli/src/bin.test.ts @@ -80,7 +80,8 @@ describe('binarka CLI pod natywnym Node', () => { }, 20_000) it('pełna ścieżka plan → today (ładuje core, sync, yaml)', () => { - expect(run(['plan', '--date', '2026-08-05'])).toContain('Zapisano') + // katalog bywa już z planem z poprzedniego testu: wtedy regeneracja mówi „aktualny” (ADR-033) + expect(run(['plan', '--date', '2026-08-05'])).toMatch(/Zapisano|Plan aktualny/) expect(run(['today', '--date', '2026-08-04'])).toMatch(/tydzień \d+\/\d+/) }, 20_000) // dwa starty realnej binarki — domyślne 5 s bywa ciasne na obciążonej maszynie diff --git a/packages/cli/src/bin.ts b/packages/cli/src/bin.ts index 91f7665..77b190f 100644 --- a/packages/cli/src/bin.ts +++ b/packages/cli/src/bin.ts @@ -4,7 +4,9 @@ * Cienki adapter: handlery zwracają bloki, tu zamieniamy je na kolorowy tekst. * MCP używa tych samych handlerów i dostaje wersję bez ANSI (ui/blocks.ts). */ -import { Command } from 'commander' +import { existsSync } from 'node:fs' +import { resolve } from 'node:path' +import { Command, InvalidArgumentError, type Option } from 'commander' import { resolveLocale, setLocale } from 'trainctl-core' import { readConfigLanguage } from './config.ts' import { loadEnvFile, ENV_FILE } from './env-file.ts' @@ -25,22 +27,46 @@ import { cmdReview, cmdShift, cmdShorten, + cmdStatus, cmdToday, cmdWeek, cmdWhy, + completionScript, fetchInferredProfile, hasApiKey, localToday, + resolveDateInput, + simulationNotice, + SHELLS, type CmdResult, + type CompletionSpec, + type DateDirection, + type Shell, } from './commands.ts' -import { runExportPicker, runShiftPicker, runWeekBrowser } from './interactive.ts' -import { renderAnsi } from './ui/blocks.ts' +import { runExportPicker, runLogPrompt, runShiftPicker, runWeekBrowser } from './interactive.ts' +import { b, renderAnsi, renderPlain } from './ui/blocks.ts' import { Theme } from './ui/theme.ts' import { withSpinner } from './ui/spinner.ts' import { runWizard, toYaml } from './ui/wizard.ts' import { packageVersion } from './version.ts' -const cwd = process.cwd() +/** Wartość globalnej opcji czytana z argv PRZED zbudowaniem drzewa komend. */ +function argValue(names: string[]): string | undefined { + const argv = process.argv + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]! + for (const name of names) { + if (arg === name) return argv[i + 1] + if (name.startsWith('--') && arg.startsWith(`${name}=`)) return arg.slice(name.length + 1) + } + } + return undefined +} + +// Katalog treningowy: -C/--dir > TRAINCTL_DIR > bieżący katalog. Ustalany przed +// `.env` i językiem, bo oba czytamy z katalogu treningowego, nie z procesu. +const cwd = resolve(process.cwd(), argValue(['-C', '--dir']) ?? process.env['TRAINCTL_DIR'] ?? '.') +const jsonMode = process.argv.includes('--json') // `.env` PRZED wszystkim innym: ma działać nie tylko dla klucza API, ale też // dla TRAINCTL_LANG, a język ustalamy zaraz niżej. `loadEnvFile` nie nadpisuje @@ -50,16 +76,9 @@ const envFile = loadEnvFile(cwd) // Język ustalamy PRZED zbudowaniem drzewa komend: opisy w `--help` też są // tłumaczone, a commander czyta je w momencie definiowania komendy. // Kolejność źródeł: --lang > TRAINCTL_LANG > language w trainctl.yaml > angielski. -const langFlagIndex = process.argv.findIndex((a) => a === '--lang' || a.startsWith('--lang=')) -const langFlag = - langFlagIndex === -1 - ? undefined - : process.argv[langFlagIndex]!.includes('=') - ? process.argv[langFlagIndex]!.split('=')[1] - : process.argv[langFlagIndex + 1] setLocale( resolveLocale({ - flag: langFlag, + flag: argValue(['--lang']), env: process.env['TRAINCTL_LANG'], config: readConfigLanguage(cwd), }), @@ -67,6 +86,8 @@ setLocale( const theme = new Theme() const program = new Command() +/** Tryby interaktywne tylko w terminalu i nigdy przy --json (wyjście ma być danymi). */ +const tty = process.stdin.isTTY === true && !jsonMode // Ostrzeżenie na stderr, nie na stdout: wyjście komend bywa przekierowywane // do pliku albo potoku, a to jest komunikat dla człowieka, nie dane. @@ -77,10 +98,54 @@ if (envFile.unprotected) { } function print(result: CmdResult): void { - console.log(result.blocks ? renderAnsi(result.blocks, theme) : result.output) + // Symulowana data nigdy nie jest cicha (ADR-034): pierwszy wiersz każdego wyjścia. + const notice = simulationNotice() + if (jsonMode) { + console.log(JSON.stringify({ + code: result.code, + ...(notice ? { notice } : {}), + data: result.data ?? {}, + output: result.blocks ? renderPlain(result.blocks) : result.output, + }, null, 2)) + } else if (result.blocks) { + console.log(renderAnsi(notice ? [b.warn(notice), ...result.blocks] : result.blocks, theme)) + } else { + // gotowy tekst (bywa wielowierszowy i już pokolorowany) — bez ponownego zawijania + if (notice) console.log(renderAnsi([b.warn(notice)], theme)) + console.log(result.output) + } + process.exitCode = result.code +} + +/** Wynik trybu interaktywnego (gotowy tekst z kolorami) — z tym samym ostrzeżeniem. */ +function printInteractive(result: { output: string; code: number }): void { + const notice = simulationNotice() + if (notice) console.log(renderAnsi([b.warn(notice)], theme)) + console.log(result.output) process.exitCode = result.code } +const spin = (label: string, fn: () => Promise): Promise => (jsonMode ? fn() : withSpinner(label, fn, theme)) + +// --- daty względne (ADR: tylko CLI; MCP przyjmuje ISO) ----------------------- +const dateArg = (direction: DateDirection) => (value: string): string => { + try { + return resolveDateInput(value, localToday(), direction) + } catch (e) { + throw new InvalidArgumentError(e instanceof Error ? e.message : String(e)) + } +} +const datesArg = (direction: DateDirection) => (value: string, previous?: string[]): string[] => + [...(previous ?? []), dateArg(direction)(value)] +/** `--time thu=40` → `2026-08-06=40`: data może być względna, minuty bez zmian. */ +const budgetArg = (value: string, previous?: string[]): string[] => { + const at = value.lastIndexOf('=') + const date = at === -1 ? value : value.slice(0, at) + return [...(previous ?? []), at === -1 ? value : `${dateArg('forward')(date)}${value.slice(at)}`] +} +const ahead = dateArg('forward') +const back = dateArg('back') + const s = theme.sym const banner = theme.bold(theme.color('trainctl', 'brand')) + @@ -91,6 +156,8 @@ program .description(banner) .version(packageVersion(), '-V, --version', ui().cmd.version) .option('--lang ', ui().cmd.lang) + .option('-C, --dir ', ui().cmd.optDir) + .option('--json', ui().cmd.optJson) .configureHelp({ styleTitle: (str) => theme.bold(theme.color(str, 'accent')), styleCommandText: (str) => theme.color(str, 'brand'), @@ -100,184 +167,227 @@ program .configureOutput({ outputError: (str, write) => write(`${theme.color(s.fail, 'error')} ${str}`), }) + // Błąd użycia (nieznana komenda albo flaga, zła data) to kod 2 — skrypt i hook + // odróżnią go od błędu danych albo odmowy (kod 1). + .exitOverride((err) => { + process.exit(err.exitCode === 0 ? 0 : 2) + }) -program - .command('init') - .description(ui().cmd.init) - .option('--template', ui().cmd.initTemplate) - .option('--from-intervals', ui().cmd.initFromIntervals) - .action(async (opts) => { - const interactive = opts.template !== true && process.stdin.isTTY === true - if (!interactive) { - if (opts.fromIntervals === true) { - return print( - await withSpinner(ui().cmd.spinnerInit, () => cmdInitFromIntervals(cwd), theme), - ) - } - return print(cmdInit(cwd)) - } - try { - const answers = await runWizard(theme, { - available: hasApiKey(cwd), - force: opts.fromIntervals === true, - fetch: () => fetchInferredProfile(cwd, localToday()), - }) - print(cmdInit(cwd, toYaml(answers))) - } catch (e) { - // Ctrl+C w kreatorze nie powinno zostawiać stack trace'u - console.log(theme.dim(`\n${ui().common.interrupted}`)) - process.exitCode = 1 - void e +/** Przykłady pod `trainctl help ` — z katalogu, w języku katalogu treningowego. */ +function withExamples(command: Command, name: keyof ReturnType['examples']): Command { + const lines = ui().examples[name] + return command.addHelpText('after', `\n${theme.dim(ui().cmd.examples)}\n${lines.map((l) => ` ${l}`).join('\n')}`) +} + +const commitOption = (command: Command) => command.option('--commit [message]', ui().cmd.optCommit) + +if (!existsSync(cwd)) { + console.error(`${theme.color(s.fail, 'error')} ${ui().cmd.dirMissing(cwd)}`) + process.exit(1) +} + +commitOption( + program + .command('init') + .description(ui().cmd.init) + .option('--template', ui().cmd.initTemplate) + .option('--from-intervals', ui().cmd.initFromIntervals), +).action(async (opts) => { + const interactive = opts.template !== true && tty + if (!interactive) { + if (opts.fromIntervals === true) { + return print(await spin(ui().cmd.spinnerInit, () => cmdInitFromIntervals(cwd))) } - }) + return print(cmdInit(cwd, undefined, { commit: opts.commit })) + } + try { + const answers = await runWizard(theme, { + available: hasApiKey(cwd), + force: opts.fromIntervals === true, + fetch: () => fetchInferredProfile(cwd, localToday()), + }) + print(cmdInit(cwd, toYaml(answers), { commit: opts.commit })) + } catch (e) { + // Ctrl+C w kreatorze nie powinno zostawiać stack trace'u + console.log(theme.dim(`\n${ui().common.interrupted}`)) + process.exitCode = 1 + void e + } +}) -program - .command('plan') - .description(ui().cmd.plan) - .option('--date ', ui().cmd.optDate) - .action((opts) => print(cmdPlan(cwd, opts))) +withExamples( + commitOption( + program + .command('plan') + .description(ui().cmd.plan) + .option('--date ', ui().cmd.optDate, ahead) + .option('--fresh', ui().cmd.optFresh), + ), + 'plan', +).action((opts) => print(cmdPlan(cwd, opts))) program .command('today') .description(ui().cmd.today) - .option('--date ', ui().cmd.optDateOther) + .option('--date ', ui().cmd.optDateOther, ahead) .action((opts) => print(cmdToday(cwd, opts))) program .command('week') .description(ui().cmd.week) - .option('--date ', ui().cmd.optDateWeek) + .option('--date ', ui().cmd.optDateWeek, ahead) .option('-i, --interactive', ui().cmd.weekInteractive) .action(async (opts) => { - if (opts.interactive !== true) return print(cmdWeek(cwd, opts)) - const result = await runWeekBrowser(cwd, opts.date ?? localToday(), theme) - console.log(result.output) - process.exitCode = result.code + if (opts.interactive !== true || !tty) return print(cmdWeek(cwd, opts)) + printInteractive(await runWeekBrowser(cwd, opts.date ?? localToday(), theme)) }) -program - .command('log') - .description(ui().cmd.log) - .option('--date ', ui().cmd.optDate) - .option('--status ', ui().cmd.optStatus, 'done') - .option('--km ', ui().cmd.optKm) - .option('--time ', ui().cmd.optTime) - .option('--test-time ', ui().improve.testTime) - .option('--rpe ', ui().cmd.optRpe) - .option('--note ', ui().cmd.optNote) - .action((opts) => print(cmdLog(cwd, opts))) +withExamples( + commitOption( + program + .command('log') + .description(ui().cmd.log) + .option('--date ', ui().cmd.optDate, back) + .option('--status ', ui().cmd.optStatus, 'done') + .option('--km ', ui().cmd.optKm) + .option('--time ', ui().cmd.optTime) + .option('--test-time ', ui().improve.testTime) + .option('--rpe ', ui().cmd.optRpe) + .option('--note ', ui().cmd.optNote), + ), + 'log', +).action(async (opts, command: Command) => { + // Bez żadnej flagi w terminalu: pytania zamiast cichego „dziś: done". + // Poza terminalem (skrypt, agent) zachowanie bez zmian. + const flags = ['date', 'km', 'time', 'testTime', 'rpe', 'note', 'commit'].some((k) => opts[k] !== undefined) || + command.getOptionValueSource('status') !== 'default' + if (!flags && tty) return printInteractive(await runLogPrompt(cwd, localToday(), theme)) + print(cmdLog(cwd, opts)) +}) -program - .command('shift') - .description(ui().cmd.shift) - .option('--from ', ui().cmd.optFrom) - .option('--to ', ui().cmd.optTo) - .action(async (opts) => { - if (opts.from && opts.to) return print(cmdShift(cwd, opts)) - if (opts.from || opts.to) { - return print({ - code: 1, - output: ui().shift.bothDates, - }) - } - const result = await runShiftPicker(cwd, localToday(), theme) - console.log(result.output) - process.exitCode = result.code - }) +commitOption( + program + .command('shift') + .description(ui().cmd.shift) + .option('--from ', ui().cmd.optFrom, ahead) + .option('--to ', ui().cmd.optTo, ahead), +).action(async (opts) => { + if (opts.from && opts.to) return print(cmdShift(cwd, opts)) + if (opts.from || opts.to || !tty) { + return print({ code: 1, output: ui().shift.bothDates }) + } + printInteractive(await runShiftPicker(cwd, localToday(), theme)) +}) program .command('why') .description(ui().cmd.why) - .option('--date ', ui().cmd.optDateOther) + .option('--date ', ui().cmd.optDateOther, ahead) .action((opts) => print(cmdWhy(cwd, opts))) -program - .command('adapt') - .description(ui().cmd.adapt) - .option('--prepare', ui().improve.prepare) - .option('--apply ', ui().improve.apply) - .option('--date ', ui().cmd.optDate) - .action((opts) => print(cmdAdapt(cwd, opts))) +withExamples( + commitOption( + program + .command('adapt') + .description(ui().cmd.adapt) + .option('--prepare', ui().improve.prepare) + .option('--apply ', ui().improve.apply) + .option('--date ', ui().cmd.optDate, back), + ), + 'adapt', +).action((opts) => print(cmdAdapt(cwd, opts))) -program - .command('shorten') - .description(ui().coach.shorten) - .option('--minutes ', ui().coach.minutes) - .option('--date ', ui().cmd.optDateOther) - .option('--apply ', ui().improve.apply) - .action((opts) => print(cmdShorten(cwd, opts))) +withExamples( + commitOption( + program + .command('shorten') + .description(ui().coach.shorten) + .option('--minutes ', ui().coach.minutes) + .option('--date ', ui().cmd.optDateOther, ahead) + .option('--apply ', ui().improve.apply), + ), + 'shorten', +).action((opts) => print(cmdShorten(cwd, opts))) program .command('desk') .description(ui().cmd.desk) - .option('--date ', ui().cmd.optDateOther) + .option('--date ', ui().cmd.optDateOther, ahead) .option('--heavy', ui().cmd.optHeavy) .action((opts) => print(cmdDesk(cwd, opts))) -program - .command('push') - .description(ui().cmd.push) - .option('--from ', ui().cmd.optFromRange) - .option('--to ', ui().cmd.optToRange) - .option('--days ', ui().cmd.optDaysAhead) - .action(async (opts) => - print(await withSpinner(ui().cmd.spinnerPush, () => cmdPush(cwd, opts), theme)), - ) +withExamples( + program + .command('push') + .description(ui().cmd.push) + .option('--from ', ui().cmd.optFromRange, ahead) + .option('--to ', ui().cmd.optToRange, ahead) + .option('--days ', ui().cmd.optDaysAhead), + 'push', +).action(async (opts) => print(await spin(ui().cmd.spinnerPush, () => cmdPush(cwd, opts)))) -program - .command('pull') - .description(ui().cmd.pull) - .option('--date ', ui().cmd.optDate) - .option('--days ', ui().cmd.optDaysBack) - .action(async (opts) => - print(await withSpinner(ui().cmd.spinnerPull, () => cmdPull(cwd, opts), theme)), - ) +withExamples( + program + .command('pull') + .description(ui().cmd.pull) + .option('--date ', ui().cmd.optDate, back) + .option('--days ', ui().cmd.optDaysBack), + 'pull', +).action(async (opts) => print(await spin(ui().cmd.spinnerPull, () => cmdPull(cwd, opts)))) -program - .command('export') - .description(ui().cmd.export) - .option('--what ', ui().cmd.optExportWhat) - .option('--date ', ui().cmd.optExportDate) - .action(async (opts) => { - if (opts.what) return print(cmdExport(cwd, opts)) - if (process.stdin.isTTY !== true) { - return print({ - code: 1, - output: ui().exportCmd.pickWhat, - }) - } - const answer = await runExportPicker(cwd, localToday(), theme) - if (!answer) return print({ code: 0, output: theme.dim(ui().common.cancelled) }) - print(cmdExport(cwd, answer)) - }) +withExamples( + program + .command('export') + .description(ui().cmd.export) + .option('--what ', ui().cmd.optExportWhat) + .option('--date ', ui().cmd.optExportDate, ahead), + 'export', +).action(async (opts) => { + if (opts.what) return print(cmdExport(cwd, opts)) + if (!tty) { + return print({ + code: 1, + output: ui().exportCmd.pickWhat, + }) + } + const answer = await runExportPicker(cwd, localToday(), theme) + if (!answer) return print({ code: 0, output: theme.dim(ui().common.cancelled) }) + print(cmdExport(cwd, answer)) +}) -program - .command('reschedule') - .description(ui().cmd.reschedule) - .option('--time ', ui().improve.time) - .option('--pin ', ui().improve.pin) - .option('--preparation ', ui().improve.preparation) - .option('--strategy ', ui().improve.strategy) - .option('--block ', ui().cmd.optBlock) - .option('--date ', ui().cmd.optWhichWeek) - .option('--apply', ui().cmd.optApply) - .action((opts) => print(cmdReschedule(cwd, opts))) +withExamples( + commitOption( + program + .command('reschedule') + .description(ui().cmd.reschedule) + .option('--time ', ui().improve.time, budgetArg) + .option('--pin ', ui().improve.pin, datesArg('forward')) + .option('--preparation ', ui().improve.preparation) + .option('--strategy ', ui().improve.strategy) + .option('--block ', ui().cmd.optBlock, datesArg('forward')) + .option('--date ', ui().cmd.optWhichWeek, ahead) + .option('--apply', ui().cmd.optApply), + ), + 'reschedule', +).action((opts) => print(cmdReschedule(cwd, opts))) -program - .command('review') - .description(ui().cmd.review) - .option('--prepare', ui().coach.reviewPrepare) - .option('--days ', ui().cmd.optReviewDays) - .option('--date ', ui().cmd.optDate) - .action(async (opts) => - print(await withSpinner(ui().cmd.spinnerReview, () => cmdReview(cwd, opts), theme)), - ) +withExamples( + program + .command('review') + .description(ui().cmd.review) + .option('--prepare', ui().coach.reviewPrepare) + .option('--days ', ui().cmd.optReviewDays) + .option('--date ', ui().cmd.optDate, back), + 'review', +).action(async (opts) => print(await spin(ui().cmd.spinnerReview, () => cmdReview(cwd, opts)))) -program - .command('diff') - .description(ui().cmd.diff) - .option('--plan ', ui().cmd.optDiffPlan) - .action((opts) => print(cmdDiff(cwd, opts))) +withExamples( + program + .command('diff') + .description(ui().cmd.diff) + .option('--plan ', ui().cmd.optDiffPlan), + 'diff', +).action((opts) => print(cmdDiff(cwd, opts))) program .command('check') @@ -285,6 +395,31 @@ program .option('--strict', ui().cmd.optStrict) .action((opts) => print(cmdCheck(cwd, opts))) +withExamples( + program + .command('status') + .description(ui().cmd.status), + 'status', +).action(() => print(cmdStatus(cwd))) + +program + .command('completion') + .description(ui().cmd.completion) + .argument('', SHELLS.join(' | ')) + .action((shell: string) => { + if (!(SHELLS as readonly string[]).includes(shell)) { + return print({ code: 2, output: ui().cmd.completionShell(SHELLS.join(', ')) }) + } + const optionsOf = (options: readonly Option[]) => + options.map((o) => ({ long: o.long ?? '', ...(o.short ? { short: o.short } : {}), description: o.description })) + .filter((o) => o.long) + const specs: CompletionSpec[] = program.commands + .filter((c) => c.name() !== 'completion') + .map((c) => ({ name: c.name(), description: c.description(), options: optionsOf(c.options) })) + // skrypt to dane dla powłoki — bez ostrzeżeń i bez JSON + process.stdout.write(completionScript(shell as Shell, specs, optionsOf(program.options))) + }) + program.addHelpText( 'after', '\n' + @@ -301,7 +436,11 @@ program.addHelpText( theme.color('trainctl week -i', 'brand') + theme.dim(ui().cmd.browseArrows) + '\n' + + theme.dim(ui().cmd.datesHint) + + '\n' + + theme.dim(ui().cmd.dirHint) + + '\n' + theme.dim(ui().cmd.colorsHint), ) -program.parse() +await program.parseAsync() diff --git a/packages/cli/src/cli-040.test.ts b/packages/cli/src/cli-040.test.ts new file mode 100644 index 0000000..ea1a790 --- /dev/null +++ b/packages/cli/src/cli-040.test.ts @@ -0,0 +1,238 @@ +/** + * Etap B (docs/PLAN-v0.4.md): CLI, które da się skryptować — `--json`, `-C`, + * jawny zegar symulacji, daty względne, `status`, `--commit`, completion, + * przykłady w pomocy i kody wyjścia. Część testów uruchamia prawdziwą binarkę. + */ +import { execFileSync, spawnSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { setLocale } from 'trainctl-core' +import { cmdLog, cmdPlan, cmdShift, cmdStatus, cmdToday, completionScript, resolveDateInput } from './commands.ts' +import { logChoices, parseLogStatus } from './interactive.ts' +import { loadPlan } from './planfile.ts' + +setLocale('en') +const HERE = dirname(fileURLToPath(import.meta.url)) +const CLI_BIN = join(HERE, 'bin.ts') + +const CONFIG = `athlete: + recentWeeklyKm: 45 + daysAvailable: [tue, wed, thu, sat, sun] + results: + - { date: "2026-03-29", distanceKm: 10, timeSec: 2580 } +goal: + name: "Half marathon" + date: "2026-11-29" + distanceKm: 21.0975 + priority: A +` + +let dir: string +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'trainctl-040-')) + writeFileSync(join(dir, 'trainctl.yaml'), CONFIG, 'utf-8') +}) +afterEach(() => rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })) + +const run = (args: string[], env: NodeJS.ProcessEnv = {}, cwd = dir) => + spawnSync(process.execPath, [CLI_BIN, ...args], { + cwd, encoding: 'utf-8', env: { ...process.env, TRAINCTL_LANG: 'en', NO_COLOR: '1', ...env }, + }) + +describe('daty względne (tylko CLI)', () => { + const today = '2026-08-12' // środa + it.each([ + ['2026-08-20', 'forward', '2026-08-20'], + ['today', 'forward', '2026-08-12'], + ['yesterday', 'back', '2026-08-11'], + ['jutro', 'forward', '2026-08-13'], + ['+3', 'forward', '2026-08-15'], + ['-7', 'back', '2026-08-05'], + ['thu', 'forward', '2026-08-13'], + ['thu', 'back', '2026-08-06'], + ['wed', 'forward', '2026-08-12'], + ['wed', 'back', '2026-08-12'], + ['Śr', 'forward', '2026-08-12'], + ['niedziela', 'back', '2026-08-09'], + ['MONDAY', 'forward', '2026-08-17'], + ] as const)('%s (%s) → %s', (input, direction, expected) => { + expect(resolveDateInput(input, today, direction)).toBe(expected) + }) + it('odrzuca to, co nie jest datą, i niemożliwą datę', () => { + expect(() => resolveDateInput('someday', today)).toThrow(/not a date/) + expect(() => resolveDateInput('2026-02-30', today)).toThrow() + }) +}) + +describe('binarka: --json, -C, TRAINCTL_TODAY, daty względne, kody wyjścia', () => { + it('--json: czyste dane, bez ANSI, kod zgodny z kodem procesu', () => { + expect(run(['plan', '--date', '2026-08-08', '--json']).status).toBe(0) + const r = run(['today', '--date', '2026-08-11', '--json']) + expect(r.status).toBe(0) + expect(r.stdout).not.toMatch(/\u001b\[/) + const parsed = JSON.parse(r.stdout) as { code: number; data: { date: string; day: { workout: { kind: string } } }; output: string } + expect(parsed.code).toBe(0) + expect(parsed.data.date).toBe('2026-08-11') + expect(parsed.output).toContain('2026-08-11') + const fail = run(['today', '--json'], {}, mkdtempSync(join(tmpdir(), 'trainctl-040-empty-'))) + expect(fail.status).toBe(1) + expect(JSON.parse(fail.stdout)).toMatchObject({ code: 1 }) + }, 30_000) + + it('-C i TRAINCTL_DIR wskazują katalog treningowy spoza cwd', () => { + const elsewhere = mkdtempSync(join(tmpdir(), 'trainctl-040-cwd-')) + try { + expect(run(['-C', dir, 'plan', '--date', '2026-08-08'], {}, elsewhere).stdout).toContain('Saved plan/plan.yaml') + expect(run(['today', '--date', '2026-08-11'], { TRAINCTL_DIR: dir }, elsewhere).stdout).toContain('2026-08-11 · Tuesday') + expect(run(['--dir', join(dir, 'missing'), 'today'], {}, elsewhere).status).toBe(1) + } finally { + rmSync(elsewhere, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) + } + }, 30_000) + + it('TRAINCTL_TODAY: zegar przesunięty i ogłoszony w pierwszym wierszu', () => { + run(['plan', '--date', '2026-08-08']) + const r = run(['today'], { TRAINCTL_TODAY: '2026-08-11' }) + expect(r.stdout.split('\n')[0]).toContain('simulated date 2026-08-11 (TRAINCTL_TODAY)') + expect(r.stdout).toContain('2026-08-11 · Tuesday') + // ochrona przeszłości idzie za symulacją: dzień przed nią jest przeszły + expect(run(['shift', '--from', '2026-08-10', '--to', '2026-08-11'], { TRAINCTL_TODAY: '2026-08-11' }).status).toBe(1) + const json = JSON.parse(run(['today', '--json'], { TRAINCTL_TODAY: '2026-08-11' }).stdout) as { notice: string } + expect(json.notice).toContain('2026-08-11') + expect(run(['today'], { TRAINCTL_TODAY: 'tomorrow' }).stdout).toContain('is not a date') + }, 30_000) + + it('daty względne w prawdziwej binarce i kod 2 dla błędu użycia', () => { + run(['plan', '--date', '2026-08-08']) + expect(run(['why', '--date', 'tue'], { TRAINCTL_TODAY: '2026-08-10' }).stdout).toContain('Why this session · 2026-08-11') + const bad = run(['today', '--date', 'someday']) + expect(bad.status).toBe(2) + expect(bad.stderr).toContain('not a date') + expect(run(['no-such-command']).status).toBe(2) + }, 30_000) + + it('help komendy niesie przykłady; status i completion działają', () => { + expect(run(['help', 'log']).stdout).toContain('trainctl log --km 8') + run(['plan', '--date', '2026-08-08']) + expect(run(['status']).stdout).toContain('Training directory') + const bash = run(['completion', 'bash']) + expect(bash.status).toBe(0) + expect(bash.stdout).toContain('complete -F _trainctl trainctl') + expect(bash.stdout).toContain('--fresh') + expect(run(['completion', 'tcsh']).status).toBe(2) + }, 30_000) +}) + +describe('status', () => { + it('pusty katalog: profil jest, planu nie ma — podpowiada plan', () => { + const r = cmdStatus(dir) + expect(r.code).toBe(0) + expect(r.output).toContain('No plan yet.') + expect(r.output).toContain('next: trainctl plan') + expect(r.data).toMatchObject({ config: { exists: true, valid: true }, plan: null, git: null }) + }) + it('z planem: wersja silnika, dziennik i niezacommitowane pliki', () => { + cmdPlan(dir, { date: '2026-08-08' }) + cmdLog(dir, { date: '2026-08-11', km: '8' }) + execFileSync('git', ['init', '-q'], { cwd: dir }) + const r = cmdStatus(dir) + expect(r.output).toContain('Half marathon · 2026-11-29') + expect(r.output).toMatch(/log\.jsonl: 1 entry, last 2026-08-11 \(done\)/) + expect(r.data).toMatchObject({ git: { uncommitted: expect.arrayContaining(['trainctl.yaml']) } }) + }) + it('nigdy nie ujawnia wartości klucza z .env', () => { + writeFileSync(join(dir, '.env'), 'TRAINCTL_INTERVALS_API_KEY=super-secret-value\n', 'utf-8') + const r = cmdStatus(dir) + expect(r.output).not.toContain('super-secret-value') + expect(JSON.stringify(r.data)).not.toContain('super-secret-value') + expect(r.data).toMatchObject({ key: { source: '.env' } }) + }) +}) + +describe('--commit', () => { + const gitEnv = { GIT_AUTHOR_NAME: 't', GIT_AUTHOR_EMAIL: 't@example.test', GIT_COMMITTER_NAME: 't', GIT_COMMITTER_EMAIL: 't@example.test' } + beforeEach(() => { Object.assign(process.env, gitEnv) }) + afterEach(() => { for (const k of Object.keys(gitEnv)) delete process.env[k] }) + const gitOut = (args: string[]) => execFileSync('git', args, { cwd: dir, encoding: 'utf-8' }) + + it('commituje wyłącznie pliki zmienione przez komendę — nigdy sekretów ani cudzych zmian', () => { + execFileSync('git', ['init', '-q'], { cwd: dir }) + writeFileSync(join(dir, '.env'), 'TRAINCTL_INTERVALS_API_KEY=x\n', 'utf-8') + writeFileSync(join(dir, 'notes.md'), 'mine\n', 'utf-8') + execFileSync('git', ['add', 'notes.md'], { cwd: dir }) + const r = cmdPlan(dir, { date: '2026-08-08', commit: true }) + expect(r.code).toBe(0) + expect(r.output).toMatch(/Committed [0-9a-f]+: plan\/plan\.yaml, plan\/PLAN\.md/) + expect(gitOut(['show', '--name-only', '--format=%s', 'HEAD']).trim().split('\n')).toEqual( + ['trainctl plan: Half marathon (2026-11-29)', '', 'plan/PLAN.md', 'plan/plan.yaml']) + // cudza zmiana w indeksie została w indeksie, sekret nietknięty + expect(gitOut(['diff', '--cached', '--name-only']).trim()).toBe('notes.md') + expect(gitOut(['ls-files'])).not.toContain('.env') + }) + it('własna wiadomość; dziennik; brak gita to informacja, nie błąd', () => { + cmdPlan(dir, { date: '2026-08-08' }) + const noGit = cmdLog(dir, { date: '2026-08-11', km: '8', commit: true }) + expect(noGit.code).toBe(0) + expect(noGit.output).toContain('Not a git repository') + execFileSync('git', ['init', '-q'], { cwd: dir }) + const r = cmdLog(dir, { date: '2026-08-13', km: '10', commit: 'easy run, legs fine' }) + expect(r.output).toMatch(/Committed [0-9a-f]+: log\.jsonl/) + expect(gitOut(['log', '-1', '--format=%s']).trim()).toBe('easy run, legs fine') + }) + it('odmowa zapisu nie commituje niczego', () => { + cmdPlan(dir, { date: '2026-08-08' }) + execFileSync('git', ['init', '-q'], { cwd: dir }) + const r = cmdShift(dir, { from: '2026-11-29', to: '2026-11-28', commit: true }) + expect(r.code).toBe(1) + expect(spawnSync('git', ['rev-parse', 'HEAD'], { cwd: dir }).status).not.toBe(0) + }) +}) + +describe('today i interaktywny log', () => { + it('today pokazuje szacowany czas i następną sesję', () => { + cmdPlan(dir, { date: '2026-08-08' }) + const r = cmdToday(dir, { date: '2026-08-11' }) + expect(r.output).toMatch(/about \d+ min including preparation/) + expect(r.output).toMatch(/next: \w+ 2026-08-1\d · /) + expect(r.data).toMatchObject({ next: { date: expect.stringMatching(/^2026-08-1\d$/) } }) + }) + it('lista wyboru: ostatnie siedem dni od dziś wstecz, ze statusem z dziennika', () => { + cmdPlan(dir, { date: '2026-08-08' }) + const choices = logChoices(loadPlan(dir), '2026-08-13', new Map([['2026-08-11', 'done']])) + expect(choices.map((c) => c.value)).toEqual(['2026-08-13', '2026-08-12', '2026-08-11', '2026-08-10', '2026-08-09', '2026-08-08', '2026-08-07']) + expect(choices.find((c) => c.value === '2026-08-11')!.hint).toContain('[logged: done]') + }) + it('status odpowiedzi: skróty i pełne nazwy', () => { + expect(parseLogStatus('d')).toBe('done') + expect(parseLogStatus('Skipped')).toBe('skipped') + expect(parseLogStatus('m')).toBe('modified') + expect(() => parseLogStatus('maybe')).toThrow() + }) +}) + +describe('completion', () => { + const specs = [{ name: 'plan', description: "plan it's", options: [{ long: '--fresh', description: 'start over' }] }] + it.each(['bash', 'zsh', 'fish', 'pwsh'] as const)('%s: każda komenda i flaga w skrypcie', (shell) => { + const script = completionScript(shell, specs, [{ long: '--json', description: 'json' }]) + expect(script).toContain('plan') + expect(script).toContain(shell === 'fish' ? '-l fresh' : '--fresh') + }) +}) + +// katalog z planem w podkatalogu git — -C działa także na ścieżkach względnych +describe('-C ze ścieżką względną', () => { + it('rozwiązuje ją względem katalogu procesu', () => { + const parent = mkdtempSync(join(tmpdir(), 'trainctl-040-rel-')) + try { + mkdirSync(join(parent, 'training')) + writeFileSync(join(parent, 'training', 'trainctl.yaml'), CONFIG, 'utf-8') + expect(run(['-C', 'training', 'plan', '--date', '2026-08-08'], {}, parent).status).toBe(0) + expect(readFileSync(join(parent, 'training', 'plan', 'plan.yaml'), 'utf-8')).toContain('Half marathon') + } finally { + rmSync(parent, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) + } + }, 30_000) +}) diff --git a/packages/cli/src/clock.ts b/packages/cli/src/clock.ts new file mode 100644 index 0000000..f0eb670 --- /dev/null +++ b/packages/cli/src/clock.ts @@ -0,0 +1,45 @@ +/** + * Zegar CLI: lokalna data kalendarzowa albo jawna symulacja (ADR-034). + * + * Ochrona przeszłości (A05) idzie po prawdziwym zegarze, nie po `--date` — + * i słusznie. Bez sankcjonowanej symulacji nie dało się jednak odtworzyć + * przykładów z dokumentacji ani ręcznie sprawdzić scenariusza „za trzy + * tygodnie" na katalogu z planem w przeszłości. `TRAINCTL_TODAY` przesuwa + * zegar w całości — ochrona przeszłości obowiązuje względem daty symulowanej — + * i nigdy nie jest cicha: CLI i MCP mówią o niej w każdym wyjściu. + */ +import { parseIso } from 'trainctl-core' +import { ui } from './i18n/index.ts' + +export const SIMULATED_TODAY_ENV = 'TRAINCTL_TODAY' + +/** Data symulowana albo undefined; zły format to błąd, nie cichy powrót do zegara. */ +export function simulatedToday(): string | undefined { + const raw = process.env[SIMULATED_TODAY_ENV]?.trim() + if (!raw) return undefined + try { + parseIso(raw) + } catch { + throw new Error(ui().clock.badSimulatedDate(SIMULATED_TODAY_ENV, raw)) + } + return raw +} + +/** „Dziś" dla wszystkich komend: symulacja, a bez niej lokalna data kalendarzowa. */ +export function clockToday(): string { + const simulated = simulatedToday() + if (simulated) return simulated + const d = new Date() + const p = (n: number) => String(n).padStart(2, '0') + return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}` +} + +/** Ostrzeżenie do dołożenia przed każdym wyjściem; undefined, gdy zegar jest prawdziwy. */ +export function simulationNotice(): string | undefined { + try { + const simulated = simulatedToday() + return simulated ? ui().clock.simulated(SIMULATED_TODAY_ENV, simulated) : undefined + } catch (e) { + return e instanceof Error ? e.message : String(e) + } +} diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index 73dc917..1e07303 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -32,13 +32,17 @@ import { inferredConfigYaml, loadConfig, writeConfigTemplate, CONFIG_FILE } from import { appendLog, logFor, parseTime, readLog, type LogEntry } from './logfile.ts' import { computePlan, + cycleWeeksOf, + dayFingerprint, findDay, fmtTime, loadPlan, loadPlanFile, + loadPlanIfUsable, readPlanDocument, shiftWorkout, workoutText, + weekPosition, writePlan, PLAN_MD, PLAN_YAML, @@ -46,12 +50,20 @@ import { } from './planfile.ts' import { foundationsUrl, kindPurpose, ruleExplain, ruleEvidence } from './rules-explain.ts' import { packageVersion } from './version.ts' +import { clockToday } from './clock.ts' +import { rebuildPlan, type Regeneration } from './regenerate.ts' +import { commitFiles } from './git.ts' +import { LOG_FILE } from './logfile.ts' +export { cmdStatus } from './status.ts' +export { resolveDateInput, type DateDirection } from './date-input.ts' +export { completionScript, SHELLS, type CompletionSpec, type Shell } from './completion.ts' +export { simulationNotice, simulatedToday, SIMULATED_TODAY_ENV } from './clock.ts' import { runExport, EXPORT_DIR, type ExportWhat } from './export.ts' import { b, renderPlain, type Block } from './ui/blocks.ts' import type { ColorName } from './ui/theme.ts' import { buildExecution, isRunningActivity } from './execution.ts' import { resultKey } from './calibration.ts' -import { applyProposal, prepareProposal, prepareShortening, type PlanProposal } from './proposals.ts' +import { applyProposal, prepareProposal, prepareShortening, recordedDates, type PlanProposal } from './proposals.ts' import { explainSession } from './explain-session.ts' export { buildExecution } from './execution.ts' @@ -112,6 +124,34 @@ const fail = (e: unknown): CmdResult => { return { output: message, code: 1, blocks: [b.error(message)] } } +/** Wartość flagi `--commit`: brak, `true` (domyślna wiadomość) albo własna wiadomość. */ +export type CommitOption = boolean | string | undefined + +const PLAN_FILES = [PLAN_YAML, PLAN_MD] + +/** + * `--commit` po udanym zapisie (ADR-040) — nigdy zamiast niego: brak gita albo + * brak zmian to informacja, nieudany commit to ostrzeżenie, a zapis zostaje. + */ +function commitBlocks(cwd: string, commit: CommitOption, files: string[], message: string): { blocks: Block[]; outcome: unknown } { + if (commit === undefined || commit === false) return { blocks: [], outcome: null } + const outcome = commitFiles(cwd, files, typeof commit === 'string' && commit.trim() ? commit.trim() : message) + const t = ui().commit + const block = outcome.status === 'committed' ? b.success(t.done(outcome.sha, outcome.files.join(', '))) + : outcome.status === 'no-git' ? b.info(t.noGit) + : outcome.status === 'nothing' ? b.info(t.nothing) + : b.warn(t.failed(outcome.detail)) + return { blocks: [block], outcome } +} + +/** Dokłada wynik commita do gotowego wyniku komendy (bloki i dane). */ +function withCommit(result: CmdResult, cwd: string, commit: CommitOption, files: string[], message: string): CmdResult { + if (result.code !== 0 || commit === undefined || commit === false) return result + const { blocks, outcome } = commitBlocks(cwd, commit, files, message) + const all = [...(result.blocks ?? []), ...blocks] + return { ...result, blocks: all, output: renderPlain(all), data: { ...(result.data ?? {}), commit: outcome } } +} + /** * Plan z innego minora silnika nadal działa, ale poniżej 1.0 regeneracja może dać * inne tygodnie (CHANGELOG). Mówimy o tym przy czytaniu planu — nie blokujemy. @@ -123,11 +163,8 @@ export function compatibilityNotes(plan: StoredPlan): Block[] { return minor(plan.engineVersion) === minor(current) ? [] : [b.info(ui().common.planFromOtherEngine(plan.engineVersion, current))] } -export function localToday(): string { - const d = new Date() - const p = (n: number) => String(n).padStart(2, '0') - return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}` -} +/** „Dziś" komend: lokalny kalendarz albo jawna symulacja TRAINCTL_TODAY (ADR-034). */ +export const localToday = (): string => clockToday() const weekdayName = (day: Weekday): string => messages().weekday[day] /** Skróty jak w planach trenera (korpus) — po angielsku Mon/Tue/… */ @@ -242,7 +279,11 @@ function protectSecrets(cwd: string): string[] { return missing } -export function cmdInit(cwd: string, content?: string): CmdResult { +export function cmdInit(cwd: string, content?: string, opts: { commit?: CommitOption } = {}): CmdResult { + return withCommit(initImpl(cwd, content), cwd, opts.commit, [CONFIG_FILE, AGENTS_FILE, '.gitignore'], ui().commit.init) +} + +function initImpl(cwd: string, content?: string): CmdResult { try { writeConfigTemplate(cwd, content) const agents = writeAgentsFile(cwd) @@ -263,16 +304,29 @@ export function cmdInit(cwd: string, content?: string): CmdResult { } } -export function cmdPlan(cwd: string, opts: { date?: string | undefined } = {}): CmdResult { +export function cmdPlan(cwd: string, opts: { date?: string | undefined; fresh?: boolean | undefined; commit?: CommitOption } = {}): CmdResult { + const result = planImpl(cwd, opts) + const goal = (result.data?.['plan'] as StoredPlan | undefined)?.goal + return withCommit(result, cwd, opts.commit, PLAN_FILES, ui().commit.plan(goal?.name ?? '', goal?.date ?? '')) +} + +function planImpl(cwd: string, opts: { date?: string | undefined; fresh?: boolean | undefined }): CmdResult { try { const today = opts.date ?? localToday() const config = loadConfig(cwd) - const plan = computePlan(config, today) + // Istniejący plan regenerujemy z ochroną przeszłości i zatwierdzonych decyzji + // (ADR-033); od zera wyłącznie na jawne --fresh albo gdy pliku nie da się użyć. + const existing = loadPlanIfUsable(cwd) + const rebuild = existing && opts.fresh !== true + ? rebuildPlan(existing, config, { today, recorded: recordedDates(cwd) }) + : undefined + const plan = rebuild ? rebuild.plan : computePlan(config, today) const issues = validatePlan(plan) if (issues.some(issue => issue.severity === 'error')) throw new Error(issues.map(describeIssue).join('\n')) - writePlan(cwd, plan) + if (rebuild?.upToDate !== true) writePlan(cwd, plan) - const weeksToRace = plan.weeks.length + const cycle = cycleWeeksOf(plan) + const weeksToRace = cycle.length const blocks: Block[] = [ b.title( `${plan.goal.name} · ${plan.goal.distanceKm} km`, @@ -321,7 +375,7 @@ export function cmdPlan(cwd: string, opts: { date?: string | undefined } = {}): const phases: string[] = [] let current = '' let from = 0 - plan.weeks.forEach((w, i) => { + cycle.forEach((w, i) => { const label = phaseLabel(w.skeleton.phase) if (label !== current) { if (current) phases.push(ui().plan.phaseSpan(current, from + 1, i)) @@ -329,8 +383,13 @@ export function cmdPlan(cwd: string, opts: { date?: string | undefined } = {}): from = i } }) - if (current) phases.push(ui().plan.phaseSpan(current, from + 1, plan.weeks.length)) + if (current) phases.push(ui().plan.phaseSpan(current, from + 1, cycle.length)) blocks.push(b.section(ui().plan.structure), b.bullets(phases)) + if (rebuild && existing && !rebuild.upToDate) blocks.push(...regenerationBlocks(existing, rebuild)) + if (opts.fresh === true && existing) { + const dropped = freshDropped(existing) + if (dropped) blocks.push(b.blank(), b.warn(ui().plan.freshDropped(dropped))) + } if (plan.feasibilityWarnings.length) { blocks.push(b.blank()) @@ -339,15 +398,60 @@ export function cmdPlan(cwd: string, opts: { date?: string | undefined } = {}): for (const issue of issues) blocks.push(b.warn(describeIssue(issue))) blocks.push( b.blank(), - b.success(ui().common.saved(`${PLAN_YAML} + ${PLAN_MD}`)), + rebuild?.upToDate ? b.success(ui().plan.upToDate) : b.success(ui().common.saved(`${PLAN_YAML} + ${PLAN_MD}`)), b.hint('trainctl today · trainctl week · trainctl why'), ) - return okDoc(blocks, { plan, issues }) + return okDoc(blocks, { plan, issues, regeneration: rebuild ? regenerationData(rebuild) : null }) } catch (e) { return fail(e) } } +const regenerationData = (r: Regeneration) => ({ + mode: r.mode, changedDates: r.changedDates, protectedDays: r.protectedDays, + loadState: r.loadState, droppedWeeks: r.droppedWeeks, upToDate: r.upToDate, +}) + +/** Co regeneracja zmienia, czego nie rusza i dlaczego — jedno źródło dla `plan` i `diff`. */ +function regenerationBlocks(existing: StoredPlan, r: Regeneration, opts: { diffLines?: boolean } = {}): Block[] { + const t = ui().plan + const blocks: Block[] = [b.section(t.regenSection)] + blocks.push(b.text(r.mode === 'same-cycle' + ? t.sameCycle(r.plan.generatedAt) + : t.newCycle(r.plan.cycleStart ?? r.plan.weeks[0]?.weekStart ?? r.plan.generatedAt))) + const counts = new Map() + for (const p of r.protectedDays) counts.set(p.reason, (counts.get(p.reason) ?? 0) + 1) + const reasons = [...counts].map(([reason, count]) => `${t.reasons[reason as keyof typeof t.reasons]} ${count}`).join(', ') + blocks.push(b.kv([ + [t.changedDays, String(r.changedDates.length)], + ...(r.protectedDays.length ? ([[t.keptDays, reasons]] as [string, string][]) : []), + ])) + if (r.loadState === 'kept' && r.plan.loadState) blocks.push(b.info(t.loadKept(r.plan.loadState.baselineWeeklyKm, r.plan.loadState.effectiveFrom))) + if (r.loadState === 'cleared' && existing.loadState) blocks.push(b.info(t.loadCleared(existing.loadState.baselineWeeklyKm))) + if (r.droppedWeeks.length) blocks.push(b.warn(t.droppedWeeks(r.droppedWeeks.join(', ')))) + if (opts.diffLines !== false) { + const lines = diffWeeks(existing.weeks, r.plan.weeks) + if (lines.length) blocks.push(b.bullets(lines.slice(0, 12))) + if (lines.length > 12) blocks.push(b.text(t.moreLines(lines.length - 12), 'muted')) + } + return blocks +} + +/** Czego `--fresh` się pozbywa — mówimy przed faktem dokonanym, nie po nim. */ +function freshDropped(existing: StoredPlan): string { + const t = ui().plan.freshItems + const days = existing.weeks.flatMap((w) => w.days) + const edited = existing.generatedDays ? days.filter((d) => existing.generatedDays![d.date] !== undefined && existing.generatedDays![d.date] !== dayFingerprint(d)).length : 0 + return [ + ...(existing.loadState ? [t.loadState(existing.loadState.baselineWeeklyKm)] : []), + ...(days.some((d) => d.pinned) ? [t.pinned(days.filter((d) => d.pinned).length)] : []), + ...(Object.keys(existing.timeBudgets ?? {}).length ? [t.budgets(Object.keys(existing.timeBudgets!).length)] : []), + ...(days.some((d) => d.timeAdjustment) ? [t.approved(days.filter((d) => d.timeAdjustment).length)] : []), + ...(edited ? [t.edited(edited)] : []), + ...(existing.changes.length ? [t.history(existing.changes.length)] : []), + ].join(', ') +} + export function cmdToday(cwd: string, opts: { date?: string | undefined } = {}): CmdResult { try { const date = opts.date ?? localToday() @@ -364,7 +468,7 @@ export function cmdToday(cwd: string, opts: { date?: string | undefined } = {}): const blocks: Block[] = [ b.title( `${date} · ${weekdayName(day.weekday)}`, - `${ui().today.weekOf(sk.index + 1, plan.weeks.length)} · ${phaseLabel(sk.phase)}` + + `${ui().today.weekOf(weekPosition(plan, week).index + 1, weekPosition(plan, week).total)} · ${phaseLabel(sk.phase)}` + `${sk.deload ? ` · ${ui().today.deload}` : ''} · ${ui().today.daysToRace(toRace)}`, ), ...compatibilityNotes(plan), @@ -408,9 +512,15 @@ export function cmdToday(cwd: string, opts: { date?: string | undefined } = {}): ), ) } + const estimatedMinutes = (day.workout ? estimateWorkoutMinutes(day.workout, plan.preparationMinutes ?? 15) : 0) + (day.strength?.durationMin ?? 0) + // Dla biegacza zza biurka dwie najważniejsze liczby dnia: ile to potrwa i co dalej. + if ((day.workout || day.strength) && Number.isFinite(estimatedMinutes)) blocks.push(b.text(ui().today.estimate(estimatedMinutes), 'muted')) + const next = plan.weeks.flatMap((w) => w.days).find((d) => d.date > date && d.workout) + if (next?.workout) { + blocks.push(b.text(ui().today.next(next.date, weekdayName(next.weekday), kindLabel(next.workout.kind), next.workout.raceDistanceKm ?? next.workout.distanceKm), 'muted')) + } if (day.workout) blocks.push(b.hint(ui().today.whyHint(date))) - const estimatedMinutes = (day.workout ? estimateWorkoutMinutes(day.workout) : 0) + (day.strength?.durationMin ?? 0) - return okDoc(blocks, { date, day, week: { weekStart: week.weekStart, phase: sk.phase }, log: entry ?? null, calibration: plan.calibration ?? null, estimatedMinutes: Number.isFinite(estimatedMinutes) ? estimatedMinutes : null }) + return okDoc(blocks, { date, day, week: { weekStart: week.weekStart, phase: sk.phase }, log: entry ?? null, calibration: plan.calibration ?? null, estimatedMinutes: Number.isFinite(estimatedMinutes) ? estimatedMinutes : null, next: next ? { date: next.date, kind: next.workout!.kind, distanceKm: next.workout!.raceDistanceKm ?? next.workout!.distanceKm } : null }) } catch (e) { return fail(e) } @@ -443,7 +553,7 @@ export function cmdWeek(cwd: string, opts: { date?: string | undefined } = {}): } const blocks: Block[] = [ b.title( - ui().week.title(sk.index + 1, plan.weeks.length, week.weekStart), + ui().week.title(weekPosition(plan, week).index + 1, weekPosition(plan, week).total, week.weekStart), ui().week.subtitle(phaseLabel(sk.phase), model, sk.targetKm, week.totalKm) + (sk.deload ? ` · ${ui().week.deloadUpper}` : ''), ), @@ -460,18 +570,23 @@ export function cmdWeek(cwd: string, opts: { date?: string | undefined } = {}): } } -export function cmdLog( - cwd: string, - opts: { - date?: string | undefined - status?: string | undefined - km?: string | undefined - time?: string | undefined - testTime?: string | undefined - rpe?: string | undefined - note?: string | undefined - } = {}, -): CmdResult { +type LogOptions = { + date?: string | undefined + status?: string | undefined + km?: string | undefined + time?: string | undefined + testTime?: string | undefined + rpe?: string | undefined + note?: string | undefined +} + +export function cmdLog(cwd: string, opts: LogOptions & { commit?: CommitOption } = {}): CmdResult { + const result = logImpl(cwd, opts) + const entry = result.data?.['entry'] as LogEntry | undefined + return withCommit(result, cwd, opts.commit, [LOG_FILE], ui().commit.log(entry?.date ?? '', entry?.status ?? '')) +} + +function logImpl(cwd: string, opts: LogOptions): CmdResult { try { const date = opts.date ?? localToday() const plan = loadPlan(cwd) @@ -533,7 +648,11 @@ export function cmdLog( } } -export function cmdShift(cwd: string, opts: { from: string; to: string }): CmdResult { +export function cmdShift(cwd: string, opts: { from: string; to: string; commit?: CommitOption }): CmdResult { + return withCommit(shiftImpl(cwd, opts), cwd, opts.commit, PLAN_FILES, ui().commit.shift(opts.from, opts.to)) +} + +function shiftImpl(cwd: string, opts: { from: string; to: string }): CmdResult { try { if (opts.from < localToday() || opts.to < localToday()) throw new Error(ui().improve.pastWrite) const plan = loadPlan(cwd) @@ -827,7 +946,12 @@ function analyzeAdapt(cwd: string, opts: { date?: string | undefined } = {}): Cm } } -export function cmdAdapt(cwd: string, opts: { date?: string | undefined; prepare?: boolean | undefined; apply?: string | undefined } = {}): CmdResult { +export function cmdAdapt(cwd: string, opts: { date?: string | undefined; prepare?: boolean | undefined; apply?: string | undefined; commit?: CommitOption } = {}): CmdResult { + const result = adaptImpl(cwd, opts) + return opts.apply ? withCommit(result, cwd, opts.commit, PLAN_FILES, ui().commit.apply(opts.apply)) : result +} + +function adaptImpl(cwd: string, opts: { date?: string | undefined; prepare?: boolean | undefined; apply?: string | undefined }): CmdResult { try { if (opts.prepare && opts.apply) throw new Error(ui().improve.proposalOptions) if (opts.apply) { @@ -854,11 +978,11 @@ function proposalBlocks(saved: PlanProposal): Block[] { ] } -export function cmdShorten(cwd: string, opts: { date?: string | undefined; minutes?: string | number | undefined; apply?: string | undefined } = {}): CmdResult { +export function cmdShorten(cwd: string, opts: { date?: string | undefined; minutes?: string | number | undefined; apply?: string | undefined; commit?: CommitOption } = {}): CmdResult { try { if (opts.apply) { if (opts.minutes !== undefined || opts.date !== undefined) throw new Error(ui().coach.options) - return cmdAdapt(cwd, { apply: opts.apply }) + return cmdAdapt(cwd, { apply: opts.apply, commit: opts.commit }) } if (opts.minutes === undefined || String(opts.minutes).trim() === '') throw new Error(ui().coach.options) const date = opts.date ?? localToday() @@ -941,12 +1065,19 @@ export function cmdDesk( } } -export function cmdReschedule( - cwd: string, - opts: { block?: string[] | undefined; date?: string | undefined; apply?: boolean | undefined; - time?: string[] | undefined; pin?: string[] | undefined; preparation?: string | undefined; - strategy?: string | undefined } = {}, -): CmdResult { +type RescheduleOptions = { block?: string[] | undefined; date?: string | undefined; apply?: boolean | undefined; + time?: string[] | undefined; pin?: string[] | undefined; preparation?: string | undefined; + strategy?: string | undefined } + +export function cmdReschedule(cwd: string, opts: RescheduleOptions & { commit?: CommitOption } = {}): CmdResult { + const result = rescheduleImpl(cwd, opts) + const weekStart = mondayOf(opts.date ?? opts.block?.[0] ?? localToday()) + return opts.apply === true && result.data?.['applied'] === true && (result.data?.['result'] as { changed?: boolean } | undefined)?.changed !== false + ? withCommit(result, cwd, opts.commit, PLAN_FILES, ui().commit.reschedule(weekStart)) + : result +} + +function rescheduleImpl(cwd: string, opts: RescheduleOptions): CmdResult { try { const date = opts.date ?? opts.block?.[0] ?? localToday() const plan = loadPlan(cwd) @@ -1549,9 +1680,12 @@ export function cmdDiff(cwd: string, opts: { plan?: string | undefined } = {}): return diffAgainstPlanFile(stored, isAbsolute(opts.plan) ? opts.plan : join(cwd, opts.plan)) } const config = loadConfig(cwd) - const fresh = computePlan(config, stored.generatedAt) + // Dry-run dokładnie tej regeneracji, którą wykona `plan` (ADR-033) — inaczej + // diff pokazywałby zmiany dni, których plan i tak nie ruszy. + const rebuild = rebuildPlan(stored, config, { today: localToday(), recorded: recordedDates(cwd) }) + const fresh = rebuild.plan const lines: string[] = [] - if (stored.changes.length) { + if (rebuild.protectedDays.some((p) => p.reason === 'edited')) { lines.push(ui().diff.manualShifts) } // Sam `diff` porównuje rodzaje jednostek (klucze), więc zmiana języka go nie @@ -1563,16 +1697,17 @@ export function cmdDiff(cwd: string, opts: { plan?: string | undefined } = {}): const localeNote = staleLocale ? [b.warn(ui().diff.localeChanged(stored.locale!, current))] : [] - if (lines.length === 0) { - return okDoc([b.success(ui().diff.upToDate), ...localeNote]) + if (lines.length === 0 && rebuild.upToDate) { + return okDoc([b.success(ui().diff.upToDate), ...localeNote], { regeneration: regenerationData(rebuild) }) } return okDoc([ b.title(ui().diff.title), - b.bullets(lines), + b.bullets(lines.length ? lines : [ui().diff.metadataOnly]), + ...regenerationBlocks(stored, rebuild, { diffLines: false }), ...localeNote, b.blank(), b.hint(ui().diff.applyHint), - ]) + ], { regeneration: regenerationData(rebuild) }) } catch (e) { return fail(e) } diff --git a/packages/cli/src/completion.ts b/packages/cli/src/completion.ts new file mode 100644 index 0000000..6a19718 --- /dev/null +++ b/packages/cli/src/completion.ts @@ -0,0 +1,92 @@ +/** + * `trainctl completion ` — skrypty uzupełniania generowane z drzewa + * komend, więc nowa komenda albo flaga nie wymaga ręcznej aktualizacji czterech + * plików. Zero zależności: statyczny tekst do wklejenia w profil powłoki. + */ +export interface CompletionSpec { + name: string + description: string + options: { long: string; short?: string; description: string }[] +} + +export const SHELLS = ['bash', 'zsh', 'fish', 'pwsh'] as const +export type Shell = (typeof SHELLS)[number] + +const fishQuote = (text: string) => text.replace(/\\/g, '\\\\').replace(/'/g, "\\'") +const psQuote = (text: string) => text.replace(/'/g, "''") + +function bash(commands: CompletionSpec[], global: CompletionSpec['options']): string { + const names = commands.map((c) => c.name).join(' ') + const globals = global.map((o) => o.long).join(' ') + const cases = commands + .map((c) => ` ${c.name}) opts="${[...c.options.map((o) => o.long), globals].join(' ')}" ;;`) + .join('\n') + return `# trainctl — bash completion. Load with: eval "$(trainctl completion bash)" +_trainctl() { + local cur="\${COMP_WORDS[COMP_CWORD]}" opts + if [ "$COMP_CWORD" -eq 1 ]; then + COMPREPLY=( $(compgen -W "${names} ${globals}" -- "$cur") ) + return + fi + case "\${COMP_WORDS[1]}" in +${cases} + *) opts="${globals}" ;; + esac + COMPREPLY=( $(compgen -W "$opts" -- "$cur") ) +} +complete -F _trainctl trainctl +` +} + +function fish(commands: CompletionSpec[], global: CompletionSpec['options']): string { + const lines = ['# trainctl — fish completion. Load with: trainctl completion fish | source', 'complete -c trainctl -f'] + for (const c of commands) { + lines.push(`complete -c trainctl -n '__fish_use_subcommand' -a '${c.name}' -d '${fishQuote(c.description)}'`) + for (const o of c.options) { + const short = o.short ? ` -s ${o.short.replace(/^-/, '')}` : '' + lines.push(`complete -c trainctl -n '__fish_seen_subcommand_from ${c.name}' -l ${o.long.replace(/^--/, '')}${short} -d '${fishQuote(o.description)}'`) + } + } + for (const o of global) lines.push(`complete -c trainctl -l ${o.long.replace(/^--/, '')} -d '${fishQuote(o.description)}'`) + return lines.join('\n') + '\n' +} + +function pwsh(commands: CompletionSpec[], global: CompletionSpec['options']): string { + const table = commands + .map((c) => ` '${c.name}' = @(${[...c.options.map((o) => `'${o.long}'`), ...global.map((o) => `'${o.long}'`)].join(', ')})`) + .join("\n") + return `# trainctl — PowerShell completion. Load with: trainctl completion pwsh | Out-String | Invoke-Expression +$trainctlOptions = @{ +${table} +} +Register-ArgumentCompleter -Native -CommandName trainctl -ScriptBlock { + param($wordToComplete, $commandAst, $cursorPosition) + $words = @($commandAst.CommandElements | ForEach-Object { $_.ToString() }) + if ($words.Count -le 1 -or ($words.Count -eq 2 -and $wordToComplete)) { + $candidates = @(${commands.map((c) => `'${psQuote(c.name)}'`).join(', ')}) + } else { + $candidates = $trainctlOptions[$words[1]] + } + $candidates | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object { + [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) + } +} +` +} + +export function completionScript(shell: Shell, commands: CompletionSpec[], global: CompletionSpec['options']): string { + switch (shell) { + case 'bash': + return bash(commands, global) + case 'zsh': + // zsh rozumie skrypty bash przez bashcompinit — jedna definicja, dwie powłoki + return `# trainctl — zsh completion. Load with: eval "$(trainctl completion zsh)" +autoload -U +X bashcompinit && bashcompinit +${bash(commands, global).split('\n').slice(1).join('\n')}` + case 'fish': + return fish(commands, global) + case 'pwsh': + return pwsh(commands, global) + } +} + diff --git a/packages/cli/src/date-input.ts b/packages/cli/src/date-input.ts new file mode 100644 index 0000000..168c21e --- /dev/null +++ b/packages/cli/src/date-input.ts @@ -0,0 +1,53 @@ +/** + * Daty względne w linii poleceń: `yesterday`, `+2`, `thu`, `wczoraj`, `śr`. + * + * Tylko CLI. Narzędzia MCP przyjmują wyłącznie ISO — agent liczy daty sam, + * a „czwartek" w narzędziu byłby dwuznaczny dokładnie tam, gdzie nikt nie + * patrzy na wynik przed zapisem. + * + * Kierunek dla nazw dni: komendy, które patrzą wstecz (`log`, `review`, `adapt`, + * `pull`), biorą najbliższy taki dzień nie później niż dziś; pozostałe — + * najbliższy nie wcześniej niż dziś. Dziś pasuje w obu kierunkach. + */ +import { addDays, parseIso } from 'trainctl-core' +import { ui } from './i18n/index.ts' + +export type DateDirection = 'forward' | 'back' + +const WEEKDAY_ALIASES: Record = { + mon: 0, monday: 0, pn: 0, pon: 0, poniedzialek: 0, + tue: 1, tuesday: 1, wt: 1, wto: 1, wtorek: 1, + wed: 2, wednesday: 2, sr: 2, sro: 2, sroda: 2, + thu: 3, thursday: 3, czw: 3, czwartek: 3, + fri: 4, friday: 4, pt: 4, pia: 4, piatek: 4, + sat: 5, saturday: 5, sob: 5, sobota: 5, + sun: 6, sunday: 6, nd: 6, ndz: 6, nie: 6, niedziela: 6, +} +const OFFSETS: Record = { + today: 0, dzis: 0, dzisiaj: 0, + tomorrow: 1, jutro: 1, + yesterday: -1, wczoraj: -1, +} + +/** „Śr", „ŚRODA", „sroda" — jedno i to samo. */ +const normalize = (text: string) => + text.trim().toLowerCase().normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/ł/g, 'l') + +export function resolveDateInput(input: string, today: string, direction: DateDirection = 'forward'): string { + const raw = input.trim() + if (/^\d{4}-\d{2}-\d{2}$/.test(raw)) { + parseIso(raw) + return raw + } + const key = normalize(raw) + if (key in OFFSETS) return addDays(today, OFFSETS[key]!) + const offset = /^([+-])(\d{1,3})$/.exec(key) + if (offset) return addDays(today, (offset[1] === '-' ? -1 : 1) * Number(offset[2])) + const target = WEEKDAY_ALIASES[key] + if (target !== undefined) { + const current = (parseIso(today).getUTCDay() + 6) % 7 + const delta = direction === 'forward' ? (target - current + 7) % 7 : -((current - target + 7) % 7) + return addDays(today, delta) + } + throw new Error(ui().dates.badInput(input)) +} diff --git a/packages/cli/src/env-file.ts b/packages/cli/src/env-file.ts index e27a4dc..9e13a65 100644 --- a/packages/cli/src/env-file.ts +++ b/packages/cli/src/env-file.ts @@ -76,6 +76,22 @@ function insideGitRepo(cwd: string): boolean { } } +/** + * Stan `.env` bez wczytywania — dla `trainctl status`. Klucz rozpoznajemy po + * NAZWIE zmiennej, nigdy nie czytając ani nie zwracając jej wartości. + */ +export function inspectEnvFile(cwd: string, keyName: string): { exists: boolean; unprotected: boolean; hasKey: boolean } { + const path = join(cwd, ENV_FILE) + if (!existsSync(path)) return { exists: false, unprotected: false, hasKey: false } + let hasKey = false + try { + hasKey = readFileSync(path, 'utf-8').split('\n').some((l) => new RegExp(`^\\s*(export\\s+)?${keyName}\\s*=\\s*\\S`).test(l)) + } catch { + hasKey = false + } + return { exists: true, unprotected: insideGitRepo(cwd) && !isIgnored(cwd), hasKey } +} + /** * Wczytuje `.env` z katalogu, jeśli istnieje. Brak pliku to normalna sytuacja, * nie błąd — większość użytkowników trzyma klucz w zmiennej środowiskowej. diff --git a/packages/cli/src/export.ts b/packages/cli/src/export.ts index 666039a..08cd436 100644 --- a/packages/cli/src/export.ts +++ b/packages/cli/src/export.ts @@ -19,7 +19,7 @@ import { type RaceScenario, } from 'trainctl-export' import { ui } from './i18n/index.ts' -import { findDay, loadPlan, workoutText, type StoredPlan } from './planfile.ts' +import { cycleWeeksOf, findDay, loadPlan, weekPosition, workoutText, type StoredPlan } from './planfile.ts' import { kindPurpose, ruleExplain, ruleEvidence } from './rules-explain.ts' /** @@ -257,8 +257,10 @@ export function runExport(cwd: string, req: ExportRequest): ExportedFile[] { // rozpiska do wydruku const core = messages() const p = ui().print - const weeks: PrintWeek[] = plan.weeks.map((w) => ({ - index: w.skeleton.index, + // Kartka na lodówkę to bieżący cykl — historia poprzedniego zostaje w pliku i w gicie. + const cycle = cycleWeeksOf(plan) + const weeks: PrintWeek[] = cycle.map((w) => ({ + index: weekPosition(plan, w).index, weekStart: w.weekStart, phase: core.phase[w.skeleton.phase] ?? w.skeleton.phase, targetKm: w.skeleton.targetKm, @@ -276,7 +278,7 @@ export function runExport(cwd: string, req: ExportRequest): ExportedFile[] { })) const html = toPrintableHtml({ title: `${plan.goal.name} — ${plan.goal.date}`, - subtitle: p.subtitle(plan.weeks.length, plan.peakKmPlanned, plan.vdot, plan.generatedAt), + subtitle: p.subtitle(cycle.length, plan.peakKmPlanned, plan.vdot, plan.generatedAt), weeks, footer: p.footer, labels: { lang: getLocale(), ...p }, @@ -286,7 +288,7 @@ export function runExport(cwd: string, req: ExportRequest): ExportedFile[] { files.push({ path: file, bytes: Buffer.byteLength(html), - description: t.printedWeeks(plan.weeks.length), + description: t.printedWeeks(cycle.length), }) return files } diff --git a/packages/cli/src/git.ts b/packages/cli/src/git.ts new file mode 100644 index 0000000..2f6c159 --- /dev/null +++ b/packages/cli/src/git.ts @@ -0,0 +1,57 @@ +/** + * `--commit`: domknięcie historii gita po udanym zapisie (ADR-040). + * + * AGENTS.md każe commitować po każdej zmianie planu — flaga robi dokładnie to, + * bez stawania się klientem gita. Zasady: commit obejmuje WYŁĄCZNIE pliki, które + * komenda zmieniła (pathspec przy `git commit`, więc cudze zmiany w indeksie + * zostają nietknięte); nigdy sekretów ani migawki synchronizacji; brak gita to + * informacja, nie błąd — zapis już się udał. + */ +import { spawnSync } from 'node:child_process' +import { existsSync } from 'node:fs' +import { dirname, join } from 'node:path' + +/** Pliki, których `--commit` nie doda nigdy, nawet gdyby trafiły na listę. */ +const NEVER = new Set(['.env', '.trainctl-secret', 'sync.json']) + +export type CommitOutcome = + | { status: 'committed'; sha: string; files: string[] } + | { status: 'no-git' } + | { status: 'nothing' } + | { status: 'failed'; detail: string } + +export function insideGitRepo(cwd: string): boolean { + let dir = cwd + for (;;) { + if (existsSync(join(dir, '.git'))) return true + const parent = dirname(dir) + if (parent === dir) return false + dir = parent + } +} + +const git = (cwd: string, args: string[]) => + spawnSync('git', args, { cwd, encoding: 'utf-8', windowsHide: true }) + +export function commitFiles(cwd: string, files: string[], message: string): CommitOutcome { + if (!insideGitRepo(cwd)) return { status: 'no-git' } + const present = files.filter((f) => !NEVER.has(f.replace(/^\.\//, '')) && existsSync(join(cwd, f))) + if (present.length === 0) return { status: 'nothing' } + const add = git(cwd, ['add', '--', ...present]) + if (add.error) return { status: 'failed', detail: add.error.message } + if (add.status !== 0) return { status: 'failed', detail: (add.stderr || add.stdout).trim() } + const staged = git(cwd, ['diff', '--cached', '--quiet', '--', ...present]) + if (staged.status === 0) return { status: 'nothing' } + const commit = git(cwd, ['commit', '-m', message, '--', ...present]) + if (commit.status !== 0) return { status: 'failed', detail: (commit.stderr || commit.stdout).trim() } + const sha = git(cwd, ['rev-parse', '--short', 'HEAD']).stdout.trim() + return { status: 'committed', sha, files: present } +} + +/** Niezacommitowane zmiany w plikach katalogu treningowego (dla `status`). */ +export function uncommitted(cwd: string, paths: string[]): string[] | undefined { + if (!insideGitRepo(cwd)) return undefined + const r = git(cwd, ['status', '--porcelain', '--', ...paths]) + if (r.status !== 0) return undefined + return r.stdout.split('\n').map((l) => l.slice(3).trim()).filter(Boolean) +} diff --git a/packages/cli/src/i18n/cli-en.ts b/packages/cli/src/i18n/cli-en.ts index f1d86a1..ee78bef 100644 --- a/packages/cli/src/i18n/cli-en.ts +++ b/packages/cli/src/i18n/cli-en.ts @@ -39,6 +39,7 @@ export const cliEn = { check: 'lint the plan: engine invariants + file integrity; errors fail the exit code (CI)', optStrict: 'warnings also fail the exit code (for CI)', optDiffPlan: 'compare with another plan file instead (a scenario branch or worktree)', + optFresh: 'regenerate from scratch: discard kept past days, approvals, pins and budgets (they stay in git)', optDate: 'date (defaults to today)', optDateOther: 'a date other than today', optDateWeek: 'any date inside the week you care about', @@ -65,6 +66,18 @@ export const cliEn = { pickFromList: ' (pick from a list) · ', browseArrows: ' (browse with arrows)', colorsHint: 'Colours: NO_COLOR=1 disables them, TRAINCTL_ASCII=1 forces ASCII glyphs.', + datesHint: + 'Dates: YYYY-MM-DD, today/tomorrow/yesterday, +N/-N days, or a weekday (mon…sun). ' + + 'log, review, adapt and pull look back; the other commands look ahead.', + dirHint: 'Directory: -C or TRAINCTL_DIR; TRAINCTL_TODAY=YYYY-MM-DD simulates the date (always announced).', + optJson: 'print JSON ({ code, data, output }) instead of formatted text', + optDir: 'training directory (defaults to TRAINCTL_DIR, then the current directory)', + optCommit: 'commit the files this command changed (optionally with your own message)', + status: 'state of the training directory: profile, plan, data, proposals, git', + completion: 'print a shell completion script: bash | zsh | fish | pwsh', + completionShell: (shells: string) => `Unknown shell — use one of: ${shells}`, + dirMissing: (dir: string) => `Directory ${dir} does not exist.`, + examples: 'Examples:', spinnerPush: 'sending sessions to intervals.icu…', spinnerPull: 'fetching data from intervals.icu…', spinnerReview: 'preparing the weekly review…', @@ -139,6 +152,39 @@ export const cliEn = { goalInRange: (target: string) => `The goal of ${target} sits inside the predicted range.`, structure: 'Structure', phaseSpan: (phase: string, from: number, to: number) => `${phase}: weeks ${from}–${to}`, + regenSection: 'What the regeneration changes', + sameCycle: (start: string) => + `Same training cycle: phases stay anchored to ${start}; future days follow trainctl.yaml.`, + newCycle: (weekStart: string) => + `New training cycle from ${weekStart} (different goal distance, or the previous race is behind you); ` + + 'earlier weeks stay as history.', + changedDays: 'Days changed', + keptDays: 'Days kept as they were', + reasons: { + past: 'past', + recorded: 'logged', + pinned: 'pinned', + approved: 'approved time exception', + edited: 'manual edit', + budget: 'over its time budget', + }, + loadKept: (km: number, date: string) => + `Kept the approved baseline of ${n(km)} km/week from ${date} (adapt). ` + + 'Changing athlete.recentWeeklyKm in trainctl.yaml overrides it.', + loadCleared: (km: number) => + `athlete.recentWeeklyKm changed since the approved baseline of ${n(km)} km/week — the profile wins.`, + droppedWeeks: (weeks: string) => `Weeks no longer in the plan: ${weeks} (the previous version is in git).`, + moreLines: (count: number) => `… and ${count} more — trainctl diff lists every difference.`, + upToDate: 'Plan is current — trainctl.yaml produces the same future days; nothing written.', + freshDropped: (items: string) => `Regenerated from scratch (--fresh), discarding: ${items}. The previous plan is in git.`, + freshItems: { + loadState: (km: number) => `the approved baseline (${n(km)} km/week)`, + pinned: (count: number) => `${count} pinned ${pluralEn(count, { one: 'day', other: 'days' })}`, + budgets: (count: number) => `${count} time ${pluralEn(count, { one: 'budget', other: 'budgets' })}`, + approved: (count: number) => `${count} approved time ${pluralEn(count, { one: 'exception', other: 'exceptions' })}`, + edited: (count: number) => `${count} manually edited ${pluralEn(count, { one: 'day', other: 'days' })}`, + history: (count: number) => `${count} change-log ${pluralEn(count, { one: 'entry', other: 'entries' })}`, + }, }, today: { @@ -149,6 +195,8 @@ export const cliEn = { restDayBody: 'Rest is part of the plan — adaptation happens in recovery.', logged: (status: string) => `Logged: ${status}`, whyHint: (date: string) => `why this session: trainctl why --date ${date}`, + estimate: (minutes: number) => `about ${minutes} min including preparation`, + next: (date: string, weekday: string, kind: string, km: number) => `next: ${weekday} ${date} · ${kind} · ${n(km)} km`, strengthTitle: (minutes: number) => `Strength · ~${n(minutes)} min`, strengthAloneDay: 'No running today — a clean day for the gym (no clash with running).', strengthWithEasy: @@ -185,6 +233,21 @@ export const cliEn = { recorded: 'Recorded', testTime: (time: string) => `test segment ${time}`, unplanned: 'The plan had a rest day here — the entry counts as an unplanned run.', + prompt: { + which: 'Which session?', + status: 'Status', + statusHint: 'done / skipped / modified', + km: 'Kilometres', + time: 'Time', + timeHint: 'MM:SS or H:MM:SS, Enter skips', + testTime: 'Time of the measured segment only', + rpe: 'Effort 1–10 (RPE)', + rpeHint: 'Enter skips', + note: 'Note', + noteHint: 'how it went, conditions — Enter skips', + badStatus: 'Use done, skipped or modified (d / s / m).', + logged: 'logged', + }, }, shift: { @@ -311,7 +374,8 @@ export const cliEn = { diff: { title: 'Differences: saved plan → plan from current trainctl.yaml', upToDate: 'Plan is current — no differences against a regeneration from trainctl.yaml.', - manualShifts: 'the plan contains manual shifts — they will show up as differences', + manualShifts: 'the plan contains manual changes — regeneration keeps those days as they are', + metadataOnly: 'no day changes; plan metadata would be refreshed (engine version, calibration, approved baseline)', weekGone: (weekStart: string) => `- week ${weekStart}: disappears from the plan`, weekVolume: (weekStart: string, before: number, after: number) => `~ week ${weekStart}: volume ${n(before)} → ${n(after)} km`, @@ -328,7 +392,7 @@ export const cliEn = { strengthDuration: (date: string, before: number, after: number) => `~ ${date}: strength ${before} → ${after} min`, weekNew: (weekStart: string, km: number) => `+ week ${weekStart}: new (${n(km)} km)`, - applyHint: 'to apply: trainctl plan (overwrites plan/ — you have it in git)', + applyHint: 'to apply: trainctl plan — past, logged, pinned and approved days stay; --fresh starts over', localeChanged: (planLocale: string, current: string) => `the plan was generated in "${planLocale}", you are running in "${current}" — ` + 'run trainctl plan to regenerate the descriptions', @@ -607,6 +671,130 @@ export const cliEn = { strengthSummary: (minutes: number) => `strength ~${n(minutes)} min`, }, + clock: { + simulated: (env: string, date: string) => + `simulated date ${date} (${env}) — "today", past-day protection and proposal expiry follow it`, + badSimulatedDate: (env: string, value: string) => `${env}="${value}" is not a date — use YYYY-MM-DD or unset it.`, + }, + + dates: { + badInput: (input: string) => + `"${input}" is not a date — use YYYY-MM-DD, today/tomorrow/yesterday, +N/-N or a weekday (mon…sun)`, + }, + + commit: { + done: (sha: string, files: string) => `Committed ${sha}: ${files}`, + noGit: 'Not a git repository — nothing committed (the change itself is saved).', + nothing: 'Nothing to commit — the files are unchanged.', + failed: (detail: string) => `The change is saved, but git commit failed: ${detail}`, + init: 'trainctl init: profile and coach instructions', + plan: (goal: string, date: string) => `trainctl plan: ${goal} (${date})`, + log: (date: string, status: string) => `trainctl log: ${date} ${status}`, + shift: (from: string, to: string) => `trainctl shift: ${from} ↔ ${to}`, + reschedule: (weekStart: string) => `trainctl reschedule: week of ${weekStart}`, + apply: (id: string) => `trainctl: apply reviewed proposal ${id}`, + }, + + status: { + title: 'Training directory', + profile: 'Profile', + language: 'Language', + ok: 'valid', + missing: 'missing — trainctl init', + invalid: 'has errors (below)', + plan: 'Plan', + goal: 'Goal', + toRace: 'To race day', + daysToRace: (days: number) => (days >= 0 ? `${days} ${pluralEn(days, { one: 'day', other: 'days' })}` : `${-days} ${pluralEn(-days, { one: 'day', other: 'days' })} ago`), + weeks: 'This cycle', + weeksSessions: (weeks: number, sessions: number) => `${weeks} ${pluralEn(weeks, { one: 'week', other: 'weeks' })}, ${sessions} ${pluralEn(sessions, { one: 'session', other: 'sessions' })}`, + generated: 'Phases anchored to', + engine: 'Engine', + engineOther: (planVersion: string, current: string) => `${planVersion} (running ${current} — see trainctl diff)`, + engineOld: (current: string) => `before 0.2.0 (running ${current})`, + loadState: 'Approved baseline', + loadStateValue: (km: number, date: string) => `${n(km)} km/week since ${date}`, + noPlan: 'No plan yet.', + planUnusable: (file: string) => `${file} is not a usable plan — trainctl check shows what is broken.`, + calibration: 'Zone calibration', + calibrationSelected: (date: string, km: number, ageDays: number, vdot: number) => + `${date} · ${n(km)} km · ${ageDays} ${pluralEn(ageDays, { one: 'day', other: 'days' })} old · VDOT ${n(vdot)}`, + calibrationFromGoal: (vdot: number) => `from the goal time (VDOT ${n(vdot)}) — add a race result to athlete.results`, + calibrationNone: 'no result recorded in the plan', + data: 'Data', + key: 'intervals.icu key', + keyFromEnv: 'environment variable', + keyNone: 'none — offline mode (export works without it)', + envProtected: 'ignored by git', + envUnprotected: 'NOT ignored by git', + never: 'never pulled', + syncValue: (pulledAt: string, activities: number, withheld: number) => + `pulled ${pulledAt}, ${activities} ${pluralEn(activities, { one: 'activity', other: 'activities' })}` + + (withheld ? `, ${withheld} without data (Strava)` : ''), + empty: 'empty', + logValue: (entries: number, date: string, status: string) => + `${entries} ${pluralEn(entries, { one: 'entry', other: 'entries' })}, last ${date} (${status})`, + unconfirmed: (dates: string) => `Unconfirmed sessions this week: ${dates} — trainctl log or trainctl pull.`, + proposals: 'Proposals', + columns: { id: 'id', kind: 'kind', for: 'for', state: 'state', changes: 'changes' }, + state: { + valid: 'valid today', + expired: 'expired — prepare again', + stale: 'inputs changed — prepare again', + invalid: 'unreadable', + }, + git: 'Git', + noGit: 'Not a git repository — the history of your training lives nowhere. git init is enough.', + clean: 'Everything committed.', + dirty: (files: string) => `Uncommitted: ${files}`, + next: (steps: string) => `next: ${steps}`, + }, + + examples: { + plan: [ + 'trainctl plan # regenerate the future, keep the past and approvals', + 'trainctl diff # the same changes, without saving', + 'trainctl plan --fresh # start over (the old plan stays in git)', + ], + log: [ + 'trainctl log # in a terminal: pick the session and answer a few questions', + 'trainctl log --km 8 --time 41:20 --rpe 4 --note "felt good"', + 'trainctl log --date yesterday --status skipped --note "work"', + ], + shorten: [ + 'trainctl shorten --minutes 40 # today, as a proposal', + 'trainctl shorten --minutes 30 --date thu', + 'trainctl shorten --apply --commit # approve what you reviewed', + ], + adapt: [ + 'trainctl adapt # proposals only', + 'trainctl adapt --prepare # a concrete patch to review', + 'trainctl adapt --apply # apply exactly what you reviewed', + ], + review: [ + 'trainctl review # the last seven days and the week ahead', + 'trainctl review --date sun # the week that ended last Sunday', + 'trainctl review --prepare # with exact changes for approval', + ], + reschedule: [ + 'trainctl reschedule --block thu sat # preview', + 'trainctl reschedule --time tue=40 --pin sun # 40 minutes on Tuesday, keep Sunday', + 'trainctl reschedule --block thu --apply --commit', + ], + export: [ + 'trainctl export --what plan # .fit workouts for the watch', + 'trainctl export --what workout --date tomorrow', + 'trainctl export --what calendar # .ics', + ], + diff: [ + 'trainctl diff # what trainctl plan would change', + 'git show what-if:plan/plan.yaml > /tmp/s.yaml && trainctl diff --plan /tmp/s.yaml', + ], + push: ['trainctl push --days 7', 'trainctl push --from mon --to sun'], + pull: ['trainctl pull --days 28', 'trainctl pull --date -7 # a range ending a week ago'], + status: ['trainctl status', 'trainctl status --json | jq .proposals'], + }, + envFile: { unprotected: (envFile: string, ignoreFile: string) => `${envFile} is loaded and this directory is a git repository, but no ${ignoreFile} ` + @@ -769,7 +957,10 @@ export const cliEn = { plan: 'Generate the training plan from trainctl.yaml → plan/plan.yaml + plan/PLAN.md. ' + 'Returns a summary: volume peak, predicted finish (a range) and how realistic the goal is. ' + - 'OVERWRITES an existing plan — when in doubt run trainctl_diff first.', + 'On an existing plan it regenerates the FUTURE only: past, logged, pinned, hand-edited and approved days ' + + 'stay, and an approved baseline from adapt is kept. fresh=true starts over. Ask before calling it; ' + + 'trainctl_diff shows exactly the same changes without saving.', + planFresh: 'true = regenerate from scratch, discarding kept days and approvals (ask the user first)', planDate: '“today” (defaults to the current date)', today: 'The session for today (or a given date): description, distance, status from the journal.', week: @@ -850,6 +1041,14 @@ export const cliEn = { 'plan/plan.yaml is internally inconsistent (usually a manual edit); WARNINGS mean a rule ' + 'deviation someone may have chosen. Run it after hand-editing the plan file. Changes nothing.', checkStrict: 'true = warnings also count as failures', + status: + 'State of the training directory in one call: whether trainctl.yaml validates, which engine version ' + + 'generated the plan, where the API key comes from and whether .env is protected, when data was last pulled, ' + + 'the journal, saved proposals with their validity today, and uncommitted files. Read-only — start here ' + + 'when something looks off.', + commit: + 'true = after a successful write, git-commit exactly the files this tool changed (never secrets). ' + + 'This writes to the user’s git history — use it only when they asked for commits.', }, /** AGENTS.md — the coach persona dropped into the training directory by `trainctl init`. */ @@ -865,6 +1064,9 @@ This directory is a training plan as code. You have the \`trainctl_*\` MCP tools - **Review and propose changes** → \`trainctl_review(prepare=true)\`. Show execution gaps and the saved changes. Approve with \`trainctl_adapt(apply=ID)\`; do not regenerate or sync between preview and approval. - **Start of the week** → \`trainctl_review\`. One call instead of pull + adapt + week. Relay the result in plain language and propose at most two things to do. +- **Something looks off** (a proposal will not apply, data seems missing, the + plan reads oddly) → \`trainctl_status\` first: config, engine version, key, + last pull, proposals with their validity, uncommitted files. - **Before any change to the week** → \`trainctl_week\` first, to see the context. “Move the intervals” without looking at the week is guesswork. - **After a race or a time trial** → ask for the time and propose an entry in @@ -883,8 +1085,9 @@ This directory is a training plan as code. You have the \`trainctl_*\` MCP tools ## Rules -1. **Do not regenerate the plan without asking.** \`trainctl_plan\` overwrites the - existing plan. When in doubt: \`trainctl_diff\` (shows the differences, saves nothing). +1. **Do not regenerate the plan without asking.** \`trainctl_plan\` rewrites the future + weeks (past, logged, pinned and approved days stay; fresh=true starts over). + When in doubt: \`trainctl_diff\` (the same changes, saves nothing). 2. **Adaptation proposes, it does not rewrite.** \`trainctl_adapt\` returns proposals; use prepare=true for a concrete patch. Show its session changes and warnings, then ask\n for approval before calling apply with that ID. If inputs changed, prepare a new proposal.\n Missing execution data is unknown, not proof of a skipped session. 3. **Ask for context before you start computing.** A missed week means one thing diff --git a/packages/cli/src/i18n/cli-i18n.test.ts b/packages/cli/src/i18n/cli-i18n.test.ts index fcfa226..df5d33a 100644 --- a/packages/cli/src/i18n/cli-i18n.test.ts +++ b/packages/cli/src/i18n/cli-i18n.test.ts @@ -94,6 +94,11 @@ describe('polski nie jest kalką', () => { 'planMd.rest', 'configFile.templateAthlete.sex', 'configFile.templateDeskPrefer', + 'log.prompt.status', + 'log.prompt.statusHint', + 'status.columns.id', + 'status.git', + 'status.plan', ].sort(), ) }) diff --git a/packages/cli/src/i18n/cli-pl.ts b/packages/cli/src/i18n/cli-pl.ts index 69c6d15..ab92fa9 100644 --- a/packages/cli/src/i18n/cli-pl.ts +++ b/packages/cli/src/i18n/cli-pl.ts @@ -53,6 +53,7 @@ export const cliPl: CliMessages = { check: 'sprawdź plan: inwarianty silnika + integralność pliku; błędy psują kod wyjścia (CI)', optStrict: 'ostrzeżenia też psują kod wyjścia (do CI)', optDiffPlan: 'porównaj z innym plikiem planu (gałąź scenariusza albo worktree)', + optFresh: 'regeneracja od zera: porzuca chronione dni, zatwierdzenia, przypięcia i budżety (zostają w gicie)', optDate: 'data (domyślnie: dziś)', optDateOther: 'inna data niż dziś', optDateWeek: 'data w interesującym tygodniu', @@ -79,6 +80,18 @@ export const cliPl: CliMessages = { pickFromList: ' (wybór z listy) · ', browseArrows: ' (przeglądanie strzałkami)', colorsHint: 'Kolory: NO_COLOR=1 wyłącza, TRAINCTL_ASCII=1 wymusza znaki ASCII.', + datesHint: + 'Daty: RRRR-MM-DD, dziś/jutro/wczoraj (także today/tomorrow/yesterday), +N/-N dni albo dzień tygodnia ' + + '(pn…nd, mon…sun). log, review, adapt i pull patrzą wstecz; pozostałe komendy — w przód.', + dirHint: 'Katalog: -C <ścieżka> albo TRAINCTL_DIR; TRAINCTL_TODAY=RRRR-MM-DD symuluje datę (zawsze ogłoszoną).', + optJson: 'wypisz JSON ({ code, data, output }) zamiast sformatowanego tekstu', + optDir: 'katalog treningowy (domyślnie TRAINCTL_DIR, potem bieżący katalog)', + optCommit: 'zacommituj pliki zmienione przez komendę (opcjonalnie z własną wiadomością)', + status: 'stan katalogu treningowego: profil, plan, dane, propozycje, git', + completion: 'wypisz skrypt uzupełniania dla powłoki: bash | zsh | fish | pwsh', + completionShell: (shells: string) => `Nieznana powłoka — użyj jednej z: ${shells}`, + dirMissing: (dir: string) => `Katalog ${dir} nie istnieje.`, + examples: 'Przykłady:', spinnerPush: 'wysyłam treningi do intervals.icu…', spinnerPull: 'pobieram dane z intervals.icu…', spinnerReview: 'przygotowuję przegląd tygodnia…', @@ -152,6 +165,39 @@ export const cliPl: CliMessages = { goalInRange: (target: string) => `Cel ${target} mieści się w przedziale predykcji.`, structure: 'Struktura', phaseSpan: (phase: string, from: number, to: number) => `${phase}: tyg. ${from}–${to}`, + regenSection: 'Co zmienia regeneracja', + sameCycle: (start: string) => + `Ten sam cykl treningowy: fazy zostają zakotwiczone w ${start}; przyszłe dni idą za trainctl.yaml.`, + newCycle: (weekStart: string) => + `Nowy cykl treningowy od ${weekStart} (inny dystans celu albo poprzedni start już za Tobą); ` + + 'wcześniejsze tygodnie zostają jako historia.', + changedDays: 'Zmienione dni', + keptDays: 'Dni bez zmian', + reasons: { + past: 'przeszłe', + recorded: 'zalogowane', + pinned: 'przypięte', + approved: 'zatwierdzony wyjątek czasowy', + edited: 'ręczna edycja', + budget: 'ponad budżet czasu', + }, + loadKept: (km: number, date: string) => + `Zostaje zatwierdzona baza ${n(km)} km/tydz. z ${date} (adapt). ` + + 'Zmiana athlete.recentWeeklyKm w trainctl.yaml ją nadpisze.', + loadCleared: (km: number) => + `athlete.recentWeeklyKm zmieniło się od zatwierdzonej bazy ${n(km)} km/tydz. — wygrywa profil.`, + droppedWeeks: (weeks: string) => `Tygodnie, których nie ma już w planie: ${weeks} (poprzednia wersja jest w gicie).`, + moreLines: (count: number) => `… i ${count} więcej — trainctl diff wypisze wszystkie różnice.`, + upToDate: 'Plan aktualny — trainctl.yaml daje te same przyszłe dni; nic nie zapisano.', + freshDropped: (items: string) => `Regeneracja od zera (--fresh); porzucono: ${items}. Poprzedni plan jest w gicie.`, + freshItems: { + loadState: (km: number) => `zatwierdzoną bazę (${n(km)} km/tydz.)`, + pinned: (count: number) => `${count} ${pluralPl(count, { one: 'przypięty dzień', few: 'przypięte dni', other: 'przypiętych dni' })}`, + budgets: (count: number) => `${count} ${pluralPl(count, { one: 'budżet czasu', few: 'budżety czasu', other: 'budżetów czasu' })}`, + approved: (count: number) => `${count} ${pluralPl(count, { one: 'zatwierdzony wyjątek czasowy', few: 'zatwierdzone wyjątki czasowe', other: 'zatwierdzonych wyjątków czasowych' })}`, + edited: (count: number) => `${count} ${pluralPl(count, { one: 'ręcznie edytowany dzień', few: 'ręcznie edytowane dni', other: 'ręcznie edytowanych dni' })}`, + history: (count: number) => `${count} ${pluralPl(count, { one: 'wpis historii zmian', few: 'wpisy historii zmian', other: 'wpisów historii zmian' })}`, + }, }, today: { @@ -162,6 +208,8 @@ export const cliPl: CliMessages = { restDayBody: 'Odpoczynek jest częścią planu — adaptacja zachodzi w regeneracji.', logged: (status: string) => `Zalogowano: ${status}`, whyHint: (date: string) => `dlaczego ten trening: trainctl why --date ${date}`, + estimate: (minutes: number) => `około ${minutes} min razem z przygotowaniem`, + next: (date: string, weekday: string, kind: string, km: number) => `następny: ${weekday} ${date} · ${kind} · ${n(km)} km`, strengthTitle: (minutes: number) => `Siła · ~${n(minutes)} min`, strengthAloneDay: 'Dzień bez biegania — idealny na siłownię (zero konfliktu z sesjami biegowymi).', strengthWithEasy: @@ -198,6 +246,21 @@ export const cliPl: CliMessages = { recorded: 'Zapis', testTime: (time: string) => `odcinek pomiarowy ${time}`, unplanned: 'W planie był tu dzień wolny — wpis liczy się jako bieg poza planem.', + prompt: { + which: 'Który trening?', + status: 'Status', + statusHint: 'done / skipped / modified', + km: 'Kilometry', + time: 'Czas', + timeHint: 'MM:SS albo G:MM:SS, Enter pomija', + testTime: 'Czas samego odcinka pomiarowego', + rpe: 'Wysiłek 1–10 (RPE)', + rpeHint: 'Enter pomija', + note: 'Notatka', + noteHint: 'jak poszło, warunki — Enter pomija', + badStatus: 'Wpisz done, skipped albo modified (d / s / m).', + logged: 'zalogowany', + }, }, shift: { @@ -326,7 +389,8 @@ export const cliPl: CliMessages = { diff: { title: 'Różnice: plan zapisany → plan z aktualnego trainctl.yaml', upToDate: 'Plan aktualny — brak różnic względem regeneracji z trainctl.yaml.', - manualShifts: 'plan zawiera ręczne przesunięcia — pokażą się jako różnice', + manualShifts: 'plan zawiera ręczne przesunięcia — regeneracja zostawi te dni bez zmian', + metadataOnly: 'bez zmian w dniach; odświeżyłyby się metadane planu (wersja silnika, kalibracja, zatwierdzona baza)', weekGone: (weekStart: string) => `- tydzień ${weekStart}: znika z planu`, weekVolume: (weekStart: string, before: number, after: number) => `~ tydzień ${weekStart}: objętość ${n(before)} → ${n(after)} km`, @@ -343,7 +407,7 @@ export const cliPl: CliMessages = { strengthDuration: (date: string, before: number, after: number) => `~ ${date}: siła ${before} → ${after} min`, weekNew: (weekStart: string, km: number) => `+ tydzień ${weekStart}: nowy (${n(km)} km)`, - applyHint: 'zastosowanie: trainctl plan (nadpisze plan/ — masz go w gicie)', + applyHint: 'zastosowanie: trainctl plan — dni przeszłe, zalogowane, przypięte i zatwierdzone zostają; --fresh zaczyna od zera', localeChanged: (planLocale: string, current: string) => `plan wygenerowano w języku „${planLocale}”, a pracujesz w „${current}” — ` + 'uruchom trainctl plan, żeby przegenerować opisy', @@ -631,6 +695,130 @@ export const cliPl: CliMessages = { strengthSummary: (minutes: number) => `siła ~${n(minutes)} min`, }, + clock: { + simulated: (env: string, date: string) => + `data symulowana ${date} (${env}) — „dziś”, ochrona przeszłości i ważność propozycji idą za nią`, + badSimulatedDate: (env: string, value: string) => `${env}=„${value}” to nie data — użyj RRRR-MM-DD albo usuń zmienną.`, + }, + + dates: { + badInput: (input: string) => + `„${input}” to nie data — użyj RRRR-MM-DD, dziś/jutro/wczoraj, +N/-N albo dnia tygodnia (pn…nd)`, + }, + + commit: { + done: (sha: string, files: string) => `Commit ${sha}: ${files}`, + noGit: 'To nie jest repozytorium gita — nic nie zacommitowano (sama zmiana jest zapisana).', + nothing: 'Nie ma czego commitować — pliki są bez zmian.', + failed: (detail: string) => `Zmiana jest zapisana, ale git commit się nie powiódł: ${detail}`, + init: 'trainctl init: profil i instrukcja trenera', + plan: (goal: string, date: string) => `trainctl plan: ${goal} (${date})`, + log: (date: string, status: string) => `trainctl log: ${date} ${status}`, + shift: (from: string, to: string) => `trainctl shift: ${from} ↔ ${to}`, + reschedule: (weekStart: string) => `trainctl reschedule: tydzień od ${weekStart}`, + apply: (id: string) => `trainctl: zatwierdzona propozycja ${id}`, + }, + + status: { + title: 'Katalog treningowy', + profile: 'Profil', + language: 'Język', + ok: 'poprawny', + missing: 'brak — trainctl init', + invalid: 'zawiera błędy (niżej)', + plan: 'Plan', + goal: 'Cel', + toRace: 'Do startu', + daysToRace: (days: number) => (days >= 0 ? dni(days) : `${dni(-days)} temu`), + weeks: 'Bieżący cykl', + weeksSessions: (weeks: number, sessions: number) => `${tygodnie(weeks)}, ${sesje(sessions)}`, + generated: 'Fazy zakotwiczone w', + engine: 'Silnik', + engineOther: (planVersion: string, current: string) => `${planVersion} (działa ${current} — zobacz trainctl diff)`, + engineOld: (current: string) => `sprzed 0.2.0 (działa ${current})`, + loadState: 'Zatwierdzona baza', + loadStateValue: (km: number, date: string) => `${n(km)} km/tydz. od ${date}`, + noPlan: 'Jeszcze nie ma planu.', + planUnusable: (file: string) => `${file} to nie jest użyteczny plan — trainctl check pokaże, co jest połamane.`, + calibration: 'Kalibracja stref', + calibrationSelected: (date: string, km: number, ageDays: number, vdot: number) => + `${date} · ${n(km)} km · sprzed ${dni(ageDays)} · VDOT ${n(vdot)}`, + calibrationFromGoal: (vdot: number) => `z czasu docelowego (VDOT ${n(vdot)}) — dopisz wynik startu do athlete.results`, + calibrationNone: 'plan nie zapisuje wyniku kalibracji', + data: 'Dane', + key: 'Klucz intervals.icu', + keyFromEnv: 'zmienna środowiskowa', + keyNone: 'brak — tryb offline (eksport działa bez niego)', + envProtected: 'ignorowany przez gita', + envUnprotected: 'NIE jest ignorowany przez gita', + never: 'jeszcze nie pobrano', + syncValue: (pulledAt: string, activities: number, withheld: number) => + `pobrano ${pulledAt}, ${activities} ${pluralPl(activities, { one: 'aktywność', few: 'aktywności', other: 'aktywności' })}` + + (withheld ? `, ${withheld} bez danych (Strava)` : ''), + empty: 'pusty', + logValue: (entries: number, date: string, status: string) => + `${entries} ${pluralPl(entries, { one: 'wpis', few: 'wpisy', other: 'wpisów' })}, ostatni ${date} (${status})`, + unconfirmed: (dates: string) => `Niepotwierdzone sesje w tym tygodniu: ${dates} — trainctl log albo trainctl pull.`, + proposals: 'Propozycje', + columns: { id: 'id', kind: 'rodzaj', for: 'dla', state: 'stan', changes: 'zmiany' }, + state: { + valid: 'ważna dziś', + expired: 'wygasła — przygotuj ponownie', + stale: 'dane się zmieniły — przygotuj ponownie', + invalid: 'nieczytelna', + }, + git: 'Git', + noGit: 'To nie jest repozytorium gita — historia treningu nigdzie się nie zapisuje. Wystarczy git init.', + clean: 'Wszystko zacommitowane.', + dirty: (files: string) => `Niezacommitowane: ${files}`, + next: (steps: string) => `dalej: ${steps}`, + }, + + examples: { + plan: [ + 'trainctl plan # regeneruj przyszłość, zachowaj przeszłość i zatwierdzenia', + 'trainctl diff # te same zmiany, bez zapisu', + 'trainctl plan --fresh # od zera (stary plan zostaje w gicie)', + ], + log: [ + 'trainctl log # w terminalu: wybierz trening i odpowiedz na kilka pytań', + 'trainctl log --km 8 --time 41:20 --rpe 4 --note "dobrze się biegło"', + 'trainctl log --date wczoraj --status skipped --note "praca"', + ], + shorten: [ + 'trainctl shorten --minutes 40 # dziś, jako propozycja', + 'trainctl shorten --minutes 30 --date czw', + 'trainctl shorten --apply --commit # zatwierdź to, co obejrzałeś', + ], + adapt: [ + 'trainctl adapt # same propozycje', + 'trainctl adapt --prepare # konkretna łatka do przejrzenia', + 'trainctl adapt --apply # zastosuj dokładnie to, co obejrzałeś', + ], + review: [ + 'trainctl review # ostatnie siedem dni i tydzień przed nami', + 'trainctl review --date nd # tydzień zakończony w ostatnią niedzielę', + 'trainctl review --prepare # z dokładnymi zmianami do zatwierdzenia', + ], + reschedule: [ + 'trainctl reschedule --block czw sob # podgląd', + 'trainctl reschedule --time wt=40 --pin nd # 40 minut we wtorek, niedziela bez zmian', + 'trainctl reschedule --block czw --apply --commit', + ], + export: [ + 'trainctl export --what plan # treningi .fit na zegarek', + 'trainctl export --what workout --date jutro', + 'trainctl export --what calendar # .ics', + ], + diff: [ + 'trainctl diff # co zmieniłby trainctl plan', + 'git show co-jesli:plan/plan.yaml > /tmp/s.yaml && trainctl diff --plan /tmp/s.yaml', + ], + push: ['trainctl push --days 7', 'trainctl push --from pn --to nd'], + pull: ['trainctl pull --days 28', 'trainctl pull --date -7 # zakres kończący się tydzień temu'], + status: ['trainctl status', 'trainctl status --json | jq .proposals'], + }, + envFile: { unprotected: (envFile: string, ignoreFile: string) => `Wczytano ${envFile}, a ten katalog jest repozytorium gita i żaden ${ignoreFile} ` + @@ -788,7 +976,10 @@ export const cliPl: CliMessages = { plan: 'Wygeneruj plan treningowy z trainctl.yaml → plan/plan.yaml + plan/PLAN.md. ' + 'Zwraca podsumowanie: szczyt objętości, predykcję wyniku (przedział) i ocenę realności celu. ' + - 'NADPISUJE istniejący plan — przy wątpliwościach najpierw trainctl_diff.', + 'Na istniejącym planie regeneruje wyłącznie PRZYSZŁOŚĆ: dni przeszłe, zalogowane, przypięte, ręcznie ' + + 'edytowane i zatwierdzone zostają, a zatwierdzona baza z adapt obowiązuje dalej. fresh=true zaczyna od zera. ' + + 'Zapytaj przed wywołaniem; trainctl_diff pokazuje dokładnie te same zmiany bez zapisu.', + planFresh: 'true = regeneracja od zera, porzuca chronione dni i zatwierdzenia (najpierw zapytaj użytkownika)', planDate: 'data „dzisiaj” (domyślnie: bieżąca)', today: 'Trening na dziś (albo wskazaną datę): opis jednostki, kilometraż, status z dziennika.', week: @@ -873,6 +1064,14 @@ export const cliPl: CliMessages = { 'to odstępstwa od reguł, które ktoś mógł wybrać świadomie. Uruchamiaj po ręcznej edycji ' + 'pliku planu. Nic nie zmienia.', checkStrict: 'true = ostrzeżenia też liczą się jak błędy', + status: + 'Stan katalogu treningowego w jednym wywołaniu: czy trainctl.yaml się waliduje, która wersja silnika ' + + 'wygenerowała plan, skąd jest klucz API i czy .env jest chroniony, kiedy ostatnio pobrano dane, dziennik, ' + + 'zapisane propozycje z ich ważnością na dziś i niezacommitowane pliki. Tylko odczyt — zacznij od tego, ' + + 'gdy coś się nie zgadza.', + commit: + 'true = po udanym zapisie zacommituj w gicie dokładnie pliki zmienione przez narzędzie (nigdy sekretów). ' + + 'To zapis do historii gita użytkownika — używaj wyłącznie, gdy prosił o commity.', }, agentsMd: (foundationsUrl: string): string => `# Trener — instrukcja dla agenta @@ -887,6 +1086,9 @@ Ten katalog to plan treningowy jako kod. Masz narzędzia MCP \`trainctl_*\` - **Przejrzyj tydzień i zaproponuj zmiany** → \`trainctl_review(prepare=true)\`. Pokaż luki w wykonaniu i zapisane zmiany. Zatwierdzenie przez \`trainctl_adapt(apply=ID)\`; nie regeneruj ani nie synchronizuj pomiędzy podglądem a zatwierdzeniem. - **Początek tygodnia** → \`trainctl_review\`. Jedno wywołanie zamiast pull + adapt + week. Zrelacjonuj wynik po ludzku i zaproponuj co najwyżej dwie rzeczy do zrobienia. +- **Coś się nie zgadza** (propozycja nie chce się zastosować, brakuje danych, + plan wygląda dziwnie) → najpierw \`trainctl_status\`: profil, wersja silnika, + klucz, ostatni pull, propozycje z ważnością, niezacommitowane pliki. - **Przed każdą zmianą w tygodniu** → najpierw \`trainctl_week\`, żeby zobaczyć kontekst. „Przesuń interwały” bez spojrzenia na tydzień to zgadywanie. - **Po starcie albo sprawdzianie** → dopytaj o czas i zaproponuj wpis do @@ -907,8 +1109,9 @@ Ten katalog to plan treningowy jako kod. Masz narzędzia MCP \`trainctl_*\` ## Zasady -1. **Nie regeneruj planu bez pytania.** \`trainctl_plan\` nadpisuje istniejący plan. - Przy wątpliwościach: \`trainctl_diff\` (pokazuje różnice, nic nie zapisuje). +1. **Nie regeneruj planu bez pytania.** \`trainctl_plan\` przepisuje przyszłe tygodnie + (dni przeszłe, zalogowane, przypięte i zatwierdzone zostają; fresh=true zaczyna od zera). + Przy wątpliwościach: \`trainctl_diff\` (te same zmiany, nic nie zapisuje). 2. **Adaptacja proponuje, nie przepisuje.** \`trainctl_adapt\` zwraca propozycje; użyj prepare=true, aby zapisać konkretną zmianę. Pokaż zmieniane sesje i ostrzeżenia,\n zapytaj o zgodę, a następnie wywołaj apply z zatwierdzonym ID. Zmienione dane\n wymagają nowej propozycji. Brak danych nie potwierdza pominięcia treningu. 3. **Pytaj o kontekst, zanim zaczniesz liczyć.** Pominięty tydzień to co innego diff --git a/packages/cli/src/interactive.ts b/packages/cli/src/interactive.ts index c558f1d..de439d9 100644 --- a/packages/cli/src/interactive.ts +++ b/packages/cli/src/interactive.ts @@ -4,14 +4,17 @@ * w funkcjach `*Choices` — pętla wejścia jest cienka i wymaga TTY. */ import { emitKeypressEvents } from 'node:readline' -import { messages, type Microcycle, type PlannedDay } from 'trainctl-core' -import { cmdShift, cmdWeek } from './commands.ts' +import { createInterface } from 'node:readline/promises' +import { addDays, messages, type Microcycle, type PlannedDay } from 'trainctl-core' +import { cmdLog, cmdShift, cmdWeek, kindLabel } from './commands.ts' import { ui } from './i18n/index.ts' -import { loadPlan, workoutText, type StoredPlan } from './planfile.ts' +import { parseTime, readLog } from './logfile.ts' +import { findDay, loadPlan, workoutText, type StoredPlan } from './planfile.ts' import { renderAnsi } from './ui/blocks.ts' import { clampIndex, keyAction, type KeyEvent } from './ui/keys.ts' import { canPrompt, select, type Choice } from './ui/select.ts' import { Theme } from './ui/theme.ts' +import { ask } from './ui/wizard.ts' /** Pozycje listy dla dni tygodnia; dzień startu jest zablokowany (nie ruszamy go). */ export function dayChoices(week: Microcycle, exclude?: string): Choice[] { @@ -83,6 +86,89 @@ export async function runShiftPicker( } } +/** Ostatnie siedem dni planu, od dziś wstecz — wybór przy `trainctl log` bez flag. */ +export function logChoices(plan: StoredPlan, today: string, logged: Map): Choice[] { + const from = addDays(today, -6) + return plan.weeks + .flatMap((w) => w.days) + .filter((d) => d.date >= from && d.date <= today) + .sort((a, b) => b.date.localeCompare(a.date)) + .map((day) => ({ + label: `${messages().weekdayShort[day.weekday]} ${day.date.slice(5)}`, + value: day.date, + hint: [ + day.workout ? `${kindLabel(day.workout.kind)} · ${day.workout.raceDistanceKm ?? day.workout.distanceKm} km` : ui().week.rest, + logged.has(day.date) ? `[${ui().log.prompt.logged}: ${logged.get(day.date)}]` : '', + ].filter(Boolean).join(' '), + })) +} + +/** „d", „done", „S" → kanoniczny status dziennika. */ +export function parseLogStatus(text: string): 'done' | 'skipped' | 'modified' { + const key = text.trim().toLowerCase() + if (key === 'd' || key === 'done') return 'done' + if (key === 's' || key === 'skipped') return 'skipped' + if (key === 'm' || key === 'modified') return 'modified' + throw new Error(ui().log.prompt.badStatus) +} + +const parseKmText = (text: string): string => { + const value = Number(text.trim().replace(',', '.')) + if (!Number.isFinite(value) || value < 0) throw new Error(ui().improve.badDistance) + return String(value) +} +const parseTimeText = (text: string): string => { + parseTime(text.trim()) + return text.trim() +} +const parseRpeText = (text: string): string => { + const value = Number(text.trim()) + if (!Number.isInteger(value) || value < 1 || value > 10) throw new Error(ui().log.badRpe(text)) + return String(value) +} + +/** + * `trainctl log` bez flag w terminalu: wybierz trening z ostatniego tygodnia + * i odpowiedz na kilka pytań (Enter = wartość z planu albo pominięcie). + * Ta sama walidacja i zapis co z flag — pytania tylko zbierają argumenty. + */ +export async function runLogPrompt(cwd: string, today: string, theme = new Theme()): Promise { + if (!canPrompt()) return { code: 1, output: ui().common.needsTerminal('trainctl log --km … --time …') } + let plan: StoredPlan + try { + plan = loadPlan(cwd) + } catch (e) { + return { code: 1, output: e instanceof Error ? e.message : String(e) } + } + const q = ui().log.prompt + const logged = new Map(readLog(cwd).map((e) => [e.date, e.status] as const)) + const choices = logChoices(plan, today, logged) + if (choices.length === 0) return { code: 1, output: ui().log.outsidePlan(today) } + const date = await select(q.which, choices, theme) + if (!date) return { code: 0, output: theme.dim(ui().common.cancelled) } + const day = findDay(plan, date)!.day + const rl = createInterface({ input: process.stdin, output: process.stdout }) + const opts: Parameters[1] = { date } + try { + const status = await ask(rl, theme, q.status, parseLogStatus, { hint: q.statusHint, default: 'done' }) + opts.status = status ?? 'done' + if (opts.status !== 'skipped') { + const planned = day.workout ? String(day.workout.raceDistanceKm ?? day.workout.distanceKm) : undefined + opts.km = await ask(rl, theme, q.km, parseKmText, planned ? { default: planned } : { optional: true }) + opts.time = await ask(rl, theme, q.time, parseTimeText, { hint: q.timeHint, optional: true }) + if (['test', 'race'].includes(day.workout?.kind ?? '')) { + opts.testTime = await ask(rl, theme, q.testTime, parseTimeText, { hint: q.timeHint, optional: true }) + } + opts.rpe = await ask(rl, theme, q.rpe, parseRpeText, { hint: q.rpeHint, optional: true }) + } + opts.note = await ask(rl, theme, q.note, (text) => text.trim(), { hint: q.noteHint, optional: true }) + } finally { + rl.close() + } + const result = cmdLog(cwd, opts) + return { code: result.code, output: result.blocks ? renderAnsi(result.blocks, theme) : result.output } +} + /** `trainctl export` bez argumentów: pyta, co wyeksportować (i który trening). */ export async function runExportPicker( cwd: string, diff --git a/packages/cli/src/planfile.ts b/packages/cli/src/planfile.ts index 222a925..efeaf10 100644 --- a/packages/cli/src/planfile.ts +++ b/packages/cli/src/planfile.ts @@ -42,7 +42,14 @@ export interface PlanChange { } export interface StoredPlan { - loadState?: { baselineWeeklyKm: number; effectiveFrom: string } + /** + * Zatwierdzona baza objętości (adapt --apply). `profileWeeklyKm` to wartość + * `athlete.recentWeeklyKm` z chwili decyzji: gdy profil się od niej różni, + * użytkownik świadomie zmienił bazę i regeneracja słucha profilu (ADR-033). + */ + loadState?: { baselineWeeklyKm: number; effectiveFrom: string; profileWeeklyKm?: number } + /** Pierwszy tydzień bieżącego cyklu, gdy wcześniejsze tygodnie to historia poprzedniego. */ + cycleStart?: string schemaVersion?: number engineVersion?: string calibration?: Calibration @@ -207,6 +214,30 @@ export function loadPlanFile(path: string): StoredPlan { return doc } +/** Plik planu, jeśli da się go użyć; połamany albo brakujący = undefined, nowszy schemat = błąd. */ +export function loadPlanIfUsable(cwd: string): StoredPlan | undefined { + if (!existsSync(join(cwd, PLAN_YAML))) return undefined + const doc = parse(readFileSync(join(cwd, PLAN_YAML), 'utf-8')) + if (!looksLikePlan(doc)) return undefined + return loadPlan(cwd) +} + +/** Tygodnie bieżącego cyklu — bez historii poprzedniego, która została w pliku. */ +export const cycleWeeksOf = (plan: StoredPlan): Microcycle[] => + plan.cycleStart ? plan.weeks.filter((w) => w.weekStart >= plan.cycleStart!) : plan.weeks + +/** + * Położenie tygodnia w jego cyklu — „tydzień 3/14" liczy tygodnie tego cyklu, + * a nie historię poprzedniego, która została w pliku. + */ +export function weekPosition(plan: StoredPlan, week: Microcycle): { index: number; total: number } { + const start = plan.cycleStart + if (!start) return { index: plan.weeks.indexOf(week), total: plan.weeks.length } + const inCycle = week.weekStart >= start + const group = plan.weeks.filter((w) => (w.weekStart >= start) === inCycle) + return { index: group.indexOf(week), total: group.length } +} + export function findDay( plan: StoredPlan, date: string, @@ -278,7 +309,7 @@ export function renderMarkdown(plan: StoredPlan): string { `${week.totalKm} km`, ...(sk.deload ? [m.deload] : []), ].join(' · ') - lines.push('', `## ${m.weekHeading(sk.index + 1, week.weekStart, label)}`, '') + lines.push('', `## ${m.weekHeading(weekPosition(plan, week).index + 1, week.weekStart, label)}`, '') lines.push( `| ${m.columns.day} | ${m.columns.date} | ${m.columns.workout} |`, '|---|---|---|', diff --git a/packages/cli/src/proposals.ts b/packages/cli/src/proposals.ts index c6733d1..a8df60a 100644 --- a/packages/cli/src/proposals.ts +++ b/packages/cli/src/proposals.ts @@ -1,5 +1,5 @@ import { createHash } from 'node:crypto' -import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { estimateWorkoutMinutes, validatePlan, weekTotals, withLocale, generateMicrocycle, paceZones, recalibrateWorkout, testDistanceKm, parseIso, shortenWorkout, type ShortenedWorkout, type AdaptationProposal, type PlannedDay } from 'trainctl-core' import { CONFIG_FILE, loadConfig } from './config.ts' @@ -8,6 +8,7 @@ import { computePlan, dayFingerprint, loadPlan, PLAN_YAML, writePlan, workoutTex import { ui } from './i18n/index.ts' import { readSnapshot } from './sync.ts' import { isRunningActivity } from './execution.ts' +import { clockToday } from './clock.ts' import { resultKey } from './calibration.ts' export interface PlanProposal { @@ -27,10 +28,8 @@ export interface PlanProposal { } const hash = (text: string): string => createHash('sha256').update(text).digest('hex') -export function calendarToday(): string { - const d = new Date() - return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}` -} +/** Prawdziwy (albo jawnie symulowany) dzień kalendarzowy — granica ochrony przeszłości. */ +export const calendarToday = (): string => clockToday() export function workspaceHash(cwd: string): string { return hash(JSON.stringify([PLAN_YAML, CONFIG_FILE, LOG_FILE, 'sync.json'].map((name) => { const path = join(cwd, name) @@ -48,7 +47,8 @@ function saveProposal(cwd: string, body: Omit): PlanProposal return proposal } -function recordedDates(cwd: string): Set { +/** Daty z zapisem wykonania (dziennik albo bieg z synchronizacji) — nienaruszalne dla zmian planu. */ +export function recordedDates(cwd: string): Set { const dates = new Set(readLog(cwd).map(entry => entry.date)) for (const a of readSnapshot(cwd)?.activities ?? []) if (isRunningActivity(a) && (a.distanceKm ?? 0) > 0) dates.add(a.date) return dates @@ -159,7 +159,7 @@ export function prepareProposal(cwd: string, today: string, analysis: Adaptation } } next.calibration = candidate.calibration! - if (volume) next.loadState = { baselineWeeklyKm: volume.suggestedWeeklyKm!, effectiveFrom: today } + if (volume) next.loadState = { baselineWeeklyKm: volume.suggestedWeeklyKm!, effectiveFrom: today, profileWeeklyKm: config.athlete.recentWeeklyKm } next.vdot = candidate.vdot next.vdotSource = candidate.vdotSource if (candidate.prediction) next.prediction = candidate.prediction @@ -174,6 +174,36 @@ export function prepareProposal(cwd: string, today: string, analysis: Adaptation return saveProposal(cwd, { schemaVersion: 1, kind: 'adaptation', preparedOn: calendarToday(), baseHash, createdFor: today, analysis, vdotBefore: plan.vdot, changes, protectedDates, plan: next }) } +export type ProposalState = 'valid' | 'expired' | 'stale' | 'invalid' + +/** + * Zapisane propozycje z ich stanem na dziś — te same warunki, które sprawdza + * `applyProposal`, w tej samej kolejności. Dziś nic ich nie listowało, więc + * zgubiony ID trzeba było szukać w `plan/proposals/`. + */ +export function listProposals(cwd: string): { id: string; kind: string; createdFor: string; preparedOn: string | null; changes: number; firstDate: string | null; state: ProposalState }[] { + const dir = join(cwd, 'plan', 'proposals') + if (!existsSync(dir)) return [] + const base = workspaceHash(cwd) + const today = calendarToday() + return readdirSync(dir).filter((f) => /^[a-f0-9]{24}\.json$/.test(f)).sort().map((file) => { + const id = file.slice(0, 24) + try { + const proposal = JSON.parse(readFileSync(join(dir, file), 'utf-8')) as PlanProposal + const { id: storedId, ...body } = proposal + const state: ProposalState = + storedId !== id || proposalId(body) !== id || proposal.schemaVersion !== 1 ? 'invalid' + : proposal.baseHash !== base ? 'stale' + : !proposal.preparedOn || proposal.preparedOn !== today || proposal.changes.some((c) => c.date < today) ? 'expired' + : 'valid' + return { id, kind: proposal.kind ?? 'adaptation', createdFor: proposal.createdFor, preparedOn: proposal.preparedOn ?? null, + changes: proposal.changes.length, firstDate: proposal.changes[0]?.date ?? null, state } + } catch { + return { id, kind: '?', createdFor: '', preparedOn: null, changes: 0, firstDate: null, state: 'invalid' as const } + } + }) +} + /** Apply exactly the reviewed bytes; do not recompute using new data. */ export function applyProposal(cwd: string, id: string): PlanProposal { if (!/^[a-f0-9]{24}$/.test(id)) throw new Error(ui().improve.invalidProposal) diff --git a/packages/cli/src/regenerate.test.ts b/packages/cli/src/regenerate.test.ts new file mode 100644 index 0000000..d16084b --- /dev/null +++ b/packages/cli/src/regenerate.test.ts @@ -0,0 +1,150 @@ +/** + * Chroniona regeneracja planu (ADR-033): `trainctl plan` na istniejącym planie + * nie kasuje przeszłości ani zatwierdzonych decyzji. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { setLocale, validatePlan } from 'trainctl-core' +import { cmdDiff, cmdLog, cmdPlan, cmdToday } from './commands.ts' +import { computePlan, cycleWeeksOf, loadPlan, writePlan, PLAN_YAML, type StoredPlan } from './planfile.ts' +import { applyProposal, prepareProposal } from './proposals.ts' +import type { TrainctlConfig } from './config.ts' + +let dir: string +let config: TrainctlConfig +beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date'] }) + vi.setSystemTime(new Date('2026-09-06T12:00:00Z')) + setLocale('en') + dir = mkdtempSync(join(tmpdir(), 'trainctl-regen-')) + config = { + athlete: { recentWeeklyKm: 55, daysAvailable: ['tue', 'wed', 'thu', 'sat', 'sun'], longRunDay: 'sun', + results: [{ date: '2026-03-29', distanceKm: 10, timeSec: 2580 }] }, + goal: { name: 'Test HM', date: '2026-11-29', distanceKm: 21.0975, priority: 'A' }, + } +}) +afterEach(() => { + vi.useRealTimers() + rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) +}) + +const saveConfig = () => writeFileSync(join(dir, 'trainctl.yaml'), JSON.stringify(config)) +function initialize(): StoredPlan { + saveConfig() + const plan = computePlan(config, '2026-08-03') + writePlan(dir, plan) + return plan +} +const dayOf = (plan: StoredPlan, date: string) => plan.weeks.flatMap((w) => w.days).find((d) => d.date === date)! +const futureWorkouts = (plan: StoredPlan) => plan.weeks.flatMap((w) => w.days).filter((d) => d.workout && d.date > '2026-09-06' && d.workout.kind !== 'race') +const reduction = { dataStatus: 'complete' as const, unknownSessions: 0, windowDays: 21, complianceKm: 0.5, + missedSessions: 0, diagnosis: [], warnings: [], actions: [{ type: 'reduce-volume' as const, detail: 'reduce', suggestedWeeklyKm: 20, ruleRefs: [] }] } + +describe('trainctl plan na istniejącym planie', () => { + it('bez zmian na wejściu: „plan aktualny" i nic nie zapisuje', () => { + initialize() + const before = readFileSync(join(dir, PLAN_YAML), 'utf-8') + const r = cmdPlan(dir) + expect(r.code).toBe(0) + expect(r.output).toContain('Plan is current') + expect(r.data).toMatchObject({ regeneration: { upToDate: true, mode: 'same-cycle' } }) + expect(readFileSync(join(dir, PLAN_YAML), 'utf-8')).toBe(before) + }) + + it('nowy wynik po zatwierdzonej redukcji: baza zostaje, tempa się aktualizują', () => { + initialize() + const reduced = prepareProposal(dir, '2026-09-06', reduction) + applyProposal(dir, reduced.id) + const reducedWeek = reduced.plan.weeks.find((w) => w.weekStart === '2026-09-07')! + config.athlete.results.push({ date: '2026-09-05', distanceKm: 10, timeSec: 2400 }) + saveConfig() + const r = cmdPlan(dir) + expect(r.code).toBe(0) + expect(r.output).toContain('Kept the approved baseline of 20 km/week') + const plan = loadPlan(dir) + const week = plan.weeks.find((w) => w.weekStart === '2026-09-07')! + expect(week.totalKm).toBeCloseTo(reducedWeek.totalKm, 1) + expect(week.days.map((d) => [d.date, d.workout?.kind, d.workout?.distanceKm])).toEqual(reducedWeek.days.map((d) => [d.date, d.workout?.kind, d.workout?.distanceKm])) + expect(plan.vdot).toBeGreaterThan(reduced.plan.vdot) + expect(plan.loadState).toMatchObject({ baselineWeeklyKm: 20, profileWeeklyKm: 55 }) + // przeszłość nietknięta bajt w bajt + for (const date of ['2026-08-04', '2026-09-01', '2026-09-05']) expect(dayOf(plan, date)).toEqual(dayOf(reduced.plan, date)) + }) + + it('zmiana athlete.recentWeeklyKm po redukcji: wygrywa profil, baza znika', () => { + initialize() + applyProposal(dir, prepareProposal(dir, '2026-09-06', reduction).id) + config.athlete.recentWeeklyKm = 40 + saveConfig() + const r = cmdPlan(dir) + expect(r.output).toContain('the profile wins') + expect(r.data).toMatchObject({ regeneration: { loadState: 'cleared' } }) + expect(loadPlan(dir).loadState).toBeUndefined() + }) + + it('dni przeszłe, zalogowane, przypięte i z budżetem czasu zostają; reszta przyszłości się zmienia', () => { + const original = initialize() + const [logged, pinned, budgeted] = futureWorkouts(original).slice(0, 3) + expect(cmdLog(dir, { date: logged!.date, km: '5' }).code).toBe(0) + const edited = loadPlan(dir) + dayOf(edited, pinned!.date).pinned = true + edited.timeBudgets = { [budgeted!.date]: 20 } + writePlan(dir, edited) + config.athlete.recentWeeklyKm = 65 + saveConfig() + const r = cmdPlan(dir) + expect(r.code).toBe(0) + const plan = loadPlan(dir) + expect(dayOf(plan, '2026-09-01')).toEqual(dayOf(original, '2026-09-01')) + expect(dayOf(plan, logged!.date)).toEqual(dayOf(original, logged!.date)) + expect(dayOf(plan, pinned!.date)).toMatchObject({ pinned: true, workout: dayOf(original, pinned!.date).workout }) + expect(dayOf(plan, budgeted!.date).workout).toEqual(dayOf(original, budgeted!.date).workout) + expect(plan.timeBudgets).toEqual({ [budgeted!.date]: 20 }) + const regen = r.data!['regeneration'] as { changedDates: string[]; protectedDays: { date: string; reason: string }[] } + expect(regen.changedDates.length).toBeGreaterThan(0) + expect(regen.changedDates.every((d) => d > '2026-09-06')).toBe(true) + expect(regen.protectedDays).toEqual(expect.arrayContaining([ + { date: logged!.date, reason: 'recorded' }, { date: pinned!.date, reason: 'pinned' }, + ])) + expect(validatePlan(plan).filter((i) => i.severity === 'error')).toEqual([]) + }) + + it('diff pokazuje dokładnie te zmiany, które wykona plan', () => { + initialize() + config.athlete.recentWeeklyKm = 65 + saveConfig() + const diff = cmdDiff(dir) + const plan = cmdPlan(dir) + expect((diff.data!['regeneration'] as { changedDates: string[] }).changedDates) + .toEqual((plan.data!['regeneration'] as { changedDates: string[] }).changedDates) + expect(diff.output).toContain('past, logged, pinned and approved days stay') + }) + + it('--fresh zaczyna od zera i mówi, co porzuca', () => { + initialize() + applyProposal(dir, prepareProposal(dir, '2026-09-06', reduction).id) + const r = cmdPlan(dir, { fresh: true }) + expect(r.code).toBe(0) + expect(r.output).toContain('Regenerated from scratch (--fresh), discarding: the approved baseline (20 km/week)') + expect(loadPlan(dir).loadState).toBeUndefined() + expect(r.data).toMatchObject({ regeneration: null }) + }) + + it('inny dystans celu: nowy cykl od bieżącego tygodnia, wcześniejsze tygodnie zostają jako historia', () => { + const original = initialize() + config.goal = { name: 'Autumn 10K', date: '2026-11-15', distanceKm: 10, priority: 'A' } + saveConfig() + const r = cmdPlan(dir) + expect(r.code).toBe(0) + expect(r.output).toContain('New training cycle from 2026-08-31') + const plan = loadPlan(dir) + expect(plan.cycleStart).toBe('2026-08-31') + expect(plan.weeks.filter((w) => w.weekStart < '2026-08-31')).toEqual(original.weeks.filter((w) => w.weekStart < '2026-08-31')) + const cycle = cycleWeeksOf(plan) + expect(cycle[0]!.weekStart).toBe('2026-08-31') + expect(cmdToday(dir, { date: '2026-09-08' }).output).toContain(`week 2/${cycle.length}`) + expect(validatePlan(plan).filter((i) => i.severity === 'error')).toEqual([]) + }) +}) diff --git a/packages/cli/src/regenerate.ts b/packages/cli/src/regenerate.ts new file mode 100644 index 0000000..b843137 --- /dev/null +++ b/packages/cli/src/regenerate.ts @@ -0,0 +1,224 @@ +/** + * Chroniona regeneracja planu (ADR-033). + * + * `trainctl plan` na istniejącym planie liczył wszystko od zera z `trainctl.yaml` + * i nadpisywał plik. Przepadały wtedy decyzje, które użytkownik świadomie + * zatwierdził albo zapisał: baza objętości po `adapt --apply` (`loadState`), + * przypięte dni, budżety czasu, skrócenia z `shorten --apply`, ręczne przesunięcia + * — a dokumentowana ścieżka „nowy wynik → trainctl.yaml → plan" prowadziła + * dokładnie tędy. Ochrona z ADR-029 obejmowała propozycje, nie regenerację. + * + * Zasady: + * - **ten sam cykl** (ten sam dystans celu, start jeszcze przed nami): makrocykl + * liczony od pierwotnej daty startu planu, więc granice faz zostają na miejscu; + * przesunięta data startu wydłuża albo skraca fazy tak, jak w scenariuszu + * „co jeśli" z README; + * - **nowy cykl** (zmieniony dystans albo start już za nami): makrocykl od dziś, + * wcześniejsze tygodnie zostają w pliku jako historia (o ile przylegają); + * - dni przeszłe, zalogowane, przypięte, ręcznie edytowane, zatwierdzone skrócenia + * i dni, w których nowa jednostka nie mieści się w zapisanym budżecie czasu, + * zostają bez zmian; + * - zatwierdzona baza (`loadState`) obowiązuje, dopóki użytkownik nie zmieni + * `athlete.recentWeeklyKm` w profilu — wtedy wygrywa profil. + */ +import { + addDays, + estimateWorkoutMinutes, + generateMicrocycle, + mondayOf, + paceZones, + testDistanceKm, + weekTotals, + type Microcycle, + type PlannedDay, +} from 'trainctl-core' +import type { TrainctlConfig } from './config.ts' +import { computePlan, dayFingerprint, type StoredPlan } from './planfile.ts' +import { clockToday } from './clock.ts' + +export type ProtectionReason = 'past' | 'recorded' | 'pinned' | 'approved' | 'edited' | 'budget' +export type RegenerationMode = 'same-cycle' | 'new-cycle' + +export interface Regeneration { + plan: StoredPlan + mode: RegenerationMode + /** Dni, które dostały nową treść. */ + changedDates: string[] + /** Dni, które zmieniłyby się, ale zostały — z powodem. */ + protectedDays: { date: string; reason: ProtectionReason }[] + /** Los zatwierdzonej bazy objętości. */ + loadState: 'kept' | 'cleared' | 'none' + /** Tygodnie, które wypadły: po nowej, wcześniejszej dacie startu albo nieprzylegająca historia. */ + droppedWeeks: string[] + /** Nic istotnego się nie zmienia — zapis niepotrzebny. */ + upToDate: boolean +} + +/** Profil zmienia się w obrębie cyklu; dystans celu zmienia cykl. */ +const sameDistance = (a: number, b: number) => Math.abs(a - b) < 0.001 + +/** + * Skalowanie objętości do zatwierdzonej bazy — ta sama arytmetyka, co w + * `prepareProposal` (proposals.ts), żeby regeneracja po zatwierdzonej propozycji + * bez zmian na wejściu dawała te same dni: kotwica to pierwszy pełny tydzień + * budowania po dacie decyzji, cele tygodni skalowane proporcjonalnie, siła + * przepisana z wersji nieskalowanej (siła to osobny tor, korekta objętości jej + * nie przestawia). + */ +function scaleFrom(fresh: StoredPlan, config: TrainctlConfig, baseline: number, effectiveFrom: string): void { + const zones = paceZones(fresh.vdot) + const anchor = + fresh.weeks.find((w) => w.weekStart > effectiveFrom && !w.skeleton.deload && !['taper', 'race'].includes(w.skeleton.phase)) ?? + fresh.weeks.find((w) => w.days.some((d) => d.date > effectiveFrom)) + const from = mondayOf(effectiveFrom) + fresh.weeks = fresh.weeks.map((week) => { + if (week.weekStart < from) return week + const skeleton = structuredClone(week.skeleton) + skeleton.targetKm = Math.round((baseline * skeleton.targetKm) / Math.max(1, anchor?.skeleton.targetKm ?? skeleton.targetKm)) + const generated = generateMicrocycle({ skeleton, athlete: config.athlete, goal: fresh.goal, zones, testDistanceKm: testDistanceKm(fresh.goal) }) + for (const day of generated.days) { + const strength = week.days.find((d) => d.date === day.date)?.strength + if (strength) day.strength = structuredClone(strength) + } + return generated + }) + fresh.peakKmPlanned = Math.max(...fresh.weeks.map((w) => w.totalKm)) +} + +export function rebuildPlan( + existing: StoredPlan, + config: TrainctlConfig, + opts: { today: string; recorded: Set }, +): Regeneration { + const now = clockToday() + const today = opts.today + const raceBehind = existing.goal.date < now + const mode: RegenerationMode = + !raceBehind && sameDistance(existing.goal.distanceKm, config.goal.distanceKm) ? 'same-cycle' : 'new-cycle' + + const ls = existing.loadState + const keepLoad = ls !== undefined && (ls.profileWeeklyKm === undefined || ls.profileWeeklyKm === config.athlete.recentWeeklyKm) + const macroStart = mode === 'same-cycle' ? existing.generatedAt : today + const fresh = computePlan(config, macroStart, today) + const loadState = keepLoad + ? { ...ls!, effectiveFrom: mode === 'same-cycle' ? ls!.effectiveFrom : today, profileWeeklyKm: config.athlete.recentWeeklyKm } + : undefined + if (loadState) scaleFrom(fresh, config, loadState.baselineWeeklyKm, loadState.effectiveFrom) + + const existingDays = new Map(existing.weeks.flatMap((w) => w.days).map((d) => [d.date, d])) + const minutesOf = (day: PlannedDay) => + (day.workout ? estimateWorkoutMinutes(day.workout, existing.preparationMinutes ?? 15) : 0) + (day.strength?.durationMin ?? 0) + const protection = (before: PlannedDay, after: PlannedDay): ProtectionReason | undefined => { + if (before.date < now) return 'past' + if (opts.recorded.has(before.date)) return 'recorded' + if (before.pinned) return 'pinned' + if (before.timeAdjustment) return 'approved' + // Bez mapy odcisków (plan sprzed 0.2.0) edycji nie da się odróżnić od generacji. + if (existing.generatedDays && existing.generatedDays[before.date] !== dayFingerprint(before)) return 'edited' + const budget = existing.timeBudgets?.[before.date] + if (budget !== undefined && minutesOf(after) > budget) return 'budget' + return undefined + } + + const freshStart = fresh.weeks[0]!.weekStart + const freshEnd = fresh.weeks.at(-1)!.weekStart + const droppedWeeks: string[] = [] + let history = existing.weeks.filter((w) => w.weekStart < freshStart) + // Walidator wymaga ciągłości tygodni: historia, która nie przylega do nowego + // cyklu, zostaje w gicie, nie w pliku. + if (history.length && addDays(history.at(-1)!.weekStart, 7) !== freshStart) { + droppedWeeks.push(...history.map((w) => w.weekStart)) + history = [] + } + for (const w of existing.weeks) if (w.weekStart > freshEnd) droppedWeeks.push(w.weekStart) + + const changedDates: string[] = [] + const protectedDays: Regeneration['protectedDays'] = [] + const kept = new Set() + const weeks: Microcycle[] = history.map((w) => structuredClone(w)) + for (const fw of fresh.weeks) { + const ew = existing.weeks.find((w) => w.weekStart === fw.weekStart) + let replaced = false + const days = fw.days.map((fd) => { + const ed = existingDays.get(fd.date) + if (!ed) { + replaced = true + return fd + } + const differs = dayFingerprint(ed) !== dayFingerprint(fd) + const reason = protection(ed, fd) + if (reason) { + kept.add(fd.date) + if (differs) protectedDays.push({ date: fd.date, reason }) + return structuredClone(ed) + } + if (differs) { + changedDates.push(fd.date) + replaced = true + } + return fd + }) + // Tydzień w całości chroniony to historia: zostaje razem ze swoim szkieletem + // (cel km, faza), inaczej `week` pokazywałby przeszłości cudzy cel. + if (ew && !replaced && days.every((d) => kept.has(d.date))) { + weeks.push(structuredClone(ew)) + continue + } + const week: Microcycle = { ...fw, days } + Object.assign(week, weekTotals(days)) + weeks.push(week) + } + + const generatedDays: Record = {} + for (const day of weeks.flatMap((w) => w.days)) { + generatedDays[day.date] = kept.has(day.date) || !fresh.weeks.some((w) => w.days.includes(day)) + ? existing.generatedDays?.[day.date] ?? dayFingerprint(day) + : dayFingerprint(day) + } + const dates = new Set(weeks.flatMap((w) => w.days.map((d) => d.date))) + const timeBudgets = Object.fromEntries(Object.entries(existing.timeBudgets ?? {}).filter(([date]) => dates.has(date))) + const cycleStart = mode === 'same-cycle' ? existing.cycleStart : history.length ? freshStart : undefined + const cycleWeeks = cycleStart ? weeks.filter((w) => w.weekStart >= cycleStart) : weeks + + const plan: StoredPlan = { + ...fresh, + generatedAt: macroStart, + weeks, + generatedDays, + changes: [...existing.changes], + peakKmPlanned: Math.max(...cycleWeeks.map((w) => w.totalKm)), + } + if (cycleStart) plan.cycleStart = cycleStart + else delete plan.cycleStart + if (loadState) plan.loadState = loadState + else delete plan.loadState + if (Object.keys(timeBudgets).length) plan.timeBudgets = timeBudgets + if (existing.preparationMinutes !== undefined) plan.preparationMinutes = existing.preparationMinutes + + const sameWeeks = weeks.length === existing.weeks.length && weeks.every((w, i) => w.weekStart === existing.weeks[i]!.weekStart) + const upToDate = + changedDates.length === 0 && + droppedWeeks.length === 0 && + sameWeeks && + plan.vdot === existing.vdot && + JSON.stringify(plan.goal) === JSON.stringify(existing.goal) && + plan.locale === existing.locale && + plan.engineVersion === existing.engineVersion && + JSON.stringify(plan.loadState ?? null) === JSON.stringify(existing.loadState ?? null) + if (!upToDate) { + plan.changes.push({ + at: now, + action: 'regenerate', + detail: `${mode}: ${changedDates.length} changed, ${protectedDays.length} kept`, + }) + } + return { + plan, + mode, + changedDates, + protectedDays, + loadState: loadState ? 'kept' : ls ? 'cleared' : 'none', + droppedWeeks, + upToDate, + } +} diff --git a/packages/cli/src/status.ts b/packages/cli/src/status.ts new file mode 100644 index 0000000..1537bb3 --- /dev/null +++ b/packages/cli/src/status.ts @@ -0,0 +1,151 @@ +/** + * `trainctl status` — jeden ekran stanu katalogu treningowego. + * + * Read-only. Odpowiada na pytania, które dziś wymagały kilku komend albo + * zaglądania do plików: czy profil się waliduje, z której wersji silnika jest + * plan, skąd jest klucz i czy `.env` jest chroniony, kiedy był ostatni pull, + * które propozycje są jeszcze ważne i co nie trafiło do gita. + */ +import { existsSync } from 'node:fs' +import { join } from 'node:path' +import { diffDays, messages, mondayOf } from 'trainctl-core' +import { CONFIG_FILE, loadConfig, readConfigLanguage } from './config.ts' +import { ENV_FILE, inspectEnvFile } from './env-file.ts' +import { buildExecution } from './execution.ts' +import { uncommitted } from './git.ts' +import { ui } from './i18n/index.ts' +import { LOG_FILE, readLog } from './logfile.ts' +import { cycleWeeksOf, loadPlanIfUsable, PLAN_DIR, PLAN_YAML, type StoredPlan } from './planfile.ts' +import { listProposals } from './proposals.ts' +import { readSnapshot, SECRET_FILE, SYNC_FILE } from './sync.ts' +import { b, renderPlain, type Block } from './ui/blocks.ts' +import { clockToday } from './clock.ts' +import { packageVersion } from './version.ts' + +const KEY_ENV = 'TRAINCTL_INTERVALS_API_KEY' + +export interface StatusResult { + output: string + code: number + blocks: Block[] + data: Record +} + +export function cmdStatus(cwd: string): StatusResult { + const t = ui().status + const today = clockToday() + const blocks: Block[] = [b.title(t.title, cwd)] + const next: string[] = [] + + // profil + let configErrors: string | undefined + const hasConfig = existsSync(join(cwd, CONFIG_FILE)) + if (hasConfig) { + try { + loadConfig(cwd) + } catch (e) { + configErrors = e instanceof Error ? e.message : String(e) + } + } + blocks.push(b.section(t.profile), b.kv([ + [CONFIG_FILE, !hasConfig ? t.missing : configErrors ? t.invalid : t.ok], + [t.language, readConfigLanguage(cwd) ?? 'en'], + ])) + if (configErrors) blocks.push(b.warn(configErrors)) + if (!hasConfig) next.push('trainctl init') + + // plan + let plan: StoredPlan | undefined + let planError: string | undefined + try { + plan = loadPlanIfUsable(cwd) + } catch (e) { + planError = e instanceof Error ? e.message : String(e) + } + const current = packageVersion() + if (plan) { + const cycle = cycleWeeksOf(plan) + const sessions = cycle.reduce((s, w) => s + w.days.filter((d) => d.workout).length, 0) + const minor = (v: string) => v.split('.').slice(0, 2).join('.') + blocks.push(b.section(t.plan), b.kv([ + [t.goal, `${plan.goal.name} · ${plan.goal.date} · ${messages().units.kmPerWeek(plan.peakKmPlanned)}`], + [t.toRace, t.daysToRace(diffDays(today, plan.goal.date))], + [t.weeks, t.weeksSessions(cycle.length, sessions)], + [t.generated, plan.generatedAt], + [t.engine, plan.engineVersion + ? minor(plan.engineVersion) === minor(current) ? plan.engineVersion : t.engineOther(plan.engineVersion, current) + : t.engineOld(current)], + ...(plan.loadState ? ([[t.loadState, t.loadStateValue(plan.loadState.baselineWeeklyKm, plan.loadState.effectiveFrom)]] as [string, string][]) : []), + ])) + const selected = plan.calibration?.selected + blocks.push(b.section(t.calibration), b.text(selected + ? t.calibrationSelected(selected.date, selected.distanceKm, diffDays(selected.date, today), plan.vdot) + : plan.vdotSource === 'goal-target' ? t.calibrationFromGoal(plan.vdot) : t.calibrationNone)) + } else { + blocks.push(b.section(t.plan), b.text(planError ?? (existsSync(join(cwd, PLAN_YAML)) ? t.planUnusable(PLAN_YAML) : t.noPlan))) + if (hasConfig && !configErrors) next.push('trainctl plan') + } + + // dane: klucz, synchronizacja, dziennik + const env = inspectEnvFile(cwd, KEY_ENV) + const keySource = existsSync(join(cwd, SECRET_FILE)) + ? SECRET_FILE + : env.hasKey ? ENV_FILE : process.env[KEY_ENV]?.trim() ? t.keyFromEnv : undefined + const snapshot = readSnapshot(cwd) + const logs = readLog(cwd) + const last = logs.at(-1) + const weekStart = mondayOf(today) + const unconfirmed = plan + ? buildExecution(plan, snapshot?.activities ?? [], logs, today) + .filter((e) => e.status === 'unknown' && e.date >= weekStart && e.date < today).map((e) => e.date) + : [] + blocks.push(b.section(t.data), b.kv([ + [t.key, keySource ?? t.keyNone], + ...(env.exists ? ([[ENV_FILE, env.unprotected ? t.envUnprotected : t.envProtected]] as [string, string][]) : []), + [SYNC_FILE, snapshot + ? t.syncValue(snapshot.pulledAt, snapshot.activities.length, snapshot.activities.filter((a) => a.dataWithheld).length) + : t.never], + [LOG_FILE, last ? t.logValue(logs.length, last.date, last.status) : t.empty], + ])) + if (env.unprotected) blocks.push(b.warn(ui().envFile.unprotected(ENV_FILE, '.gitignore'))) + if (unconfirmed.length) blocks.push(b.info(t.unconfirmed(unconfirmed.join(', ')))) + + // propozycje + const proposals = listProposals(cwd) + if (proposals.length) { + blocks.push(b.section(t.proposals), b.table( + [t.columns.id, t.columns.kind, t.columns.for, t.columns.state, t.columns.changes], + proposals.map((p) => [p.id, p.kind, p.createdFor, t.state[p.state], String(p.changes)]), + proposals.map((p) => (p.state === 'valid' ? 'success' : 'muted')), + )) + const valid = proposals.find((p) => p.state === 'valid') + if (valid) next.push(`trainctl ${valid.kind === 'shorten' ? 'shorten' : 'adapt'} --apply ${valid.id}`) + } + + // git + const dirty = uncommitted(cwd, [CONFIG_FILE, PLAN_DIR, LOG_FILE, 'AGENTS.md']) + blocks.push(b.section(t.git), b.text(dirty === undefined ? t.noGit : dirty.length ? t.dirty(dirty.join(', ')) : t.clean)) + if (dirty?.length) next.push('git add -A && git commit') + + if (next.length) blocks.push(b.blank(), b.hint(t.next(next.join(' · ')))) + return { + output: renderPlain(blocks), + code: 0, + blocks, + data: { + dir: cwd, + today, + config: { exists: hasConfig, valid: hasConfig && !configErrors, errors: configErrors ?? null }, + plan: plan + ? { goal: plan.goal, generatedAt: plan.generatedAt, engineVersion: plan.engineVersion ?? null, cliVersion: current, + weeks: cycleWeeksOf(plan).length, loadState: plan.loadState ?? null, vdot: plan.vdot, + calibration: plan.calibration?.selected ?? null } + : null, + key: { source: keySource ?? null, envFileUnprotected: env.unprotected }, + sync: snapshot ? { pulledAt: snapshot.pulledAt, from: snapshot.from ?? null, to: snapshot.to ?? null, activities: snapshot.activities.length } : null, + journal: { entries: logs.length, last: last ?? null, unconfirmedThisWeek: unconfirmed }, + proposals, + git: dirty === undefined ? null : { uncommitted: dirty }, + }, + } +} diff --git a/packages/cli/src/ui/wizard.ts b/packages/cli/src/ui/wizard.ts index b17a6dc..7977d75 100644 --- a/packages/cli/src/ui/wizard.ts +++ b/packages/cli/src/ui/wizard.ts @@ -132,7 +132,7 @@ export function toYaml(a: WizardAnswers): string { ].join('\n') } -async function ask( +export async function ask( rl: Interface, theme: Theme, question: string, diff --git a/packages/core/src/engine/macrocycle.test.ts b/packages/core/src/engine/macrocycle.test.ts index ad59d0d..175f8f0 100644 --- a/packages/core/src/engine/macrocycle.test.ts +++ b/packages/core/src/engine/macrocycle.test.ts @@ -153,3 +153,21 @@ describe('planMacrocycle — przypadki brzegowe', () => { ).toThrow() }) }) + +describe('planMacrocycle — rytm kalibracji liczy wyniki z horyzontu planu (W-12)', () => { + const athlete: AthleteProfile = { + recentWeeklyKm: 55, + daysAvailable: ['tue', 'wed', 'thu', 'sat', 'sun'], + results: [{ date: '2026-03-29', distanceKm: 10, timeSec: 2580 }], + } + const goal: RaceGoal = { name: 'HM', date: '2026-11-29', distanceKm: 21.0975, priority: 'A' } + const tests = (a: AthleteProfile) => planMacrocycle({ today: '2026-08-03', goal, athlete: a }).weeks.filter((w) => w.testPlanned).map((w) => w.weekStart) + + it('wynik wpisany w trakcie planu przesuwa kolejny sprawdzian o pełny odstęp od siebie', () => { + const withResult = tests({ ...athlete, results: [...athlete.results, { date: '2026-09-05', distanceKm: 10, timeSec: 2400 }] }) + // żaden sprawdzian w ciągu pięciu tygodni po świeżym wyniku + expect(withResult.filter((w) => w > '2026-08-31' && w < '2026-10-05')).toEqual([]) + // przed wynikiem rytm liczy się od starszego wyniku, jak w planie bez nowego wpisu + expect(withResult.filter((w) => w < '2026-08-31')).toEqual(tests(athlete).filter((w) => w < '2026-08-31')) + }) +}) diff --git a/packages/core/src/engine/macrocycle.ts b/packages/core/src/engine/macrocycle.ts index acfbe06..279739f 100644 --- a/packages/core/src/engine/macrocycle.ts +++ b/packages/core/src/engine/macrocycle.ts @@ -74,9 +74,16 @@ export interface MacrocycleInput { athlete: AthleteProfile } -/** Data ostatniego wyniku startowego — punkt zerowy rytmu kalibracji (W-12). */ -function lastResultDate(athlete: AthleteProfile): string | undefined { - return athlete.results.map((r) => r.date).sort().at(-1) +/** + * Data ostatniego wyniku startowego PRZED początkiem planu — punkt zerowy rytmu + * kalibracji (W-12). Wyniki z horyzontu planu zerują rytm w swoim tygodniu + * (pętla w `planMacrocycle`); wcześniej liczył się tylko najświeższy wynik, a jego + * data spoza początku planu dawała ujemny odstęp przycięty do zera — i sprawdzian + * lądował tydzień po świeżym wyniku na 10 km (regeneracja liczona od pierwotnej + * daty startu planu, ADR-033). + */ +function lastResultBefore(athlete: AthleteProfile, firstWeek: string): string | undefined { + return athlete.results.map((r) => r.date).filter((d) => d < firstWeek).sort().at(-1) } export function planMacrocycle(input: MacrocycleInput): MacrocyclePlan { @@ -136,12 +143,15 @@ export function planMacrocycle(input: MacrocycleInput): MacrocyclePlan { let loadTarget = start let sinceDeload = 0 // rytm kalibracji: liczony od ostatniego wyniku, resetowany startem kontrolnym (W-12) - const lastResult = lastResultDate(athlete) + const lastResult = lastResultBefore(athlete, firstWeek) + const resultDates = athlete.results.map((r) => r.date) let weeksSinceCalibration = lastResult ? Math.max(0, Math.floor(diffDays(mondayOf(lastResult), firstWeek) / 7)) : CALIBRATION_GAP_WEEKS for (let i = 0; i < totalWeeks; i++) { const weekStart = addDays(firstWeek, i * 7) + // wynik w tym tygodniu to kalibracja tak samo jak start kontrolny (W-12) + if (resultDates.some((d) => d >= weekStart && d < addDays(weekStart, 7))) weeksSinceCalibration = 0 const inTaper = i >= loadWeeks let phase: MacroPhase let intensityModel: IntensityModel diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 9cb8f44..e55fb45 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -18,7 +18,7 @@ terminal can never disagree: `trainctl_plan`, `trainctl_today`, `trainctl_week`, `trainctl_log`, `trainctl_shift`, `trainctl_why`, `trainctl_diff`, `trainctl_check`, `trainctl_init`, `trainctl_push`, `trainctl_pull`, `trainctl_adapt`, `trainctl_desk`, `trainctl_reschedule`, `trainctl_export`, -`trainctl_review`, `trainctl_shorten`. +`trainctl_review`, `trainctl_shorten`, `trainctl_status`. For “only 40 minutes today”, use `trainctl_shorten({minutes: 40})`; it saves a proposal and explains any lost purpose. `trainctl_why` explains the actual diff --git a/packages/mcp/src/server.test.ts b/packages/mcp/src/server.test.ts index 5df3ac2..5441cc5 100644 --- a/packages/mcp/src/server.test.ts +++ b/packages/mcp/src/server.test.ts @@ -71,16 +71,36 @@ describe('serwer MCP trainctl', () => { expect(data.budgetRows.find((row) => row.date === '2026-08-27')!.minutes).toBeLessThanOrEqual(35) }) - it('wystawia komplet 17 narzędzi', async () => { + it('wystawia komplet narzędzi', async () => { const { tools } = await client.listTools() const names = tools.map((t) => t.name).sort() expect(names).toEqual([ 'trainctl_adapt', 'trainctl_check', 'trainctl_desk', 'trainctl_diff', 'trainctl_export', 'trainctl_init', 'trainctl_log', 'trainctl_plan', 'trainctl_pull', 'trainctl_push', 'trainctl_reschedule', 'trainctl_review', 'trainctl_shift', 'trainctl_shorten', - 'trainctl_today', 'trainctl_week', 'trainctl_why', + 'trainctl_status', 'trainctl_today', 'trainctl_week', 'trainctl_why', ]) }) + it('status: stan katalogu tylko do odczytu, z danymi strukturalnymi', async () => { + await call('trainctl_plan', { date: '2026-08-05' }) + const { tools } = await client.listTools() + expect(tools.find((tool) => tool.name === 'trainctl_status')?.annotations?.readOnlyHint).toBe(true) + const result = await client.callTool({ name: 'trainctl_status', arguments: {} }) + expect(result.isError).not.toBe(true) + expect(result.structuredContent).toMatchObject({ code: 0, data: { config: { exists: true, valid: true }, plan: { goal: { distanceKm: 42.195 } } } }) + }) + + it('symulowana data jest ogłoszona w wyniku narzędzia', async () => { + process.env['TRAINCTL_TODAY'] = '2026-08-11' + try { + const result = await client.callTool({ name: 'trainctl_today', arguments: {} }) + expect((result.structuredContent as { output: string }).output).toMatch(/^(simulated date|data symulowana) 2026-08-11/) + expect(result.structuredContent).toMatchObject({ data: { date: '2026-08-11' } }) + } finally { + delete process.env['TRAINCTL_TODAY'] + } + }) + it('prepares a 40-minute variant, explains its tradeoff and applies its exact ID', async () => { await call('trainctl_plan', { date: '2026-08-05' }) const before = readFileSync(join(dir, 'plan/plan.yaml'), 'utf8') diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts index ca6b7a4..84a2e36 100644 --- a/packages/mcp/src/server.ts +++ b/packages/mcp/src/server.ts @@ -23,10 +23,12 @@ import { cmdReview, cmdShift, cmdShorten, + cmdStatus, cmdToday, cmdWeek, cmdWhy, defaultProviderFactory, + simulationNotice, type CmdResult, type ProviderFactory, } from 'trainctl' @@ -34,11 +36,16 @@ import { const isoDate = () => z.string().regex(/^\d{4}-\d{2}-\d{2}$/, ui().mcp.isoDate) const toolOutputSchema = { code: z.number(), output: z.string(), data: z.record(z.string(), z.unknown()) } +/** `commit` na narzędziach, które zapisują plan albo dziennik (ADR-040). */ +const commitParam = () => z.boolean().optional().describe(ui().mcp.commit) function toTool(r: CmdResult) { + // Symulowana data (TRAINCTL_TODAY) nigdy nie jest cicha — także dla agenta (ADR-034). + const notice = simulationNotice() + const output = notice ? `${notice}\n\n${r.output}` : r.output return { - content: [{ type: 'text' as const, text: r.output }, { type: 'text' as const, text: JSON.stringify(r.data ?? {}) }], - structuredContent: { code: r.code, output: r.output, data: r.data ?? {} }, + content: [{ type: 'text' as const, text: output }, { type: 'text' as const, text: JSON.stringify(r.data ?? {}) }], + structuredContent: { code: r.code, output, data: r.data ?? {} }, ...(r.code !== 0 ? { isError: true } : {}), } } @@ -58,10 +65,11 @@ export function createTrainctlServer( annotations: { readOnlyHint: false, openWorldHint: true }, inputSchema: { fromIntervals: z.boolean().optional().describe(t.initFromIntervals), + commit: commitParam(), }, }, async (args) => - toTool(args?.fromIntervals === true ? await cmdInitFromIntervals(dir, {}, factory) : cmdInit(dir)), + toTool(args?.fromIntervals === true ? await cmdInitFromIntervals(dir, {}, factory) : cmdInit(dir, undefined, { commit: args?.commit })), ) server.registerTool( @@ -70,7 +78,7 @@ export function createTrainctlServer( description: t.plan, outputSchema: toolOutputSchema, annotations: { readOnlyHint: false, openWorldHint: false }, - inputSchema: { date: isoDate().optional().describe(t.planDate) }, + inputSchema: { date: isoDate().optional().describe(t.planDate), fresh: z.boolean().optional().describe(t.planFresh), commit: commitParam() }, }, async (args) => toTool(cmdPlan(dir, args)), ) @@ -111,6 +119,7 @@ export function createTrainctlServer( testTime: z.string().optional().describe(ui().improve.testTime), rpe: z.string().optional().describe(t.logRpe), note: z.string().optional().describe(t.logNote), + commit: commitParam(), }, }, async (args) => toTool(cmdLog(dir, args)), @@ -125,6 +134,7 @@ export function createTrainctlServer( inputSchema: { from: isoDate().describe(t.shiftFrom), to: isoDate().describe(t.shiftTo), + commit: commitParam(), }, }, async (args) => toTool(cmdShift(dir, args)), @@ -151,6 +161,7 @@ export function createTrainctlServer( date: isoDate().optional().describe(t.adaptDate), prepare: z.boolean().optional().describe(ui().improve.prepare), apply: z.string().optional().describe(ui().improve.apply), + commit: commitParam(), }, }, async (args) => toTool(cmdAdapt(dir, args)), @@ -180,6 +191,7 @@ export function createTrainctlServer( date: isoDate().optional(), minutes: z.number().int().min(0).max(1440).optional().describe(ui().coach.minutes), apply: z.string().optional().describe(ui().improve.apply), + commit: commitParam(), }, }, async (args) => toTool(cmdShorten(dir, args)), @@ -213,6 +225,7 @@ export function createTrainctlServer( strategy: z.enum(['long', 'quality']).optional().describe(ui().improve.strategy), date: isoDate().optional().describe(t.rescheduleDate), apply: z.boolean().optional().describe(t.rescheduleApply), + commit: commitParam(), }, }, async (args) => toTool(cmdReschedule(dir, args)), @@ -272,6 +285,17 @@ export function createTrainctlServer( async (args) => toTool(cmdDiff(dir, args)), ) + server.registerTool( + 'trainctl_status', + { + description: t.status, + outputSchema: toolOutputSchema, + annotations: { readOnlyHint: true, openWorldHint: false }, + inputSchema: {}, + }, + async () => toTool(cmdStatus(dir)), + ) + server.registerTool( 'trainctl_check', { From 146a9cf9e42ad7a62c996a206324bb26e9db4059 Mon Sep 17 00:00:00 2001 From: Dariusz Tyszka Date: Wed, 21 Oct 2026 11:52:38 +0200 Subject: [PATCH 03/19] feat(plugin): trainctl jako plugin Claude Code i Codex, zasoby i prompty MCP MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Etap C z docs/PLAN-v0.4.md (ADR-036). - plugin/: serwer MCP, persona trenera generowana z tego samego tekstu co AGENTS.md, skille review/debrief/shorten/what-if, a w Claude Code hooki: instrukcja trenera na starcie sesji w katalogu treningowym i trainctl check po edycji plan/plan.yaml (błąd → kod 2, ostrzeżenia → additionalContext). - Repozytorium jest marketplace'em dla obu agentów (.claude-plugin/, .agents/plugins/); walidacja `claude plugin validate` przechodzi. - init --agent claude|codex|all: .claude/settings.json albo .codex/config.toml, bez nadpisywania istniejących plików i bez duplikowania serwera MCP. - MCP: trainctl_rule, zasoby trainctl://plan|config|agents|rules/{id}, prompty weekly-review i debrief; CLI: trainctl rules [id]. - check zwraca ustalenia jako data; tools/release/bump-version.mjs przesuwa wszystkie przypięte wersje razem; CI sprawdza świeżość skilli. Co-Authored-By: Claude Opus 5.5 --- .agents/plugins/marketplace.json | 12 ++ .claude-plugin/marketplace.json | 15 +++ .github/workflows/ci.yml | 4 + CHANGELOG.md | 22 ++++ CONTRIBUTING.md | 10 ++ README.md | 29 ++++- README.pl.md | 29 ++++- SPEC.md | 1 + docs/integrations/agents.md | 80 +++++++++++++ packages/cli/src/agent-setup.ts | 73 ++++++++++++ packages/cli/src/bin.ts | 22 +++- packages/cli/src/commands.ts | 69 ++++++++++- packages/cli/src/i18n/cli-en.ts | 40 +++++++ packages/cli/src/i18n/cli-pl.ts | 40 +++++++ packages/cli/src/plugin-skills.ts | 89 ++++++++++++++ packages/cli/src/plugin.test.ts | 185 ++++++++++++++++++++++++++++++ packages/mcp/README.md | 8 +- packages/mcp/src/server.test.ts | 27 ++++- packages/mcp/src/server.ts | 58 +++++++++- plugin/.claude-plugin/plugin.json | 10 ++ plugin/.codex-plugin/plugin.json | 12 ++ plugin/.mcp.json | 9 ++ plugin/README.md | 22 ++++ plugin/codex.mcp.json | 8 ++ plugin/hooks/hooks.json | 20 ++++ plugin/scripts/check-plan.mjs | 88 ++++++++++++++ plugin/scripts/session-start.mjs | 32 ++++++ plugin/skills/coach/SKILL.md | 103 +++++++++++++++++ plugin/skills/debrief/SKILL.md | 13 +++ plugin/skills/review/SKILL.md | 14 +++ plugin/skills/shorten/SKILL.md | 12 ++ plugin/skills/what-if/SKILL.md | 14 +++ tools/plugin/render-skills.ts | 35 ++++++ tools/release/bump-version.mjs | 48 ++++++++ 34 files changed, 1236 insertions(+), 17 deletions(-) create mode 100644 .agents/plugins/marketplace.json create mode 100644 .claude-plugin/marketplace.json create mode 100644 docs/integrations/agents.md create mode 100644 packages/cli/src/agent-setup.ts create mode 100644 packages/cli/src/plugin-skills.ts create mode 100644 packages/cli/src/plugin.test.ts create mode 100644 plugin/.claude-plugin/plugin.json create mode 100644 plugin/.codex-plugin/plugin.json create mode 100644 plugin/.mcp.json create mode 100644 plugin/README.md create mode 100644 plugin/codex.mcp.json create mode 100644 plugin/hooks/hooks.json create mode 100644 plugin/scripts/check-plan.mjs create mode 100644 plugin/scripts/session-start.mjs create mode 100644 plugin/skills/coach/SKILL.md create mode 100644 plugin/skills/debrief/SKILL.md create mode 100644 plugin/skills/review/SKILL.md create mode 100644 plugin/skills/shorten/SKILL.md create mode 100644 plugin/skills/what-if/SKILL.md create mode 100644 tools/plugin/render-skills.ts create mode 100644 tools/release/bump-version.mjs diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json new file mode 100644 index 0000000..825e5b3 --- /dev/null +++ b/.agents/plugins/marketplace.json @@ -0,0 +1,12 @@ +{ + "name": "trainctl", + "interface": { "displayName": "trainctl" }, + "plugins": [ + { + "name": "trainctl", + "source": { "source": "local", "path": "./plugin" }, + "policy": { "installation": "AVAILABLE", "authentication": "ON_FIRST_USE" }, + "category": "Productivity" + } + ] +} diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json new file mode 100644 index 0000000..b7aa736 --- /dev/null +++ b/.claude-plugin/marketplace.json @@ -0,0 +1,15 @@ +{ + "name": "trainctl", + "owner": { "name": "Dariusz Tyszka" }, + "description": "trainctl: a running coach in your terminal and in your agent — training plan as code, MCP tools, coach skills", + "plugins": [ + { + "name": "trainctl", + "source": "./plugin", + "description": "Running coach as your agent's tool: training plan as code, MCP tools, coach skills and a lint after plan edits", + "version": "0.3.0", + "category": "productivity", + "keywords": ["running", "training-plan", "coach", "mcp"] + } + ] +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aeb4de5..b6864eb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,6 +43,10 @@ jobs: # repository, so the seven backtest cases skip here by design. - run: pnpm test + # The plugin's skills are generated from the AGENTS.md text; a stale copy + # would give the agent a different coach than `trainctl init` writes. + - run: node tools/plugin/render-skills.ts --check + # What the repository cannot see about itself: the published packages run from # node_modules, where Node refuses to strip TypeScript types. 0.1.0 shipped # broken because every other check runs from the source tree. diff --git a/CHANGELOG.md b/CHANGELOG.md index 634932e..fe701ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -65,6 +65,28 @@ change between minor versions — a regenerated plan can differ. - `trainctl completion bash|zsh|fish|pwsh`, examples under `trainctl help `. - Usage errors (unknown command or flag, a date that is not a date) exit with 2. +### Added — trainctl in Claude Code and Codex (ADR-036) + +- A plugin in `plugin/`, with this repository as its marketplace for both agents: + `/plugin marketplace add dithiothreitol/trainctl` + `/plugin install trainctl@trainctl` + in Claude Code, `codex plugin marketplace add dithiothreitol/trainctl` in Codex. + It bundles the MCP server, the coach persona and four task skills + (`review`, `debrief`, `shorten`, `what-if`), and in Claude Code two hooks: the + coach instructions at session start in a training directory, and + `trainctl check` after an edit of `plan/plan.yaml`. +- Skills are generated from the same text as `AGENTS.md` + (`node tools/plugin/render-skills.ts`); `plugin.test.ts` fails on drift. +- `trainctl init --agent claude|codex|all` (MCP `agent`) writes + `.claude/settings.json` or `.codex/config.toml`; existing files are never + overwritten. +- MCP: `trainctl_rule` explains a rule by ID with its source class and a link to + FOUNDATIONS for this version; resources `trainctl://plan`, `trainctl://config`, + `trainctl://agents`, `trainctl://rules/{id}`; prompts `weekly-review` and + `debrief`. CLI: `trainctl rules [id]`. +- `trainctl check` returns its findings as `data` (`--json`, MCP, the hook). +- `tools/release/bump-version.mjs` moves every pinned version together: packages, + plugin manifests, MCP configs, the hook and the CI examples. + ### Docs - README command tables list `shorten` and the missing flags; tool lists no diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 80f2e0b..85b9c4e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -41,6 +41,16 @@ MCP server imports only from `trainctl`. A command handler that formats its own output with colours is a bug — handlers return semantic blocks (`packages/cli/src/ui/blocks.ts`) and the CLI renderer adds the colour. +## The agent plugin + +`plugin/` packages the MCP server for Claude Code and Codex (see +[docs/integrations/agents.md](docs/integrations/agents.md)). Its skills are +generated: after changing the `AGENTS.md` text in the CLI catalogues or +`packages/cli/src/plugin-skills.ts`, run `node tools/plugin/render-skills.ts`. +Versions are pinned in several places (packages, plugin manifests, MCP configs, +the check hook, CI examples); `node tools/release/bump-version.mjs ` moves +them together, and the tests fail when one is left behind. + ## What a change needs **Engine rules need a source.** Every rule carries an ID from diff --git a/README.md b/README.md index d299ae2..befb71a 100644 --- a/README.md +++ b/README.md @@ -242,7 +242,7 @@ a key is configured). `trainctl adapt` compares execution with the plan and | command | what it does | key flags | |---|---|---| -| `init` | profile wizard | `--template`, `--from-intervals`, `--commit` | +| `init` | profile wizard | `--template`, `--from-intervals`, `--agent claude\|codex\|all`, `--commit` | | `plan` | generate the plan; on an existing plan regenerate only the future | `--date`, `--fresh`, `--commit` | | `today` | the session for today | `--date` | | `week` | the week, with journal status | `--date`, `-i` (arrow-key browsing) | @@ -260,6 +260,7 @@ a key is configured). `trainctl adapt` compares execution with the plan and | `diff` | what a regeneration would change | `--plan ` | | `check` | lint the plan; fails the exit code | `--strict` | | `status` | the directory at a glance: profile, plan, key, data, proposals, git | | +| `rules` | every engine rule with its source class, or one in full | `[id]` | | `completion` | shell completion script | `bash`, `zsh`, `fish`, `pwsh` | Every command takes `--lang en|pl`, `--json` (prints `{ code, data, output }` — @@ -394,6 +395,27 @@ The same engine as tools for an agent, so the interface becomes conversation: *"what am I running today?"*, *"release on Thursday — move the intervals"*, *"how did last week go?"* +**Claude Code — as a plugin.** The plugin brings the MCP tools, five coach skills +(`/trainctl:review`, `/trainctl:debrief`, `/trainctl:shorten`, `/trainctl:what-if` +and the coach persona) and two hooks: the coach instructions at session start in +a training directory, and `trainctl check` after an edit of `plan/plan.yaml`. + +```text +/plugin marketplace add dithiothreitol/trainctl +/plugin install trainctl@trainctl +``` + +`trainctl init --agent claude` writes `.claude/settings.json` into the training +directory, so the plugin is enabled there for anyone who clones it. + +**Codex** reads `AGENTS.md` on its own. `trainctl init --agent codex` adds the MCP +server in `.codex/config.toml` (loaded once you trust the project); or install +the plugin with `codex plugin marketplace add dithiothreitol/trainctl` and +`/plugins`. Use one of the two, not both. Details and limits: +[docs/integrations/agents.md](docs/integrations/agents.md). + +**Without the plugin** — Claude Code: + ```bash claude mcp add trainctl --env TRAINCTL_DIR="/path/to/my-training" \ -- npx -y trainctl-mcp @@ -418,7 +440,10 @@ terminal can never disagree: `trainctl_plan`, `trainctl_today`, `trainctl_week`, `trainctl_log`, `trainctl_shift`, `trainctl_why`, `trainctl_diff`, `trainctl_check`, `trainctl_init`, `trainctl_push`, `trainctl_pull`, `trainctl_adapt`, `trainctl_shorten`, `trainctl_desk`, `trainctl_reschedule`, -`trainctl_export`, `trainctl_review`, `trainctl_status`. +`trainctl_export`, `trainctl_review`, `trainctl_status`, `trainctl_rule`. The +server also exposes `plan/PLAN.md`, `trainctl.yaml`, `AGENTS.md` and every rule as +resources (`trainctl://plan`, `trainctl://rules/I-7`, …), and the weekly review +and the post-run debrief as prompts. The `AGENTS.md` written by `trainctl init` turns the agent into a coach rather than a command runner: ask before regenerating a plan, ask for context when a diff --git a/README.pl.md b/README.pl.md index 2f832e4..858935e 100644 --- a/README.pl.md +++ b/README.pl.md @@ -245,7 +245,7 @@ Twoimi plecami. | komenda | co robi | ważniejsze flagi | |---|---|---| -| `init` | kreator profilu | `--template`, `--from-intervals`, `--commit` | +| `init` | kreator profilu | `--template`, `--from-intervals`, `--agent claude\|codex\|all`, `--commit` | | `plan` | generuje plan; na istniejącym regeneruje tylko przyszłość | `--date`, `--fresh`, `--commit` | | `today` | trening na dziś | `--date` | | `week` | tydzień ze statusem z dziennika | `--date`, `-i` (przeglądanie strzałkami) | @@ -263,6 +263,7 @@ Twoimi plecami. | `diff` | co zmieniłaby regeneracja planu | `--plan ` | | `check` | lint planu; psuje kod wyjścia | `--strict` | | `status` | stan katalogu na jednym ekranie: profil, plan, klucz, dane, propozycje, git | | +| `rules` | wszystkie reguły silnika z klasą źródła albo jedna w całości | `[id]` | | `completion` | skrypt uzupełniania dla powłoki | `bash`, `zsh`, `fish`, `pwsh` | Każda komenda przyjmuje `--lang en|pl`, `--json` (wypisuje `{ code, data, @@ -400,6 +401,27 @@ Ten sam silnik jako narzędzia agenta — interfejsem staje się rozmowa: „co dziś wybiegać?", „w czwartek release, przesuń interwały", „jak mi poszedł tydzień?". +**Claude Code — jako plugin.** Plugin daje narzędzia MCP, pięć skilli trenera +(`/trainctl:review`, `/trainctl:debrief`, `/trainctl:shorten`, `/trainctl:what-if` +i personę trenera) oraz dwa hooki: instrukcję trenera na starcie sesji w katalogu +treningowym i `trainctl check` po edycji `plan/plan.yaml`. + +```text +/plugin marketplace add dithiothreitol/trainctl +/plugin install trainctl@trainctl +``` + +`trainctl init --agent claude` zapisuje `.claude/settings.json` w katalogu +treningowym, więc plugin jest tam włączony dla każdego, kto sklonuje repo. + +**Codex** sam czyta `AGENTS.md`. `trainctl init --agent codex` dodaje serwer MCP +w `.codex/config.toml` (ładowany, gdy zaufasz projektowi); albo zainstaluj plugin +przez `codex plugin marketplace add dithiothreitol/trainctl` i `/plugins`. Jedno +z dwóch, nie oba naraz. Szczegóły i ograniczenia: +[docs/integrations/agents.md](docs/integrations/agents.md). + +**Bez pluginu** — Claude Code: + ```bash claude mcp add trainctl --env TRAINCTL_DIR="C:\sciezka\do\mojego-treningu" ^ -- npx -y trainctl-mcp @@ -424,7 +446,10 @@ agent i terminal nie mogą się rozjechać: `trainctl_plan`, `trainctl_today`, `trainctl_week`, `trainctl_log`, `trainctl_shift`, `trainctl_why`, `trainctl_diff`, `trainctl_check`, `trainctl_init`, `trainctl_push`, `trainctl_pull`, `trainctl_adapt`, `trainctl_shorten`, `trainctl_desk`, -`trainctl_reschedule`, `trainctl_export`, `trainctl_review`, `trainctl_status`. +`trainctl_reschedule`, `trainctl_export`, `trainctl_review`, `trainctl_status`, +`trainctl_rule`. Serwer wystawia też `plan/PLAN.md`, `trainctl.yaml`, `AGENTS.md` +i każdą regułę jako zasoby (`trainctl://plan`, `trainctl://rules/I-7`, …), a +przegląd tygodnia i odprawę po treningu jako prompty. `AGENTS.md`, który zostawia `trainctl init`, robi z agenta trenera, a nie wykonawcę komend: pyta przed regeneracją planu, dopytuje o kontekst przy diff --git a/SPEC.md b/SPEC.md index 0f4e5fc..f8248e1 100644 --- a/SPEC.md +++ b/SPEC.md @@ -329,4 +329,5 @@ dane strukturalne MCP i samodzielny eksport mobilny. Opis poleceń i granic: | 033 | 2026-10-21 | `trainctl plan` na istniejącym planie = **regeneracja chroniona**: dni przeszłe, zalogowane, przypięte, ręcznie edytowane, zatwierdzone skrócenia i przekraczające budżet zostają; zatwierdzona baza `loadState` obowiązuje, dopóki profil nie zmieni `recentWeeklyKm`; ten sam cykl liczony od pierwotnej daty startu planu (granice faz), inny dystans albo cel po starcie = nowy cykl z historią w pliku; `--fresh` zaczyna od zera; `diff` pokazuje tę samą regenerację | dokumentowana ścieżka „nowy wynik → trainctl.yaml → plan" kasowała zatwierdzone decyzje — ochrona z ADR-029 obejmowała propozycje, nie regenerację. To była luka, nie wybór | | 034 | 2026-10-21 | Zegar symulacji `TRAINCTL_TODAY` jest **jawny**: każde wyjście CLI i MCP zaczyna się od informacji o nim, ochrona przeszłości i ważność propozycji idą za datą symulowaną | A05 słusznie oddzielił wybór tygodnia od zegara, ale bez sankcjonowanej symulacji dokumentacja i próby ręczne stały się niemożliwe; cicha symulacja byłaby powtórką A05 | | 035 | 2026-10-21 | `--json` zwraca `CmdResult.data` — te same dane, które dostaje MCP; stabilność kształtu do 1.0 tylko w polach używanych przez MCP | jedno źródło danych dla agenta i skryptów, bez drugiej logiki wyjścia (ADR-013) | +| 036 | 2026-10-21 | Plugin Claude Code/Codex to **kanał dystrybucji, nie nowa logika**: repozytorium jest marketplace’em (`.claude-plugin/`, `.agents/plugins/`), plugin pakuje serwer MCP, personę (generowaną z tego samego tekstu co AGENTS.md) i skille zadaniowe; hooki tylko w Claude Code; `init --agent` zapisuje pliki agenta wyłącznie na jawną flagę i nigdy nie nadpisuje istniejących | dryf między AGENTS.md a skillami dałby dwóch różnych trenerów; plugin i projektowy `.mcp.json` naraz uruchomiłyby dwa serwery; cicha konfiguracja agenta w repo użytkownika łamie zasadę „nic bez pytania" (ADR-019) | | 040 | 2026-10-21 | `--commit` commituje wyłącznie pliki zmienione przez komendę (pathspec przy `git commit`), nigdy sekretów ani `sync.json`; brak gita to informacja, nie błąd | AGENTS.md każe commitować po każdej zmianie planu — flaga robi to, co i tak jest zalecane, bez stawania się klientem gita i bez zabierania cudzych zmian z indeksu | diff --git a/docs/integrations/agents.md b/docs/integrations/agents.md new file mode 100644 index 0000000..2b7aec2 --- /dev/null +++ b/docs/integrations/agents.md @@ -0,0 +1,80 @@ +# trainctl in Claude Code and Codex + +The coach reaches an agent in three layers. The **MCP server** (`trainctl-mcp`) +gives it the tools, resources and prompts. **`AGENTS.md`** in the training +directory tells it how to behave like a coach. The **plugin** bundles both for +one-step installation, adds task skills and, in Claude Code, two hooks. + +Facts about both agents below were checked against their documentation on +2026-10-21; plugin systems change quickly, so the date matters. + +## Claude Code + +```text +/plugin marketplace add dithiothreitol/trainctl +/plugin install trainctl@trainctl +``` + +The repository is its own marketplace (`.claude-plugin/marketplace.json` points +at `plugin/`). Once installed, in every session where the plugin is enabled: + +| part | what it does | +|---|---| +| MCP server | `npx -y trainctl-mcp@` with `TRAINCTL_DIR` set to the project directory | +| skill `coach` | the coach persona — the same text `trainctl init` writes as `AGENTS.md` | +| skills `/trainctl:review`, `/trainctl:debrief`, `/trainctl:shorten`, `/trainctl:what-if` | one ritual each: which tool, what to show, what not to do | +| hook `SessionStart` | in a directory with `trainctl.yaml`, puts its `AGENTS.md` into context (Claude Code does not read `AGENTS.md` by itself); elsewhere it stays silent | +| hook `PostToolUse` on `Edit\|Write` | after an edit of `plan/plan.yaml`, runs `trainctl check`: errors reach the agent as a blocking message, warnings as added context | + +**Enabling it for a training repository.** `trainctl init --agent claude` writes +`.claude/settings.json` with `extraKnownMarketplaces` and `enabledPlugins`. +Whoever clones the repository and trusts the folder is offered the plugin; +it still has to be installed once per machine. + +**Limits.** + +- A plugin cannot enable itself only in some directories. The hooks check for + `trainctl.yaml` and stay silent elsewhere; the MCP tools are available in every + session where the plugin is enabled, and answer "run trainctl init" outside a + training directory. +- The `PostToolUse` hook sees edits made through Claude's Edit and Write tools, + not files rewritten by a shell command or another program. +- The hook runs `npx -y trainctl@`; the first run downloads the package. + Offline, the hook stays silent rather than blocking the edit. +- Anthropic's official marketplace does not take submissions; this repository is + the marketplace. + +Without the plugin, the server alone: + +```bash +claude mcp add trainctl --env TRAINCTL_DIR="/path/to/my-training" -- npx -y trainctl-mcp +``` + +Do not combine that with the plugin — two servers would expose the same tools twice. + +## Codex + +Codex reads `AGENTS.md` natively, so the persona needs nothing extra. For the +tools, pick **one** of: + +- **`trainctl init --agent codex`** writes `.codex/config.toml` with an + `[mcp_servers.trainctl]` entry. Codex loads project configuration only after + you trust the project. If the tools report the wrong directory, set + `env = { TRAINCTL_DIR = "/absolute/path" }` in that entry. +- **The plugin**: `codex plugin marketplace add dithiothreitol/trainctl`, then + `/plugins` in a session. It brings the MCP server and the same skills. + Codex plugins with hooks are not eligible for its public directory, so the + Codex manifest (`.codex-plugin/plugin.json`) declares no hooks. + +## Working on the plugin + +```bash +node tools/plugin/render-skills.ts # after changing AGENTS.md or a skill +claude --plugin-dir ./plugin # try it without installing +TRAINCTL_PLUGIN_CLI=packages/cli/src/bin.ts # make the check hook use your working tree +node tools/release/bump-version.mjs 0.4.0 # versions of packages, plugin, hooks and examples together +``` + +`plugin.test.ts` fails when the skills drift from their source, when a skill +mentions a tool the server does not register, or when any pinned version differs +from the packages. diff --git a/packages/cli/src/agent-setup.ts b/packages/cli/src/agent-setup.ts new file mode 100644 index 0000000..ca05660 --- /dev/null +++ b/packages/cli/src/agent-setup.ts @@ -0,0 +1,73 @@ +/** + * `trainctl init --agent claude|codex|all` — pliki integracji agenta w katalogu + * treningowym (ADR-036). Wyłącznie na jawną flagę: konfiguracja agenta w repo + * użytkownika to decyzja użytkownika, nie efekt uboczny `init`. + * + * Claude Code: `.claude/settings.json` rejestruje marketplace z tego repozytorium + * i włącza plugin (serwer MCP, skille, hooki). Bez pliku `.mcp.json` obok — + * plugin i projektowy `.mcp.json` uruchomiłyby dwa serwery trainctl naraz. + * + * Codex: `.codex/config.toml` z serwerem MCP. AGENTS.md Codex czyta sam; plugin + * z marketplace (`codex plugin marketplace add`) to alternatywa — nie oba naraz, + * z tego samego powodu. + * + * Istniejących plików nie nadpisujemy: drukujemy, co do nich dopisać. + */ +import { existsSync, mkdirSync, writeFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { packageVersion } from './version.ts' + +export const AGENTS = ['claude', 'codex', 'all'] as const +export type AgentChoice = (typeof AGENTS)[number] + +export const MARKETPLACE_REPO = 'dithiothreitol/trainctl' +export const PLUGIN_ID = 'trainctl@trainctl' +export const CLAUDE_SETTINGS = '.claude/settings.json' +export const CODEX_CONFIG = '.codex/config.toml' + +export function claudeSettings(): string { + return JSON.stringify({ + extraKnownMarketplaces: { trainctl: { source: { source: 'github', repo: MARKETPLACE_REPO } } }, + enabledPlugins: { [PLUGIN_ID]: true }, + }, null, 2) + '\n' +} + +export function codexConfig(): string { + return [ + '# trainctl — coach tools for Codex in this training directory.', + '# Codex reads AGENTS.md on its own; this adds the trainctl MCP server.', + '# Project config loads only after you trust this directory in Codex.', + '# Use either this server or the trainctl plugin (codex plugin marketplace add', + `# ${MARKETPLACE_REPO}), not both — they would start two servers.`, + '[mcp_servers.trainctl]', + 'command = "npx"', + `args = ["-y", "trainctl-mcp@${packageVersion()}"]`, + '# If the tools see the wrong directory, point them here explicitly:', + '# env = { TRAINCTL_DIR = "/absolute/path/to/this/directory" }', + '', + ].join('\n') +} + +export interface AgentSetup { + created: string[] + /** Pliki, które już istniały — z treścią do ręcznego dopisania. */ + existing: { file: string; content: string }[] +} + +export function writeAgentSetup(cwd: string, agent: AgentChoice): AgentSetup { + const wanted: { file: string; content: string }[] = [] + if (agent === 'claude' || agent === 'all') wanted.push({ file: CLAUDE_SETTINGS, content: claudeSettings() }) + if (agent === 'codex' || agent === 'all') wanted.push({ file: CODEX_CONFIG, content: codexConfig() }) + const setup: AgentSetup = { created: [], existing: [] } + for (const { file, content } of wanted) { + const path = join(cwd, file) + if (existsSync(path)) { + setup.existing.push({ file, content }) + continue + } + mkdirSync(dirname(path), { recursive: true }) + writeFileSync(path, content, 'utf-8') + setup.created.push(file) + } + return setup +} diff --git a/packages/cli/src/bin.ts b/packages/cli/src/bin.ts index 77b190f..66fac38 100644 --- a/packages/cli/src/bin.ts +++ b/packages/cli/src/bin.ts @@ -25,6 +25,7 @@ import { cmdPush, cmdReschedule, cmdReview, + cmdRules, cmdShift, cmdShorten, cmdStatus, @@ -48,6 +49,7 @@ import { b, renderAnsi, renderPlain } from './ui/blocks.ts' import { Theme } from './ui/theme.ts' import { withSpinner } from './ui/spinner.ts' import { runWizard, toYaml } from './ui/wizard.ts' +import { select } from './ui/select.ts' import { packageVersion } from './version.ts' /** Wartość globalnej opcji czytana z argv PRZED zbudowaniem drzewa komend. */ @@ -191,14 +193,15 @@ commitOption( .command('init') .description(ui().cmd.init) .option('--template', ui().cmd.initTemplate) - .option('--from-intervals', ui().cmd.initFromIntervals), + .option('--from-intervals', ui().cmd.initFromIntervals) + .option('--agent ', ui().cmd.optAgent), ).action(async (opts) => { const interactive = opts.template !== true && tty if (!interactive) { if (opts.fromIntervals === true) { return print(await spin(ui().cmd.spinnerInit, () => cmdInitFromIntervals(cwd))) } - return print(cmdInit(cwd, undefined, { commit: opts.commit })) + return print(cmdInit(cwd, undefined, { commit: opts.commit, agent: opts.agent })) } try { const answers = await runWizard(theme, { @@ -206,7 +209,14 @@ commitOption( force: opts.fromIntervals === true, fetch: () => fetchInferredProfile(cwd, localToday()), }) - print(cmdInit(cwd, toYaml(answers), { commit: opts.commit })) + // Pliki agenta tylko na wyraźną odpowiedź — „żadnego" to pełnoprawny wybór. + const agent = opts.agent ?? await select(ui().init.agentQuestion, [ + { label: 'Claude Code', value: 'claude' }, + { label: 'Codex', value: 'codex' }, + { label: 'Claude Code + Codex', value: 'all' }, + { label: ui().init.agentNone, value: 'none' }, + ], theme) + print(cmdInit(cwd, toYaml(answers), { commit: opts.commit, agent: agent === 'none' ? undefined : agent })) } catch (e) { // Ctrl+C w kreatorze nie powinno zostawiać stack trace'u console.log(theme.dim(`\n${ui().common.interrupted}`)) @@ -395,6 +405,12 @@ program .option('--strict', ui().cmd.optStrict) .action((opts) => print(cmdCheck(cwd, opts))) +program + .command('rules') + .description(ui().cmd.rules) + .argument('[id]', 'I-7, T-10, …') + .action((id?: string) => print(cmdRules({ id }))) + withExamples( program .command('status') diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index 1e07303..a28a8dc 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -55,6 +55,10 @@ import { rebuildPlan, type Regeneration } from './regenerate.ts' import { commitFiles } from './git.ts' import { LOG_FILE } from './logfile.ts' export { cmdStatus } from './status.ts' +export { pluginSkills, renderSkill, type Skill } from './plugin-skills.ts' +export { AGENTS, type AgentChoice } from './agent-setup.ts' +export { foundationsUrl } from './rules-explain.ts' +import { AGENTS, writeAgentSetup, type AgentChoice } from './agent-setup.ts' export { resolveDateInput, type DateDirection } from './date-input.ts' export { completionScript, SHELLS, type CompletionSpec, type Shell } from './completion.ts' export { simulationNotice, simulatedToday, SIMULATED_TODAY_ENV } from './clock.ts' @@ -279,26 +283,47 @@ function protectSecrets(cwd: string): string[] { return missing } -export function cmdInit(cwd: string, content?: string, opts: { commit?: CommitOption } = {}): CmdResult { - return withCommit(initImpl(cwd, content), cwd, opts.commit, [CONFIG_FILE, AGENTS_FILE, '.gitignore'], ui().commit.init) +export function cmdInit(cwd: string, content?: string, opts: { commit?: CommitOption; agent?: string | undefined } = {}): CmdResult { + if (opts.agent !== undefined && !(AGENTS as readonly string[]).includes(opts.agent)) { + return fail(new Error(ui().init.agentUnknown(opts.agent, AGENTS.join(', ')))) + } + const result = initImpl(cwd, content, opts.agent as AgentChoice | undefined) + const extra = (result.data?.['agentFiles'] as string[] | undefined) ?? [] + return withCommit(result, cwd, opts.commit, [CONFIG_FILE, AGENTS_FILE, '.gitignore', ...extra], ui().commit.init) +} + +/** + * Pliki integracji agenta — tylko na jawne `--agent` (ADR-036). Istniejących + * nie nadpisujemy: pokazujemy, co do nich dopisać. + */ +function agentBlocks(cwd: string, agent: AgentChoice | undefined): { blocks: Block[]; files: string[] } { + if (!agent) return { blocks: [b.hint(ui().init.agentHint)], files: [] } + const setup = writeAgentSetup(cwd, agent) + const blocks: Block[] = setup.created.map((file) => b.success(ui().init.agentCreated(file))) + for (const e of setup.existing) blocks.push(b.warn(ui().init.agentExists(e.file)), b.text(e.content, 'muted')) + if (agent === 'claude' || agent === 'all') blocks.push(b.info(ui().init.agentClaudeNext)) + if (agent === 'codex' || agent === 'all') blocks.push(b.info(ui().init.agentCodexNext)) + return { blocks, files: setup.created } } -function initImpl(cwd: string, content?: string): CmdResult { +function initImpl(cwd: string, content: string | undefined, agent: AgentChoice | undefined): CmdResult { try { writeConfigTemplate(cwd, content) const agents = writeAgentsFile(cwd) const ignored = protectSecrets(cwd) + const integration = agentBlocks(cwd, agent) return okDoc([ b.success(ui().init.created(CONFIG_FILE)), ...(agents ? [b.success(ui().init.createdAgents(AGENTS_FILE))] : []), ...(ignored.length ? [b.success(ui().init.gitignoreUpdated(ignored.join(', ')))] : []), + ...integration.blocks, ...(content ? [] : [ b.text(ui().init.fillProfile), ]), b.hint(ui().common.nextStep('trainctl plan')), - ]) + ], { agentFiles: integration.files }) } catch (e) { return fail(e) } @@ -1544,7 +1569,7 @@ export function cmdCheck(cwd: string, opts: { strict?: boolean | undefined } = { if (issues.length === 0) { const weeks = plan.weeks ?? [] const sessions = weeks.reduce((sum, w) => sum + w.days.filter((d) => d.workout).length, 0) - return okDoc([b.success(t.passed(weeks.length, sessions)), ...versionNotes]) + return okDoc([b.success(t.passed(weeks.length, sessions)), ...versionNotes], { issues: [], errors: 0, warnings: 0 }) } const blocks: Block[] = [b.title(t.title, t.subtitle(PLAN_YAML)), ...versionNotes] @@ -1563,7 +1588,39 @@ export function cmdCheck(cwd: string, opts: { strict?: boolean | undefined } = { } else if (!failed && warns.length > 0) { blocks.push(b.hint(t.strictHint)) } - return { output: renderPlain(blocks), code: failed ? 1 : 0, blocks } + return { output: renderPlain(blocks), code: failed ? 1 : 0, blocks, data: { issues, errors: errors.length, warnings: warns.length } } + } catch (e) { + return fail(e) + } +} + +/** + * Reguły silnika po ID — dla agenta, który nie ma FOUNDATIONS na dysku, i dla + * człowieka, który chce zobaczyć całą listę (`trainctl rules`). + */ +export function cmdRules(opts: { id?: string | undefined } = {}): CmdResult { + try { + const t = ui().rulesCmd + const ids = [...Object.keys(ui().rules), 'E-1'].sort((a, z) => a.localeCompare(z, 'en', { numeric: true })) + const url = foundationsUrl() + if (!opts.id) { + return okDoc([ + b.title(t.title, t.subtitle(ids.length)), + b.bullets(ids.map((id) => ui().why.ruleLine(id, ruleExplain(id), ui().improve[ruleEvidence(id)]))), + b.blank(), + b.hint(ui().why.sourcesHint(url, '§10')), + ], { rules: ids.map((id) => ({ id, explanation: ruleExplain(id), origin: ruleEvidence(id) })), source: url }) + } + const id = opts.id.trim().toUpperCase() + const explanation = ruleExplain(id) + if (!explanation) throw new Error(t.unknown(opts.id, ids.join(', '))) + const origin = ruleEvidence(id) + return okDoc([ + b.title(id, ui().improve[origin]), + b.text(explanation), + b.blank(), + b.hint(ui().why.sourcesHint(url, '§10')), + ], { id, explanation, origin, source: url }) } catch (e) { return fail(e) } diff --git a/packages/cli/src/i18n/cli-en.ts b/packages/cli/src/i18n/cli-en.ts index ee78bef..39db9df 100644 --- a/packages/cli/src/i18n/cli-en.ts +++ b/packages/cli/src/i18n/cli-en.ts @@ -39,6 +39,8 @@ export const cliEn = { check: 'lint the plan: engine invariants + file integrity; errors fail the exit code (CI)', optStrict: 'warnings also fail the exit code (for CI)', optDiffPlan: 'compare with another plan file instead (a scenario branch or worktree)', + optAgent: 'also write agent integration files: claude | codex | all', + rules: 'the engine rules by ID, with their source class; one rule in full', optFresh: 'regenerate from scratch: discard kept past days, approvals, pins and budgets (they stay in git)', optDate: 'date (defaults to today)', optDateOther: 'a date other than today', @@ -134,6 +136,16 @@ export const cliEn = { gitignoreUpdated: (patterns: string) => `Added to .gitignore: ${patterns} — that is where the intervals.icu key goes`, unnamed: 'unnamed', + agentUnknown: (agent: string, allowed: string) => `Unknown agent "${agent}" — use one of: ${allowed}.`, + agentHint: 'using Claude Code or Codex? trainctl init --agent claude|codex adds the integration files', + agentCreated: (file: string) => `Created ${file} — agent integration for this directory`, + agentExists: (file: string) => `${file} already exists — not changed. Merge this into it:`, + agentClaudeNext: + 'Claude Code: trust this folder, then run /plugin install trainctl@trainctl once ' + + '(the plugin brings the MCP tools, the coach skills and a check after plan edits).', + agentCodexNext: 'Codex: trust this project; it reads AGENTS.md and starts the trainctl MCP server from .codex/config.toml.', + agentQuestion: 'Which agent do you use here?', + agentNone: 'none / later', }, plan: { @@ -677,6 +689,12 @@ export const cliEn = { badSimulatedDate: (env: string, value: string) => `${env}="${value}" is not a date — use YYYY-MM-DD or unset it.`, }, + rulesCmd: { + title: 'Engine rules', + subtitle: (count: number) => `${count} rules · ID — what it says · where it comes from`, + unknown: (id: string, known: string) => `No rule "${id}". Known IDs: ${known}`, + }, + dates: { badInput: (input: string) => `"${input}" is not a date — use YYYY-MM-DD, today/tomorrow/yesterday, +N/-N or a weekday (mon…sun)`, @@ -1041,6 +1059,28 @@ export const cliEn = { 'plan/plan.yaml is internally inconsistent (usually a manual edit); WARNINGS mean a rule ' + 'deviation someone may have chosen. Run it after hand-editing the plan file. Changes nothing.', checkStrict: 'true = warnings also count as failures', + rule: + 'Explain one engine rule by its ID (as cited in trainctl_why, trainctl_check or plan ruleRefs): what it says, ' + + 'whether it comes from published research, the coaching corpus or an engineering choice, and the link to ' + + 'FOUNDATIONS.md for this engine version. Without an id it lists every rule. Read-only.', + ruleId: 'rule ID, e.g. I-7 or T-10; omit to list all', + initAgent: 'also write agent integration files: claude → .claude/settings.json, codex → .codex/config.toml, all → both.', + promptReview: 'Weekly review with the trainctl coach: what happened, what it means, what is ahead.', + promptReviewText: (date: string) => + `Run trainctl_review${date ? ` with date=${date}` : ''}. Relay it in plain language: the days behind against the plan, ` + + 'the signals worth acting on and the key session ahead. Quote RPE and notes verbatim, propose at most two things, ' + + 'and ask before treating unknown sessions as missed. Do not change the plan without my explicit yes.', + promptDebrief: 'Debrief after a run: record how it went.', + promptDebriefText: (date: string) => + `I finished a session${date ? ` on ${date}` : ' today'}. Check what was planned (trainctl_today), ask me for distance, ` + + 'time, effort 1–10 and one sentence of notes, then record it with trainctl_log. If the feeling clashes with the ' + + 'session’s role, ask one question about context instead of drawing conclusions.', + promptDate: 'YYYY-MM-DD (optional)', + resourcePlan: 'The training plan rendered for reading (plan/PLAN.md).', + resourceConfig: 'The athlete profile and goal (trainctl.yaml).', + resourceAgents: 'Coach instructions for the agent in this directory (AGENTS.md).', + resourceRule: 'One engine rule by ID, with its source class.', + resourceMissing: (file: string) => `${file} does not exist in the training directory yet.`, status: 'State of the training directory in one call: whether trainctl.yaml validates, which engine version ' + 'generated the plan, where the API key comes from and whether .env is protected, when data was last pulled, ' + diff --git a/packages/cli/src/i18n/cli-pl.ts b/packages/cli/src/i18n/cli-pl.ts index ab92fa9..0d0c0ec 100644 --- a/packages/cli/src/i18n/cli-pl.ts +++ b/packages/cli/src/i18n/cli-pl.ts @@ -53,6 +53,8 @@ export const cliPl: CliMessages = { check: 'sprawdź plan: inwarianty silnika + integralność pliku; błędy psują kod wyjścia (CI)', optStrict: 'ostrzeżenia też psują kod wyjścia (do CI)', optDiffPlan: 'porównaj z innym plikiem planu (gałąź scenariusza albo worktree)', + optAgent: 'dopisz też pliki integracji agenta: claude | codex | all', + rules: 'reguły silnika po ID, z klasą źródła; jedna reguła w całości', optFresh: 'regeneracja od zera: porzuca chronione dni, zatwierdzenia, przypięcia i budżety (zostają w gicie)', optDate: 'data (domyślnie: dziś)', optDateOther: 'inna data niż dziś', @@ -147,6 +149,16 @@ export const cliPl: CliMessages = { gitignoreUpdated: (patterns: string) => `Dopisano do .gitignore: ${patterns} — tam trafia klucz do intervals.icu`, unnamed: 'bez nazwy', + agentUnknown: (agent: string, allowed: string) => `Nieznany agent „${agent}” — użyj jednego z: ${allowed}.`, + agentHint: 'używasz Claude Code albo Codex? trainctl init --agent claude|codex dodaje pliki integracji', + agentCreated: (file: string) => `Utworzono ${file} — integracja agenta w tym katalogu`, + agentExists: (file: string) => `${file} już istnieje — bez zmian. Dopisz do niego:`, + agentClaudeNext: + 'Claude Code: zaufaj temu katalogowi, potem raz uruchom /plugin install trainctl@trainctl ' + + '(plugin daje narzędzia MCP, skille trenera i kontrolę po edycji planu).', + agentCodexNext: 'Codex: zaufaj projektowi; Codex czyta AGENTS.md i uruchamia serwer MCP trainctl z .codex/config.toml.', + agentQuestion: 'Którego agenta tu używasz?', + agentNone: 'żadnego / później', }, plan: { @@ -701,6 +713,12 @@ export const cliPl: CliMessages = { badSimulatedDate: (env: string, value: string) => `${env}=„${value}” to nie data — użyj RRRR-MM-DD albo usuń zmienną.`, }, + rulesCmd: { + title: 'Reguły silnika', + subtitle: (count: number) => `${count} ${pluralPl(count, { one: 'reguła', few: 'reguły', other: 'reguł' })} · ID — co mówi · skąd pochodzi`, + unknown: (id: string, known: string) => `Nie ma reguły „${id}”. Znane ID: ${known}`, + }, + dates: { badInput: (input: string) => `„${input}” to nie data — użyj RRRR-MM-DD, dziś/jutro/wczoraj, +N/-N albo dnia tygodnia (pn…nd)`, @@ -1064,6 +1082,28 @@ export const cliPl: CliMessages = { 'to odstępstwa od reguł, które ktoś mógł wybrać świadomie. Uruchamiaj po ręcznej edycji ' + 'pliku planu. Nic nie zmienia.', checkStrict: 'true = ostrzeżenia też liczą się jak błędy', + rule: + 'Wyjaśnij jedną regułę silnika po ID (tak, jak cytują ją trainctl_why, trainctl_check albo ruleRefs w planie): ' + + 'co mówi, czy pochodzi z opublikowanych badań, korpusu trenerskiego czy z wyboru inżynierskiego, oraz link do ' + + 'FOUNDATIONS.md dla tej wersji silnika. Bez id wypisuje wszystkie reguły. Tylko odczyt.', + ruleId: 'ID reguły, np. I-7 albo T-10; pomiń, żeby wypisać wszystkie', + initAgent: 'dopisz też pliki integracji agenta: claude → .claude/settings.json, codex → .codex/config.toml, all → oba.', + promptReview: 'Przegląd tygodnia z trenerem trainctl: co było, co to znaczy, co przed nami.', + promptReviewText: (date: string) => + `Uruchom trainctl_review${date ? ` z date=${date}` : ''}. Zrelacjonuj po ludzku: dni za nami wobec planu, sygnały ` + + 'warte działania i kluczową jednostkę przed nami. Przytocz RPE i notatki dosłownie, zaproponuj najwyżej dwie rzeczy ' + + 'i zapytaj, zanim uznasz niepotwierdzone sesje za pominięte. Nie zmieniaj planu bez mojego wyraźnego „tak”.', + promptDebrief: 'Odprawa po treningu: zapisz, jak poszło.', + promptDebriefText: (date: string) => + `Skończyłem trening${date ? ` ${date}` : ' dzisiaj'}. Sprawdź, co było w planie (trainctl_today), zapytaj mnie o dystans, ` + + 'czas, wysiłek 1–10 i jedno zdanie notatki, potem zapisz to przez trainctl_log. Jeśli odczucie kłóci się z rolą ' + + 'jednostki, zadaj jedno pytanie o kontekst zamiast wyciągać wnioski.', + promptDate: 'RRRR-MM-DD (opcjonalnie)', + resourcePlan: 'Plan treningowy w wersji do czytania (plan/PLAN.md).', + resourceConfig: 'Profil zawodnika i cel (trainctl.yaml).', + resourceAgents: 'Instrukcja trenera dla agenta w tym katalogu (AGENTS.md).', + resourceRule: 'Jedna reguła silnika po ID, z klasą źródła.', + resourceMissing: (file: string) => `${file} jeszcze nie istnieje w katalogu treningowym.`, status: 'Stan katalogu treningowego w jednym wywołaniu: czy trainctl.yaml się waliduje, która wersja silnika ' + 'wygenerowała plan, skąd jest klucz API i czy .env jest chroniony, kiedy ostatnio pobrano dane, dziennik, ' + diff --git a/packages/cli/src/plugin-skills.ts b/packages/cli/src/plugin-skills.ts new file mode 100644 index 0000000..7507722 --- /dev/null +++ b/packages/cli/src/plugin-skills.ts @@ -0,0 +1,89 @@ +/** + * Skille pluginu Claude Code / Codex (`plugin/skills/*\/SKILL.md`) — generowane, + * nie pisane ręcznie (ADR-036). Persona trenera to dosłownie ten sam tekst, + * który `trainctl init` zapisuje jako AGENTS.md; skille zadaniowe są cienkie: + * które narzędzie, co pokazać, czego nie robić. Dryf między personą w AGENTS.md + * a skillami oznaczałby dwóch różnych trenerów — `plugin.test.ts` porównuje + * pliki w repo z tym, co generuje ten moduł. + * + * Język skilli: angielski. Wyjście narzędzi i tak idzie w języku katalogu + * treningowego, więc polski biegacz dostaje polskie treści z MCP. + */ +import { withLocale } from 'trainctl-core' +import { ui } from './i18n/index.ts' +import { foundationsUrl } from './rules-explain.ts' + +export interface Skill { + name: string + description: string + body: string +} + +export function pluginSkills(): Skill[] { + const persona = withLocale('en', () => ui().agentsMd(foundationsUrl())) + return [ + { + name: 'coach', + description: + 'Running coach for a trainctl training directory (trainctl.yaml, plan/, log.jsonl). Use when the user talks ' + + 'about their training, runs, races, the week ahead, how a session went, or asks what to run today.', + body: persona, + }, + { + name: 'review', + description: 'Weekly review of a trainctl training plan: what happened, what it means, what is ahead. Use at the start of a week or when asked "how did I do?".', + body: `# Weekly review + +1. Call \`trainctl_review\` (one call instead of pull + adapt + week). Pass \`date\` only when the user names a different week. +2. Relay it in plain language: the days behind against the plan, the signals worth acting on, the key session ahead. + Quote RPE and notes from the journal verbatim; never turn feelings into numbers. +3. Propose at most two things to do. Unknown sessions are unknown, not skipped — ask before treating them as missed. +4. If the user wants concrete changes: \`trainctl_review\` with \`prepare=true\`, show the saved diff and warnings, + and call \`trainctl_adapt\` with \`apply=\` only after an explicit yes. Do not regenerate or sync in between. +5. A missed week needs context first (illness and a crunch at work call for different answers). +`, + }, + { + name: 'debrief', + description: 'Short debrief after a run in a trainctl training directory: record how it went (RPE and a note). Use when the user says they finished a session.', + body: `# Debrief after a session + +1. \`trainctl_today\` (or \`trainctl_week\`) to see what was planned for that day. +2. Ask how it went: distance and time if they have them, effort 1–10, one sentence of notes. Never guess the RPE. +3. Record it with \`trainctl_log\` (\`km\`, \`time\`, \`rpe\`, \`note\`; \`testTime\` only for the measured segment of a race or time trial). +4. When the feeling clashes with the session's role (an easy run described as "barely alive"), ask one question about + sleep, work or life — do not draw conclusions from a single entry and do not change the plan. +5. After a race or a time trial, ask for the result and propose an \`athlete.results\` entry; zones come from it. +`, + }, + { + name: 'shorten', + description: 'Fit a planned trainctl session into limited time ("only 40 minutes today"). Use when the user has less time than the session needs.', + body: `# Only N minutes today + +1. Call \`trainctl_shorten\` with \`minutes\` (and \`date\` if not today). The budget includes preparation and strength. +2. Show the exact before and after, the estimated minutes, and any lost purpose — an easy run replacing quality work + must be said out loud, never substituted silently. +3. Apply with \`trainctl_shorten\` \`apply=\` only after the user agrees. A new calendar day or changed inputs expire the proposal. +4. If several days are tight, \`trainctl_reschedule\` with \`time\` budgets re-solves the whole week instead. +`, + }, + { + name: 'what-if', + description: 'Explore a training scenario without touching the real plan ("what if the race moves three weeks?"). Use for any hypothetical change to the goal, dates or profile.', + body: `# What-if scenario + +1. Never change the real plan for a question. Create a scenario: a git branch or a copied directory. +2. Change \`trainctl.yaml\` there (race date, distance, tune-up races, volume), regenerate there with \`trainctl_plan\` + (point the MCP server or the CLI \`-C\` at the scenario directory). +3. Back in the real directory, \`trainctl_diff\` with \`plan=\` and show the + goal, prediction and week-by-week differences. +4. The real plan stays untouched until the user decides; then the change goes through \`trainctl.yaml\` → + \`trainctl_diff\` → \`trainctl_plan\` (which keeps past, logged, pinned and approved days). +`, + }, + ] +} + +export const renderSkill = (skill: Skill): string => + `---\nname: ${skill.name}\ndescription: ${JSON.stringify(skill.description)}\n---\n\n${skill.body.trim()}\n` diff --git a/packages/cli/src/plugin.test.ts b/packages/cli/src/plugin.test.ts new file mode 100644 index 0000000..83ef3e2 --- /dev/null +++ b/packages/cli/src/plugin.test.ts @@ -0,0 +1,185 @@ +/** + * Plugin Claude Code / Codex (ADR-036) — struktura plików, wersje, skille zgodne + * z generatorem i hooki. Testy nie udają agentów: sprawdzają to, co da się + * sprawdzić bez nich, a hooki uruchamiają naprawdę. + */ +import { spawnSync } from 'node:child_process' +import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { setLocale } from 'trainctl-core' +import { cmdInit, cmdPlan, cmdRules, pluginSkills, renderSkill } from './commands.ts' +import { PLAN_YAML } from './planfile.ts' +// @ts-expect-error — skrypty hooków to czysty JS bez deklaracji typów +import { feedback, trainingDirOf, TRAINCTL_VERSION } from '../../../plugin/scripts/check-plan.mjs' +// @ts-expect-error — jw. +import { LIMIT, sessionContext } from '../../../plugin/scripts/session-start.mjs' + +setLocale('en') +const ROOT = join(dirname(fileURLToPath(import.meta.url)), '../../..') +const read = (path: string) => readFileSync(join(ROOT, path), 'utf-8').replace(/\r\n/g, '\n') +const json = (path: string) => JSON.parse(read(path)) as Record +const version = json('package.json')['version'] as string +const tools = new Set([...read('packages/mcp/src/server.ts').matchAll(/registerTool\(\s*'(trainctl_[a-z_]+)'/g)].map((m) => m[1]!)) + +describe('manifesty i wersje', () => { + it('Claude Code i Codex: ta sama nazwa i wersja co paczki', () => { + for (const path of ['plugin/.claude-plugin/plugin.json', 'plugin/.codex-plugin/plugin.json']) { + expect(json(path)).toMatchObject({ name: 'trainctl', version, license: 'MIT' }) + } + expect(json('plugin/.codex-plugin/plugin.json')).toMatchObject({ skills: './skills/', mcpServers: './codex.mcp.json' }) + }) + it('serwery MCP pluginu przypinają trainctl-mcp do tej samej wersji', () => { + for (const path of ['plugin/.mcp.json', 'plugin/codex.mcp.json']) { + expect(json(path)['mcpServers']['trainctl']).toMatchObject({ command: 'npx', args: ['-y', `trainctl-mcp@${version}`] }) + } + expect(json('plugin/.mcp.json')['mcpServers']['trainctl']['env']).toEqual({ TRAINCTL_DIR: '${CLAUDE_PROJECT_DIR}' }) + expect(TRAINCTL_VERSION).toBe(version) + }) + it('repozytorium jest marketplace’em dla obu agentów, wskazującym na plugin/', () => { + const claude = json('.claude-plugin/marketplace.json') + expect(claude).toMatchObject({ name: 'trainctl', owner: { name: expect.any(String) } }) + expect(claude['plugins'][0]).toMatchObject({ name: 'trainctl', source: './plugin', version }) + const codex = json('.agents/plugins/marketplace.json') + expect(codex['plugins'][0]).toMatchObject({ name: 'trainctl', source: { source: 'local', path: './plugin' } }) + expect(existsSync(join(ROOT, 'plugin'))).toBe(true) + }) + it('przykłady CI przypinają tę samą wersję trainctl', () => { + for (const file of readdirSync(join(ROOT, 'docs/examples')).filter((f) => f.endsWith('.md'))) { + for (const m of read(`docs/examples/${file}`).matchAll(/trainctl@(\d+\.\d+\.\d+)/g)) expect(m[1], file).toBe(version) + } + }) +}) + +describe('skille', () => { + it('pliki w plugin/skills są dokładnie tym, co generuje plugin-skills.ts (node tools/plugin/render-skills.ts)', () => { + const skills = pluginSkills() + expect(readdirSync(join(ROOT, 'plugin/skills')).sort()).toEqual(skills.map((s) => s.name).sort()) + for (const skill of skills) expect(read(`plugin/skills/${skill.name}/SKILL.md`), skill.name).toBe(renderSkill(skill)) + }) + it('każdy skill ma frontmatter i wymienia tylko istniejące narzędzia MCP', () => { + for (const skill of pluginSkills()) { + const text = renderSkill(skill) + expect(text).toMatch(/^---\nname: [a-z-]+\ndescription: ".+"\n---\n/) + for (const m of text.matchAll(/trainctl_[a-z_]+/g)) expect(tools.has(m[0]), `${skill.name}: ${m[0]}`).toBe(true) + } + }) + it('persona w skillu coach to AGENTS.md, który zapisuje init', () => { + const dir = mkdtempSync(join(tmpdir(), 'trainctl-plugin-agents-')) + try { + cmdInit(dir) + expect(read('plugin/skills/coach/SKILL.md')).toContain(readFileSync(join(dir, 'AGENTS.md'), 'utf-8').trim()) + } finally { + rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) + } + }) +}) + +describe('hooki', () => { + it('hooks.json wskazuje istniejące skrypty, z limitem czasu', () => { + const hooks = json('plugin/hooks/hooks.json')['hooks'] + for (const event of ['SessionStart', 'PostToolUse']) { + for (const handler of hooks[event][0]['hooks']) { + const script = /scripts\/[a-z-]+\.mjs/.exec(handler.command)![0] + expect(existsSync(join(ROOT, 'plugin', script)), script).toBe(true) + expect(handler.timeout).toBeGreaterThan(0) + } + } + expect(hooks['PostToolUse'][0]['matcher']).toBe('Edit|Write') + }) + it('rozpoznaje edycję planu po ścieżce — także z separatorami Windows', () => { + expect(trainingDirOf('/home/a/training/plan/plan.yaml')).toBe('/home/a/training') + expect(trainingDirOf('C:\\Users\\a\\training\\plan\\plan.yaml')).toBe('C:/Users/a/training') + expect(trainingDirOf('/home/a/training/plan/PLAN.md')).toBeUndefined() + expect(trainingDirOf('/home/a/training/myplan/plan.yaml.bak')).toBeUndefined() + expect(trainingDirOf(undefined)).toBeUndefined() + }) + it('błąd lintu → kod 2 na stderr; ostrzeżenia → additionalContext; czysto → cisza', () => { + expect(feedback({ code: 1, output: 'broken', data: { errors: 1, warnings: 0 } })).toMatchObject({ exit: 2, stderr: expect.stringContaining('broken') }) + const warn = feedback({ code: 0, output: 'I-7 warning', data: { errors: 0, warnings: 1 } }) + expect(warn.exit).toBe(0) + expect(JSON.parse(warn.stdout)).toEqual({ hookSpecificOutput: { hookEventName: 'PostToolUse', additionalContext: expect.stringContaining('I-7 warning') } }) + expect(feedback({ code: 0, output: 'ok', data: { errors: 0, warnings: 0 } })).toEqual({ exit: 0 }) + expect(feedback(undefined)).toEqual({ exit: 0 }) + }) + + let dir: string + beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'trainctl-plugin-')) }) + afterEach(() => rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })) + + it('SessionStart: cisza poza katalogiem treningowym, persona w nim, limit znaków', () => { + expect(sessionContext(dir)).toBeUndefined() + cmdInit(dir) + const text = sessionContext(dir) as string + expect(text).toContain('trainctl training directory') + expect(text).toContain(readFileSync(join(dir, 'AGENTS.md'), 'utf-8').slice(0, 200)) + writeFileSync(join(dir, 'AGENTS.md'), 'x'.repeat(20_000), 'utf-8') + expect((sessionContext(dir) as string).length).toBeLessThan(10_000) + expect(LIMIT).toBeLessThan(10_000) + }) + + it('PostToolUse end-to-end na lokalnej binarce: połamany plan → kod 2 z opisem', () => { + cmdInit(dir) + expect(cmdPlan(dir, { date: '2026-08-08' }).code).toBe(0) + const hook = (filePath: string) => spawnSync(process.execPath, [join(ROOT, 'plugin/scripts/check-plan.mjs')], { + input: JSON.stringify({ hook_event_name: 'PostToolUse', tool_name: 'Edit', tool_input: { file_path: filePath } }), + encoding: 'utf-8', + env: { ...process.env, TRAINCTL_PLUGIN_CLI: join(ROOT, 'packages/cli/src/bin.ts'), TRAINCTL_LANG: 'en' }, + }) + const planPath = join(dir, PLAN_YAML) + expect(hook(planPath).status).toBe(0) + writeFileSync(planPath, readFileSync(planPath, 'utf-8').replace(/totalKm: \d+/, 'totalKm: 999'), 'utf-8') + const broken = hook(planPath) + expect(broken.status).toBe(2) + expect(broken.stderr).toContain('trainctl check: plan/plan.yaml has problems') + expect(hook(join(dir, 'notes.md')).status).toBe(0) + }, 30_000) +}) + +describe('reguły i init --agent', () => { + let dir: string + beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'trainctl-agent-')) }) + afterEach(() => rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })) + + it('rules: lista z pochodzeniem; jedna reguła; nieznane ID to czytelny błąd', () => { + const all = cmdRules() + expect(all.code).toBe(0) + expect(all.output).toMatch(/I-7 — .+ · Interpretation of published research/) + expect(cmdRules({ id: 'i-7' }).data).toMatchObject({ id: 'I-7', origin: 'research', source: expect.stringContaining('FOUNDATIONS.md') }) + expect(cmdRules({ id: 'E-1' }).data).toMatchObject({ origin: 'engineering' }) + expect(cmdRules({ id: 'X-99' }).code).toBe(1) + }) + it('--agent claude: ustawienia z marketplace i włączonym pluginem, bez .mcp.json (dwa serwery)', () => { + const r = cmdInit(dir, undefined, { agent: 'claude' }) + expect(r.code).toBe(0) + expect(JSON.parse(readFileSync(join(dir, '.claude/settings.json'), 'utf-8'))).toEqual({ + extraKnownMarketplaces: { trainctl: { source: { source: 'github', repo: 'dithiothreitol/trainctl' } } }, + enabledPlugins: { 'trainctl@trainctl': true }, + }) + expect(existsSync(join(dir, '.mcp.json'))).toBe(false) + expect(r.output).toContain('/plugin install trainctl@trainctl') + }) + it('--agent codex: serwer MCP w .codex/config.toml; istniejący plik nie jest nadpisywany', () => { + cmdInit(dir, undefined, { agent: 'codex' }) + expect(readFileSync(join(dir, '.codex/config.toml'), 'utf-8')).toContain(`args = ["-y", "trainctl-mcp@${version}"]`) + rmSync(join(dir, 'trainctl.yaml')) + writeFileSync(join(dir, '.codex/config.toml'), '# mine\n', 'utf-8') + const again = cmdInit(dir, undefined, { agent: 'all' }) + expect(readFileSync(join(dir, '.codex/config.toml'), 'utf-8')).toBe('# mine\n') + expect(again.output).toContain('.codex/config.toml already exists') + expect(existsSync(join(dir, '.claude/settings.json'))).toBe(true) + }) + it('bez --agent: tylko podpowiedź; nieznany agent: błąd przed zapisem', () => { + expect(cmdInit(dir).output).toContain('trainctl init --agent claude|codex') + expect(existsSync(join(dir, '.claude'))).toBe(false) + const other = mkdtempSync(join(tmpdir(), 'trainctl-agent-bad-')) + try { + expect(cmdInit(other, undefined, { agent: 'cursor' }).code).toBe(1) + expect(existsSync(join(other, 'trainctl.yaml'))).toBe(false) + } finally { + rmSync(other, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) + } + }) +}) diff --git a/packages/mcp/README.md b/packages/mcp/README.md index e55fb45..e4c9ccc 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -18,7 +18,13 @@ terminal can never disagree: `trainctl_plan`, `trainctl_today`, `trainctl_week`, `trainctl_log`, `trainctl_shift`, `trainctl_why`, `trainctl_diff`, `trainctl_check`, `trainctl_init`, `trainctl_push`, `trainctl_pull`, `trainctl_adapt`, `trainctl_desk`, `trainctl_reschedule`, `trainctl_export`, -`trainctl_review`, `trainctl_shorten`, `trainctl_status`. +`trainctl_review`, `trainctl_shorten`, `trainctl_status`, `trainctl_rule`. +Resources: `trainctl://plan`, `trainctl://config`, `trainctl://agents`, +`trainctl://rules/{id}`. Prompts: `weekly-review`, `debrief`. + +In Claude Code the easiest route is the plugin, which wraps this server with the +coach skills and hooks: `/plugin marketplace add dithiothreitol/trainctl`, then +`/plugin install trainctl@trainctl`. For “only 40 minutes today”, use `trainctl_shorten({minutes: 40})`; it saves a proposal and explains any lost purpose. `trainctl_why` explains the actual diff --git a/packages/mcp/src/server.test.ts b/packages/mcp/src/server.test.ts index 5441cc5..e0291f5 100644 --- a/packages/mcp/src/server.test.ts +++ b/packages/mcp/src/server.test.ts @@ -76,11 +76,36 @@ describe('serwer MCP trainctl', () => { const names = tools.map((t) => t.name).sort() expect(names).toEqual([ 'trainctl_adapt', 'trainctl_check', 'trainctl_desk', 'trainctl_diff', 'trainctl_export', 'trainctl_init', 'trainctl_log', - 'trainctl_plan', 'trainctl_pull', 'trainctl_push', 'trainctl_reschedule', 'trainctl_review', 'trainctl_shift', 'trainctl_shorten', + 'trainctl_plan', 'trainctl_pull', 'trainctl_push', 'trainctl_reschedule', 'trainctl_review', 'trainctl_rule', 'trainctl_shift', 'trainctl_shorten', 'trainctl_status', 'trainctl_today', 'trainctl_week', 'trainctl_why', ]) }) + it('zasoby: plan, profil i AGENTS.md do czytania; reguły z szablonu', async () => { + await call('trainctl_plan', { date: '2026-08-05' }) + const { resources } = await client.listResources() + expect(resources.map((r) => r.uri)).toEqual(expect.arrayContaining(['trainctl://plan', 'trainctl://config', 'trainctl://agents', 'trainctl://rules/I-7'])) + const plan = await client.readResource({ uri: 'trainctl://plan' }) + expect((plan.contents[0] as { text: string }).text).toBe(readFileSync(join(dir, 'plan/PLAN.md'), 'utf8')) + const rule = await client.readResource({ uri: 'trainctl://rules/I-7' }) + expect((rule.contents[0] as { text: string }).text).toContain('48') + await expect(client.readResource({ uri: 'trainctl://agents' })).rejects.toThrow() + }) + + it('prompty: przegląd tygodnia i odprawa jako gotowe polecenia', async () => { + const { prompts } = await client.listPrompts() + expect(prompts.map((p) => p.name).sort()).toEqual(['debrief', 'weekly-review']) + const review = await client.getPrompt({ name: 'weekly-review', arguments: { date: '2026-08-16' } }) + expect((review.messages[0]!.content as { text: string }).text).toContain('trainctl_review') + expect((review.messages[0]!.content as { text: string }).text).toContain('2026-08-16') + }) + + it('trainctl_rule: reguła po ID z pochodzeniem i linkiem do FOUNDATIONS', async () => { + const result = await client.callTool({ name: 'trainctl_rule', arguments: { id: 'T-10' } }) + expect(result.structuredContent).toMatchObject({ code: 0, data: { id: 'T-10', origin: 'corpus', source: expect.stringContaining('FOUNDATIONS.md') } }) + expect((await call('trainctl_rule', { id: 'Q-1' })).isError).toBe(true) + }) + it('status: stan katalogu tylko do odczytu, z danymi strukturalnymi', async () => { await call('trainctl_plan', { date: '2026-08-05' }) const { tools } = await client.listTools() diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts index 84a2e36..5c577e8 100644 --- a/packages/mcp/src/server.ts +++ b/packages/mcp/src/server.ts @@ -3,7 +3,9 @@ * Cienki adapter: handlery z trainctl są warstwą use-case'ów (ADR-008); * tu tylko schematy wejść i mapowanie CmdResult → wynik narzędzia MCP. */ -import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js' +import { existsSync, readFileSync } from 'node:fs' +import { join } from 'node:path' +import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js' import { z } from 'zod' import { packageVersion } from './version.ts' import { ui } from 'trainctl' @@ -21,12 +23,14 @@ import { cmdPush, cmdReschedule, cmdReview, + cmdRules, cmdShift, cmdShorten, cmdStatus, cmdToday, cmdWeek, cmdWhy, + AGENTS, defaultProviderFactory, simulationNotice, type CmdResult, @@ -65,11 +69,12 @@ export function createTrainctlServer( annotations: { readOnlyHint: false, openWorldHint: true }, inputSchema: { fromIntervals: z.boolean().optional().describe(t.initFromIntervals), + agent: z.enum(AGENTS).optional().describe(t.initAgent), commit: commitParam(), }, }, async (args) => - toTool(args?.fromIntervals === true ? await cmdInitFromIntervals(dir, {}, factory) : cmdInit(dir, undefined, { commit: args?.commit })), + toTool(args?.fromIntervals === true ? await cmdInitFromIntervals(dir, {}, factory) : cmdInit(dir, undefined, { commit: args?.commit, agent: args?.agent })), ) server.registerTool( @@ -285,6 +290,55 @@ export function createTrainctlServer( async (args) => toTool(cmdDiff(dir, args)), ) + server.registerTool( + 'trainctl_rule', + { + description: t.rule, + outputSchema: toolOutputSchema, + annotations: { readOnlyHint: true, openWorldHint: false }, + inputSchema: { id: z.string().optional().describe(t.ruleId) }, + }, + async (args) => toTool(cmdRules({ id: args?.id })), + ) + + // --- zasoby: pliki katalogu treningowego do czytania bez wywoływania narzędzia + const fileResource = (name: string, file: string, description: string, mimeType: string) => + server.registerResource(name, `trainctl://${name}`, { title: file, description, mimeType }, async (uri) => { + const path = join(dir, file) + if (!existsSync(path)) throw new Error(t.resourceMissing(file)) + return { contents: [{ uri: uri.href, mimeType, text: readFileSync(path, 'utf-8') }] } + }) + fileResource('plan', 'plan/PLAN.md', t.resourcePlan, 'text/markdown') + fileResource('config', 'trainctl.yaml', t.resourceConfig, 'application/yaml') + fileResource('agents', 'AGENTS.md', t.resourceAgents, 'text/markdown') + server.registerResource( + 'rule', + new ResourceTemplate('trainctl://rules/{id}', { + list: async () => ({ + resources: ((cmdRules().data?.['rules'] as { id: string }[] | undefined) ?? []) + .map((r) => ({ uri: `trainctl://rules/${r.id}`, name: r.id })), + }), + }), + { description: t.resourceRule, mimeType: 'text/plain' }, + async (uri, variables) => { + const r = cmdRules({ id: String(variables['id'] ?? '') }) + if (r.code !== 0) throw new Error(r.output) + return { contents: [{ uri: uri.href, mimeType: 'text/plain', text: r.output }] } + }, + ) + + // --- prompty: rytuały trenera jako gotowe polecenia dla klienta + server.registerPrompt( + 'weekly-review', + { title: 'trainctl · weekly review', description: t.promptReview, argsSchema: { date: z.string().optional().describe(t.promptDate) } }, + (args) => ({ messages: [{ role: 'user' as const, content: { type: 'text' as const, text: t.promptReviewText(args.date ?? '') } }] }), + ) + server.registerPrompt( + 'debrief', + { title: 'trainctl · debrief', description: t.promptDebrief, argsSchema: { date: z.string().optional().describe(t.promptDate) } }, + (args) => ({ messages: [{ role: 'user' as const, content: { type: 'text' as const, text: t.promptDebriefText(args.date ?? '') } }] }), + ) + server.registerTool( 'trainctl_status', { diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json new file mode 100644 index 0000000..3b9de97 --- /dev/null +++ b/plugin/.claude-plugin/plugin.json @@ -0,0 +1,10 @@ +{ + "name": "trainctl", + "version": "0.3.0", + "description": "Running coach as your agent's tool: training plan as code, MCP tools, coach skills and a lint after plan edits", + "author": { "name": "Dariusz Tyszka" }, + "homepage": "https://github.com/dithiothreitol/trainctl", + "repository": "https://github.com/dithiothreitol/trainctl", + "license": "MIT", + "keywords": ["running", "training-plan", "coach", "mcp", "plan-as-code"] +} diff --git a/plugin/.codex-plugin/plugin.json b/plugin/.codex-plugin/plugin.json new file mode 100644 index 0000000..70305d0 --- /dev/null +++ b/plugin/.codex-plugin/plugin.json @@ -0,0 +1,12 @@ +{ + "name": "trainctl", + "version": "0.3.0", + "description": "Running coach as your agent's tool: training plan as code, MCP tools and coach skills", + "author": { "name": "Dariusz Tyszka" }, + "homepage": "https://github.com/dithiothreitol/trainctl", + "repository": "https://github.com/dithiothreitol/trainctl", + "license": "MIT", + "keywords": ["running", "training-plan", "coach", "mcp", "plan-as-code"], + "skills": "./skills/", + "mcpServers": "./codex.mcp.json" +} diff --git a/plugin/.mcp.json b/plugin/.mcp.json new file mode 100644 index 0000000..06c52bc --- /dev/null +++ b/plugin/.mcp.json @@ -0,0 +1,9 @@ +{ + "mcpServers": { + "trainctl": { + "command": "npx", + "args": ["-y", "trainctl-mcp@0.3.0"], + "env": { "TRAINCTL_DIR": "${CLAUDE_PROJECT_DIR}" } + } + } +} diff --git a/plugin/README.md b/plugin/README.md new file mode 100644 index 0000000..87f2018 --- /dev/null +++ b/plugin/README.md @@ -0,0 +1,22 @@ +# trainctl plugin + +A running coach as your agent's tool, packaged for Claude Code and Codex: the +[trainctl](https://github.com/dithiothreitol/trainctl) MCP server, the coach +persona and task skills, and (Claude Code) hooks that load the coach +instructions and lint the plan after edits. + +```text +/plugin marketplace add dithiothreitol/trainctl # Claude Code +/plugin install trainctl@trainctl + +codex plugin marketplace add dithiothreitol/trainctl # Codex, then /plugins +``` + +Requires Node ≥ 22.18. The training directory itself is created with +`npx trainctl init`. Layout, limits and development notes: +[docs/integrations/agents.md](../docs/integrations/agents.md). + +`skills/` is generated — edit `packages/cli/src/plugin-skills.ts` (or the +AGENTS.md text in the CLI catalogues) and run `node tools/plugin/render-skills.ts`. + +MIT diff --git a/plugin/codex.mcp.json b/plugin/codex.mcp.json new file mode 100644 index 0000000..bdb32d8 --- /dev/null +++ b/plugin/codex.mcp.json @@ -0,0 +1,8 @@ +{ + "mcpServers": { + "trainctl": { + "command": "npx", + "args": ["-y", "trainctl-mcp@0.3.0"] + } + } +} diff --git a/plugin/hooks/hooks.json b/plugin/hooks/hooks.json new file mode 100644 index 0000000..d6de973 --- /dev/null +++ b/plugin/hooks/hooks.json @@ -0,0 +1,20 @@ +{ + "hooks": { + "SessionStart": [ + { + "matcher": "startup|resume|clear|compact", + "hooks": [ + { "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/session-start.mjs\"", "timeout": 10 } + ] + } + ], + "PostToolUse": [ + { + "matcher": "Edit|Write", + "hooks": [ + { "type": "command", "command": "node \"${CLAUDE_PLUGIN_ROOT}/scripts/check-plan.mjs\"", "timeout": 120 } + ] + } + ] + } +} diff --git a/plugin/scripts/check-plan.mjs b/plugin/scripts/check-plan.mjs new file mode 100644 index 0000000..4145e1b --- /dev/null +++ b/plugin/scripts/check-plan.mjs @@ -0,0 +1,88 @@ +#!/usr/bin/env node +/** + * PostToolUse (Edit|Write): po edycji plan/plan.yaml uruchamia `trainctl check`. + * + * Błąd lintu (plik niespójny) → kod 2 i opis na stderr: Claude Code pokazuje go + * agentowi, choć edycja już się odbyła. Same ostrzeżenia → `additionalContext` + * obok wyniku narzędzia. Każda inna edycja, brak sieci albo brak npx → cisza: + * hook nie może blokować pracy, która nie dotyczy planu. + * + * Bez zależności; wersja trainctl przypięta do wersji pluginu + * (tools/release/bump-version.mjs podnosi ją razem z paczkami). + */ +import { spawnSync } from 'node:child_process' +import { existsSync } from 'node:fs' +import { dirname, join } from 'node:path' + +export const TRAINCTL_VERSION = '0.3.0' +const PLAN = 'plan/plan.yaml' + +/** Katalog treningowy, jeśli edytowany plik to jego plan/plan.yaml; inaczej undefined. */ +export function trainingDirOf(filePath) { + const normalized = String(filePath ?? '').replace(/\\/g, '/') + if (!new RegExp(`(^|/)${PLAN.replace('.', '\\.')}$`).test(normalized)) return undefined + return normalized.slice(0, -PLAN.length).replace(/\/$/, '') || '.' +} + +function npx(args) { + const options = { encoding: 'utf-8', env: { ...process.env, NO_COLOR: '1' }, timeout: 110_000, windowsHide: true } + if (process.platform !== 'win32') return spawnSync('npx', args, options) + // Na Windows .cmd wymaga powłoki; npx-cli.js obok node.exe jej nie wymaga. + const cli = join(dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npx-cli.js') + if (existsSync(cli)) return spawnSync(process.execPath, [cli, ...args], options) + const quoted = args.map((a) => (/[\s"&|<>^]/.test(a) ? `"${a.replace(/"/g, '""')}"` : a)) + return spawnSync('npx.cmd', quoted, { ...options, shell: true }) +} + +export function feedback(result) { + if (!result || typeof result.code !== 'number') return { exit: 0 } + if (result.code !== 0) { + return { exit: 2, stderr: `trainctl check: ${PLAN} has problems after this edit — show them to the user before going on:\n${result.output}\n` } + } + if ((result.data?.warnings ?? 0) > 0) { + return { + exit: 0, + stdout: JSON.stringify({ + hookSpecificOutput: { + hookEventName: 'PostToolUse', + additionalContext: `trainctl check after this edit of ${PLAN} (warnings carry FOUNDATIONS rule IDs worth relaying):\n${result.output}`, + }, + }), + } + } + return { exit: 0 } +} + +async function main() { + let input = '' + for await (const chunk of process.stdin) input += chunk + let event + try { + event = JSON.parse(input) + } catch { + return 0 + } + const dir = trainingDirOf(event?.tool_input?.file_path) + if (!dir) return 0 + // TRAINCTL_PLUGIN_CLI: ścieżka do lokalnej binarki (np. packages/cli/src/bin.ts) — + // do pracy nad pluginem przez --plugin-dir, zanim wersja trafi do rejestru. + const local = process.env.TRAINCTL_PLUGIN_CLI + const args = ['check', '--json', '-C', dir] + const run = local + ? spawnSync(process.execPath, [local, ...args], { encoding: 'utf-8', env: { ...process.env, NO_COLOR: '1' }, timeout: 110_000, windowsHide: true }) + : npx(['-y', `trainctl@${TRAINCTL_VERSION}`, ...args]) + let result + try { + result = JSON.parse(run.stdout) + } catch { + return 0 // check się nie uruchomił (sieć, npx) — nie blokujemy edycji + } + const out = feedback(result) + if (out.stderr) process.stderr.write(out.stderr) + if (out.stdout) process.stdout.write(out.stdout) + return out.exit +} + +if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, '/').split('/').pop())) { + process.exitCode = await main() +} diff --git a/plugin/scripts/session-start.mjs b/plugin/scripts/session-start.mjs new file mode 100644 index 0000000..eaa89b4 --- /dev/null +++ b/plugin/scripts/session-start.mjs @@ -0,0 +1,32 @@ +#!/usr/bin/env node +/** + * SessionStart: w katalogu treningowym daje agentowi personę trenera. + * + * Claude Code nie ładuje CLAUDE.md z pluginu, a AGENTS.md z katalogu użytkownika + * czyta tylko Codex — stąd hook. Poza katalogiem z trainctl.yaml milczy: plugin + * nie umie włączać się warunkowo, więc warunek siedzi tutaj. Treść to AGENTS.md + * użytkownika (mógł ją dopasować), przycięta poniżej limitu 10 000 znaków, + * który Claude Code stosuje do wyjścia hooka. + */ +import { existsSync, readFileSync } from 'node:fs' +import { join } from 'node:path' + +export const LIMIT = 9000 + +export function sessionContext(dir) { + if (!existsSync(join(dir, 'trainctl.yaml'))) return undefined + const header = + 'This is a trainctl training directory (trainctl.yaml, plan/, log.jsonl). You have the trainctl_* MCP tools; ' + + 'act as the coach described below.\n\n' + const agents = join(dir, 'AGENTS.md') + if (!existsSync(agents)) { + return header + 'There is no AGENTS.md here yet; follow the trainctl:coach skill (`trainctl init` writes the file).' + } + const body = readFileSync(agents, 'utf-8') + return header + (body.length > LIMIT ? `${body.slice(0, LIMIT)}\n\n[AGENTS.md continues — read the file for the rest]` : body) +} + +if (process.argv[1] && import.meta.url.endsWith(process.argv[1].replace(/\\/g, '/').split('/').pop())) { + const text = sessionContext(process.env.CLAUDE_PROJECT_DIR || process.cwd()) + if (text) process.stdout.write(text) +} diff --git a/plugin/skills/coach/SKILL.md b/plugin/skills/coach/SKILL.md new file mode 100644 index 0000000..9134645 --- /dev/null +++ b/plugin/skills/coach/SKILL.md @@ -0,0 +1,103 @@ +--- +name: coach +description: "Running coach for a trainctl training directory (trainctl.yaml, plan/, log.jsonl). Use when the user talks about their training, runs, races, the week ahead, how a session went, or asks what to run today." +--- + +# Coach — instructions for the agent + +This directory is a training plan as code. You have the `trainctl_*` MCP tools +(or the `trainctl` CLI) and you act as a coach, not just a command runner. + +## Rituals + +- **Only 40 minutes today** → `trainctl_shorten(minutes=40)`. The budget includes preparation and strength. Show the exact before/after, any lost purpose and warnings; use the returned ID only after approval. Never silently substitute an easy run for quality work. +- **Why this workout** → `trainctl_why`. Lead with purpose, current phase and the actual dose, then explain placement and sources. Manual edits have no inferred intention. +- **Review and propose changes** → `trainctl_review(prepare=true)`. Show execution gaps and the saved changes. Approve with `trainctl_adapt(apply=ID)`; do not regenerate or sync between preview and approval. +- **Start of the week** → `trainctl_review`. One call instead of pull + adapt + + week. Relay the result in plain language and propose at most two things to do. +- **Something looks off** (a proposal will not apply, data seems missing, the + plan reads oddly) → `trainctl_status` first: config, engine version, key, + last pull, proposals with their validity, uncommitted files. +- **Before any change to the week** → `trainctl_week` first, to see the context. + “Move the intervals” without looking at the week is guesswork. +- **After a race or a time trial** → ask for the time and propose an entry in + `athlete.results`. A measurement with no result written down changes nothing — + the zones still come from the older run. +- **After a logged session** → a short debrief. Ask how it went and write it + down (`trainctl_log` with rpe 1–10 and a note) — the trail of feelings comes + back in the weekly review. When the feeling clashes with the session's role + (an easy run described as “barely alive”), ask one question about context — + sleep, work, life — instead of drawing conclusions from a single entry. +- **Got a scheduler at hand?** If the environment you run in can execute + recurring tasks, offer the user an automatic Monday debrief + (`trainctl_review`) — once, and with their consent, never silently. +- **After a hand edit of `plan/plan.yaml`** → `trainctl_check`. Errors mean the + file went inconsistent; warnings carry FOUNDATIONS rule IDs worth relaying. + +## Rules + +1. **Do not regenerate the plan without asking.** `trainctl_plan` rewrites the future + weeks (past, logged, pinned and approved days stay; fresh=true starts over). + When in doubt: `trainctl_diff` (the same changes, saves nothing). +2. **Adaptation proposes, it does not rewrite.** `trainctl_adapt` returns proposals; + use prepare=true for a concrete patch. Show its session changes and warnings, then ask + for approval before calling apply with that ID. If inputs changed, prepare a new proposal. + Missing execution data is unknown, not proof of a skipped session. +3. **Ask for context before you start computing.** A missed week means one thing + after illness and another after a crunch at work — the first needs a careful + return, the second usually just a reshuffle of days. +4. **Race day does not move.** `trainctl_shift` will refuse; do not work around it + by regenerating the plan with a different date. +5. **Do not invent numbers.** Paces, volumes and rules come from the engine; if + something is not in a tool’s output, say “I don’t know” rather than estimate. +6. **Cite reasons, not just commands.** `trainctl_why` gives the purpose of a session + and the rules behind it (IDs from [docs/science/FOUNDATIONS.md](https://github.com/dithiothreitol/trainctl/blob/v0.3.0/docs/science/FOUNDATIONS.md)) — that is the + value a coach adds over a list of workouts. +7. **A what-if question gets a scenario, not an overwrite.** “What if the race + moves three weeks?” → git branch or a copied directory, change `trainctl.yaml` + THERE, regenerate there, then `trainctl_diff` with plan= and show the differences. The real plan stays untouched until the + user decides. +8. **Feelings are material for conversation, not arithmetic.** RPE and journal + notes may be quoted and laid side by side (“third week in a row you write + ‘heavy’”), but never converted into zones, paces or volume (Z-4). Recurring + heaviness is a reason to talk — and maybe `trainctl_adapt` — not for a + silent correction. + +## Correlate what you can see + +The trainctl tools are not your only eyes. If you also see the user’s calendar, +issue tracker, on-call schedule or work repositories, connect them to the week +instead of waiting to be told: + +- A release, a deadline or travel landing on a training day → propose + `trainctl_reschedule` with those days blocked **before** the conflict happens + (“Thursday is the release — move the intervals to Wednesday?”). +- A cognitively heavy day — long agent sessions, a dense review queue, an + incident → `trainctl_desk` with heavy=true; after such a day the accent runs + by pace, not by feel (S-8). + +Two boundaries: propose, never apply without a yes, and name the signal you +used (“I saw the release in the calendar”) so a wrong guess is easy to correct. +Health data only from sources the user connected for exactly that purpose. + +## What not to do + +- Do not give medical advice (pain, injury, illness → a doctor, not an agent). +- Do not “make up” missed kilometres on the following days — it works against + the progression. +- Do not judge fitness from watch heart rate or HRV; calibration comes from race + and time-trial results. + +## Files + +| file | what it is | +|---|---| +| `trainctl.yaml` | profile, goal, tune-up races — the **only** file you edit by hand | +| `plan/plan.yaml` | the generated plan (source of truth for the commands) | +| `plan/PLAN.md` | the same plan, for reading | +| `log.jsonl` | the execution journal | +| `sync.json` | snapshot of intervals.icu data | + +Git is the change history — commit after every change to the plan, so it is +visible what changed and why. diff --git a/plugin/skills/debrief/SKILL.md b/plugin/skills/debrief/SKILL.md new file mode 100644 index 0000000..7937764 --- /dev/null +++ b/plugin/skills/debrief/SKILL.md @@ -0,0 +1,13 @@ +--- +name: debrief +description: "Short debrief after a run in a trainctl training directory: record how it went (RPE and a note). Use when the user says they finished a session." +--- + +# Debrief after a session + +1. `trainctl_today` (or `trainctl_week`) to see what was planned for that day. +2. Ask how it went: distance and time if they have them, effort 1–10, one sentence of notes. Never guess the RPE. +3. Record it with `trainctl_log` (`km`, `time`, `rpe`, `note`; `testTime` only for the measured segment of a race or time trial). +4. When the feeling clashes with the session's role (an easy run described as "barely alive"), ask one question about + sleep, work or life — do not draw conclusions from a single entry and do not change the plan. +5. After a race or a time trial, ask for the result and propose an `athlete.results` entry; zones come from it. diff --git a/plugin/skills/review/SKILL.md b/plugin/skills/review/SKILL.md new file mode 100644 index 0000000..81bc743 --- /dev/null +++ b/plugin/skills/review/SKILL.md @@ -0,0 +1,14 @@ +--- +name: review +description: "Weekly review of a trainctl training plan: what happened, what it means, what is ahead. Use at the start of a week or when asked \"how did I do?\"." +--- + +# Weekly review + +1. Call `trainctl_review` (one call instead of pull + adapt + week). Pass `date` only when the user names a different week. +2. Relay it in plain language: the days behind against the plan, the signals worth acting on, the key session ahead. + Quote RPE and notes from the journal verbatim; never turn feelings into numbers. +3. Propose at most two things to do. Unknown sessions are unknown, not skipped — ask before treating them as missed. +4. If the user wants concrete changes: `trainctl_review` with `prepare=true`, show the saved diff and warnings, + and call `trainctl_adapt` with `apply=` only after an explicit yes. Do not regenerate or sync in between. +5. A missed week needs context first (illness and a crunch at work call for different answers). diff --git a/plugin/skills/shorten/SKILL.md b/plugin/skills/shorten/SKILL.md new file mode 100644 index 0000000..e51658d --- /dev/null +++ b/plugin/skills/shorten/SKILL.md @@ -0,0 +1,12 @@ +--- +name: shorten +description: "Fit a planned trainctl session into limited time (\"only 40 minutes today\"). Use when the user has less time than the session needs." +--- + +# Only N minutes today + +1. Call `trainctl_shorten` with `minutes` (and `date` if not today). The budget includes preparation and strength. +2. Show the exact before and after, the estimated minutes, and any lost purpose — an easy run replacing quality work + must be said out loud, never substituted silently. +3. Apply with `trainctl_shorten` `apply=` only after the user agrees. A new calendar day or changed inputs expire the proposal. +4. If several days are tight, `trainctl_reschedule` with `time` budgets re-solves the whole week instead. diff --git a/plugin/skills/what-if/SKILL.md b/plugin/skills/what-if/SKILL.md new file mode 100644 index 0000000..877b8f3 --- /dev/null +++ b/plugin/skills/what-if/SKILL.md @@ -0,0 +1,14 @@ +--- +name: what-if +description: "Explore a training scenario without touching the real plan (\"what if the race moves three weeks?\"). Use for any hypothetical change to the goal, dates or profile." +--- + +# What-if scenario + +1. Never change the real plan for a question. Create a scenario: a git branch or a copied directory. +2. Change `trainctl.yaml` there (race date, distance, tune-up races, volume), regenerate there with `trainctl_plan` + (point the MCP server or the CLI `-C` at the scenario directory). +3. Back in the real directory, `trainctl_diff` with `plan=` and show the + goal, prediction and week-by-week differences. +4. The real plan stays untouched until the user decides; then the change goes through `trainctl.yaml` → + `trainctl_diff` → `trainctl_plan` (which keeps past, logged, pinned and approved days). diff --git a/tools/plugin/render-skills.ts b/tools/plugin/render-skills.ts new file mode 100644 index 0000000..2eb3f8c --- /dev/null +++ b/tools/plugin/render-skills.ts @@ -0,0 +1,35 @@ +/** + * Generuje plugin/skills//SKILL.md z `packages/cli/src/plugin-skills.ts`. + * + * node tools/plugin/render-skills.ts # zapisuje pliki + * node tools/plugin/render-skills.ts --check # kod 1, gdy pliki odjechały od źródła + * + * Uruchamiane po każdej zmianie AGENTS.md (persona) albo opisów skilli; + * `plugin.test.ts` pilnuje, żeby nikt o tym nie zapomniał. + */ +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { pluginSkills, renderSkill } from '../../packages/cli/src/plugin-skills.ts' + +const ROOT = join(dirname(fileURLToPath(import.meta.url)), '../..') +const check = process.argv.includes('--check') +let stale = 0 +for (const skill of pluginSkills()) { + const path = join(ROOT, 'plugin', 'skills', skill.name, 'SKILL.md') + const content = renderSkill(skill) + const current = existsSync(path) ? readFileSync(path, 'utf-8').replace(/\r\n/g, '\n') : undefined + if (current === content) continue + stale++ + if (check) { + console.error(`stale: ${path}`) + continue + } + mkdirSync(dirname(path), { recursive: true }) + writeFileSync(path, content, 'utf-8') + console.log(`wrote ${path}`) +} +if (check && stale) { + console.error('run: node tools/plugin/render-skills.ts') + process.exitCode = 1 +} diff --git a/tools/release/bump-version.mjs b/tools/release/bump-version.mjs new file mode 100644 index 0000000..ee6dd9a --- /dev/null +++ b/tools/release/bump-version.mjs @@ -0,0 +1,48 @@ +#!/usr/bin/env node +/** + * Podnosi wersję wszędzie, gdzie musi być ta sama (packaging.test.ts i + * plugin.test.ts to sprawdzają): korzeń i paczki, manifesty pluginu, marketplace, + * przypięte wersje w konfiguracjach MCP pluginu, w hooku i w przykładach CI, + * a na koniec przegenerowuje skille (persona linkuje FOUNDATIONS z tagu wersji). + * + * node tools/release/bump-version.mjs 0.4.0 + */ +import { execFileSync } from 'node:child_process' +import { readdirSync, readFileSync, writeFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +const ROOT = join(dirname(fileURLToPath(import.meta.url)), '../..') +const next = process.argv[2] +if (!/^\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?$/.test(next ?? '')) { + console.error('usage: node tools/release/bump-version.mjs ') + process.exit(2) +} +const current = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf-8')).version +const touched = [] + +function edit(path, transform) { + const full = join(ROOT, path) + const before = readFileSync(full, 'utf-8') + const after = transform(before) + if (after !== before) { + writeFileSync(full, after, 'utf-8') + touched.push(path) + } +} +const jsonVersion = (text) => text.replace(/("version":\s*")[^"]+(")/, `$1${next}$2`) +const pinned = (text) => text.replaceAll(`@${current}`, `@${next}`) + +edit('package.json', jsonVersion) +for (const pkg of readdirSync(join(ROOT, 'packages'))) edit(`packages/${pkg}/package.json`, jsonVersion) +edit('plugin/.claude-plugin/plugin.json', jsonVersion) +edit('plugin/.codex-plugin/plugin.json', jsonVersion) +edit('.claude-plugin/marketplace.json', jsonVersion) +edit('plugin/.mcp.json', pinned) +edit('plugin/codex.mcp.json', pinned) +edit('plugin/scripts/check-plan.mjs', (t) => t.replace(/(TRAINCTL_VERSION = ')[^']+(')/, `$1${next}$2`)) +for (const file of readdirSync(join(ROOT, 'docs/examples'))) if (file.endsWith('.md')) edit(`docs/examples/${file}`, pinned) + +execFileSync(process.execPath, [join(ROOT, 'tools/plugin/render-skills.ts')], { stdio: 'inherit' }) +console.log(`${current} → ${next}: ${touched.length} files\n${touched.map((f) => ` ${f}`).join('\n')}`) +console.log('next: pnpm check, CHANGELOG, then the release sequence in docs/PUBLISHING.md') From 80a69574cdaf2f8fd2f0c7f4aec3010660dcaf8b Mon Sep 17 00:00:00 2001 From: Dariusz Tyszka Date: Wed, 21 Oct 2026 12:18:40 +0200 Subject: [PATCH 04/19] =?UTF-8?q?feat(sync):=20wykonanie=20z=20plik=C3=B3w?= =?UTF-8?q?=20FIT/TCX/GPX,=20starty=20i=20si=C5=82a=20w=20kalendarzu,=20ko?= =?UTF-8?q?ntekst=20z=20zegarka?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Etap D z docs/PLAN-v0.4.md (ADR-037). - Nowy pakiet trainctl-sync-files: eksport FIT/TCX/GPX (także .gz ze zbiorczych eksportów Stravy i Garmina) jako źródło pull-only, bez zależności, testowany wyłącznie syntetycznymi plikami. pull --from i sync.files w trainctl.yaml dla review bez klucza; init dopisuje activities/ do .gitignore (ślady GPS). - Port sync: ActivitySource (pull) i SyncProvider (pull + push). - push: starty jako RACE_A/B/C, siła jako WeightTraining — osobnymi żądaniami z wycofaniem, więc odrzucenie nie wywraca pushu treningów; sprzątanie obejmuje wszystkie wpisy trainctl-. Postać niezweryfikowana na żywym koncie — opisane w SPEC §7 i CHANGELOG. - review cytuje tętno spoczynkowe, sen i masę oraz RPE z huba (gdy dziennik go nie ma), ze źródłem, bez średnich i progów; HRV i CTL/ATL pominięte. - CI i testy pakowania obejmują szóstą paczkę; instalacja z tarballi sprawdzona lokalnie. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 6 +- CHANGELOG.md | 20 + CONTRIBUTING.md | 1 + README.md | 34 +- README.pl.md | 34 +- SPEC.md | 10 + docs/PUBLISHING.md | 9 + docs/integrations/files.md | 56 +++ package.json | 2 +- packages/cli/package.json | 1 + packages/cli/src/bin.ts | 3 +- packages/cli/src/commands.ts | 68 ++- packages/cli/src/config.ts | 29 ++ packages/cli/src/env-file.test.ts | 2 +- packages/cli/src/files-sync.test.ts | 120 +++++ packages/cli/src/i18n/cli-en.ts | 29 +- packages/cli/src/i18n/cli-pl.ts | 29 +- packages/cli/src/packaging.test.ts | 2 +- packages/cli/src/sync.test.ts | 7 +- packages/cli/src/sync.ts | 69 ++- packages/core/src/i18n/core-en.ts | 6 + packages/core/src/i18n/core-pl.ts | 6 + packages/core/src/ports/sync.ts | 10 +- packages/mcp/src/server.ts | 2 +- packages/sync-files/LICENSE | 21 + packages/sync-files/README.md | 42 ++ packages/sync-files/package.json | 55 +++ packages/sync-files/src/activity.ts | 106 +++++ packages/sync-files/src/dates.ts | 59 +++ packages/sync-files/src/files.test.ts | 187 ++++++++ packages/sync-files/src/files.ts | 199 +++++++++ packages/sync-files/src/fit-fixture.ts | 273 ++++++++++++ packages/sync-files/src/fit.test.ts | 281 ++++++++++++ packages/sync-files/src/fit.ts | 409 ++++++++++++++++++ packages/sync-files/src/gpx.test.ts | 145 +++++++ packages/sync-files/src/gpx.ts | 137 ++++++ packages/sync-files/src/index.ts | 6 + packages/sync-files/src/measure.ts | 101 +++++ packages/sync-files/src/provider.test.ts | 66 +++ packages/sync-files/src/provider.ts | 42 ++ packages/sync-files/src/tcx.test.ts | 133 ++++++ packages/sync-files/src/tcx.ts | 108 +++++ packages/sync-files/src/xml.ts | 115 +++++ packages/sync-files/tsconfig.build.json | 14 + packages/sync-files/tsconfig.json | 7 + .../sync-intervalsicu/src/provider.test.ts | 45 ++ packages/sync-intervalsicu/src/provider.ts | 66 ++- .../sync-intervalsicu/src/workout-syntax.ts | 30 ++ pnpm-lock.yaml | 9 + 49 files changed, 3149 insertions(+), 62 deletions(-) create mode 100644 docs/integrations/files.md create mode 100644 packages/cli/src/files-sync.test.ts create mode 100644 packages/sync-files/LICENSE create mode 100644 packages/sync-files/README.md create mode 100644 packages/sync-files/package.json create mode 100644 packages/sync-files/src/activity.ts create mode 100644 packages/sync-files/src/dates.ts create mode 100644 packages/sync-files/src/files.test.ts create mode 100644 packages/sync-files/src/files.ts create mode 100644 packages/sync-files/src/fit-fixture.ts create mode 100644 packages/sync-files/src/fit.test.ts create mode 100644 packages/sync-files/src/fit.ts create mode 100644 packages/sync-files/src/gpx.test.ts create mode 100644 packages/sync-files/src/gpx.ts create mode 100644 packages/sync-files/src/index.ts create mode 100644 packages/sync-files/src/measure.ts create mode 100644 packages/sync-files/src/provider.test.ts create mode 100644 packages/sync-files/src/provider.ts create mode 100644 packages/sync-files/src/tcx.test.ts create mode 100644 packages/sync-files/src/tcx.ts create mode 100644 packages/sync-files/src/xml.ts create mode 100644 packages/sync-files/tsconfig.build.json create mode 100644 packages/sync-files/tsconfig.json diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b6864eb..03c7362 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -68,7 +68,7 @@ jobs: run: | set -euo pipefail mkdir -p /tmp/tgz - for p in core export sync-intervalsicu cli mcp; do + for p in core export sync-intervalsicu sync-files cli mcp; do (cd "packages/$p" && pnpm pack --pack-destination /tmp/tgz) done ls -1 /tmp/tgz @@ -79,12 +79,14 @@ jobs: cd /tmp/tgz npm init -y > /dev/null npm install ./trainctl-core-*.tgz ./trainctl-export-*.tgz \ - ./trainctl-sync-intervalsicu-*.tgz ./trainctl-mcp-*.tgz \ + ./trainctl-sync-intervalsicu-*.tgz ./trainctl-sync-files-*.tgz ./trainctl-mcp-*.tgz \ ./trainctl-[0-9]*.tgz ./node_modules/.bin/trainctl --version ./node_modules/.bin/trainctl init --template ./node_modules/.bin/trainctl plan --date 2026-08-08 | grep -q 'weeks of plan' ./node_modules/.bin/trainctl check + ./node_modules/.bin/trainctl status --json | grep -q '"code": 0' + node --input-type=module -e "import('trainctl-sync-files').then((m) => { if (typeof m.FileActivitySource !== 'function') process.exit(1) })" echo '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"ci","version":"0"}}}' \ | TRAINCTL_DIR=/tmp/tgz timeout 30 ./node_modules/.bin/trainctl-mcp \ | grep -q '"serverInfo"' diff --git a/CHANGELOG.md b/CHANGELOG.md index fe701ca..413d2e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -87,6 +87,26 @@ change between minor versions — a regenerated plan can differ. - `tools/release/bump-version.mjs` moves every pinned version together: packages, plugin manifests, MCP configs, the hook and the CI examples. +### Added — execution without a hub, a fuller calendar, context from the watch (ADR-037) + +- New package `trainctl-sync-files`: reads exported FIT, TCX and GPX files + (also `.gz`, as in Strava and Garmin bulk exports) as a pull-only source, with + no dependencies. `trainctl pull --from ` (MCP `from`) and + `sync.files` in `trainctl.yaml` for `review` without an API key. Skipped files + are named; duplicates count once. `init` adds `activities/` to `.gitignore`. +- The sync port is split into `ActivitySource` (pull) and `SyncProvider` + (pull + push). +- `push` sends races as race events (`RACE_A`/`B`/`C`) and strength sessions as + separate `WeightTraining` entries, in their own requests: if intervals.icu + refuses either form, a race falls back to an ordinary entry, a warning says + so, and the running sessions are pushed regardless. Cleanup of stale entries + now covers every `trainctl-` entry, not only workouts. **Not yet verified on a + live intervals.icu account.** +- `review` quotes resting heart rate, sleep and weight from the synced wellness + data, and RPE recorded in the hub where the journal has none — verbatim, with + the source, never averaged or turned into a verdict. HRV and CTL/ATL are + deliberately left out (H-1, P-4). + ### Docs - README command tables list `shorten` and the missing flags; tool lists no diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 85b9c4e..3818462 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -35,6 +35,7 @@ visible rather than silent. | `trainctl-mcp` | the MCP server — 17 tools over those same handlers | | `trainctl-export` | `.fit`, `.ics`, printable HTML, race-day pack | | `trainctl-sync-intervalsicu` | the intervals.icu adapter | +| `trainctl-sync-files` | exported activity files (FIT, TCX, GPX) as a pull-only source | The dependency arrow points one way: `core` knows nothing about the CLI, and the MCP server imports only from `trainctl`. A command handler that formats its own diff --git a/README.md b/README.md index befb71a..013e7d9 100644 --- a/README.md +++ b/README.md @@ -255,7 +255,7 @@ a key is configured). `trainctl adapt` compares execution with the plan and | `review` | pull + adapt + week in one call | `--days`, `--date`, `--prepare` | | `desk` | training windows around office hours | `--heavy` | | `push` | send planned sessions to intervals.icu | `--days`, `--from`, `--to` | -| `pull` | fetch activities and wellness, compare | `--days`, `--date` | +| `pull` | fetch activities and wellness, compare | `--days`, `--date`, `--from ` | | `export` | `.fit`, `.ics`, printout, race pack | `--what`, `--date` | | `diff` | what a regeneration would change | `--plan ` | | `check` | lint the plan; fails the exit code | `--strict` | @@ -462,7 +462,27 @@ trainctl pull --days 28 # execution + wellness → compared with ``` `push` only ever touches entries it created itself (they carry a `trainctl-` -external id), so your own calendar entries stay yours. +external id), so your own calendar entries stay yours. Races go in as race +events (A/B/C) and strength sessions as separate entries; if intervals.icu +refuses either form, `push` says so and the running sessions are pushed anyway. + +**No account? Use the files your watch already exports.** `pull --from` reads +FIT, TCX and GPX files (also `.gz`, as in a Strava or Garmin bulk export), so +execution can be compared with the plan without intervals.icu — and without the +Strava restriction below: + +```bash +trainctl pull --from ./activities # once +``` + +```yaml +sync: + files: ./activities # in trainctl.yaml: review and pull read it +``` + +The files stay on your disk; `init` adds `activities/` to `.gitignore`, because +GPS tracks give away where you live. Details: +[docs/integrations/files.md](docs/integrations/files.md). > **Connect your watch to intervals.icu directly** (Settings → Connections), not > through Strava. Since December 2024 intervals.icu does not pass Strava-sourced @@ -558,8 +578,9 @@ over (the old plan is in git). Run `trainctl check` afterwards; it verifies the invariants the generator guarantees and tells you what a hand edit broke. -**Do I need intervals.icu?** No. Everything except `push`/`pull`/`review` works -offline; export covers watch, calendar and paper. +**Do I need intervals.icu?** No. Everything except `push` works without it: +`pull --from` and `review` read exported activity files, and export covers +watch, calendar and paper. **Does it support cycling, swimming, triathlon?** No. The engine is built for running; the domain model was designed with other sports in mind, but nothing @@ -582,8 +603,9 @@ pnpm check # typecheck + tests — what CI runs is not distributed; without it that suite reports itself as one skipped test rather than quietly disappearing. -Five packages: `trainctl` (CLI), `trainctl-core` (engine), `trainctl-mcp`, -`trainctl-export`, `trainctl-sync-intervalsicu`. Development runs straight from +Six packages: `trainctl` (CLI), `trainctl-core` (engine), `trainctl-mcp`, +`trainctl-export`, `trainctl-sync-intervalsicu`, `trainctl-sync-files`; the +agent plugin lives in `plugin/`. Development runs straight from TypeScript (Node's type stripping); `pnpm build` emits the `dist/` that gets published. diff --git a/README.pl.md b/README.pl.md index 858935e..b1e98c3 100644 --- a/README.pl.md +++ b/README.pl.md @@ -258,7 +258,7 @@ Twoimi plecami. | `review` | pull + adapt + week w jednym | `--days`, `--date`, `--prepare` | | `desk` | okna treningowe wokół godzin pracy | `--heavy` | | `push` | wysyła treningi do intervals.icu | `--days`, `--from`, `--to` | -| `pull` | pobiera aktywności i wellness, porównuje | `--days`, `--date` | +| `pull` | pobiera aktywności i wellness, porównuje | `--days`, `--date`, `--from ` | | `export` | `.fit`, `.ics`, rozpiska, pakiet startowy | `--what`, `--date` | | `diff` | co zmieniłaby regeneracja planu | `--plan ` | | `check` | lint planu; psuje kod wyjścia | `--strict` | @@ -471,7 +471,27 @@ trainctl pull --days 28 # wykonanie + wellness → porównanie z ``` `push` rusza wyłącznie wpisy, które sam utworzył (mają prefiks `trainctl-` -w external id), więc Twoje własne wpisy w kalendarzu zostają Twoje. +w external id), więc Twoje własne wpisy w kalendarzu zostają Twoje. Starty +trafiają jako zawody (A/B/C), a siła jako osobne wpisy; jeśli intervals.icu +odrzuci którąś z tych postaci, `push` to powie, a treningi biegowe i tak pójdą. + +**Bez konta? Użyj plików, które zegarek i tak eksportuje.** `pull --from` czyta +pliki FIT, TCX i GPX (także `.gz`, jak w zbiorczym eksporcie Stravy czy Garmina), +więc wykonanie da się porównać z planem bez intervals.icu — i bez ograniczenia +Stravy opisanego niżej: + +```bash +trainctl pull --from ./activities # jednorazowo +``` + +```yaml +sync: + files: ./activities # w trainctl.yaml: czytają go review i pull +``` + +Pliki zostają na Twoim dysku; `init` dopisuje `activities/` do `.gitignore`, bo +ślady GPS zdradzają, gdzie mieszkasz. Szczegóły: +[docs/integrations/files.md](docs/integrations/files.md). > **Zegarek musi być podpięty do intervals.icu bezpośrednio** (Settings → > Connections), nie przez Stravę: od grudnia 2024 hub nie przepuszcza danych ze @@ -566,8 +586,9 @@ zapisu; `--fresh` zaczyna od zera (stary plan jest w gicie). Uruchom potem `trainctl check`: sprawdza inwarianty, które gwarantuje generator, i mówi, co ręczna edycja zepsuła. -**Czy potrzebuję intervals.icu?** Nie. Wszystko poza `push`/`pull`/`review` -działa offline; eksport obsługuje zegarek, kalendarz i papier. +**Czy potrzebuję intervals.icu?** Nie. Wszystko poza `push` działa bez niego: +`pull --from` i `review` czytają wyeksportowane pliki aktywności, a eksport +obsługuje zegarek, kalendarz i papier. **Rower, pływanie, triathlon?** Nie. Silnik jest zbudowany pod bieganie; model domeny projektowano z myślą o innych sportach, ale nic poza bieganiem nie jest @@ -591,8 +612,9 @@ pnpm check # typecheck + testy — to samo, co robi CI nie jest dystrybuowany; bez niego ten zestaw zgłasza się jako jeden pominięty test, zamiast po cichu zniknąć. -Pięć pakietów: `trainctl` (CLI), `trainctl-core` (silnik), `trainctl-mcp`, -`trainctl-export`, `trainctl-sync-intervalsicu`. Rozwój idzie prosto z +Sześć pakietów: `trainctl` (CLI), `trainctl-core` (silnik), `trainctl-mcp`, +`trainctl-export`, `trainctl-sync-intervalsicu`, `trainctl-sync-files`; plugin +dla agentów leży w `plugin/`. Rozwój idzie prosto z TypeScriptu (type-stripping Node), a `pnpm build` produkuje `dist/`, które trafia do rejestru. diff --git a/SPEC.md b/SPEC.md index f8248e1..56c7aee 100644 --- a/SPEC.md +++ b/SPEC.md @@ -174,6 +174,15 @@ szczegóły i linki: `docs/integrations/intervalsicu.md`). Stan po weryfikacji: Bezpośrednia integracja Strava — potwierdzona jako pole minowe (od VI 2026 dodatkowo płatny tier deweloperski). Garmin developer program — omijamy hubem. +**Druga droga wykonania: pliki aktywności** (ADR-037, 0.5.0). `trainctl-sync-files` +czyta eksport FIT/TCX/GPX z dysku jako źródło pull-only — mitygacja ryzyka +zależności od jednoosobowego huba (§9) i obejście blokady danych Stravy (eksport +zbiorczy Stravy i Garmina to te same pliki). Port rozdzielony na `ActivitySource` +(pull) i `SyncProvider` (pull + push), więc adapter plikowy nie udaje, że umie +wysyłać treningi. Push startów (RACE_A/B/C) i siły (WeightTraining) idzie +osobnymi żądaniami z wycofaniem — **ta postać nie była jeszcze sprawdzona na +żywym koncie** (docs/integrations/intervalsicu.md, §2c do uzupełnienia). + ## 8. Fazy Każda faza kończy się: testami, aktualizacją SPEC/planu, wpisem do pamięci, @@ -330,4 +339,5 @@ dane strukturalne MCP i samodzielny eksport mobilny. Opis poleceń i granic: | 034 | 2026-10-21 | Zegar symulacji `TRAINCTL_TODAY` jest **jawny**: każde wyjście CLI i MCP zaczyna się od informacji o nim, ochrona przeszłości i ważność propozycji idą za datą symulowaną | A05 słusznie oddzielił wybór tygodnia od zegara, ale bez sankcjonowanej symulacji dokumentacja i próby ręczne stały się niemożliwe; cicha symulacja byłaby powtórką A05 | | 035 | 2026-10-21 | `--json` zwraca `CmdResult.data` — te same dane, które dostaje MCP; stabilność kształtu do 1.0 tylko w polach używanych przez MCP | jedno źródło danych dla agenta i skryptów, bez drugiej logiki wyjścia (ADR-013) | | 036 | 2026-10-21 | Plugin Claude Code/Codex to **kanał dystrybucji, nie nowa logika**: repozytorium jest marketplace’em (`.claude-plugin/`, `.agents/plugins/`), plugin pakuje serwer MCP, personę (generowaną z tego samego tekstu co AGENTS.md) i skille zadaniowe; hooki tylko w Claude Code; `init --agent` zapisuje pliki agenta wyłącznie na jawną flagę i nigdy nie nadpisuje istniejących | dryf między AGENTS.md a skillami dałby dwóch różnych trenerów; plugin i projektowy `.mcp.json` naraz uruchomiłyby dwa serwery; cicha konfiguracja agenta w repo użytkownika łamie zasadę „nic bez pytania" (ADR-019) | +| 037 | 2026-10-21 | Port sync rozdzielony na `ActivitySource` (pull) i `SyncProvider` (pull + push); pliki FIT/TCX/GPX jako druga implementacja źródła (`trainctl-sync-files`), bez zależności; starty i siła w push osobnymi żądaniami, które nie mogą wywrócić pushu treningów | zapowiedziana w §9 mitygacja zależności od huba; adapter pull-only w porcie z metodami push byłby kłamstwem typów; postać startów i siły w intervals.icu nie była sprawdzona na żywym koncie, więc jej odrzucenie musi być ostrzeżeniem, nie awarią | | 040 | 2026-10-21 | `--commit` commituje wyłącznie pliki zmienione przez komendę (pathspec przy `git commit`), nigdy sekretów ani `sync.json`; brak gita to informacja, nie błąd | AGENTS.md każe commitować po każdej zmianie planu — flaga robi to, co i tak jest zalecane, bez stawania się klientem gita i bez zabierania cudzych zmian z indeksu | diff --git a/docs/PUBLISHING.md b/docs/PUBLISHING.md index 0563cb2..c7874de 100644 --- a/docs/PUBLISHING.md +++ b/docs/PUBLISHING.md @@ -121,11 +121,20 @@ deklaracjami i mapami źródeł; `publishConfig` przestawia wejścia paczki na `dist/*.js`, a w repozytorium nic się nie zmienia — dalej jedziemy na natywnym type-strippingu Node ≥ 22.18, którego wymaga `engines`. +## Szósta paczka (od 0.5.0) + +`trainctl-sync-files` dołącza do pięciu paczek z tą samą wersją. Pierwsza +publikacja nowej nazwy na npm wymaga tego samego tokenu co reszta; job `dist` +w CI pakuje i instaluje ją razem z pozostałymi. Wersje wszystkich paczek, +pluginu i przykładów przesuwa razem `node tools/release/bump-version.mjs `. + ## Czego NIE publikować nigdy - `corpus/` w jakiejkolwiek postaci (PII trenera i zawodnika). - `corpus/parsed/BACKTEST.md` i `long-run-profile.json` — generowane lokalnie, zawierają daty startów użytkownika; są w .gitignore razem z resztą korpusu. - Wyników `trainctl init --from-intervals` z realnego konta w przykładach docs. +- Prawdziwych plików aktywności (FIT/TCX/GPX) w testach i przykładach — ślady + GPS; testy `trainctl-sync-files` generują wyłącznie syntetyczne pliki. - `.env`, `.trainctl-secret` — w .gitignore, weryfikowane przy każdym uruchomieniu CLI (ostrzeżenie, gdy sekret leży w repo bez ochrony). diff --git a/docs/integrations/files.md b/docs/integrations/files.md new file mode 100644 index 0000000..8e21428 --- /dev/null +++ b/docs/integrations/files.md @@ -0,0 +1,56 @@ +# Activity files instead of a hub + +`trainctl-sync-files` reads the files your watch or platform exports and turns +them into the same execution data `pull` gets from intervals.icu. Nothing leaves +your disk, and no account is needed. + +```bash +trainctl pull --from ./activities # a folder (searched recursively) or a single file +``` + +Or once, in `trainctl.yaml`, so `review` and `pull` use it whenever there is no +intervals.icu key: + +```yaml +sync: + files: ./activities +``` + +With a key configured, `review` still pulls from intervals.icu; `pull --from` +adds files at any time. Both end up in `sync.json`, merged by activity. + +## Where the files come from + +| source | how | +|---|---| +| Garmin Connect | activity → ⚙ → *Export Original* (`.fit`), or *Account → Export Your Data* for everything | +| Strava | *Settings → My Account → Download or Delete Your Account* — the archive's `activities/` folder holds `.fit.gz`, `.gpx.gz`, `.tcx.gz` | +| Coros, Polar, Suunto | each app's export of an activity as FIT, TCX or GPX | + +The Strava archive is the way around the restriction described in +[intervalsicu.md](intervalsicu.md) §1.8.1: the hub cannot pass Strava data on, +but your own export can. + +## What is read + +- **FIT**: the `session` message (sport, start, distance, moving and elapsed + time, heart rate, ascent), local date from the `activity` message's + local timestamp; multisport files count only their running parts. +- **TCX**: laps (time, distance, heart rate), sport from the `Activity` element. +- **GPX**: track points — distance by haversine, moving time without pauses over + 60 s or below 0.5 m/s (engineering choices). Without a `type`, a pace between + 3:00 and 9:30 min/km counts as a run. + +Running, trail running and treadmill sessions count as runs; everything else is +kept but not compared with the plan. Zones never come from these files — they +come from race results in `athlete.results`. + +## Limits + +- No wellness (sleep, resting heart rate) and no RPE: the files do not carry them. + Log the effort with `trainctl log --rpe`. +- TCX and GPX carry UTC times; the local date uses this machine's time zone. +- Files that are not activities, are unreadable or larger than 50 MB are skipped + and named in the output; the same activity exported twice counts once. +- `init` adds `activities/` to `.gitignore`. GPS tracks show where you live — + keep them out of a repository you might publish. diff --git a/package.json b/package.json index be40158..663df77 100644 --- a/package.json +++ b/package.json @@ -28,7 +28,7 @@ "scripts": { "test": "vitest run", "test:watch": "vitest", - "typecheck": "tsc --noEmit -p packages/core && tsc --noEmit -p packages/sync-intervalsicu && tsc --noEmit -p packages/export && tsc --noEmit -p packages/cli && tsc --noEmit -p packages/mcp", + "typecheck": "tsc --noEmit -p packages/core && tsc --noEmit -p packages/sync-intervalsicu && tsc --noEmit -p packages/sync-files && tsc --noEmit -p packages/export && tsc --noEmit -p packages/cli && tsc --noEmit -p packages/mcp", "check": "pnpm typecheck && pnpm test", "trainctl": "node packages/cli/src/bin.ts", "release:dry": "pnpm publish -r --dry-run --no-git-checks", diff --git a/packages/cli/package.json b/packages/cli/package.json index 8948a1f..bbfef78 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -55,6 +55,7 @@ "trainctl-core": "workspace:*", "trainctl-export": "workspace:*", "trainctl-sync-intervalsicu": "workspace:*", + "trainctl-sync-files": "workspace:*", "commander": "^14.0.0", "yaml": "^2.6.0" }, diff --git a/packages/cli/src/bin.ts b/packages/cli/src/bin.ts index 66fac38..f01c46a 100644 --- a/packages/cli/src/bin.ts +++ b/packages/cli/src/bin.ts @@ -341,7 +341,8 @@ withExamples( .command('pull') .description(ui().cmd.pull) .option('--date ', ui().cmd.optDate, back) - .option('--days ', ui().cmd.optDaysBack), + .option('--days ', ui().cmd.optDaysBack) + .option('--from ', ui().cmd.optPullFrom), 'pull', ).action(async (opts) => print(await spin(ui().cmd.spinnerPull, () => cmdPull(cwd, opts)))) diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index a28a8dc..a1c7744 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -19,6 +19,7 @@ import { COACH_STYLE, INFER_WINDOW_WEEKS, type ExecutionRecord, + type ActivitySource, type InferenceOutcome, type PlanIssue, type PlannedWorkout, @@ -92,6 +93,7 @@ export const kindLabel = (kind: string): string => export const phaseLabel = (phase: string): string => (messages().phase as Record)[phase] ?? phase import { + chooseSource, compare, defaultProviderFactory, defaultRange, @@ -263,7 +265,8 @@ function writeAgentsFile(cwd: string): boolean { } /** Pliki z sekretami, które nigdy nie mogą trafić do repozytorium (ADR-009). */ -const SECRET_PATTERNS = [ENV_FILE, '.env.*', SECRET_FILE] +// `activities/` to domyślny katalog eksportu FIT/TCX/GPX — ślady GPS zdradzają adres domu. +const SECRET_PATTERNS = [ENV_FILE, '.env.*', SECRET_FILE, 'activities/'] /** * Ochrona sekretów w katalogu treningowym. Katalog jest repozytorium gita, @@ -795,6 +798,7 @@ export async function cmdPush( return okDoc([ b.success(ui().push.pushed(res.pushed, provider.name, from, to)), + ...(res.warnings ?? []).map((w) => b.warn(w)), ...(stale.length ? [b.info(ui().push.removedStale(stale.length, stale.join(', ')))] : []), @@ -813,18 +817,21 @@ export async function cmdPush( export async function cmdPull( cwd: string, - opts: { days?: string | undefined; date?: string | undefined } = {}, + opts: { days?: string | undefined; date?: string | undefined; from?: string | undefined } = {}, factory: ProviderFactory = defaultProviderFactory, ): Promise { try { const today = opts.date ?? localToday() const days = Number(opts.days ?? 28) const { from, to } = defaultRange(today, -(Number.isFinite(days) ? Math.abs(days) : 28)) - const provider = factory(cwd) + // `--from ` albo hub; bez obu `factory` zgłosi brak klucza jak dotąd + const choice = chooseSource(cwd, opts.from, factory) + const provider = choice ? { name: choice.label, ...pick(choice.source) } : factory(cwd) const [activities, wellness] = await Promise.all([ provider.listActivities(from, to), provider.listWellness(from, to).catch(() => []), ]) + const skipped = choice?.skipped() ?? [] writeSnapshot(cwd, { pulledAt: today, from, to: today, activities, wellness }) const runs = activities.filter((a) => /run/i.test(a.type)) const km = Math.round(runs.reduce((s, a) => s + (a.distanceKm ?? 0), 0)) @@ -844,6 +851,9 @@ export async function cmdPull( const sources = [...new Set(withheld.map((a) => a.source ?? '?'))].sort().join(', ') blocks.push(b.warn(ui().pull.dataWithheld(withheld.length, sources))) } + if (skipped.length) { + blocks.push(b.info(ui().pull.filesSkipped(skipped.length, skipped.slice(0, 3).map((s) => s.file).join(', ')))) + } try { const plan = loadPlan(cwd) const rows = compare(plan, activities, from, to).filter((r) => r.status !== 'matched') @@ -869,7 +879,7 @@ export async function cmdPull( } catch { blocks.push(b.info(ui().pull.noPlanSkipped)) } - return okDoc(blocks, { activities, wellness, from, to }) + return okDoc(blocks, { activities, wellness, from, to, source: choice?.kind ?? 'hub', skipped }) } catch (e) { return fail(e) } @@ -1293,18 +1303,25 @@ export async function cmdReview( // 1) świeże dane, jeśli klucz jest pod ręką; inaczej pracujemy na migawce const notes: string[] = [] - if (hasApiKey(cwd)) { + let choice: ReturnType + try { + choice = chooseSource(cwd, undefined, factory) + } catch (e) { + notes.push(ui().review.refreshFailed(e instanceof Error ? e.message : String(e))) + } + if (choice) { try { - const provider = factory(cwd) + const provider = choice.source const [activities, wellness] = await Promise.all([ provider.listActivities(syncFrom, today), provider.listWellness(syncFrom, today).catch(() => []), ]) writeSnapshot(cwd, { pulledAt: today, from: syncFrom, to: today, activities, wellness }) + if (choice.kind === 'files') notes.push(ui().review.fromFiles(choice.label)) } catch (e) { notes.push(ui().review.refreshFailed(e instanceof Error ? e.message : String(e))) } - } else { + } else if (!notes.length) { notes.push(ui().review.noKey) } @@ -1351,13 +1368,30 @@ export async function cmdReview( const feel = [...latestByDate.values()] .filter((l) => l.rpe !== undefined || l.note) .sort((a, z) => a.date.localeCompare(z.date)) - if (feel.length) { - blocks.push( - b.section(ui().review.feel), - b.bullets(feel.map((l) => ui().review.feelLine(l.date, l.rpe, l.note))), - ) + // RPE wpisane w hubie (zegarek, aplikacja) — tylko tam, gdzie dziennik go nie ma: + // własny wpis biegacza ma pierwszeństwo, a źródło jest nazwane wprost. + const hubFeel = (snapshot?.activities ?? []) + .filter((a) => a.rpe !== undefined && a.date >= from && a.date <= today && isRunningActivity(a) && latestByDate.get(a.date)?.rpe === undefined) + .sort((a, z) => a.date.localeCompare(z.date)) + if (feel.length || hubFeel.length) { + const lines = [ + ...feel.map((l) => ({ date: l.date, text: ui().review.feelLine(l.date, l.rpe, l.note) })), + ...hubFeel.map((a) => ({ date: a.date, text: ui().review.feelFromHub(a.date, a.rpe!, a.source ?? 'intervals.icu') })), + ].sort((a, z) => a.date.localeCompare(z.date)) + blocks.push(b.section(ui().review.feel), b.bullets(lines.map((l) => l.text))) } + // 2c) kontekst z zegarka — cytowany jak odczucia: bez średnich, progów i + // wniosków (ADR-027). HRV i CTL/ATL świadomie pomijamy: gotowości z HRV silnik + // odmawia (H-1), a obciążenia z huba to deskryptory, nie wskazówki (P-4) — + // pokazane obok planu zaczęłyby sterować decyzjami. + const wellnessLines = (snapshot?.wellness ?? []) + .filter((w) => w.date >= from && w.date <= today) + .sort((a, z) => a.date.localeCompare(z.date)) + .map((w) => ui().review.wellnessLine(w.date, w.restingHr, w.sleepSec, w.weightKg)) + .filter((line): line is string => line !== undefined) + if (wellnessLines.length) blocks.push(b.section(ui().review.wellness), b.bullets(wellnessLines)) + // 3) sygnały adaptacji — sekcja pojawia się tylko wtedy, gdy jest co powiedzieć const adapt = cmdAdapt(cwd, { date: today }) if (adapt.code !== 0) return adapt @@ -1422,7 +1456,7 @@ export async function cmdReview( // sprawiłby, że ta gałąź milczy w angielskim interfejsie. if (adaptation?.actions.some((a) => a.type === 'recalibrate-zones')) todo.push(ui().review.todoWriteResult) if (meaningful) todo.push(ui().review.todoSeeAdapt) - if (hasApiKey(cwd)) todo.push(ui().review.todoPush) + if (choice?.kind === 'hub') todo.push(ui().review.todoPush) else todo.push(ui().review.todoPrint) if (missed.length >= 2) todo.push(ui().review.todoReschedule) const nextRace = (config.athlete.tuneUpRaces ?? []).find((r) => r.date > today) @@ -1770,6 +1804,14 @@ export function cmdDiff(cwd: string, opts: { plan?: string | undefined } = {}): } } +/** Metody źródła jako zwykłe funkcje — `this` klasy zostaje przy nich. */ +function pick(source: ActivitySource): Pick { + return { + listActivities: (a, z) => source.listActivities(a, z), + listWellness: (a, z) => source.listWellness(a, z), + } +} + export function daysToRace(plan: { goal: { date: string } }, today: string): number { return diffDays(today, plan.goal.date) } diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.ts index fad31b7..3b3517f 100644 --- a/packages/cli/src/config.ts +++ b/packages/cli/src/config.ts @@ -24,11 +24,18 @@ export interface StrengthConfig { days?: Weekday[] } +/** Źródła wykonania inne niż hub (ADR-037). */ +export interface SyncConfig { + /** Katalog (albo plik) z eksportem FIT/TCX/GPX — względem katalogu treningowego. */ + files?: string +} + export interface TrainctlConfig { athlete: AthleteProfile goal: RaceGoal desk?: DeskConfig strength?: StrengthConfig + sync?: SyncConfig /** Język interfejsu i opisów planu: 'en' (domyślny) albo 'pl'. */ language?: string } @@ -96,6 +103,8 @@ export function configTemplate(): string { pad('# strength:', t.templateStrength.section), pad('# enabled: true', t.templateStrength.enabled), pad('# days: [mon, fri]', t.templateStrength.days), + pad('# sync:', t.templateSync.section), + pad('# files: ./activities', t.templateSync.files), '', ].join('\n') } @@ -179,6 +188,10 @@ export function loadConfig(cwd: string): TrainctlConfig { } if (errs.length) fail(errs) } + const sync = raw?.sync + if (sync !== undefined && (typeof sync !== 'object' || sync === null || (sync.files !== undefined && (typeof sync.files !== 'string' || !sync.files.trim())))) { + fail([v.required('sync.files')]) + } const athlete = a as AthleteProfile return { athlete: { @@ -192,6 +205,22 @@ export function loadConfig(cwd: string): TrainctlConfig { goal: { ...goal, priority: goal.priority ?? 'A' }, ...(desk ? { desk } : {}), ...(strength ? { strength } : {}), + ...(sync?.files ? { sync: { files: sync.files } } : {}), + } +} + +/** + * `sync.files` bez pełnej walidacji profilu — `review` i `status` mają działać + * także wtedy, gdy profil ma błąd gdzie indziej. + */ +export function readSyncFiles(cwd: string): string | undefined { + const path = join(cwd, CONFIG_FILE) + if (!existsSync(path)) return undefined + try { + const raw = parse(readFileSync(path, 'utf-8')) as { sync?: { files?: unknown } } | null + return typeof raw?.sync?.files === 'string' && raw.sync.files.trim() ? raw.sync.files : undefined + } catch { + return undefined } } diff --git a/packages/cli/src/env-file.test.ts b/packages/cli/src/env-file.test.ts index 0de025e..8b7c085 100644 --- a/packages/cli/src/env-file.test.ts +++ b/packages/cli/src/env-file.test.ts @@ -126,7 +126,7 @@ describe('init domyka lukę', () => { it('uruchomiony dwa razy nie duplikuje wpisów', () => { gitRepo() - writeFileSync(join(dir, '.gitignore'), '.env\n.env.*\n.trainctl-secret\n', 'utf-8') + writeFileSync(join(dir, '.gitignore'), '.env\n.env.*\n.trainctl-secret\nactivities/\n', 'utf-8') const before = require('node:fs').readFileSync(join(dir, '.gitignore'), 'utf-8') as string cmdInit(dir) const after = require('node:fs').readFileSync(join(dir, '.gitignore'), 'utf-8') as string diff --git a/packages/cli/src/files-sync.test.ts b/packages/cli/src/files-sync.test.ts new file mode 100644 index 0000000..9ddbdb4 --- /dev/null +++ b/packages/cli/src/files-sync.test.ts @@ -0,0 +1,120 @@ +/** + * Etap D (docs/PLAN-v0.4.md): wykonanie z plików aktywności bez konta (ADR-037) + * i kontekst z zegarka w przeglądzie — cytowany, nie interpretowany (ADR-027). + * Wyłącznie syntetyczne dane: żadnych prawdziwych śladów GPS w repozytorium. + */ +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { setLocale } from 'trainctl-core' +import { cmdInit, cmdLog, cmdPlan, cmdPull, cmdReview } from './commands.ts' +import type { SyncSnapshot } from './sync.ts' + +setLocale('en') + +const CONFIG = `athlete: + recentWeeklyKm: 45 + daysAvailable: [tue, wed, thu, sat, sun] + results: + - { date: "2026-03-29", distanceKm: 10, timeSec: 2580 } +goal: + name: "Half marathon" + date: "2026-11-29" + distanceKm: 21.0975 + priority: A +` + +/** Prosty ślad biegu na północ: `km` kilometrów w `minutes` minut, start o 07:00 czasu lokalnego. */ +function gpxRun(date: string, km: number, minutes: number): string { + const points = Math.round((minutes * 60) / 10) + const start = new Date(`${date}T07:00:00`) + const step = km / 111.195 / points // stopnie szerokości na odcinek + const pts = Array.from({ length: points + 1 }, (_, i) => + ``) + return `\nMorning runrunning${pts.join('')}` +} + +let dir: string +beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'trainctl-files-')) + writeFileSync(join(dir, 'trainctl.yaml'), CONFIG, 'utf-8') + expect(cmdPlan(dir, { date: '2026-08-08' }).code).toBe(0) + mkdirSync(join(dir, 'activities')) + writeFileSync(join(dir, 'activities', 'run.gpx'), gpxRun('2026-08-11', 8, 41), 'utf-8') + writeFileSync(join(dir, 'activities', 'broken.fit'), 'not a fit file', 'utf-8') +}) +afterEach(() => rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })) + +const snapshot = () => JSON.parse(readFileSync(join(dir, 'sync.json'), 'utf-8')) as SyncSnapshot + +describe('pull --from: wykonanie z eksportu plików', () => { + it('czyta GPX, zapisuje migawkę, porównuje z planem i nazywa pominięte pliki', async () => { + const r = await cmdPull(dir, { from: 'activities', date: '2026-08-16', days: '7' }) + expect(r.code).toBe(0) + expect(r.output).toContain('Pulled from activity files (activities)') + expect(r.output).toContain('1 file was skipped') + expect(r.output).toContain('broken.fit') + const [run] = snapshot().activities + expect(run).toMatchObject({ date: '2026-08-11', type: 'Run', source: 'file' }) + expect(run!.distanceKm).toBeCloseTo(8, 0) + expect(r.data).toMatchObject({ source: 'files' }) + }) + + it('brak katalogu: czytelny błąd zamiast wyjątku systemowego', async () => { + const r = await cmdPull(dir, { from: 'nope' }) + expect(r.code).toBe(1) + expect(r.output).toContain('No activity export at nope') + }) + + it('review bez klucza czyta sync.files z profilu', async () => { + writeFileSync(join(dir, 'trainctl.yaml'), `${CONFIG}sync:\n files: ./activities\n`, 'utf-8') + const r = await cmdReview(dir, { date: '2026-08-16' }) + expect(r.code).toBe(0) + expect(r.output).toContain('Refreshed from activity files (activities)') + expect(r.output).not.toContain('No API key') + const execution = r.data!['execution'] as { date: string; status: string }[] + expect(execution.find((e) => e.date === '2026-08-11')).toMatchObject({ status: 'done' }) + }) + + it('init dopisuje activities/ do .gitignore — ślady GPS nie trafiają do repozytorium', () => { + const other = mkdtempSync(join(tmpdir(), 'trainctl-files-init-')) + try { + cmdInit(other) + expect(readFileSync(join(other, '.gitignore'), 'utf-8')).toContain('activities/') + } finally { + rmSync(other, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) + } + }) +}) + +describe('przegląd: kontekst z zegarka cytowany, nie interpretowany', () => { + const writeSnapshot = (s: Partial) => + writeFileSync(join(dir, 'sync.json'), JSON.stringify({ pulledAt: '2026-08-16', activities: [], wellness: [], ...s }), 'utf-8') + + it('tętno spoczynkowe, sen i masa z dni przeglądu; bez HRV i CTL/ATL', async () => { + writeSnapshot({ wellness: [ + { date: '2026-08-12', restingHr: 46, sleepSec: 25_800, hrv: 88, ctl: 51, atl: 60 }, + { date: '2026-08-14', weightKg: 71.2 }, + { date: '2026-08-01', restingHr: 40 }, + ] }) + const r = await cmdReview(dir, { date: '2026-08-16' }) + expect(r.output).toContain('From your watch (quoted, not interpreted)') + expect(r.output).toContain('2026-08-12 · resting HR 46 · sleep 7:10') + expect(r.output).toContain('2026-08-14 · 71.2 kg') + expect(r.output).not.toContain('2026-08-01 · resting HR') + expect(r.output).not.toMatch(/HRV|CTL|ATL/) + }) + + it('RPE z huba tylko tam, gdzie dziennik go nie ma — ze źródłem', async () => { + writeSnapshot({ activities: [ + { externalId: 'a1', date: '2026-08-11', type: 'Run', distanceKm: 8, rpe: 6, source: 'GARMIN_CONNECT' }, + { externalId: 'a2', date: '2026-08-13', type: 'Run', distanceKm: 10, rpe: 3 }, + ] }) + cmdLog(dir, { date: '2026-08-13', km: '10', rpe: '5', note: 'heavy legs' }) + const r = await cmdReview(dir, { date: '2026-08-16' }) + expect(r.output).toContain('2026-08-11 · RPE 6 · from GARMIN_CONNECT') + expect(r.output).toContain('RPE 5') + expect(r.output).not.toContain('RPE 3') + }) +}) diff --git a/packages/cli/src/i18n/cli-en.ts b/packages/cli/src/i18n/cli-en.ts index 39db9df..9e680d9 100644 --- a/packages/cli/src/i18n/cli-en.ts +++ b/packages/cli/src/i18n/cli-en.ts @@ -56,6 +56,7 @@ export const cliEn = { optToRange: 'range end', optDaysAhead: 'how many days ahead (default 14)', optDaysBack: 'how many days back (default 28)', + optPullFrom: 'read exported FIT/TCX/GPX files from this folder (or file) instead of intervals.icu', optReviewDays: 'how many days back to review (default 7)', optHeavy: 'today was cognitively heavy (long sessions with agents)', optBlock: 'days you cannot train on', @@ -132,9 +133,9 @@ export const cliEn = { raceCandidates: 'Possible races for zone calibration (confirm before adding!)', noRaceCandidates: 'I found no race candidates — add a calibration result by hand.', fillGoal: 'fill in the goal section in trainctl.yaml → trainctl plan', - gitignoreHeader: 'trainctl — secrets, never commit these', + gitignoreHeader: 'trainctl — secrets and GPS tracks, never commit these', gitignoreUpdated: (patterns: string) => - `Added to .gitignore: ${patterns} — that is where the intervals.icu key goes`, + `Added to .gitignore: ${patterns} — the intervals.icu key and exported GPS tracks stay out of git`, unnamed: 'unnamed', agentUnknown: (agent: string, allowed: string) => `Unknown agent "${agent}" — use one of: ${allowed}.`, agentHint: 'using Claude Code or Codex? trainctl init --agent claude|codex adds the integration files', @@ -313,6 +314,10 @@ export const cliEn = { pull: { title: (provider: string) => `Pulled from ${provider}`, + filesLabel: (path: string) => `activity files (${path})`, + filesMissing: (path: string) => `No activity export at ${path} — point --from (or sync.files in trainctl.yaml) at a folder of FIT, TCX or GPX files.`, + filesSkipped: (count: number, sample: string) => + `${count} ${pluralEn(count, { one: 'file was', other: 'files were' })} skipped (not an activity, unreadable or unsupported): ${sample}`, activities: 'Activities', activitiesValue: (total: number, runs: number, km: number) => `${total} (running: ${runs}, ${n(km)} km)`, @@ -544,7 +549,18 @@ export const cliEn = { `${from} → ${today} · ${goalName} (${goalDate})`, refreshFailed: (error: string) => `Could not refresh the data (${error}) — reviewing the last snapshot.`, - noKey: 'No API key — reviewing from the journal and the last snapshot (trainctl pull once you have one).', + noKey: 'No API key — reviewing from the journal and the last snapshot (trainctl pull once you have one, or trainctl pull --from ).', + fromFiles: (label: string) => `Refreshed from ${label}.`, + feelFromHub: (date: string, rpe: number, source: string) => `${date} · RPE ${n(rpe)} · from ${source}`, + wellness: 'From your watch (quoted, not interpreted)', + wellnessLine: (date: string, restingHr?: number, sleepSec?: number, weightKg?: number) => { + const parts = [ + ...(restingHr !== undefined ? [`resting HR ${n(restingHr)}`] : []), + ...(sleepSec !== undefined ? [`sleep ${Math.floor(Math.round(sleepSec / 60) / 60)}:${String(Math.round(sleepSec / 60) % 60).padStart(2, '0')}`] : []), + ...(weightKg !== undefined ? [`${n(weightKg)} kg`] : []), + ] + return parts.length ? `${date} · ${parts.join(' · ')}` : undefined + }, doneSessions: 'Sessions done', volume: 'Volume', volumeValue: (actualKm: number, plannedKm: number) => @@ -809,7 +825,7 @@ export const cliEn = { 'git show what-if:plan/plan.yaml > /tmp/s.yaml && trainctl diff --plan /tmp/s.yaml', ], push: ['trainctl push --days 7', 'trainctl push --from mon --to sun'], - pull: ['trainctl pull --days 28', 'trainctl pull --date -7 # a range ending a week ago'], + pull: ['trainctl pull --days 28', 'trainctl pull --date -7 # a range ending a week ago', 'trainctl pull --from ./activities # exported FIT/TCX/GPX, no account'], status: ['trainctl status', 'trainctl status --json | jq .proposals'], }, @@ -874,6 +890,10 @@ export const cliEn = { }, templateDesk: 'desk mode (trainctl desk) — optional', templateDeskPrefer: 'morning | lunch | evening', + templateSync: { + section: 'execution without an intervals.icu account (optional)', + files: 'folder of exported FIT/TCX/GPX files — trainctl pull and review read it', + }, templateStrength: { section: 'strength 2×/week alongside running (opt-in; needs access to weights)', enabled: 'the point is running economy (F-8) — NOT "injury protection" (F-9)', @@ -1037,6 +1057,7 @@ export const cliEn = { 'Fetch completed activities and wellness data from intervals.icu, save a snapshot (sync.json) ' + 'and compare execution with the plan (mismatches: shorter/longer/not done/unplanned).', pullDays: 'how many days back, default 28', + pullFrom: 'path (relative to the training directory) of a folder or file with exported FIT/TCX/GPX activities; read instead of intervals.icu.', review: 'The whole weekly review in one call: the days behind vs the plan, signals worth acting on, ' + 'the week ahead (phase, volume, key session, races/time trials) and a list of concrete ' + diff --git a/packages/cli/src/i18n/cli-pl.ts b/packages/cli/src/i18n/cli-pl.ts index 0d0c0ec..f745fef 100644 --- a/packages/cli/src/i18n/cli-pl.ts +++ b/packages/cli/src/i18n/cli-pl.ts @@ -70,6 +70,7 @@ export const cliPl: CliMessages = { optToRange: 'koniec zakresu', optDaysAhead: 'ile dni do przodu (domyślnie 14)', optDaysBack: 'ile dni wstecz (domyślnie 28)', + optPullFrom: 'czytaj eksport plików FIT/TCX/GPX z tego katalogu (albo pliku) zamiast z intervals.icu', optReviewDays: 'ile dni wstecz podsumować (domyślnie 7)', optHeavy: 'dziś ciężki dzień kognitywny (długie sesje z agentami)', optBlock: 'dni, w których nie możesz trenować', @@ -145,9 +146,9 @@ export const cliPl: CliMessages = { raceCandidates: 'Możliwe starty do kalibracji stref (potwierdź, zanim dopiszesz!)', noRaceCandidates: 'Nie znalazłem kandydatów na starty — wynik do kalibracji dopisz ręcznie.', fillGoal: 'uzupełnij sekcję goal w trainctl.yaml → trainctl plan', - gitignoreHeader: 'trainctl — sekrety, nigdy ich nie commituj', + gitignoreHeader: 'trainctl — sekrety i ślady GPS, nigdy ich nie commituj', gitignoreUpdated: (patterns: string) => - `Dopisano do .gitignore: ${patterns} — tam trafia klucz do intervals.icu`, + `Dopisano do .gitignore: ${patterns} — klucz do intervals.icu i eksportowane ślady GPS nie trafią do gita`, unnamed: 'bez nazwy', agentUnknown: (agent: string, allowed: string) => `Nieznany agent „${agent}” — użyj jednego z: ${allowed}.`, agentHint: 'używasz Claude Code albo Codex? trainctl init --agent claude|codex dodaje pliki integracji', @@ -328,6 +329,10 @@ export const cliPl: CliMessages = { pull: { title: (provider: string) => `Pobrano z ${provider}`, + filesLabel: (path: string) => `plików aktywności (${path})`, + filesMissing: (path: string) => `Brak eksportu aktywności w ${path} — wskaż przez --from (albo sync.files w trainctl.yaml) katalog z plikami FIT, TCX lub GPX.`, + filesSkipped: (count: number, sample: string) => + `Pominięto ${count} ${pluralPl(count, { one: 'plik', few: 'pliki', other: 'plików' })} (to nie aktywność, nieczytelny albo nieobsługiwany): ${sample}`, activities: 'Aktywności', activitiesValue: (total: number, runs: number, km: number) => `${total} (biegowych: ${runs}, ${n(km)} km)`, @@ -564,7 +569,18 @@ export const cliPl: CliMessages = { refreshFailed: (error: string) => `Nie udało się odświeżyć danych (${error}) — przegląd na ostatniej migawce.`, noKey: - 'Bez klucza API — przegląd z dziennika i ostatniej migawki (trainctl pull, gdy będzie klucz).', + 'Bez klucza API — przegląd z dziennika i ostatniej migawki (trainctl pull, gdy będzie klucz, albo trainctl pull --from ).', + fromFiles: (label: string) => `Odświeżono z ${label}.`, + feelFromHub: (date: string, rpe: number, source: string) => `${date} · RPE ${n(rpe)} · z ${source}`, + wellness: 'Z zegarka (cytowane, nie interpretowane)', + wellnessLine: (date: string, restingHr?: number, sleepSec?: number, weightKg?: number) => { + const parts = [ + ...(restingHr !== undefined ? [`tętno spoczynkowe ${n(restingHr)}`] : []), + ...(sleepSec !== undefined ? [`sen ${Math.floor(Math.round(sleepSec / 60) / 60)}:${String(Math.round(sleepSec / 60) % 60).padStart(2, '0')}`] : []), + ...(weightKg !== undefined ? [`${n(weightKg)} kg`] : []), + ] + return parts.length ? `${date} · ${parts.join(' · ')}` : undefined + }, doneSessions: 'Wykonane sesje', volume: 'Objętość', volumeValue: (actualKm: number, plannedKm: number) => @@ -833,7 +849,7 @@ export const cliPl: CliMessages = { 'git show co-jesli:plan/plan.yaml > /tmp/s.yaml && trainctl diff --plan /tmp/s.yaml', ], push: ['trainctl push --days 7', 'trainctl push --from pn --to nd'], - pull: ['trainctl pull --days 28', 'trainctl pull --date -7 # zakres kończący się tydzień temu'], + pull: ['trainctl pull --days 28', 'trainctl pull --date -7 # zakres kończący się tydzień temu', 'trainctl pull --from ./activities # eksport FIT/TCX/GPX, bez konta'], status: ['trainctl status', 'trainctl status --json | jq .proposals'], }, @@ -896,6 +912,10 @@ export const cliPl: CliMessages = { }, templateDesk: 'tryb biurkowy (trainctl desk) — opcjonalny', templateDeskPrefer: 'morning | lunch | evening', + templateSync: { + section: 'wykonanie bez konta w intervals.icu (opcjonalnie)', + files: 'katalog z eksportem plików FIT/TCX/GPX — czytają go trainctl pull i review', + }, templateStrength: { section: 'siła 2×/tydz. obok biegania (opt-in; wymaga ciężarów)', enabled: 'cel: ekonomia biegu (F-8) — NIE „ochrona przed urazami” (F-9)', @@ -1058,6 +1078,7 @@ export const cliPl: CliMessages = { 'Pobierz wykonane aktywności i dane wellness z intervals.icu, zapisz migawkę (sync.json) ' + 'i porównaj wykonanie z planem (rozjazdy: krótsze/dłuższe/brak wykonania/nieplanowane).', pullDays: 'ile dni wstecz, domyślnie 28', + pullFrom: 'ścieżka (względem katalogu treningowego) do katalogu albo pliku z eksportem aktywności FIT/TCX/GPX; czytana zamiast intervals.icu.', review: 'Przegląd tygodnia w jednym wywołaniu: wykonanie minionych dni vs plan, sygnały ' + 'do korekty, nadchodzący tydzień (faza, objętość, kluczowa jednostka, starty/sprawdziany) ' + diff --git a/packages/cli/src/packaging.test.ts b/packages/cli/src/packaging.test.ts index d2d7aed..f3fb25e 100644 --- a/packages/cli/src/packaging.test.ts +++ b/packages/cli/src/packaging.test.ts @@ -16,7 +16,7 @@ import { fileURLToPath } from 'node:url' import { describe, expect, it } from 'vitest' const ROOT = join(dirname(fileURLToPath(import.meta.url)), '../../..') -const PACKAGES = ['core', 'export', 'sync-intervalsicu', 'cli', 'mcp'] +const PACKAGES = ['core', 'export', 'sync-intervalsicu', 'sync-files', 'cli', 'mcp'] interface Manifest { name: string diff --git a/packages/cli/src/sync.test.ts b/packages/cli/src/sync.test.ts index 9646178..28efea7 100644 --- a/packages/cli/src/sync.test.ts +++ b/packages/cli/src/sync.test.ts @@ -89,11 +89,14 @@ describe('trainctl push', () => { expect(pushed.some((w) => w.date === '2026-08-03')).toBe(false) }) - it('tydzień startowy: start nie jest wypychany jako trening', () => { + it('tydzień startowy: start idzie jako zawody (ranga A), nie jako trening z krokami', () => { const plan = loadPlan(dir) const raceWeek = plan.weeks.at(-1)! const ws = workoutsToPush(plan, raceWeek.weekStart, plan.goal.date) - expect(ws.some((w) => w.date === plan.goal.date)).toBe(false) + const race = ws.filter((w) => w.date === plan.goal.date) + expect(race).toHaveLength(1) + expect(race[0]).toMatchObject({ race: { priority: 'A' }, sport: 'run' }) + expect(race[0]!.description).not.toMatch(/Pace/) }) it('usuwa nieaktualne wpisy po przesunięciu treningu (duch na zegarku)', async () => { diff --git a/packages/cli/src/sync.ts b/packages/cli/src/sync.ts index 5d8cf3a..3133e70 100644 --- a/packages/cli/src/sync.ts +++ b/packages/cli/src/sync.ts @@ -4,9 +4,11 @@ * czytamy z env TRAINCTL_INTERVALS_API_KEY albo z .trainctl-secret (gitignore). */ import { existsSync, readFileSync, writeFileSync } from 'node:fs' -import { join } from 'node:path' -import { addDays, type SyncProvider, type SyncedActivity, type SyncedWellness } from 'trainctl-core' -import { IntervalsIcuProvider, toPushableWorkout } from 'trainctl-sync-intervalsicu' +import { join, relative, resolve } from 'node:path' +import { FileActivitySource } from 'trainctl-sync-files' +import { readSyncFiles } from './config.ts' +import { addDays, type ActivitySource, type PushableWorkout, type SyncProvider, type SyncedActivity, type SyncedWellness } from 'trainctl-core' +import { IntervalsIcuProvider, toPushableRace, toPushableStrength, toPushableWorkout } from 'trainctl-sync-intervalsicu' import { buildExecution } from './execution.ts' import type { LogEntry } from './logfile.ts' import { ui } from './i18n/index.ts' @@ -49,13 +51,60 @@ export type ProviderFactory = (cwd: string) => SyncProvider export const defaultProviderFactory: ProviderFactory = (cwd) => new IntervalsIcuProvider({ apiKey: readApiKey(cwd) }) -/** Treningi z planu w zakresie dat — do wypchnięcia na zegarek. */ -export function workoutsToPush(plan: StoredPlan, from: string, to: string) { - return plan.weeks - .flatMap((w) => w.days) - .filter((d) => d.date >= from && d.date <= to) - .map((d) => toPushableWorkout(d, plan.goal.name)) - .filter((w): w is NonNullable => w !== undefined) +/** Źródło wykonania wybrane dla `pull`/`review` i to, co o nim powiedzieć użytkownikowi. */ +export interface SourceChoice { + source: ActivitySource + kind: 'hub' | 'files' + /** Nazwa do nagłówka: serwis albo ścieżka eksportu. */ + label: string + /** Pliki pominięte w ostatnim odczycie (tylko źródło plikowe). */ + skipped: () => readonly { file: string; reason: string }[] +} + +function filesSource(cwd: string, path: string): SourceChoice { + const full = resolve(cwd, path) + if (!existsSync(full)) throw new Error(ui().pull.filesMissing(path)) + const source = new FileActivitySource({ path: full }) + const shown = relative(cwd, full) || '.' + return { source, kind: 'files', label: ui().pull.filesLabel(shown.startsWith('..') ? full : shown), skipped: () => source.lastSkipped } +} + +/** + * Kolejność: jawne `--from` → hub, gdy jest klucz → `sync.files` z profilu. + * Bez żadnego z nich undefined — wołający decyduje, czy to błąd (`pull`), czy + * praca na dzienniku i ostatniej migawce (`review`). + */ +export function chooseSource(cwd: string, from: string | undefined, factory: ProviderFactory): SourceChoice | undefined { + if (from) return filesSource(cwd, from) + if (hasApiKey(cwd)) { + const provider = factory(cwd) + return { source: provider, kind: 'hub', label: provider.name, skipped: () => [] } + } + const configured = readSyncFiles(cwd) + return configured ? filesSource(cwd, configured) : undefined +} + +/** Treningi, starty i siła z planu w zakresie dat — do wypchnięcia do kalendarza. */ +export function workoutsToPush(plan: StoredPlan, from: string, to: string): PushableWorkout[] { + const out: PushableWorkout[] = [] + for (const week of plan.weeks) { + for (const d of week.days) { + if (d.date < from || d.date > to) continue + const run = toPushableWorkout(d, plan.goal.name) + if (run) out.push(run) + if (d.workout?.kind === 'race') { + // cel A albo start kontrolny B/C z tygodnia — nazwa i ranga z planu + const tuneUp = week.skeleton.tuneUp?.date === d.date ? week.skeleton.tuneUp : undefined + const race = d.date === plan.goal.date + ? toPushableRace(d, plan.goal.name, plan.goal.priority) + : toPushableRace(d, tuneUp?.name ?? plan.goal.name, tuneUp?.priority ?? 'B') + if (race) out.push(race) + } + const strength = toPushableStrength(d, plan.goal.name) + if (strength) out.push(strength) + } + } + return out } export function writeSnapshot(cwd: string, snapshot: SyncSnapshot): void { diff --git a/packages/core/src/i18n/core-en.ts b/packages/core/src/i18n/core-en.ts index 2c6ca5c..e77335a 100644 --- a/packages/core/src/i18n/core-en.ts +++ b/packages/core/src/i18n/core-en.ts @@ -123,6 +123,12 @@ export const coreEn = { sharpener: 'Pre-race sharpener', test: 'Time trial', race: 'RACE', + strength: 'Strength', + }, + + syncNotice: { + strengthRejected: (dates: string) => `intervals.icu did not accept the strength sessions (${dates}); the running sessions are pushed.`, + raceFallback: (dates: string) => `intervals.icu did not accept race events (${dates}); they were pushed as ordinary calendar entries.`, }, syncError: { diff --git a/packages/core/src/i18n/core-pl.ts b/packages/core/src/i18n/core-pl.ts index 2f5209e..a658834 100644 --- a/packages/core/src/i18n/core-pl.ts +++ b/packages/core/src/i18n/core-pl.ts @@ -128,6 +128,12 @@ export const corePl: CoreMessages = { sharpener: 'Rozruch przedstartowy', test: 'Sprawdzian na czas', race: 'START', + strength: 'Siła', + }, + + syncNotice: { + strengthRejected: (dates: string) => `intervals.icu nie przyjęło sesji siłowych (${dates}); treningi biegowe są wypchnięte.`, + raceFallback: (dates: string) => `intervals.icu nie przyjęło startów jako zawodów (${dates}); trafiły do kalendarza jako zwykłe wpisy.`, }, syncError: { diff --git a/packages/core/src/ports/sync.ts b/packages/core/src/ports/sync.ts index 938e32e..541f4b6 100644 --- a/packages/core/src/ports/sync.ts +++ b/packages/core/src/ports/sync.ts @@ -47,13 +47,21 @@ export interface PushableWorkout { name: string /** Opis w formacie docelowego serwisu (np. składnia „steps" intervals.icu). */ description: string - sport: 'run' + /** Siła to osobny tor (ADR-023): w kalendarzu osobny wpis, nigdy trening biegowy. */ + sport: 'run' | 'strength' distanceKm?: number + /** Start (A/B/C) zamiast treningu — serwis może go pokazać jako zawody. */ + race?: { priority: 'A' | 'B' | 'C' } } export interface PushResult { pushed: number externalIds: string[] + /** + * Wpisy dodatkowe (starty, siła), których serwis nie przyjął w docelowej + * postaci — treningi biegowe i tak zostały wypchnięte. + */ + warnings?: string[] } /** Zaplanowany trening już obecny w serwisie (do sprzątania po renegocjacji). */ diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts index 5c577e8..cbedba2 100644 --- a/packages/mcp/src/server.ts +++ b/packages/mcp/src/server.ts @@ -257,7 +257,7 @@ export function createTrainctlServer( description: t.pull, outputSchema: toolOutputSchema, annotations: { readOnlyHint: false, openWorldHint: true }, - inputSchema: { days: z.string().optional().describe(t.pullDays), date: isoDate().optional() }, + inputSchema: { days: z.string().optional().describe(t.pullDays), date: isoDate().optional(), from: z.string().optional().describe(t.pullFrom) }, }, async (args) => toTool(await cmdPull(dir, args, factory)), ) diff --git a/packages/sync-files/LICENSE b/packages/sync-files/LICENSE new file mode 100644 index 0000000..51bcdeb --- /dev/null +++ b/packages/sync-files/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Dariusz Tyszka + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/sync-files/README.md b/packages/sync-files/README.md new file mode 100644 index 0000000..8a095da --- /dev/null +++ b/packages/sync-files/README.md @@ -0,0 +1,42 @@ +# trainctl-sync-files + +Exported activity files for [trainctl](https://www.npmjs.com/package/trainctl): +compare what you ran with the plan, without an account anywhere. + +- Reads `.fit`, `.tcx` and `.gpx` files and their `.gz` variants — what a Strava + bulk export or a Garmin Connect export contains — from a directory (searched + recursively) or a single file. +- `FileActivitySource` implements trainctl's `ActivitySource` port. It only + reads: nothing is pushed anywhere, and activity files carry no wellness data. +- An activity's id is a hash of the file's content, so renaming a file or + exporting the same activity twice gives one entry. +- A broken or foreign file never stops the scan. It is reported in `skipped` + with a reason: `unreadable`, `not-an-activity` or `unsupported`. +- Multisport files count the running legs only. + +```ts +import { FileActivitySource } from 'trainctl-sync-files' + +const source = new FileActivitySource({ path: './activities' }) +const september = await source.listActivities('2026-09-01', '2026-09-30') +console.log(source.lastSkipped) +``` + +**Dates.** FIT files record the device's UTC offset, so their local date is +exact. TCX and GPX files usually hold UTC times only (`…Z`); those are converted +with the time zone of the machine running trainctl. A run at 23:30 in Lisbon, +read on a machine set to Warsaw time, lands on the next day. Timestamps written +with an explicit non-zero offset are taken as written. + +**GPX** has no summary, so distance (haversine), moving time (pauses over 60 s +and speeds under 0.5 m/s left out) and ascent (1 m noise threshold) come from +the track points. A track without a sport type counts as a run when its pace +falls between 3:00 and 9:30 min/km. These are engineering choices for comparing +execution with the plan; pace zones are never derived from activity files. + +Activity files contain GPS tracks. Keep them out of public repositories. + +Requires Node ≥ 22.18. Ships compiled JavaScript with type declarations. Depends +only on `trainctl-core`; the FIT decoder and the XML reading are built in. + +MIT · https://github.com/dithiothreitol/trainctl diff --git a/packages/sync-files/package.json b/packages/sync-files/package.json new file mode 100644 index 0000000..bfbcf8d --- /dev/null +++ b/packages/sync-files/package.json @@ -0,0 +1,55 @@ +{ + "name": "trainctl-sync-files", + "version": "0.3.0", + "description": "trainctl adapter for exported activity files (FIT, TCX, GPX): compare what you ran with the plan, no account needed", + "keywords": [ + "fit", + "tcx", + "gpx", + "garmin", + "strava", + "training-plan" + ], + "license": "MIT", + "author": "Dariusz Tyszka", + "homepage": "https://github.com/dithiothreitol/trainctl", + "repository": { + "type": "git", + "url": "git+https://github.com/dithiothreitol/trainctl.git", + "directory": "packages/sync-files" + }, + "bugs": { + "url": "https://github.com/dithiothreitol/trainctl/issues" + }, + "type": "module", + "engines": { + "node": ">=22.18.0" + }, + "exports": { + ".": "./src/index.ts" + }, + "files": [ + "dist", + "src/**/*.ts", + "!src/**/*.test.ts", + "!src/fit-fixture.ts", + "README.md", + "LICENSE" + ], + "publishConfig": { + "access": "public", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + } + } + }, + "dependencies": { + "trainctl-core": "workspace:*" + }, + "scripts": { + "build": "tsc -p tsconfig.build.json" + } +} diff --git a/packages/sync-files/src/activity.ts b/packages/sync-files/src/activity.ts new file mode 100644 index 0000000..cfd5287 --- /dev/null +++ b/packages/sync-files/src/activity.ts @@ -0,0 +1,106 @@ +/** + * Wspólny wynik parserów FIT/TCX/GPX — przed normalizacją do `SyncedActivity`. + * Jednostki „surowe" (metry, sekundy); zamianę na km i tempo robi `files.ts`. + * + * Nazewnictwo typów jak w intervals.icu/Stravie, bo CLI rozpoznaje bieg + * wyrażeniem `/^(run|running|trailrun|…|virtualrun|treadmill…)$/i` na `type`. + */ + +/** Typy, które parsery zwracają. Wszystko spoza listy trafia do `Other`. */ +export type ActivityType = + | 'Run' + | 'TrailRun' + | 'VirtualRun' + | 'Ride' + | 'Walk' + | 'Hike' + | 'Swim' + | 'WeightTraining' + | 'Other' + +export interface ParsedActivity { + /** Lokalna data startu `YYYY-MM-DD` (strefa: patrz README — ograniczenia TCX/GPX). */ + date: string + /** Chwila startu w UTC (ISO 8601) — do sortowania; `SyncedActivity` jej nie niesie. */ + startTime: string + type: ActivityType + /** Nazwa nadana aktywności w źródle (TCX `Notes`, GPX `trk/name`). FIT jej nie ma. */ + name?: string + distanceM?: number + /** Czas ruchu: FIT `total_timer_time`, TCX suma `TotalTimeSeconds`, GPX z punktów. */ + movingTimeSec?: number + elapsedTimeSec?: number + elevationGainM?: number + avgHr?: number +} + +export const isRunType = (type: ActivityType): boolean => + type === 'Run' || type === 'TrailRun' || type === 'VirtualRun' + +/** Fragment aktywności: sesja FIT albo `Activity` z multisportowego TCX. */ +export interface ActivityPart { + /** Start w ms od epoki uniksowej (UTC). */ + startMs: number + type: ActivityType + distanceM?: number + movingTimeSec?: number + elapsedTimeSec?: number + elevationGainM?: number + avgHr?: number +} + +const sum = (values: (number | undefined)[]): number | undefined => { + const present = values.filter((v): v is number => v !== undefined) + return present.length ? present.reduce((a, b) => a + b, 0) : undefined +} + +/** + * Multisport (triathlon, duathlon, brick): z planem biegowym porównujemy + * wyłącznie bieg, więc sumujemy tylko części biegowe — 40 km roweru nie może + * udawać 40 km biegu. Gdy części biegowych brak, sumujemy wszystkie, a typ + * bierzemy z pierwszej. Start zawsze z pierwszej części (data całego zdarzenia). + * Tętno: średnia ważona czasem ruchu (albo czasem całkowitym, gdy ruchu brak). + */ +export function combineParts(parts: ActivityPart[]): ActivityPart | undefined { + if (parts.length === 0) return undefined + const ordered = [...parts].sort((a, b) => a.startMs - b.startMs) + const first = ordered[0]! + if (ordered.length === 1) return first + const runs = ordered.filter((p) => isRunType(p.type)) + const chosen = runs.length > 0 ? runs : ordered + const combined: ActivityPart = { startMs: first.startMs, type: chosen[0]!.type } + const distanceM = sum(chosen.map((p) => p.distanceM)) + const movingTimeSec = sum(chosen.map((p) => p.movingTimeSec)) + const elapsedTimeSec = sum(chosen.map((p) => p.elapsedTimeSec)) + const elevationGainM = sum(chosen.map((p) => p.elevationGainM)) + if (distanceM !== undefined) combined.distanceM = distanceM + if (movingTimeSec !== undefined) combined.movingTimeSec = movingTimeSec + if (elapsedTimeSec !== undefined) combined.elapsedTimeSec = elapsedTimeSec + if (elevationGainM !== undefined) combined.elevationGainM = elevationGainM + let hrWeight = 0 + let hrSum = 0 + for (const p of chosen) { + const weight = p.movingTimeSec ?? p.elapsedTimeSec ?? 0 + if (p.avgHr === undefined || weight <= 0) continue + hrWeight += weight + hrSum += p.avgHr * weight + } + if (hrWeight > 0) combined.avgHr = hrSum / hrWeight + return combined +} + +/** Złożenie wyniku z części i daty — ten sam kształt dla FIT i TCX. */ +export function toParsed(part: ActivityPart, date: string, name?: string): ParsedActivity { + const parsed: ParsedActivity = { + date, + startTime: new Date(part.startMs).toISOString(), + type: part.type, + } + if (name) parsed.name = name + if (part.distanceM !== undefined) parsed.distanceM = part.distanceM + if (part.movingTimeSec !== undefined) parsed.movingTimeSec = Math.round(part.movingTimeSec) + if (part.elapsedTimeSec !== undefined) parsed.elapsedTimeSec = Math.round(part.elapsedTimeSec) + if (part.elevationGainM !== undefined) parsed.elevationGainM = Math.round(part.elevationGainM) + if (part.avgHr !== undefined) parsed.avgHr = Math.round(part.avgHr) + return parsed +} diff --git a/packages/sync-files/src/dates.ts b/packages/sync-files/src/dates.ts new file mode 100644 index 0000000..06c5dbf --- /dev/null +++ b/packages/sync-files/src/dates.ts @@ -0,0 +1,59 @@ +/** + * Data lokalna aktywności (`YYYY-MM-DD`) — po niej CLI łączy wykonanie z dniem planu. + * + * FIT niesie przesunięcie strefy (komunikat `activity`: local_timestamp − timestamp). + * TCX i GPX niosą zwykle sam czas UTC (`…Z`) — wtedy jedynym źródłem strefy + * jest strefa maszyny, na której działa CLI. Bieg o 23:30 w Lizbonie czytany + * w Warszawie trafi na następny dzień; to udokumentowane ograniczenie (README). + */ + +const pad = (n: number): string => String(n).padStart(2, '0') + +/** Data w strefie maszyny dla chwili `ms` (ms od epoki uniksowej). */ +export function localDateFromMs(ms: number): string { + const d = new Date(ms) + return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}` +} + +/** Data „ścienna" UTC przesunięta o `offsetSec` — dla FIT ze znaną strefą. */ +export function dateWithOffset(ms: number, offsetSec: number): string { + return new Date(ms + offsetSec * 1000).toISOString().slice(0, 10) +} + +const ISO = /^(\d{4}-\d{2}-\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:[.,](\d+))?)?\s*(Z|[+-]\d{2}(?::?\d{2})?)?$/i + +/** + * ISO 8601 → ms od epoki. Ułamki sekund przycinamy do milisekund (część + * eksporterów pisze mikrosekundy). Zwraca `undefined` dla nieczytelnego zapisu. + */ +export function parseIsoMs(iso: string): number | undefined { + const m = ISO.exec(iso.trim()) + if (!m) return undefined + const [, date, hh, mm, ss = '00', frac = '', zone = ''] = m + const ms = frac ? `.${frac.slice(0, 3).padEnd(3, '0')}` : '' + const z = zone.toUpperCase() === 'Z' || zone === '' ? zone.toUpperCase() : normaliseOffset(zone) + const value = Date.parse(`${date}T${hh}:${mm}:${ss}${ms}${z}`) + return Number.isFinite(value) ? value : undefined +} + +function normaliseOffset(zone: string): string { + const digits = zone.slice(1).replace(':', '') + const hours = digits.slice(0, 2) + const minutes = digits.slice(2, 4) || '00' + return `${zone[0]}${hours}:${minutes}` +} + +/** + * Data lokalna z zapisu ISO. + * - `Z` (albo `+00:00`, którym wiele bibliotek zapisuje UTC) → strefa maszyny. + * - Jawne przesunięcie ≠ 0 albo brak strefy → data tak, jak ją zapisano + * (to już czas ścienny miejsca aktywności). + */ +export function localDateFromIso(iso: string): string | undefined { + const m = ISO.exec(iso.trim()) + const ms = parseIsoMs(iso) + if (!m || ms === undefined) return undefined + const zone = (m[6] ?? '').toUpperCase() + const isUtc = zone === 'Z' || /^[+-]00(?::?00)?$/.test(zone) + return isUtc ? localDateFromMs(ms) : m[1] +} diff --git a/packages/sync-files/src/files.test.ts b/packages/sync-files/src/files.test.ts new file mode 100644 index 0000000..3452a8b --- /dev/null +++ b/packages/sync-files/src/files.test.ts @@ -0,0 +1,187 @@ +/** + * Skan katalogu na tymczasowym drzewie z syntetycznymi plikami. + */ +import { mkdirSync, mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { basename, join } from 'node:path' +import { gzipSync } from 'node:zlib' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { activityFit, FitBuilder, FILE_ID_FIELDS, fileIdValues } from './fit-fixture.ts' +import { MAX_FILE_BYTES, scanActivityFiles, type ScanResult } from './files.ts' + +const RUN_FIT = activityFit({ + sessions: [ + { start: '2026-09-14T05:00:00Z', sport: 1, timerSec: 3000, elapsedSec: 3100, distanceM: 10012.34, avgHr: 150 }, + ], + utcOffsetSec: 2 * 3600, +}) + +const RIDE_FIT = activityFit({ + sessions: [{ start: '2026-09-10T15:00:00Z', sport: 2, timerSec: 3600, distanceM: 30000 }], + utcOffsetSec: 2 * 3600, +}) + +const TRAIL_FIT = activityFit({ + sessions: [{ start: '2026-09-11T06:00:00Z', sport: 1, subSport: 3, timerSec: 1800, distanceM: 5000 }], + utcOffsetSec: 2 * 3600, +}) + +const tcx = (sport: string, start: string, notes?: string) => ` + + ${start} + 360030000 + ${notes ? `${notes}` : ''} + +` + +const WALK_GPX = ` +walking + + + +` + +const WORKOUT_FIT = new FitBuilder().define(0, 0, FILE_ID_FIELDS).data(0, fileIdValues(5, 0)).build() +const BROKEN_FIT = new FitBuilder().define(0, 0, FILE_ID_FIELDS).data(0, fileIdValues(4, 0)).build({ fileCrc: 'corrupt' }) + +let dir: string +let result: ScanResult + +beforeAll(() => { + dir = mkdtempSync(join(tmpdir(), 'trainctl-sync-files-')) + const put = (rel: string, content: Uint8Array | string) => { + const full = join(dir, rel) + mkdirSync(join(full, '..'), { recursive: true }) + writeFileSync(full, content) + } + put('2026/09/a-run.fit', RUN_FIT) + put('2026/09/b-copy.FIT', RUN_FIT) // ta sama treść pod inną nazwą + put('copy.fit.gz', gzipSync(RUN_FIT)) // i jeszcze raz, spakowana + put('ride.FIT', RIDE_FIT) + put('nested/deeper/trail.Fit.GZ', gzipSync(TRAIL_FIT)) + put('2026/ride.tcx.gz', gzipSync(tcx('Biking', '2026-09-12T08:00:00+02:00', 'Rower do pracy'))) + put('walk.gpx', WALK_GPX) + put('notes.txt', 'nie jest aktywnością') + put('summary.csv', 'id,date\n1,2026-09-14\n') + put('.hidden/secret.fit', RUN_FIT) + put('broken.fit', BROKEN_FIT) + put('workout.fit', WORKOUT_FIT) + put('bad.gpx.gz', 'to nie jest gzip') + put('empty.tcx', '') + put('bomb.fit.gz', gzipSync(Buffer.alloc(MAX_FILE_BYTES + 1024))) + put('huge.gpx', '') + truncateSync(join(dir, 'huge.gpx'), MAX_FILE_BYTES + 1) + result = scanActivityFiles(dir) +}) + +afterAll(() => { + // Windows potrafi chwilowo trzymać uchwyt (EBUSY) — stąd ponowienia. + rmSync(dir, { recursive: true, force: true, maxRetries: 5 }) +}) + +describe('scanActivityFiles: katalog', () => { + it('rekurencyjnie, z wariantami .gz i dowolną wielkością liter; posortowane po dacie', () => { + expect(result.activities.map((a) => [a.date, a.type])).toEqual([ + ['2026-09-10', 'Ride'], + ['2026-09-11', 'TrailRun'], + ['2026-09-12', 'Ride'], + ['2026-09-13', 'Walk'], + ['2026-09-14', 'Run'], + ]) + }) + + it('ta sama aktywność trzy razy (dwie nazwy + .gz) → jeden wpis, id z treści', () => { + const runs = result.activities.filter((a) => a.type === 'Run') + expect(runs).toHaveLength(1) + expect(runs[0]!.externalId).toMatch(/^file-[0-9a-f]{16}$/) + // pierwszy w kolejności przejścia (katalogi i pliki alfabetycznie) + expect(runs[0]!.name).toBe('a-run') + const ids = result.activities.map((a) => a.externalId) + expect(new Set(ids).size).toBe(ids.length) + }) + + it('normalizacja do SyncedActivity: km do 2 miejsc, tempo z czasu ruchu, źródło file', () => { + const run = result.activities.find((a) => a.type === 'Run')! + expect(run).toEqual({ + externalId: run.externalId, + date: '2026-09-14', + type: 'Run', + name: 'a-run', + source: 'file', + distanceKm: 10.01, + movingTimeSec: 3000, + elapsedTimeSec: 3100, + avgHr: 150, + // 3000 s / 10,01234 km = 299,6 → 300 + avgPaceSecPerKm: 300, + }) + }) + + it('nazwa: z pliku, gdy ją niesie (TCX Notes), inaczej nazwa pliku bez rozszerzenia', () => { + const byDate = Object.fromEntries(result.activities.map((a) => [a.date, a.name])) + expect(byDate['2026-09-12']).toBe('Rower do pracy') + expect(byDate['2026-09-11']).toBe('trail') + expect(byDate['2026-09-13']).toBe('walk') + }) + + it('pominięte pliki z powodem; obce rozszerzenia i pliki ukryte — po cichu', () => { + const skipped = result.skipped.map((s) => [basename(s.file), s.reason]).sort() + expect(skipped).toEqual( + [ + ['bad.gpx.gz', 'unreadable'], + ['bomb.fit.gz', 'unsupported'], + ['broken.fit', 'unreadable'], + ['empty.tcx', 'not-an-activity'], + ['huge.gpx', 'unsupported'], + ['workout.fit', 'not-an-activity'], + ].sort(), + ) + const all = JSON.stringify(result) + expect(all).not.toContain('notes.txt') + expect(all).not.toContain('summary.csv') + expect(all).not.toContain('secret') + }) +}) + +describe('scanActivityFiles: pojedynczy plik', () => { + it('wskazany plik aktywności', () => { + const one = scanActivityFiles(join(dir, 'walk.gpx')) + expect(one.activities).toHaveLength(1) + expect(one.activities[0]!.type).toBe('Walk') + expect(one.skipped).toEqual([]) + }) + + it('id nie zależy od nazwy ani od spakowania', () => { + const plain = scanActivityFiles(join(dir, '2026', '09', 'b-copy.FIT')).activities[0]! + const packed = scanActivityFiles(join(dir, 'copy.fit.gz')).activities[0]! + expect(plain.externalId).toBe(packed.externalId) + expect(plain.name).toBe('b-copy') + }) + + it('wskazany wprost plik o obcym rozszerzeniu → unsupported', () => { + const one = scanActivityFiles(join(dir, 'notes.txt')) + expect(one.activities).toEqual([]) + expect(one.skipped).toEqual([{ file: join(dir, 'notes.txt'), reason: 'unsupported' }]) + }) + + it('uszkodzony plik nie rzuca — trafia do skipped', () => { + expect(scanActivityFiles(join(dir, 'broken.fit')).skipped).toEqual([ + { file: join(dir, 'broken.fit'), reason: 'unreadable' }, + ]) + }) + + it('kodowanie z prologu XML (windows-1250) — polskie znaki w nazwie przeżywają', () => { + const [head, tail] = tcx('Running', '2026-09-15T06:00:00+02:00', 'Bieg z@bkowy') + .replace('encoding="UTF-8"', 'encoding="windows-1250"') + .split('@') + // „ą" w windows-1250 to jeden bajt 0xB9 — jako UTF-8 byłby nieczytelny + const bytes = Buffer.concat([Buffer.from(head!, 'latin1'), Buffer.from([0xb9]), Buffer.from(tail!, 'latin1')]) + const file = join(dir, 'cp1250.tcx') + writeFileSync(file, bytes) + expect(scanActivityFiles(file).activities[0]!.name).toBe('Bieg ząbkowy') + }) + + it('nieistniejąca ścieżka to błąd konfiguracji — wyjątek ENOENT', () => { + expect(() => scanActivityFiles(join(dir, 'nie-ma-mnie'))).toThrow(/ENOENT/) + }) +}) diff --git a/packages/sync-files/src/files.ts b/packages/sync-files/src/files.ts new file mode 100644 index 0000000..e3b5abb --- /dev/null +++ b/packages/sync-files/src/files.ts @@ -0,0 +1,199 @@ +/** + * Skan katalogu z wyeksportowanymi aktywnościami (eksport zbiorczy Stravy, + * Garmin Connect, Coros, Polar Flow…) → znormalizowane `SyncedActivity`. + * + * Zasada: pojedynczy zły plik nigdy nie przerywa skanu — trafia do `skipped` + * z powodem, który CLI zamienia na komunikat. Wyjątek leci tylko wtedy, gdy + * wskazanej ścieżki nie ma wcale (to błąd konfiguracji, nie pliku). + */ +import { createHash } from 'node:crypto' +import { readdirSync, readFileSync, statSync } from 'node:fs' +import { basename, join } from 'node:path' +import { gunzipSync } from 'node:zlib' +import type { SyncedActivity } from 'trainctl-core' +import type { ParsedActivity } from './activity.ts' +import { parseFitActivity } from './fit.ts' +import { parseGpxActivity } from './gpx.ts' +import { parseTcxActivity } from './tcx.ts' + +export type SkipReason = 'unreadable' | 'not-an-activity' | 'unsupported' + +export interface SkippedFile { + file: string + reason: SkipReason +} + +export interface ScanResult { + activities: SyncedActivity[] + skipped: SkippedFile[] +} + +/** + * Wartość inżynierska: górna granica rozmiaru pliku i treści po rozpakowaniu + * `.gz` (ochrona przed „bombą" gzip). Większy plik pomijamy jako `unsupported`, + * zamiast wczytywać go w całości do pamięci. + */ +export const MAX_FILE_BYTES = 50 * 1024 * 1024 + +type Format = 'fit' | 'tcx' | 'gpx' + +interface FileKind { + format: Format + gzip: boolean + /** Nazwa pliku bez rozszerzenia aktywności (`123.fit.gz` → `123`). */ + stem: string +} + +const FORMATS: Format[] = ['fit', 'tcx', 'gpx'] + +/** Porównanie po kodach znaków — niezależne od locale maszyny (kolejność deterministyczna). */ +const compare = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0) + +export function activityFileKind(fileName: string): FileKind | undefined { + const lower = fileName.toLowerCase() + for (const format of FORMATS) { + if (lower.endsWith(`.${format}`)) return { format, gzip: false, stem: fileName.slice(0, -(format.length + 1)) } + if (lower.endsWith(`.${format}.gz`)) return { format, gzip: true, stem: fileName.slice(0, -(format.length + 4)) } + } + return undefined +} + +/** + * Pliki ukryte i katalogi ukryte (`.git`, `._plik.fit` z macOS) pomijamy — + * wartość inżynierska: to śmieci systemowe, nie eksporty aktywności. + * Dowiązań do katalogów nie śledzimy (ochrona przed pętlą). + */ +function walk(dir: string, files: string[], skipped: SkippedFile[]): void { + let entries + try { + entries = readdirSync(dir, { withFileTypes: true }) + } catch { + skipped.push({ file: dir, reason: 'unreadable' }) + return + } + entries.sort((a, b) => compare(a.name, b.name)) + for (const entry of entries) { + if (entry.name.startsWith('.')) continue + const full = join(dir, entry.name) + if (entry.isDirectory()) walk(full, files, skipped) + else if (entry.isFile() || entry.isSymbolicLink()) files.push(full) + } +} + +/** XML w kodowaniu z prologu (`encoding="windows-1250"`), domyślnie UTF-8 (BOM zdejmuje TextDecoder). */ +function decodeXml(bytes: Uint8Array): string { + const head = new TextDecoder('latin1').decode(bytes.subarray(0, 256)) + const label = /<\?xml[^>]*\bencoding\s*=\s*["']([\w.:-]+)["']/i.exec(head)?.[1] + if (label) { + try { + return new TextDecoder(label).decode(bytes) + } catch { + // nieznana etykieta kodowania — próbujemy UTF-8 + } + } + return new TextDecoder('utf-8').decode(bytes) +} + +function parse(format: Format, bytes: Uint8Array): ParsedActivity | undefined { + switch (format) { + case 'fit': + return parseFitActivity(bytes) + case 'tcx': + return parseTcxActivity(decodeXml(bytes)) + case 'gpx': + return parseGpxActivity(decodeXml(bytes)) + } +} + +type Outcome = { parsed: ParsedActivity; externalId: string } | { reason: SkipReason } + +function readActivityFile(file: string, kind: FileKind): Outcome { + let raw: Uint8Array + try { + if (statSync(file).size > MAX_FILE_BYTES) return { reason: 'unsupported' } + raw = readFileSync(file) + } catch { + return { reason: 'unreadable' } + } + let bytes = raw + if (kind.gzip) { + try { + bytes = gunzipSync(raw, { maxOutputLength: MAX_FILE_BYTES }) + } catch (error) { + const tooLarge = (error as { code?: string }).code === 'ERR_BUFFER_TOO_LARGE' + return { reason: tooLarge ? 'unsupported' : 'unreadable' } + } + } + let parsed: ParsedActivity | undefined + try { + parsed = parse(kind.format, bytes) + } catch { + return { reason: 'unreadable' } + } + if (!parsed) return { reason: 'not-an-activity' } + // Skrót z TREŚCI (po rozpakowaniu): stabilny przy zmianie nazwy, a ta sama + // aktywność wyeksportowana dwa razy (np. `.fit` i `.fit.gz`) daje jeden wpis. + const externalId = 'file-' + createHash('sha1').update(bytes).digest('hex').slice(0, 16) + return { parsed, externalId } +} + +function toSynced(parsed: ParsedActivity, externalId: string, fallbackName: string): SyncedActivity { + const activity: SyncedActivity = { + externalId, + date: parsed.date, + type: parsed.type, + name: parsed.name ?? fallbackName, + source: 'file', + } + if (parsed.distanceM !== undefined) activity.distanceKm = Math.round(parsed.distanceM / 10) / 100 + if (parsed.movingTimeSec !== undefined) activity.movingTimeSec = parsed.movingTimeSec + if (parsed.elapsedTimeSec !== undefined) activity.elapsedTimeSec = parsed.elapsedTimeSec + if (parsed.elevationGainM !== undefined) activity.elevationGainM = parsed.elevationGainM + if (parsed.avgHr !== undefined) activity.avgHr = parsed.avgHr + if (parsed.distanceM !== undefined && parsed.distanceM > 0 && parsed.movingTimeSec) { + activity.avgPaceSecPerKm = Math.round(parsed.movingTimeSec / (parsed.distanceM / 1000)) + } + return activity +} + +/** + * Katalog (rekurencyjnie) albo pojedynczy plik → aktywności posortowane po dacie. + * Rozszerzenia: `.fit .tcx .gpx` i ich warianty `.gz`, bez względu na wielkość liter. + * W katalogu inne pliki są ignorowane; wskazany wprost plik o innym + * rozszerzeniu trafia do `skipped` jako `unsupported`. + * Rzuca błąd systemu plików (np. `ENOENT`), gdy samej ścieżki nie ma. + */ +export function scanActivityFiles(path: string): ScanResult { + const skipped: SkippedFile[] = [] + const candidates: string[] = [] + if (statSync(path).isDirectory()) { + walk(path, candidates, skipped) + } else if (activityFileKind(basename(path))) { + candidates.push(path) + } else { + skipped.push({ file: path, reason: 'unsupported' }) + } + + const seen = new Set() + const found: { parsed: ParsedActivity; activity: SyncedActivity }[] = [] + for (const file of candidates) { + const kind = activityFileKind(basename(file)) + if (!kind) continue + const outcome = readActivityFile(file, kind) + if ('reason' in outcome) { + skipped.push({ file, reason: outcome.reason }) + continue + } + if (seen.has(outcome.externalId)) continue + seen.add(outcome.externalId) + found.push({ parsed: outcome.parsed, activity: toSynced(outcome.parsed, outcome.externalId, kind.stem) }) + } + + found.sort( + (a, b) => + compare(a.activity.date, b.activity.date) || + compare(a.parsed.startTime, b.parsed.startTime) || + compare(a.activity.externalId, b.activity.externalId), + ) + return { activities: found.map((f) => f.activity), skipped } +} diff --git a/packages/sync-files/src/fit-fixture.ts b/packages/sync-files/src/fit-fixture.ts new file mode 100644 index 0000000..5c0e219 --- /dev/null +++ b/packages/sync-files/src/fit-fixture.ts @@ -0,0 +1,273 @@ +/** + * Testowy koder plików FIT — WYŁĄCZNIE do syntetycznych fixture'ów (żadnych + * realnych aktywności w repo). Poza buildem i paczką: tsconfig.build.json + * i `files` w package.json go wykluczają. + * + * Celowo niezależny od dekodera: CRC liczone bitowo (CRC-16/ARC — wielomian + * 0xA001 w odwróconej postaci, start 0), a nie tablicą po półbajtach jak + * w `fit.ts`, żeby test nie potwierdzał błędu tym samym kodem. + */ + +const FIT_EPOCH_OFFSET_SEC = 631065600 + +export const BASE = { + enum: 0x00, + sint8: 0x01, + uint8: 0x02, + sint16: 0x83, + uint16: 0x84, + sint32: 0x85, + uint32: 0x86, + string: 0x07, + uint32z: 0x8c, +} as const + +export type BaseName = keyof typeof BASE + +const SIZE: Record = { + enum: 1, + sint8: 1, + uint8: 1, + sint16: 2, + uint16: 2, + sint32: 4, + uint32: 4, + string: 1, + uint32z: 4, +} + +/** Wartość „invalid" — wpisywana, gdy test poda `undefined`. */ +const INVALID: Record = { + enum: 0xff, + sint8: 0x7f, + uint8: 0xff, + sint16: 0x7fff, + uint16: 0xffff, + sint32: 0x7fffffff, + uint32: 0xffffffff, + string: 0, + uint32z: 0, +} + +export interface FieldSpec { + num: number + type: BaseName + /** Rozmiar w bajtach (domyślnie rozmiar typu; większy = tablica). */ + size?: number +} + +export interface DevFieldSpec { + num: number + size: number + devIndex: number +} + +interface Def { + fields: FieldSpec[] + bigEndian: boolean + devSize: number +} + +export function crc16Arc(bytes: ArrayLike): number { + let crc = 0 + for (let i = 0; i < bytes.length; i++) { + crc ^= bytes[i]! + for (let bit = 0; bit < 8; bit++) crc = crc & 1 ? (crc >>> 1) ^ 0xa001 : crc >>> 1 + } + return crc +} + +/** ISO 8601 (UTC) → sekundy od epoki FIT. */ +export const fitTime = (iso: string): number => Date.parse(iso) / 1000 - FIT_EPOCH_OFFSET_SEC + +export class FitBuilder { + private readonly body: number[] = [] + private readonly defs = new Map() + + private int(value: number, size: number, bigEndian: boolean): void { + const bytes: number[] = [] + let v = BigInt.asUintN(size * 8, BigInt(Math.trunc(value))) + for (let i = 0; i < size; i++) { + bytes.push(Number(v & 0xffn)) + v >>= 8n + } + this.body.push(...(bigEndian ? bytes.reverse() : bytes)) + } + + define( + local: number, + global: number, + fields: FieldSpec[], + opts: { bigEndian?: boolean; devFields?: DevFieldSpec[] } = {}, + ): this { + const bigEndian = opts.bigEndian ?? false + const dev = opts.devFields ?? [] + this.body.push(0x40 | (dev.length ? 0x20 : 0) | local, 0, bigEndian ? 1 : 0) + this.int(global, 2, bigEndian) + this.body.push(fields.length) + for (const f of fields) this.body.push(f.num, f.size ?? SIZE[f.type], BASE[f.type]) + if (dev.length) { + this.body.push(dev.length) + for (const d of dev) this.body.push(d.num, d.size, d.devIndex) + } + this.defs.set(local, { fields, bigEndian, devSize: dev.reduce((a, d) => a + d.size, 0) }) + return this + } + + private values(local: number, values: (number | undefined)[], devBytes?: number[]): void { + const def = this.defs.get(local) + if (!def) throw new Error(`fixture: no definition for local ${local}`) + def.fields.forEach((f, i) => { + const size = f.size ?? SIZE[f.type] + const value = values[i] ?? INVALID[f.type] + const element = SIZE[f.type] + // Tablica: pierwszy element z wartością, reszta „invalid". + this.int(value, element, def.bigEndian) + for (let at = element; at < size; at += element) this.int(INVALID[f.type], element, def.bigEndian) + }) + const dev = devBytes ?? new Array(def.devSize).fill(0) + if (dev.length !== def.devSize) throw new Error('fixture: developer bytes do not match the definition') + this.body.push(...dev) + } + + data(local: number, values: (number | undefined)[], devBytes?: number[]): this { + this.body.push(local & 0x0f) + this.values(local, values, devBytes) + return this + } + + /** Rekord ze skompresowanym czasem: typ lokalny 0–3, przesunięcie 0–31. */ + compressed(local: number, offset: number, values: (number | undefined)[]): this { + this.body.push(0x80 | ((local & 0x03) << 5) | (offset & 0x1f)) + this.values(local, values) + return this + } + + /** Surowe bajty — do składania celowo uszkodzonych plików. */ + raw(...bytes: number[]): this { + this.body.push(...bytes) + return this + } + + build( + opts: { headerSize?: 12 | 14; headerCrc?: 'valid' | 'zero' | 'corrupt'; fileCrc?: 'valid' | 'corrupt' | 'omit' } = {}, + ): Uint8Array { + const headerSize = opts.headerSize ?? 14 + const header: number[] = [headerSize, 0x20] + header.push(2132 & 0xff, 2132 >> 8) // wersja profilu (dowolna — dekoder jej nie sprawdza) + const n = this.body.length + header.push(n & 0xff, (n >> 8) & 0xff, (n >> 16) & 0xff, (n >>> 24) & 0xff) + header.push(...[...'.FIT'].map((c) => c.charCodeAt(0))) + if (headerSize === 14) { + const mode = opts.headerCrc ?? 'valid' + const crc = mode === 'zero' ? 0 : crc16Arc(header) ^ (mode === 'corrupt' ? 0x5555 : 0) + header.push(crc & 0xff, crc >> 8) + } + const file = [...header, ...this.body] + const mode = opts.fileCrc ?? 'valid' + if (mode !== 'omit') { + const crc = crc16Arc(file) ^ (mode === 'corrupt' ? 0x0101 : 0) + file.push(crc & 0xff, crc >> 8) + } + return Uint8Array.from(file) + } +} + +// ------------------------------------------------- typowy plik aktywności + +export interface SessionSpec { + start: string + sport: number + subSport?: number + elapsedSec?: number + timerSec?: number + distanceM?: number + avgHr?: number + ascentM?: number +} + +export interface ActivitySpec { + /** file_id.type; 4 = activity (domyślnie). */ + fileType?: number + sessions: SessionSpec[] + /** Przesunięcie strefy w komunikacie `activity`; `undefined` = brak komunikatu. */ + utcOffsetSec?: number + bigEndian?: boolean + /** Pola deweloperskie w definicji sesji (rozmiary w bajtach). */ + devFieldSizes?: number[] +} + +export const FILE_ID_FIELDS: FieldSpec[] = [ + { num: 0, type: 'enum' }, // type + { num: 1, type: 'uint16' }, // manufacturer + { num: 2, type: 'uint16' }, // product + { num: 3, type: 'uint32z' }, // serial_number + { num: 4, type: 'uint32' }, // time_created +] + +export const SESSION_FIELDS: FieldSpec[] = [ + { num: 253, type: 'uint32' }, // timestamp + { num: 2, type: 'uint32' }, // start_time + { num: 5, type: 'enum' }, // sport + { num: 6, type: 'enum' }, // sub_sport + { num: 7, type: 'uint32' }, // total_elapsed_time (ms) + { num: 8, type: 'uint32' }, // total_timer_time (ms) + { num: 9, type: 'uint32' }, // total_distance (cm) + { num: 16, type: 'uint8' }, // avg_heart_rate + { num: 22, type: 'uint16' }, // total_ascent +] + +export const ACTIVITY_FIELDS: FieldSpec[] = [ + { num: 253, type: 'uint32' }, // timestamp + { num: 0, type: 'uint32' }, // total_timer_time (ms) + { num: 1, type: 'uint16' }, // num_sessions + { num: 5, type: 'uint32' }, // local_timestamp +] + +export function fileIdValues(fileType: number, created: number): number[] { + return [fileType, 255, 0, 12345, created] +} + +export function sessionValues(s: SessionSpec): (number | undefined)[] { + const start = fitTime(s.start) + const scale = (v: number | undefined, k: number) => (v === undefined ? undefined : Math.round(v * k)) + return [ + start + (s.elapsedSec ?? 0), + start, + s.sport, + s.subSport ?? 0, + scale(s.elapsedSec, 1000), + scale(s.timerSec, 1000), + scale(s.distanceM, 100), + s.avgHr, + s.ascentM, + ] +} + +/** Plik aktywności: file_id → sesje → activity (z przesunięciem strefy). */ +export function activityFit(spec: ActivitySpec): Uint8Array { + const bigEndian = spec.bigEndian ?? false + const first = spec.sessions[0] + const created = first ? fitTime(first.start) : 0 + const b = new FitBuilder() + .define(0, 0, FILE_ID_FIELDS, { bigEndian }) + .data(0, fileIdValues(spec.fileType ?? 4, created)) + const devFields = (spec.devFieldSizes ?? []).map((size, i) => ({ num: i, size, devIndex: 0 })) + b.define(1, 18, SESSION_FIELDS, { bigEndian, devFields }) + let end = created + for (const s of spec.sessions) { + const devBytes = devFields.length ? devFields.flatMap((d) => new Array(d.size).fill(0xab)) : undefined + b.data(1, sessionValues(s), devBytes) + end = Math.max(end, fitTime(s.start) + (s.elapsedSec ?? 0)) + } + if (spec.utcOffsetSec !== undefined) { + const timer = spec.sessions.reduce((a, s) => a + (s.timerSec ?? 0), 0) + b.define(2, 34, ACTIVITY_FIELDS, { bigEndian }).data(2, [ + end, + Math.round(timer * 1000), + spec.sessions.length, + end + spec.utcOffsetSec, + ]) + } + return b.build() +} diff --git a/packages/sync-files/src/fit.test.ts b/packages/sync-files/src/fit.test.ts new file mode 100644 index 0000000..a1e90ed --- /dev/null +++ b/packages/sync-files/src/fit.test.ts @@ -0,0 +1,281 @@ +/** + * Dekoder FIT na syntetycznych plikach z testowego kodera (fit-fixture.ts). + * Żadnych realnych aktywności — wszystkie wartości są wymyślone. + */ +import { describe, expect, it } from 'vitest' +import { localDateFromMs } from './dates.ts' +import { fitCrc, parseFitActivity } from './fit.ts' +import { + ACTIVITY_FIELDS, + FILE_ID_FIELDS, + FitBuilder, + SESSION_FIELDS, + activityFit, + crc16Arc, + fileIdValues, + fitTime, + sessionValues, + type SessionSpec, +} from './fit-fixture.ts' + +const RUN: SessionSpec = { + start: '2026-09-14T22:30:00Z', + sport: 1, + elapsedSec: 3150, + timerSec: 3000, + distanceM: 10012.34, + avgHr: 152, + ascentM: 85, +} + +describe('CRC', () => { + it('tablicowy CRC dekodera = CRC-16/ARC (wartość kontrolna 0xBB3D dla „123456789")', () => { + const check = new TextEncoder().encode('123456789') + expect(fitCrc(check)).toBe(0xbb3d) + expect(crc16Arc(check)).toBe(0xbb3d) + }) +}) + +describe('parseFitActivity: bieg', () => { + it('sesja biegowa: dystans, czas stopera vs całkowity, tętno, podejścia', () => { + const a = parseFitActivity(activityFit({ sessions: [RUN], utcOffsetSec: 2 * 3600 }))! + expect(a).toMatchObject({ + type: 'Run', + startTime: '2026-09-14T22:30:00.000Z', + distanceM: 10012.34, + movingTimeSec: 3000, + elapsedTimeSec: 3150, + avgHr: 152, + elevationGainM: 85, + }) + }) + + it('data lokalna z local_timestamp: 22:30 UTC przy UTC+2 to już następny dzień', () => { + const a = parseFitActivity(activityFit({ sessions: [RUN], utcOffsetSec: 2 * 3600 }))! + expect(a.date).toBe('2026-09-15') + }) + + it('data lokalna przy ujemnym przesunięciu: 02:00 UTC przy UTC−5 to poprzedni dzień', () => { + const a = parseFitActivity( + activityFit({ sessions: [{ ...RUN, start: '2026-09-15T02:00:00Z' }], utcOffsetSec: -5 * 3600 }), + )! + expect(a.date).toBe('2026-09-14') + }) + + it('bez komunikatu activity — data w strefie maszyny', () => { + const a = parseFitActivity(activityFit({ sessions: [RUN] }))! + expect(a.date).toBe(localDateFromMs(Date.parse(RUN.start))) + }) + + it('wartości „invalid" (0xFF tętno, 0xFFFF podejścia) to brak pola, nie liczba', () => { + const a = parseFitActivity( + activityFit({ sessions: [{ start: RUN.start, sport: 1, timerSec: 600, distanceM: 2000 }], utcOffsetSec: 0 }), + )! + expect(a.avgHr).toBeUndefined() + expect(a.elevationGainM).toBeUndefined() + expect(a.elapsedTimeSec).toBeUndefined() + expect(a.distanceM).toBe(2000) + }) + + it.each([ + [1, 0, 'Run'], + [1, 3, 'TrailRun'], + [1, 1, 'VirtualRun'], + [1, 45, 'VirtualRun'], + [1, 58, 'VirtualRun'], + [2, 0, 'Ride'], + [11, 0, 'Walk'], + [17, 0, 'Hike'], + [5, 17, 'Swim'], + [4, 20, 'WeightTraining'], + [10, 20, 'WeightTraining'], + [4, 15, 'Other'], + [15, 0, 'Other'], + ])('sport %i / sub_sport %i → %s', (sport, subSport, type) => { + const a = parseFitActivity(activityFit({ sessions: [{ ...RUN, sport, subSport }], utcOffsetSec: 0 }))! + expect(a.type).toBe(type) + }) +}) + +describe('parseFitActivity: format', () => { + it('definicje big-endian dają ten sam wynik co little-endian', () => { + const little = parseFitActivity(activityFit({ sessions: [RUN], utcOffsetSec: 3600 })) + const big = parseFitActivity(activityFit({ sessions: [RUN], utcOffsetSec: 3600, bigEndian: true })) + expect(big).toEqual(little) + expect(big?.distanceM).toBe(10012.34) + }) + + it('pola deweloperskie są pomijane po rozmiarach — kolejne komunikaty czytają się poprawnie', () => { + const a = parseFitActivity(activityFit({ sessions: [RUN], utcOffsetSec: 2 * 3600, devFieldSizes: [4, 1, 7] }))! + expect(a.distanceM).toBe(10012.34) + expect(a.avgHr).toBe(152) + // `activity` stoi PO sesji z polami deweloperskimi — przesunięcie strefy musi przetrwać + expect(a.date).toBe('2026-09-15') + }) + + it('nagłówek 12-bajtowy (bez CRC nagłówka)', () => { + const b = new FitBuilder() + .define(0, 0, FILE_ID_FIELDS) + .data(0, fileIdValues(4, fitTime(RUN.start))) + .define(1, 18, SESSION_FIELDS) + .data(1, sessionValues(RUN)) + expect(parseFitActivity(b.build({ headerSize: 12 }))?.distanceM).toBe(10012.34) + }) + + it('CRC nagłówka 0x0000 jest dozwolone, plik bez CRC końcowego też', () => { + const b = () => + new FitBuilder() + .define(0, 0, FILE_ID_FIELDS) + .data(0, fileIdValues(4, 0)) + .define(1, 18, SESSION_FIELDS) + .data(1, sessionValues(RUN)) + expect(parseFitActivity(b().build({ headerCrc: 'zero' }))?.type).toBe('Run') + expect(parseFitActivity(b().build({ fileCrc: 'omit' }))?.type).toBe('Run') + }) + + it('uszkodzenia → wyjątek: CRC pliku, niezerowe złe CRC nagłówka, sygnatura, ucięcie', () => { + const good = activityFit({ sessions: [RUN], utcOffsetSec: 0 }) + const b = () => new FitBuilder().define(0, 0, FILE_ID_FIELDS).data(0, fileIdValues(4, 0)) + expect(() => parseFitActivity(b().build({ fileCrc: 'corrupt' }))).toThrow(/CRC/) + expect(() => parseFitActivity(b().build({ headerCrc: 'corrupt' }))).toThrow(/header CRC/) + const noSignature = good.slice() + noSignature[8] = 0x2a + expect(() => parseFitActivity(noSignature)).toThrow(/signature/) + expect(() => parseFitActivity(good.slice(0, good.length - 20))).toThrow() + expect(() => parseFitActivity(new Uint8Array(5))).toThrow() + }) + + it('rekord danych bez definicji → wyjątek', () => { + const bytes = new FitBuilder().raw(0x03, 0x00).build() + expect(() => parseFitActivity(bytes)).toThrow(/definition/) + }) + + it('file_id.type ≠ 4 (np. 5 = trening) → nie jest aktywnością', () => { + expect(parseFitActivity(activityFit({ fileType: 5, sessions: [RUN], utcOffsetSec: 0 }))).toBeUndefined() + }) + + it('brak file_id → nie jest aktywnością', () => { + const bytes = new FitBuilder().define(1, 18, SESSION_FIELDS).data(1, sessionValues(RUN)).build() + expect(parseFitActivity(bytes)).toBeUndefined() + }) +}) + +describe('parseFitActivity: multisport', () => { + it('bieg + rower + bieg: sumujemy tylko bieg, typ Run, start z pierwszej sesji', () => { + const a = parseFitActivity( + activityFit({ + sessions: [ + { start: '2026-09-20T07:00:00Z', sport: 1, timerSec: 1500, elapsedSec: 1510, distanceM: 5000, avgHr: 160 }, + { start: '2026-09-20T07:26:00Z', sport: 2, timerSec: 2400, elapsedSec: 2420, distanceM: 20000, avgHr: 150 }, + { start: '2026-09-20T08:07:00Z', sport: 1, timerSec: 800, elapsedSec: 805, distanceM: 2500, avgHr: 170 }, + ], + utcOffsetSec: 3600, + }), + )! + expect(a.type).toBe('Run') + expect(a.distanceM).toBe(7500) + expect(a.movingTimeSec).toBe(2300) + expect(a.elapsedTimeSec).toBe(2315) + // tętno ważone czasem stopera: (160·1500 + 170·800) / 2300 ≈ 163,5 + expect(a.avgHr).toBe(163) + expect(a.startTime).toBe('2026-09-20T07:00:00.000Z') + expect(a.date).toBe('2026-09-20') + }) + + it('multisport bez biegu: suma wszystkich części, typ z pierwszej', () => { + const a = parseFitActivity( + activityFit({ + sessions: [ + { start: '2026-09-20T07:00:00Z', sport: 5, timerSec: 900, distanceM: 1500 }, + { start: '2026-09-20T07:20:00Z', sport: 2, timerSec: 3600, distanceM: 30000 }, + ], + utcOffsetSec: 0, + }), + )! + expect(a.type).toBe('Swim') + expect(a.distanceM).toBe(31500) + }) +}) + +describe('parseFitActivity: bez sesji (punkty record)', () => { + const RECORD_FULL = [ + { num: 253, type: 'uint32' as const }, + { num: 5, type: 'uint32' as const }, // distance (cm) + { num: 3, type: 'uint8' as const }, // heart_rate + { num: 2, type: 'uint16' as const }, // altitude (skala 5, offset 500) + ] + const alt = (m: number) => Math.round((m + 500) * 5) + + it('dystans z ostatniego punktu, pauza > 60 s poza czasem ruchu, sport z komunikatu sport', () => { + const t0 = fitTime('2026-09-16T05:00:00Z') + const b = new FitBuilder() + .define(0, 0, FILE_ID_FIELDS) + .data(0, fileIdValues(4, t0)) + .define(3, 12, [ + { num: 0, type: 'enum' }, + { num: 1, type: 'enum' }, + ]) + .data(3, [1, 3]) // running / trail + .define(1, 20, RECORD_FULL) + const points: [number, number, number, number][] = [ + // [s od startu, m, tętno, wysokość] + [0, 0, 120, 100], + [10, 30, 130, 101], + [20, 60, 140, 103], + [30, 90, 150, 103.4], + [200, 95, 110, 103], // 170 s przerwy — pauza + [210, 125, 140, 105], + [220, 155, 150, 106], + ] + for (const [dt, d, hr, a] of points) b.data(1, [t0 + dt, d * 100, hr, alt(a)]) + const a = parseFitActivity(b.build())! + expect(a.type).toBe('TrailRun') + expect(a.distanceM).toBe(155) + expect(a.elapsedTimeSec).toBe(220) + expect(a.movingTimeSec).toBe(50) + expect(a.avgHr).toBe(Math.round((120 + 130 + 140 + 150 + 110 + 140 + 150) / 7)) + // histereza 1 m: 100→101 (+1), →103 (+2), 103,4 i 103 to szum, →105 (+2), →106 (+1) + expect(a.elevationGainM).toBe(6) + expect(a.startTime).toBe('2026-09-16T05:00:00.000Z') + }) + + it('skompresowany znacznik czasu, także z przeniesieniem przez granicę 32 s', () => { + // t0 ≡ 28 (mod 32), żeby przesunięcia 29, 31, 1, 5 dawały +1, +3, +5 (przeniesienie), +9 + let t0 = fitTime('2026-09-17T06:00:00Z') + t0 += (28 - (t0 % 32) + 32) % 32 + const b = new FitBuilder() + .define(0, 0, FILE_ID_FIELDS) + .data(0, fileIdValues(4, t0)) + .define(1, 20, [ + { num: 253, type: 'uint32' }, + { num: 5, type: 'uint32' }, + ]) + .data(1, [t0, 0]) + .define(2, 20, [{ num: 5, type: 'uint32' }]) // bez timestamp — czas z nagłówka + .compressed(2, 29, [300]) + .compressed(2, 31, [900]) + .compressed(2, 1, [1500]) + .compressed(2, 5, [2700]) + const a = parseFitActivity(b.build())! + expect(a.elapsedTimeSec).toBe(9) + expect(a.movingTimeSec).toBe(9) + expect(a.distanceM).toBe(27) + // brak komunikatu sport: heurystyka tempa (3 m/s ≈ 5:33 min/km → bieg) + expect(a.type).toBe('Run') + }) + + it('skompresowany znacznik bez wcześniejszego pełnego → wyjątek', () => { + const b = new FitBuilder() + .define(0, 0, FILE_ID_FIELDS) + .data(0, fileIdValues(4, 0)) // file_id nie ma pola 253 — to nie jest punkt odniesienia + .define(2, 20, [{ num: 5, type: 'uint32' }]) + .compressed(2, 3, [100]) + expect(() => parseFitActivity(b.build())).toThrow(/compressed/) + }) + + it('plik aktywności bez sesji i bez punktów → nie ma czego porównać', () => { + const b = new FitBuilder().define(0, 0, FILE_ID_FIELDS).data(0, fileIdValues(4, 0)) + b.define(2, 34, ACTIVITY_FIELDS).data(2, [1000, 0, 0, 1000]) + expect(parseFitActivity(b.build())).toBeUndefined() + }) +}) diff --git a/packages/sync-files/src/fit.ts b/packages/sync-files/src/fit.ts new file mode 100644 index 0000000..dc7dae6 --- /dev/null +++ b/packages/sync-files/src/fit.ts @@ -0,0 +1,409 @@ +/** + * Dekoder plików AKTYWNOŚCI FIT (Garmin, Coros, Polar, Suunto, Wahoo…). + * + * Bez SDK Garmina i bez bibliotek (ADR-017 — ta sama logika co przy koderze + * treningów w trainctl-export, z którego celowo nie importujemy: to dwie + * niezależne implementacje formatu). Źródła: FIT Protocol z Garmin FIT SDK + * (nagłówek, rekordy, typy bazowe, CRC) i Profile.xlsx z tego SDK (numery + * komunikatów, pól i wyliczeń; sprawdzone z profile.py w python-fitparse). + * + * Plik: nagłówek 12/14 B → rekordy (definicje i dane) → CRC-16 pliku. + * Czytamy tylko to, czego potrzebuje porównanie z planem: + * - file_id (0): `type` = 4 (activity) — inaczej to nie jest aktywność; + * - session (18): start, sport, czasy, dystans, tętno, podejścia; + * - activity (34): local_timestamp − timestamp = przesunięcie strefy; + * - sport (12) i record (20): tylko gdy pliku nie zamyka żadna sesja. + * Pliki łańcuchowe (kilka FIT sklejonych w jeden) czytamy do końca pierwszego. + */ +import { combineParts, toParsed, type ActivityPart, type ActivityType, type ParsedActivity } from './activity.ts' +import { dateWithOffset, localDateFromMs } from './dates.ts' +import { classifyByPace, elevationGainM, movingTimeSec, type MotionSample } from './measure.ts' + +/** 1989-12-31T00:00:00Z w sekundach uniksowych — epoka typu `date_time` (FIT SDK). */ +export const FIT_EPOCH_OFFSET_SEC = 631065600 + +// ---------------------------------------------------------------- prymitywy + +/** CRC-16 z FIT Protocol (wariant tablicowy po półbajtach; równoważny CRC-16/ARC). */ +const CRC_TABLE = [ + 0x0000, 0xcc01, 0xd801, 0x1400, 0xf001, 0x3c00, 0x2800, 0xe401, + 0xa001, 0x6c00, 0x7800, 0xb401, 0x5000, 0x9c01, 0x8801, 0x4400, +] + +export function fitCrc(data: Uint8Array, start = 0, end = data.length): number { + let crc = 0 + for (let i = start; i < end; i++) { + const byte = data[i]! + let tmp = CRC_TABLE[crc & 0xf]! + crc = (crc >> 4) & 0x0fff + crc = crc ^ tmp ^ CRC_TABLE[byte & 0xf]! + tmp = CRC_TABLE[crc & 0xf]! + crc = (crc >> 4) & 0x0fff + crc = crc ^ tmp ^ CRC_TABLE[(byte >> 4) & 0xf]! + } + return crc & 0xffff +} + +/** Rozmiar elementu typu bazowego (FIT Protocol, tabela „Base Types"; indeks = numer typu). */ +const BASE_SIZE = [1, 1, 1, 2, 2, 4, 4, 1, 4, 8, 1, 2, 4, 1, 8, 8, 8] + +/** + * Wartość pola liczbowego albo `undefined`, gdy pole niesie wartość „invalid" + * swojego typu bazowego (np. 0xFF dla uint8, 0 dla uint32z). Tablice czytamy + * do pierwszego elementu — żadne z potrzebnych pól nie jest tablicą. + */ +function readValue(view: DataView, offset: number, size: number, baseType: number, little: boolean): number | undefined { + const num = baseType & 0x1f + const elementSize = BASE_SIZE[num] + if (elementSize === undefined || size < elementSize) return undefined + switch (num) { + case 0x00: // enum + case 0x02: { // uint8 + const v = view.getUint8(offset) + return v === 0xff ? undefined : v + } + case 0x01: { // sint8 + const v = view.getInt8(offset) + return v === 0x7f ? undefined : v + } + case 0x03: { // sint16 + const v = view.getInt16(offset, little) + return v === 0x7fff ? undefined : v + } + case 0x04: { // uint16 + const v = view.getUint16(offset, little) + return v === 0xffff ? undefined : v + } + case 0x05: { // sint32 + const v = view.getInt32(offset, little) + return v === 0x7fffffff ? undefined : v + } + case 0x06: { // uint32 + const v = view.getUint32(offset, little) + return v === 0xffffffff ? undefined : v + } + case 0x08: { // float32 + if (view.getUint32(offset, little) === 0xffffffff) return undefined + const v = view.getFloat32(offset, little) + return Number.isFinite(v) ? v : undefined + } + case 0x09: { // float64 + if (view.getBigUint64(offset, little) === 0xffffffffffffffffn) return undefined + const v = view.getFloat64(offset, little) + return Number.isFinite(v) ? v : undefined + } + case 0x0a: { // uint8z + const v = view.getUint8(offset) + return v === 0 ? undefined : v + } + case 0x0b: { // uint16z + const v = view.getUint16(offset, little) + return v === 0 ? undefined : v + } + case 0x0c: { // uint32z + const v = view.getUint32(offset, little) + return v === 0 ? undefined : v + } + case 0x0e: { // sint64 + const v = view.getBigInt64(offset, little) + return v === 0x7fffffffffffffffn ? undefined : Number(v) + } + case 0x0f: { // uint64 + const v = view.getBigUint64(offset, little) + return v === 0xffffffffffffffffn ? undefined : Number(v) + } + case 0x10: { // uint64z + const v = view.getBigUint64(offset, little) + return v === 0n ? undefined : Number(v) + } + default: // 0x07 string, 0x0d byte — niepotrzebne do porównania z planem + return undefined + } +} + +// ---------------------------------------------------------------- rekordy + +interface FieldDef { + num: number + size: number + baseType: number +} + +interface Definition { + global: number + little: boolean + fields: FieldDef[] + /** Łączny rozmiar pól deweloperskich — pomijamy je w całości. */ + devSize: number +} + +/** Numer pola → wartość (tylko pola liczbowe z poprawną wartością). */ +export type FitFields = Map + +const TIMESTAMP_FIELD = 253 + +/** + * Przejście po wszystkich komunikatach danych pliku FIT. + * Rzuca błąd przy uszkodzonym pliku (sygnatura, długość, CRC, brak definicji). + */ +export function readFitMessages(bytes: Uint8Array, onMessage: (global: number, fields: FitFields) => void): void { + if (bytes.length < 12) throw new Error('FIT: file shorter than the header') + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength) + const headerSize = bytes[0]! + if (headerSize < 12 || headerSize > bytes.length) throw new Error('FIT: bad header size') + if (String.fromCharCode(bytes[8]!, bytes[9]!, bytes[10]!, bytes[11]!) !== '.FIT') { + throw new Error('FIT: missing .FIT signature') + } + const dataSize = view.getUint32(4, true) + if (headerSize >= 14) { + // CRC nagłówka 0x0000 jest dozwolone (FIT Protocol: „opcjonalne") — nie odrzucamy. + const headerCrc = view.getUint16(12, true) + if (headerCrc !== 0 && headerCrc !== fitCrc(bytes, 0, 12)) throw new Error('FIT: bad header CRC') + } + const end = headerSize + dataSize + if (end > bytes.length) throw new Error('FIT: truncated file') + // CRC pliku liczone od pierwszego bajtu nagłówka do końca danych. + if (bytes.length >= end + 2 && view.getUint16(end, true) !== fitCrc(bytes, 0, end)) { + throw new Error('FIT: bad file CRC') + } + + const defs: (Definition | undefined)[] = [] + let lastTimestamp: number | undefined + let pos = headerSize + const need = (n: number): void => { + if (pos + n > end) throw new Error('FIT: record crosses the end of data') + } + + const readData = (def: Definition): FitFields => { + const fields: FitFields = new Map() + for (const f of def.fields) { + need(f.size) + const value = readValue(view, pos, f.size, f.baseType, def.little) + if (value !== undefined) fields.set(f.num, value) + pos += f.size + } + need(def.devSize) + pos += def.devSize + return fields + } + + while (pos < end) { + const header = bytes[pos]! + pos += 1 + if (header & 0x80) { + // Nagłówek ze skompresowanym czasem: typ lokalny 0–3, 5 bitów przesunięcia + // względem ostatniego pełnego znacznika czasu (z przeniesieniem co 32 s). + const def = defs[(header >> 5) & 0x03] + if (!def) throw new Error('FIT: data record without a definition') + if (lastTimestamp === undefined) throw new Error('FIT: compressed timestamp without a reference') + const offset = header & 0x1f + const low = lastTimestamp % 32 + let timestamp = lastTimestamp - low + offset + if (offset < low) timestamp += 32 + lastTimestamp = timestamp + const fields = readData(def) + if (!fields.has(TIMESTAMP_FIELD)) fields.set(TIMESTAMP_FIELD, timestamp) + onMessage(def.global, fields) + } else if (header & 0x40) { + // Rekord definicji: rezerwa, architektura, numer globalny, pola, [pola deweloperskie]. + need(5) + const arch = bytes[pos + 1]! + if (arch !== 0 && arch !== 1) throw new Error('FIT: unknown architecture') + const little = arch === 0 + const global = view.getUint16(pos + 2, little) + const count = bytes[pos + 4]! + pos += 5 + need(count * 3) + const fields: FieldDef[] = [] + for (let i = 0; i < count; i++) { + fields.push({ num: bytes[pos]!, size: bytes[pos + 1]!, baseType: bytes[pos + 2]! }) + pos += 3 + } + let devSize = 0 + if (header & 0x20) { + need(1) + const devCount = bytes[pos]! + pos += 1 + need(devCount * 3) + for (let i = 0; i < devCount; i++) { + devSize += bytes[pos + 1]! // numer pola, ROZMIAR, indeks dewelopera + pos += 3 + } + } + defs[header & 0x0f] = { global, little, fields, devSize } + } else { + const def = defs[header & 0x0f] + if (!def) throw new Error('FIT: data record without a definition') + const fields = readData(def) + const timestamp = fields.get(TIMESTAMP_FIELD) + if (timestamp !== undefined) lastTimestamp = timestamp + onMessage(def.global, fields) + } + } +} + +// ---------------------------------------------------------------- aktywność + +const MESG_FILE_ID = 0 +const MESG_SPORT = 12 +const MESG_SESSION = 18 +const MESG_RECORD = 20 +const MESG_ACTIVITY = 34 +/** file_id.type: 4 = activity (Profile, typ `file`). */ +const FILE_TYPE_ACTIVITY = 4 + +/** + * Sport FIT → typ w nazewnictwie intervals.icu/Stravy (Profile: `sport`, `sub_sport`). + * sport: 1 running, 2 cycling, 4 fitness_equipment, 5 swimming, 10 training, + * 11 walking, 17 hiking. sub_sport: 1 treadmill, 3 trail, 20 strength_training, + * 45 indoor_running, 58 virtual_activity. + */ +export function fitSportType(sport: number | undefined, subSport: number | undefined): ActivityType | undefined { + if (sport === undefined) return undefined + switch (sport) { + case 1: + if (subSport === 3) return 'TrailRun' + if (subSport === 1 || subSport === 45 || subSport === 58) return 'VirtualRun' + return 'Run' + case 2: + return 'Ride' + case 5: + return 'Swim' + case 11: + return 'Walk' + case 17: + return 'Hike' + case 4: + case 10: + return subSport === 20 ? 'WeightTraining' : 'Other' + default: + return 'Other' + } +} + +const fitTimeToMs = (t: number): number => (t + FIT_EPOCH_OFFSET_SEC) * 1000 + +/** + * Najszersza strefa czasowa na świecie to UTC−12…UTC+14. Przesunięcie spoza + * tego zakresu oznacza uszkodzony `local_timestamp` — wtedy strefa maszyny. + */ +const MAX_UTC_OFFSET_SEC = 14 * 3600 + +interface RecordSample { + t?: number + d?: number + hr?: number + alt?: number +} + +const scaled = (v: number | undefined, scale: number, offset = 0): number | undefined => + v === undefined ? undefined : v / scale - offset + +/** Sesja FIT → część aktywności. Bez czasu startu sesja jest bezużyteczna. */ +function sessionPart(f: FitFields, fallbackType: ActivityType | undefined): ActivityPart | undefined { + const elapsed = scaled(f.get(7), 1000) // total_elapsed_time [s], skala 1000 + const timer = scaled(f.get(8), 1000) // total_timer_time [s], skala 1000 + const distance = scaled(f.get(9), 100) // total_distance [m], skala 100 + const startTime = f.get(2) ?? (f.has(TIMESTAMP_FIELD) && elapsed !== undefined ? f.get(TIMESTAMP_FIELD)! - elapsed : undefined) + if (startTime === undefined) return undefined + const part: ActivityPart = { + startMs: fitTimeToMs(startTime), + type: fitSportType(f.get(5), f.get(6)) ?? fallbackType ?? 'Other', + } + if (distance !== undefined) part.distanceM = distance + if (timer !== undefined) part.movingTimeSec = timer + if (elapsed !== undefined) part.elapsedTimeSec = elapsed + const hr = f.get(16) // avg_heart_rate [bpm] + if (hr !== undefined) part.avgHr = hr + const ascent = f.get(22) // total_ascent [m] + if (ascent !== undefined) part.elevationGainM = ascent + return part +} + +/** Plik bez `session` (przerwany zapis, część eksporterów): suma z punktów `record`. */ +function recordsPart(records: RecordSample[], sportType: ActivityType | undefined): ActivityPart | undefined { + const timed = records.filter((r): r is RecordSample & { t: number } => r.t !== undefined) + const first = timed[0] + const last = timed[timed.length - 1] + if (!first || !last) return undefined + const samples: MotionSample[] = timed + .filter((r): r is RecordSample & { t: number; d: number } => r.d !== undefined) + .map((r) => ({ t: r.t, d: r.d })) + const distance = samples.length ? samples[samples.length - 1]!.d : undefined + const moving = samples.length >= 2 ? movingTimeSec(samples) : undefined + const part: ActivityPart = { + startMs: fitTimeToMs(first.t), + type: sportType ?? classifyByPace(distance, moving), + elapsedTimeSec: last.t - first.t, + } + if (distance !== undefined) part.distanceM = distance + if (moving !== undefined) part.movingTimeSec = moving + // Średnia z próbek, nie ważona czasem — zapis „smart" bywa nierówny, ale + // to ścieżka awaryjna; plik z sesją niesie średnią policzoną przez zegarek. + const hrs = records.map((r) => r.hr).filter((v): v is number => v !== undefined) + if (hrs.length) part.avgHr = hrs.reduce((a, b) => a + b, 0) / hrs.length + const gain = elevationGainM(records.map((r) => r.alt).filter((v): v is number => v !== undefined)) + if (gain !== undefined) part.elevationGainM = gain + return part +} + +/** + * Bajty pliku FIT → aktywność. `undefined`, gdy plik jest poprawny, ale nie jest + * aktywnością (np. trening, kurs, ustawienia) albo nie niesie żadnych danych. + * Rzuca błąd, gdy plik jest uszkodzony (zła sygnatura, długość, CRC). + */ +export function parseFitActivity(bytes: Uint8Array): ParsedActivity | undefined { + let fileType: number | undefined + const sessions: FitFields[] = [] + const records: RecordSample[] = [] + let activity: FitFields | undefined + let sport: FitFields | undefined + + readFitMessages(bytes, (global, f) => { + switch (global) { + case MESG_FILE_ID: + fileType ??= f.get(0) + break + case MESG_SESSION: + sessions.push(f) + break + case MESG_ACTIVITY: + activity = f + break + case MESG_SPORT: + sport ??= f + break + case MESG_RECORD: { + const sample: RecordSample = {} + const t = f.get(TIMESTAMP_FIELD) + const d = scaled(f.get(5), 100) // distance [m], skala 100 + const hr = f.get(3) // heart_rate [bpm] + // enhanced_altitude (78) ma pierwszeństwo przed altitude (2); obie: skala 5, offset 500 m. + const alt = scaled(f.get(78) ?? f.get(2), 5, 500) + if (t !== undefined) sample.t = t + if (d !== undefined) sample.d = d + if (hr !== undefined) sample.hr = hr + if (alt !== undefined) sample.alt = alt + records.push(sample) + break + } + } + }) + + if (fileType !== FILE_TYPE_ACTIVITY) return undefined + const sportType = sport ? fitSportType(sport.get(0), sport.get(1)) : undefined + const parts = sessions + .map((s) => sessionPart(s, sportType)) + .filter((p): p is ActivityPart => p !== undefined) + const part = parts.length ? combineParts(parts) : recordsPart(records, sportType) + if (!part) return undefined + + const ts = activity?.get(TIMESTAMP_FIELD) + const localTs = activity?.get(5) // local_timestamp + const offset = ts !== undefined && localTs !== undefined ? localTs - ts : undefined + const date = + offset !== undefined && Math.abs(offset) <= MAX_UTC_OFFSET_SEC + ? dateWithOffset(part.startMs, offset) + : localDateFromMs(part.startMs) + return toParsed(part, date) +} diff --git a/packages/sync-files/src/gpx.test.ts b/packages/sync-files/src/gpx.test.ts new file mode 100644 index 0000000..c905408 --- /dev/null +++ b/packages/sync-files/src/gpx.test.ts @@ -0,0 +1,145 @@ +/** + * Parser GPX na syntetycznych śladach o znanej geometrii. + */ +import { describe, expect, it } from 'vitest' +import { localDateFromMs } from './dates.ts' +import { gpxType, parseGpxActivity } from './gpx.ts' +import { EARTH_RADIUS_M, haversineM } from './measure.ts' + +interface Pt { + lat: number + lon: number + /** Sekundy od startu; `undefined` = punkt bez czasu. */ + t?: number + ele?: number + hr?: number +} + +const START_MS = Date.parse('2026-09-14T06:00:00Z') +const iso = (t: number) => new Date(START_MS + t * 1000).toISOString() + +const trkpt = (p: Pt) => + `` + + (p.ele === undefined ? '' : `${p.ele}`) + + (p.t === undefined ? '' : ``) + + (p.hr === undefined + ? '' + : `${p.hr}`) + + `` + +const gpx = (segments: Pt[][], meta: { name?: string; type?: string } = {}) => ` + + + + ${meta.name === undefined ? '' : `${meta.name}`} + ${meta.type === undefined ? '' : `${meta.type}`} + ${segments.map((s) => `${s.map(trkpt).join('\n')}`).join('\n')} + +` + +/** Ślad na południk 21°E: co 30 s o 0,001° na północ (~111 m → ~3,7 m/s). */ +const northward = (n: number, from = 0, latStart = 52): Pt[] => + Array.from({ length: n }, (_, i) => ({ lat: latStart + i * 0.001, lon: 21, t: from + i * 30 })) + +/** Łuk południka: R · Δφ — dokładny wynik dla modelu kulistego, niezależny od wzoru haversine. */ +const meridianM = (dLatDeg: number) => EARTH_RADIUS_M * ((dLatDeg * Math.PI) / 180) + +describe('haversine', () => { + it('wzdłuż południka zgadza się z R·Δφ', () => { + expect(haversineM(52, 21, 53, 21)).toBeCloseTo(meridianM(1), 3) + }) + + it('wzdłuż równoleżnika 52° — w granicach 0,5% od R·cos φ·Δλ', () => { + const expected = EARTH_RADIUS_M * Math.cos((52 * Math.PI) / 180) * ((0.01 * Math.PI) / 180) + const d = haversineM(52, 21, 52, 21.01) + expect(Math.abs(d - expected) / expected).toBeLessThan(0.005) + }) +}) + +describe('parseGpxActivity', () => { + it('ślad o znanych współrzędnych: dystans w granicach 0,5%, czasy, nazwa i typ z trk', () => { + const points = northward(11).map((p, i) => ({ ...p, ele: 100 + i * 0.5, hr: 150 })) + const text = gpx([points], { name: 'Poranny bieg', type: 'running' }).replace( + 'punkt, nie ślad { + const points = [...northward(3, 0), ...northward(3, 300, 52.002 + 0.0005)] + const a = parseGpxActivity(gpx([points], { type: 'running' }))! + expect(a.elapsedTimeSec).toBe(360) + expect(a.movingTimeSec).toBe(120) + }) + + it('odcinek między segmentami (utrata sygnału) nie wlicza się do dystansu', () => { + const a = parseGpxActivity(gpx([northward(6, 0), northward(6, 200, 53)], { type: 'running' }))! + const expected = 2 * meridianM(0.005) + expect(Math.abs(a.distanceM! - expected) / expected).toBeLessThan(0.005) + expect(a.elapsedTimeSec).toBe(350) + }) + + it('brak typu: heurystyka tempa — ~4:30 min/km to bieg, rower i marsz to Other', () => { + const at = (stepDeg: number) => + Array.from({ length: 11 }, (_, i) => ({ lat: 52 + i * stepDeg, lon: 21, t: i * 30 })) + expect(parseGpxActivity(gpx([at(0.001)]))!.type).toBe('Run') // ~3,7 m/s + expect(parseGpxActivity(gpx([at(0.003)]))!.type).toBe('Other') // ~11 m/s + expect(parseGpxActivity(gpx([at(0.0003)]))!.type).toBe('Other') // ~1,1 m/s + }) + + it('typ cycling → Ride (nawet przy tempie biegowym)', () => { + expect(parseGpxActivity(gpx([northward(5)], { type: 'cycling' }))!.type).toBe('Ride') + }) + + it.each([ + ['running', 'Run'], + ['Run', 'Run'], + ['9', 'Run'], + ['trail_running', 'TrailRun'], + ['cycling', 'Ride'], + ['1', 'Ride'], + ['walking', 'Walk'], + ['Hiking', 'Hike'], + ['kayaking', 'Other'], + ])('trk/type %s → %s', (raw, type) => { + expect(gpxType(raw)).toBe(type) + }) + + it('nazwa w CDATA i czas z jawnym przesunięciem (data jak zapisana, nie ze strefy maszyny)', () => { + // Te same chwile zapisane jako czas ścienny UTC−12: 06:00Z to 18:00 poprzedniego dnia. + // Maszyna w strefie od −6 do +14 policzyłaby 14 września — zapis mówi 13. + const minus12 = (z: string) => new Date(Date.parse(z) - 12 * 3600_000).toISOString().slice(0, 19) + '-12:00' + const text = gpx([northward(4)], { name: '', type: 'running' }).replace( + /