diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json new file mode 100644 index 0000000..ac3d072 --- /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_USE" }, + "category": "Productivity" + } + ] +} diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json new file mode 100644 index 0000000..7540ef7 --- /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.4.0", + "category": "productivity", + "keywords": ["running", "training-plan", "coach", "mcp"] + } + ] +} diff --git a/.gitattributes b/.gitattributes index 176a458..b4b5324 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1,4 @@ * text=auto +# Skrypty z shebangiem (hooki pluginu): vitest zdejmuje `#!` tylko przed LF — +# z CRLF po checkoucie na Windows import kończy się SyntaxError. +*.mjs text eol=lf diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aeb4de5..03c7362 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. @@ -64,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 @@ -75,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 a299838..5d03313 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,166 @@ change between minor versions — a regenerated plan can differ. ## [Unreleased] +## [0.4.0] — 2026-10-21 + +### 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 advice to + upgrade trainctl. +- 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. + +### 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). On race day the race + counts as done only when most of its distance is logged or synced (a day + logged as skipped never counts), so a morning shakeout before a postponed + race keeps the same cycle. +- Right after `adapt --apply`, `plan` reproduces the approved days, including + strength sessions, time-budget caps and the day of the decision. Later, + strength follows the current phases and `strength.days`. +- A `plan/plan.yaml` that cannot be read (a merge conflict, a missing goal) is + never overwritten silently: `plan` refuses until it is fixed or `--fresh` is + given, and `status` no longer suggests a `plan` that would fail. +- `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). `init --commit` includes `.gitignore` when it created it or when it + had no uncommitted changes before the secret patterns were added. +- `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. + +### 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. + +### 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. The same run exported in two formats (start within 60 s, similar + distance) counts once, keeping the richest file: FIT, then TCX, then GPX. + `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). + +### Added — the engine: time, life after the race, a plan without a race + +- **Time budget** (`time.weeklyMinutes`, `weekdayMinutes`, `weekendMinutes`, + E-2): weeks over the weekly budget get a lower volume target, days over their + limit are shortened with the same rules as `shorten` and carry the trade-off; + the plan says when the budget lowers the peak below the level recommended + for the distance, and what the peak would be without it (P-7/P-8). Races and + time trials are never cut. + A week keeps its macrocycle target; the volume the budget leaves is stored + next to it (`timeCappedKm`), and `week`, `adapt`, `diff` and `export` show it. + A zone recalibration from `adapt` changes paces: day limits shorten + sessions that no longer fit from the current week, the weekly budget lowers + volume from the next week on, and volume goes up again through `plan`. +- **Transition block after the goal race** (R-8): after a half marathon or + longer, two weeks — about half the pre-race volume, easy only, first run on + the third day after a marathon (R-1), then back to normal with one accent; + one week at ~70% after a shorter goal (R-10). Strength returns in the second + week (R-9). Measured first: `tools/corpus/post_race_profile.py` (three long + races in the corpus — a weak basis, stated as such). `today` and `why` say + "after the race" instead of "outside the plan", and a new goal set during the + block starts its cycle after it. +- **A plan without a race** (`goal.kind: base`, `until`, P-11): base weeks only, + deload every fourth week, growth to your documented peak and a plateau; no + taper, no prediction, no race pack. +- **Strength variants and journal**: two weeks of getting into it (F-18), then + heavy sessions, one maintenance session a week in the peak (F-12, F-14); + `trainctl log --strength done|skipped [--minutes]` (MCP `strength`) records a + session without touching the run entry of the same day; `review` and `today` + show it. +- **Trail results** no longer calibrate road zones while a road result exists + (Z-10); a trail-only calibration is used with a warning. +- Rules E-2, F-18, P-11, R-8, R-9, R-10 and Z-10 in FOUNDATIONS §10, marked as + engineering choices where no source exists. The corpus backtest is unchanged + (volume 1.04, Δ accents 0, Δ sessions 0, tune-ups 6/6). + +### 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/CONTRIBUTING.md b/CONTRIBUTING.md index 80f2e0b..3818462 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -35,12 +35,23 @@ 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 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 69cd31c..5b670d0 100644 --- a/README.md +++ b/README.md @@ -1,18 +1,19 @@ # trainctl -New in 0.3.0: three coaching workflows, available -through both CLI and MCP: +New in 0.4.0: trainctl as a **plugin for Claude Code and Codex**, execution read +from exported **FIT, TCX and GPX files** (no API key needed), and an engine that +knows your **time budget**, the **weeks after a race** and **plans without one**: ```sh -trainctl shorten --minutes 40 # today's session within the total time budget -trainctl why # purpose, dose, phase and placement in this plan -trainctl review --prepare # completed week and exact changes for approval -trainctl adapt --apply # apply the proposal you reviewed +trainctl init --agent claude # profile + plugin setup for your agent +trainctl pull --from ~/exports # what you ran, from watch or Strava export files +trainctl plan # regenerates the future, keeps what you decided +trainctl status # one screen: profile, plan, key, sync, proposals, git ``` -The 40 minutes include preparation and planned strength. A shorter variant may -give up the original training purpose; the preview says so. Preparing proposals -keeps the active plan unchanged. See the [workflow guide](docs/REVIEWED-ADAPTATION.md). +`plan` on an existing plan keeps past and logged days, pins, hand edits and the +volume baseline you approved. Every command takes `--json`, `-C ` and +relative dates such as `tomorrow` or `sat`. See the [changelog](CHANGELOG.md). [![CI](https://github.com/dithiothreitol/trainctl/actions/workflows/ci.yml/badge.svg)](https://github.com/dithiothreitol/trainctl/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) @@ -186,10 +187,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,25 +243,38 @@ 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`, `--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) | | `why` | purpose + research rules behind a session | `--date` | -| `log` | record a completed session | `--status`, `--km`, `--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` | +| `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` | -| `pull` | fetch activities and wellness, compare | `--days` | +| `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` | - -`--lang en|pl` works on every command. `trainctl help ` prints the full -flag list. +| `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 }` — +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). + +`--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 @@ -288,6 +307,21 @@ desk: # for trainctl desk (optional) strength: # optional strength track, 2×/week enabled: true days: [mon, fri] # optional preference +time: # optional: the minutes you actually have, preparation included + weeklyMinutes: 300 # volume levels off at what fits (E-2) + weekdayMinutes: 60 # longer sessions are shortened, with the trade-off shown (E-1) + weekendMinutes: 120 +sync: + files: ./activities # optional: exported FIT/TCX/GPX instead of intervals.icu +``` + +No race to train for? Use a base plan instead of `goal` with a date and +distance — no taper, no prediction, volume grows to your peak and levels off (P-11): + +```yaml +goal: + kind: base + until: "2027-03-01" ``` A few consequences worth knowing: @@ -300,8 +334,14 @@ A few consequences worth knowing: in that week. - **`strength` is a separate track**, not a running session: it adds no kilometres, disappears during the taper, and never lands the day before a hard - session. The justification is running economy — *not* injury prevention; see - [Where it refuses](#where-it-refuses). + session. Two weeks of getting into it, then heavy sessions, and one maintenance + session a week in the peak (F-18, F-4, F-12). Log it with + `trainctl log --strength done`. The justification is running economy — *not* + injury prevention; see [Where it refuses](#where-it-refuses). +- **The plan does not stop at the race.** After a half marathon or longer, two + transition weeks follow: about half the pre-race volume, easy only, first run on + the third day after a marathon; then back to normal with one accent (R-8, from + three races in the coaching corpus). A new goal starts its cycle after them. The intervals.icu API key never goes in this file. Use `TRAINCTL_INTERVALS_API_KEY`, a `.env` file or `.trainctl-secret`; an explicit @@ -377,6 +417,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 @@ -396,12 +457,15 @@ 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`, `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 @@ -420,7 +484,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 @@ -503,12 +587,22 @@ 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. -**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 @@ -531,8 +625,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 06d5963..139cb52 100644 --- a/README.pl.md +++ b/README.pl.md @@ -1,18 +1,21 @@ # trainctl -Nowości w 0.3.0: trzy scenariusze dostępne -przez CLI i MCP: +Nowości w 0.4.0: trainctl jako **plugin do Claude Code i Codex**, wykonanie +odczytane z wyeksportowanych **plików FIT, TCX i GPX** (bez klucza API) oraz +silnik, który zna Twój **budżet czasu**, **tygodnie po starcie** i **plan bez +startu**: ```sh -trainctl shorten --minutes 40 # dzisiejszy trening w dostępnym czasie -trainctl why # cel, dawka, faza i miejsce w tym planie -trainctl review --prepare # wykonany tydzień i zmiany do zatwierdzenia -trainctl adapt --apply # zastosuj przejrzaną propozycję +trainctl init --agent claude # profil + konfiguracja pluginu dla agenta +trainctl pull --from ~/eksport # co przebiegłeś, z plików zegarka albo Stravy +trainctl plan # przelicza przyszłość, zostawia Twoje decyzje +trainctl status # jeden ekran: profil, plan, klucz, sync, propozycje, git ``` -40 minut obejmuje przygotowanie i zaplanowaną siłę. Krótszy wariant może oznaczać -rezygnację z pierwotnego celu treningu — podgląd to opisuje. Przygotowanie propozycji -zachowuje aktywny plan. Szczegóły: [opis scenariuszy](docs/REVIEWED-ADAPTATION.md). +`plan` na istniejącym planie zostawia dni przeszłe i zalogowane, przypięcia, +ręczne edycje i zatwierdzoną bazę objętości. Każda komenda przyjmuje `--json`, +`-C ` i daty względne, np. `jutro` albo `sob`. Szczegóły: +[changelog](CHANGELOG.md). [![CI](https://github.com/dithiothreitol/trainctl/actions/workflows/ci.yml/badge.svg)](https://github.com/dithiothreitol/trainctl/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) @@ -188,10 +191,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,25 +248,39 @@ 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`, `--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) | | `why` | cel jednostki + reguły z badań | `--date` | -| `log` | zapis wykonania | `--status`, `--km`, `--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` | +| `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` | -| `pull` | pobiera aktywności i wellness, porównuje | `--days` | +| `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` | - -`--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 | | +| `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, +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 @@ -291,9 +313,25 @@ desk: # dla trainctl desk (opcjonalne) strength: # opcjonalny tor siłowy, 2×/tydz. enabled: true days: [mon, fri] # opcjonalna preferencja dni +time: # opcjonalnie: minuty, które naprawdę masz, z przygotowaniem + weeklyMinutes: 300 # objętość wypłaszcza się na tym, co się mieści (E-2) + weekdayMinutes: 60 # dłuższe jednostki są skracane, z pokazanym kompromisem (E-1) + weekendMinutes: 120 +sync: + files: ./activities # opcjonalnie: eksport FIT/TCX/GPX zamiast intervals.icu ``` -Trzy konsekwencje, o których warto wiedzieć: +Nie masz startu, do którego się przygotowujesz? Zamiast `goal` z datą i dystansem +użyj planu bazowego — bez taperu i predykcji, objętość rośnie do Twojego szczytu +i tam się wypłaszcza (P-11): + +```yaml +goal: + kind: base + until: "2027-03-01" +``` + +Kilka konsekwencji, o których warto wiedzieć: - **`results` napędza wszystko.** Bez wyniku startu nie ma VDOT-u ani stref; przy samym `targetTimeSec` plan wyliczy strefy z celu i powie wprost, że @@ -303,9 +341,16 @@ Trzy konsekwencje, o których warto wiedzieć: tygodniu. Przy pustym kalendarzu startów plan sam wstawi sprawdzian na czas — ale prawdziwy start zawsze ma pierwszeństwo. - **`strength` to osobny tor**, nie kolejna jednostka biegowa: nie dokłada - kilometrów, znika w taperze i nigdy nie ląduje dzień przed akcentem. + kilometrów, znika w taperze i nigdy nie ląduje dzień przed akcentem. Dwa + tygodnie wejścia, potem sesje ciężkie, a w szczycie jedna podtrzymująca + w tygodniu (F-18, F-4, F-12). Zapis: `trainctl log --strength done`. Uzasadnieniem jest ekonomia biegu — *nie* prewencja urazów; zob. [Gdzie silnik odmawia](#gdzie-silnik-odmawia). +- **Plan nie kończy się na starcie.** Po półmaratonie i dłuższym dystansie idą + dwa tygodnie przejściowe: mniej więcej połowa objętości sprzed startu, wyłącznie + spokojnie, pierwszy bieg trzeciego dnia po maratonie; potem powrót do zwykłego + rytmu z jednym akcentem (R-8, z trzech startów w korpusie trenera). Nowy cel + zaczyna swój cykl po nich. Klucz API do intervals.icu nigdy nie trafia do tego pliku. Użyj `TRAINCTL_INTERVALS_API_KEY`, pliku `.env` albo `.trainctl-secret`; zmienna @@ -382,6 +427,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 @@ -401,12 +467,15 @@ 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`, `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 @@ -428,7 +497,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 @@ -510,12 +599,22 @@ 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. -**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 @@ -539,8 +638,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 49d92e6..f5215d8 100644 --- a/SPEC.md +++ b/SPEC.md @@ -2,7 +2,7 @@ > Plan treningowy jako kod, trener jako narzędzie agenta. -**Status:** **Wydanie 0.3.0** (2026-09-06). Pięć pakietów: silnik (`trainctl-core`), CLI (`trainctl`, 17 komend, dwujęzyczny), MCP (`trainctl-mcp`, 17 narzędzi), sync intervals.icu (`trainctl-sync-intervalsicu`) i eksport (`trainctl-export`). **641 testów**, w tym uruchomienia binarek pod natywnym Node i backtest na korpusie (7 testów, pomijają się bez korpusu). Nowe scenariusze: skracanie jednostki do budżetu czasu, wyjaśnienia w kontekście oraz przegląd tygodnia z propozycją do zatwierdzenia; włączono również poprawki z audytu 0.2.0. Repozytorium publiczne od 2026-08-07 (MIT). Historia i procedura wydania: `docs/PUBLISHING.md`. +**Status:** **Wydanie 0.3.0** (2026-09-06) na npm; na gałęzi `dev/plan-v0.4` niewydane etapy A–E planu [docs/PLAN-v0.4.md](docs/PLAN-v0.4.md) (faza 15 niżej). Sześć pakietów: silnik (`trainctl-core`), CLI (`trainctl`, 20 komend, dwujęzyczny), MCP (`trainctl-mcp`, 19 narzędzi, zasoby i prompty), sync intervals.icu (`trainctl-sync-intervalsicu`), pliki aktywności (`trainctl-sync-files`) i eksport (`trainctl-export`); plugin Claude Code/Codex w `plugin/`. Testy: patrz `pnpm test` (backtest na korpusie pomija się bez korpusu). Repozytorium publiczne od 2026-08-07 (MIT). Historia i procedura wydania: `docs/PUBLISHING.md`. **Sync zweryfikowany e2e na żywym koncie 2026-08-05** (szczegóły: `docs/integrations/intervalsicu.md` §2a) — składnia treningów parsowana poprawnie, cele tempa zapisane, idempotencja działa. Otwarte: dostarczenie na fizyczny zegarek — wymaga zegarka spiętego z intervals.icu **bezpośrednio**, nie przez Stravę (§1.8.1). Dalej: kolejne sporty (`SportModule`), REST API/hosting. @@ -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, @@ -196,6 +205,7 @@ czystym zamknięciem sesji. | **12** | Wielojęzyczność: angielski domyślny, polski jako dodatkowy | ✅ KOMPLET (2026-08-06) — patrz niżej | | **13** | Plan-as-code na serio: lint planu + scenariusze + współpraca przez git | ✅ KOMPLET (2026-08-07): **(a) `trainctl check`** — `core/engine/validate.ts`, 25 kontroli nad stanami końcowymi, które generator/solver już definiują (bez drugiej implementacji reguł): integralność pliku = **error** (sumy vs dni, daty vs pozycje, brak dnia startu — stany nieosiągalne przez narzędzie), odstępstwa metodyczne = **warn** (I-5, I-7, T-4, T-5, T-10, S-5, F-13 — osiągalne świadomą decyzją, `shift` ostrzega i pozwala); I-5 z podłogą generatora. CLI `check --strict`, MCP `trainctl_check` (16 narzędzi), CI w docs/examples/ci-check.md. **Lint od razu wykrył, że `reschedule --apply` nie przeliczał totalKm/easyShare po odpuszczonej sesji — naprawione wspólnym `weekTotals`.** **(b) `diff --plan `** — porównanie scenariuszowe dwóch pełnych planów (gałąź „co jeśli”/worktree/kopia): cel (nazwa, dystans, data, cel czasowy), VDOT, predykcja + tygodnie/dni po danych planu — rodzaj jednostki, objętość tygodnia i dnia, układ członów, siła; wspólny `diffWeeks` z trybem regeneracyjnym. Pusty albo obcięty plik planu to zdanie („to nie jest plik planu”), a w `check` — ustalenie lintu (`weeksMissing`/`goalMissing`), nie wyjątek. **(c) AGENTS.md** — sekcja „Koreluj to, co widzisz” (kalendarz/tracker/dyżury → `reschedule` przed konfliktem, `desk --heavy` po ciężkim dniu kognitywnym; zawsze nazwać sygnał, nigdy nie stosować bez zgody) + reguła „co jeśli = scenariusz, nie nadpisanie” + rytuał `check` po ręcznej edycji. **(d) docs**: sekcja „Plan as code” w obu README (gałęzie, CI, trener-reviewer, odtwarzalność), docs/examples/coach-review.md (tydzień przez PR). 48 nowych testów (544 łącznie; 552 po korekcie dystrybucji) | | **14** | Pętla subiektywna: RPE i notatki jako materiał rozmowy | ✅ KOMPLET (2026-08-08): `LogEntry.rpe` (CR-10, całkowite 1–10; zbieranie z P-6, dolna granica 1 = wybór inżynierski) — `trainctl log --rpe`, MCP `trainctl_log(rpe)`, widoczne w `today`. `review` cytuje ślad odczuć **dosłownie** (sekcja „Jak się biegało”: data · RPE · notatka; ostatni wpis dnia wygrywa, spójnie z `logFor`), bez agregacji, progów i wniosków — interpretacja należy do rozmowy (ADR-027). AGENTS.md: rytuał odprawy po zalogowanym treningu (jedno pytanie o kontekst, gdy odczucie kłóci się z rolą jednostki), zasada 8 „odczucia to rozmowa, nie arytmetyka” (Z-4), propozycja cyklicznej odprawy wyłącznie za zgodą; docs/examples/proactive-review.md — trener odzywa się pierwszy (harmonogram agenta / cron), z jawnym kontrastem do wariantu Actions. 5 nowych testów (557 łącznie) | +| **15** | Plan rozwoju 0.3.1 → 0.6.0 ([docs/PLAN-v0.4.md](docs/PLAN-v0.4.md), etapy A–E) | ✅ KOMPLET (2026-10-21, gałąź `dev/plan-v0.4`, niewydane): **A** naprawy wykryte na żywo (review, why, log, komunikaty, wersja silnika, FOUNDATIONS jako link) + dokumentacja pod testem; **B** chroniona regeneracja planu (ADR-033), `--json`, `-C`, `TRAINCTL_TODAY` (ADR-034), daty względne, interaktywny log, `status`, `--commit` (ADR-040), completion; **C** plugin Claude Code/Codex z repozytorium jako marketplace (ADR-036), zasoby/prompty MCP, `trainctl_rule`, `init --agent`; **D** `trainctl-sync-files` (FIT/TCX/GPX, ADR-037), starty i siła w push z wycofaniem, kontekst z zegarka w review; **E** budżet czasu (E-2), blok po starcie (R-8…R-10, ADR-038), plan bez startu (P-11, ADR-039), warianty i dziennik siły (F-18), trail w kalibracji (Z-10). Backtest bez zmian | | dalej | **Sezon na sobie** (weryfikacja w boju), zegarek fizyczny, REST API, kolejne sporty | bez decyzji użytkownika nie zaczynać | ### Faza 12 — wielojęzyczność (2026-08-06) @@ -260,7 +270,10 @@ długie wybieganie zawsze czysto spokojne — **pomiar korpusu potwierdza ten wybór w 71%** (`tools/corpus/long_run_profile.py`), pozostałe 29% to osobny, KRÓTSZY wzorzec (mediana 19 km wobec 25 km), nie „długie z dodatkiem tempa"; kalibracja VDOT w backteście inżynierska (51), docelowo z wyników startów -użytkownika. +użytkownika. ~~makrocykl kończy się w dniu startu~~ (zdjęte w 0.6.0: blok +przejściowy R-8); ~~plan wymaga startu docelowego~~ (zdjęte: `goal.kind: base`, +P-11). Blok przejściowy opiera się na trzech startach z korpusu — słaba podstawa, +nazwana wprost w FOUNDATIONS. ## 9. Ryzyka (szczerze) @@ -326,3 +339,11 @@ 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) | +| 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ą | +| 038 | 2026-10-21 | Makrocykl kończy się **blokiem przejściowym**, nie tygodniem startu: po ≥HM dwa tygodnie (~50% spokojnie, potem ~100% z jednym akcentem), po krótszym jeden (~70%); nowy cel wpisany w trakcie bloku zaczyna cykl po nim | narzędzie, które milczy dzień po starcie, zostawia biegacza w najgorszym momencie; R-1/R-2 opisują pierwsze dni, kształt kolejnych tygodni zmierzono na korpusie (n=3) zamiast go zgadywać | +| 039 | 2026-10-21 | `goal.kind: base` z datą `until` — plan bez zawodów: tylko baza z odciążeniem, plateau na udokumentowanym szczycie, bez taperu i predykcji; liczba tygodni jako `weeks` celowo nieobsługiwana | większość tygodni roku nie ma celu; wymuszanie fikcyjnego startu produkowałoby fikcyjny taper. „12 tygodni od dziś" przesuwałoby koniec planu przy każdej regeneracji — data końca jest deterministyczna | +| 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/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..edd965e 100644 --- a/docs/PUBLISHING.md +++ b/docs/PUBLISHING.md @@ -4,14 +4,18 @@ , MIT, Discussions wyłączone, prywatne zgłaszanie podatności włączone. Warunek „sezon na sobie" został świadomie odpuszczony — decyzja właściciela, nie przeoczenie. -**Bieżące wydanie: 0.3.0 (2026-09-06)** dla wszystkich pięciu paczek. -Historia wydań: `v0.1.0`, `v0.1.1`, `v0.2.0`, `v0.3.0`. +**Bieżące wydanie: 0.4.0 (2026-10-21)** dla wszystkich sześciu paczek +i pluginu (Claude Code, Codex). +Historia wydań: `v0.1.0`, `v0.1.1`, `v0.2.0`, `v0.3.0`, `v0.4.0`. 0.1.0 pozostaje zdeprecjonowane — przyczynę opisano w historycznej sekcji npm. -0.3.0 obejmuje skracanie jednostki do budżetu czasu, wyjaśnianie konkretnego -treningu i przegląd tygodnia z propozycją do zatwierdzenia, a także poprawki -z audytu. Walidacja: 641 testów, typy, build oraz instalacja pięciu tarballi -w osobnym katalogu, z wykonaniem scenariuszy CLI i uruchomieniem MCP. +0.4.0 obejmuje cały plan z [PLAN-v0.4.md](PLAN-v0.4.md): chronioną +regenerację planu, CLI do skryptów (`--json`, `-C`, `status`, `--commit`), +plugin do Claude Code i Codex, wykonanie z plików FIT/TCX/GPX (nowa paczka +`trainctl-sync-files`) oraz silnik z budżetem czasu, blokiem po starcie +i planem bez startu. Walidacja: 896 testów, typy, build, dziesięć rund code +review oraz instalacja sześciu tarballi w osobnym katalogu, z wykonaniem +scenariuszy CLI i uruchomieniem MCP. Poniżej zapis rozumowania, które do tego doprowadziło — zostaje, bo tłumaczy, czemu projekt jest otwarty, a korpus nie. @@ -109,18 +113,32 @@ 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 type-strippingu Node ≥ 22.18, którego wymaga `engines`. +## Szósta paczka (od 0.4.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/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/docs/examples/ci-check.md b/docs/examples/ci-check.md index c747b00..278a1b9 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.4.0 check ``` +Zamiast `trainctl@0.4.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..5c694f8 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.4.0 review --days 7 > review.txt # wersja jak lokalnie { echo 'body<` 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/docs/integrations/files.md b/docs/integrations/files.md new file mode 100644 index 0000000..9273da0 --- /dev/null +++ b/docs/integrations/files.md @@ -0,0 +1,59 @@ +# 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. That + includes two formats of one run: a start within 60 s and a distance within 10% + (at least 500 m) mean the same run, and the richest file is kept — FIT, then + TCX, then GPX (engineering choices). The other file is listed as a duplicate. +- `init` adds `activities/` to `.gitignore`. GPS tracks show where you live — + keep them out of a repository you might publish. diff --git a/docs/science/FOUNDATIONS.md b/docs/science/FOUNDATIONS.md index 730b0d6..4648cd7 100644 --- a/docs/science/FOUNDATIONS.md +++ b/docs/science/FOUNDATIONS.md @@ -1615,6 +1615,7 @@ jako fakt). | Z-7 | Test CS terenowy: 2 próby | 1200 m + 3600 m (lub 3 min + 12 min), przerwa 30–60 min, od dłuższej do krótszej | Lipková 2025 | B | | Z-8 | 3MT tylko dla Tier 2+; korygować D′ | CS = średnia z ostatnich 30 s; D′ zaniżone ~16% | Lipková 2025 | B | | Z-9 | Rekalibracja | po każdym starcie; dodatkowo co 6–8 tyg. | Filipas 2022; Festa 2020 | D | +| Z-10 | Wynik z **trailu nie kalibruje stref szosowych**, dopóki jest wynik szosowy; sam trail — z ostrzeżeniem w planie | tabele VDOT (Daniels) powstały z szosy i bieżni; czas w terenie mówi o terenie tak samo jak o formie | **brak źródła** (inż.) | **—** | ### 10.2 `engine/` — rozkład intensywności @@ -1643,6 +1644,7 @@ jako fakt). | P-8 | Progi objętości dla celu — maraton | >65 km/tyg. → −14,09 min; <40 km/tyg. → +6,33 min; najdłuższy <25 km → +13,44 min | Fokkema 2020 | **C** | | P-9 | Sufit objętości sanity-check | elita 130–220 km/tyg. — powyżej tego plan jest błędem, nie ambicją | Haugen 2022 | D | | P-10 | Nie komunikować objętości jako czynnika ryzyka urazu w tym zakresie | „No associations between training characteristics and new RRIs" | Fokkema 2020 | C | +| P-11 | Plan **bez startu** (`goal.kind: base`): wyłącznie faza bazy, odciążenie co 4. tydzień (P-2), wzrost do `peakWeeklyKm` albo +15% bieżącej objętości i plateau; bez taperu, predykcji i tygodnia startowego | +15% — wartość inż. | **brak źródła** (inż.); spójne z P-2/P-3 | **—** | ### 10.4 `engine/` — jednostki treningowe @@ -1684,6 +1686,9 @@ jako fakt). | R-5 | Po chorobie: konserwatywny restart | objętość ×0,5–0,6, zero Z3 przez 5–7 dni, potem progresja jak po przerwie | ekstrapolacja | **—** | | R-6 | Wyświetlać objawy wymagające lekarza, z cytowaniem | ból w klatce, omdlenie, duszność, kołatanie = bezwzględne przeciwwskazania | Ruuskanen 2023 | **D** | | R-7 | Silnik **nie udziela porad medycznych** | brak evidence-based guidelines; decyzja „personalized process between athlete and medical team" | Ruuskanen 2023 | D | +| R-8 | **Blok przejściowy po starcie ≥HM** — makrocykl nie kończy się w dniu zawodów | tydz. 1: ~50% średniej 4 tygodni przed tygodniem startu, wyłącznie spokojnie, bez długiego, pierwszy bieg 3. dnia po maratonie (R-1) / 2. dnia po HM; tydz. 2: ~100%, najwyżej jeden akcent | korpus trenerski: **3 długie starty** z pełnym pokryciem 14 dni (2 maratony i dłuższe, 1 HM) — mediany: tydz. 1 0,5×, 2–3 sesje, pierwszy bieg 4. dnia, pierwszy akcent 7–8. dnia; tydz. 2 1,0× (`tools/corpus/post_race_profile.py`); spójne z R-1/R-2 i N-15 | **korpus (n=3)** + B | +| R-9 | Siła wraca w **drugim** tygodniu po starcie, jedną lżejszą sesją | — | **brak źródła** (inż.); spójne z F-13 | **—** | +| R-10 | Po krótszym celu (<21 km): **jeden** tydzień przejściowy ~70% | — | **brak źródła** (inż.); korpus nie pokrywa tygodni po krótkich startach docelowych | **—** | ### 10.7 `solver/` — ograniczenia renegocjacji tygodnia @@ -1720,6 +1725,7 @@ jako fakt). | F-14 | Utrzymanie poza blokiem: 1 sesja/tyg. wystarcza | 13 tyg. utrzymania zachowuje przyrost siły i CSA — **dane z kolarzy, ekstrapolacja** | Rønnestad 2010 (PMID 20799042) | B (pośredni) | | F-15 | **Uczciwość wobec 34–45 lat**: w tej grupie wiekowej efekt na ekonomię jest NIEISTOTNY — moduł nie obiecuje sekund, tylko przenoszenie zakupów po schodach | 21–31,5 lat: g=−0,51 ist.; 34,1–44,8 lat: g=−0,12 [−0,41; 0,17] n.i. | Eihara 2022 (10.1186/s40798-022-00511-1) | **A−** | | F-16 | Durability: siła podtrzymuje ekonomię w końcówce długiego wysiłku | RE po 90 min: +2,1% vs −0,6% kontroli (p=0,04); TTE @95% VO₂max +35% | Zanini 2025 (10.1249/MSS.0000000000003685; **1 RCT, n=28**) | B | +| F-18 | **Wejście w blok siły**: dwa pierwsze tygodnie 3 × 6 przy ~75% 1RM, zanim przyjdzie ≥80% (F-4); w szczycie jedna sesja podtrzymująca (F-12, F-14) | ~75% 1RM, 2 tyg. — wartości inż. | **brak źródła** (inż.) | **—** | | F-17 | Wynik z siły potwierdzony tylko w LABORATORIUM na 1,5–10 km — **zero badań nad maratonem/HM i realnymi zawodami**; częsty konfundent: siłę DOKŁADANO do treningu (grupy różniły się całkowitym obciążeniem) | TT/TTE: ES −0,469 [−0,872; −0,066] (ciężka siła) | Llanos-Lagos 2024b (10.1007/s40279-024-02018-z, 38 badań, 894 os.); zastrzeżenie: Blagrove 2018 | **A−** | ### 10.9 Predykcja wyniku @@ -1843,6 +1849,15 @@ Wartości 2, 50%, 60%, 0,1 km i 15 minut są progami inżynierskimi, nie zalecen fizjologicznymi. Starty i sprawdziany nie są skracane. Brak wykonalnego wariantu prowadzi do komunikatu o przesunięciu treningu lub dniu wolnym, bez zmiany planu. +**E-2** — budżet czasu z profilu (`time` w `trainctl.yaml`): tydzień ponad +`weeklyMinutes` dostaje niższy cel kilometrów (nadwyżka minut przeliczona po +wolniejszej granicy tempa spokojnego, do czterech przebiegów) i jest generowany od +nowa; dzień ponad limitem dnia (`weekdayMinutes` / `weekendMinutes`) przechodzi +przez skracanie E-1 i niesie jawny `timeAdjustment` z pochodzeniem „profil". +Przygotowanie 15 minut jak w E-1. Startów i sprawdzianów nie skracamy. Gdy budżet +ogranicza szczyt poniżej progu dla dystansu (P-7/P-8), plan mówi o tym wprost. +To wybór inżynierski: żadne badanie nie mówi, jak przeliczać minuty na bodziec. + ## 11. DO WERYFIKACJI Rzeczy, których **nie** potwierdzono z pierwszej ręki. Nic z tej listy nie powinno @@ -1904,6 +1919,11 @@ Te muszą być oznaczone w kodzie jako heurystyki, nie jako reguły oparte na do 8. **Czy istnieje RCT treningu siłowego na biegaczach elitarnych.** Nie znaleziono; trzy niezależne zespoły (Balsalobre-Fernández, Zecchin, Eihara) niezależnie zgłaszają tę samą lukę. +9. **Przelicznik wyniku z trailu na szosę.** Nie znaleziono walidowanej metody + (przewyższenie, nawierzchnia i technika zbiegu działają naraz). Stąd Z-10 + odkłada wyniki z trailu zamiast je przeliczać. +10. **Kształt powrotu po starcie.** Poza R-1/R-2 (48 h po maratonie) brak badań nad + objętością kolejnych tygodni; R-8 opiera się na trzech startach z korpusu. ### 11.3 Znane niespójności w źródłach (do rozstrzygnięcia lub udokumentowania) diff --git a/package.json b/package.json index be40158..8269b04 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "trainctl-monorepo", - "version": "0.3.0", + "version": "0.4.0", "private": true, "description": "Running coach in your terminal: training plan as code in a git repo, coach as a tool for your agent (CLI + MCP)", "keywords": [ @@ -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..a0b3ae0 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "trainctl", - "version": "0.3.0", + "version": "0.4.0", "description": "Running coach in your terminal: training plan as code in a git repo (init/plan/today/why/reschedule/check)", "keywords": [ "running", @@ -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/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/agents-md.ts b/packages/cli/src/agents-md.ts index 9e8f0f8..2515c35 100644 --- a/packages/cli/src/agents-md.ts +++ b/packages/cli/src/agents-md.ts @@ -8,7 +8,8 @@ * samym języku, co `plan/PLAN.md` i wyjście komend. */ import { ui } from './i18n/index.ts' +import { foundationsUrl } from './rules-explain.ts' export const AGENTS_FILE = 'AGENTS.md' -export const agentsTemplate = (): string => ui().agentsMd() +export const agentsTemplate = (): string => ui().agentsMd(foundationsUrl()) 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..920f234 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' @@ -23,24 +25,50 @@ import { cmdPush, cmdReschedule, cmdReview, + cmdRules, 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 { select } from './ui/select.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 +78,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 +88,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 +100,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 +158,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 +169,238 @@ 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) + .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, agent: opts.agent })) + } + try { + const answers = await runWizard(theme, { + available: hasApiKey(cwd), + force: opts.fromIntervals === true, + fetch: () => fetchInferredProfile(cwd, localToday()), + }) + // 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}`)) + 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('--strength ', ui().cmd.optStrength) + .option('--minutes ', ui().cmd.optMinutes) + .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', 'strength', 'minutes'].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) + .option('--from ', ui().cmd.optPullFrom), + '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 +408,37 @@ 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') + .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 +455,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/calibration.ts b/packages/cli/src/calibration.ts index 1d3fd8e..e077ecc 100644 --- a/packages/cli/src/calibration.ts +++ b/packages/cli/src/calibration.ts @@ -8,10 +8,10 @@ export interface Calibration { policy: 'best-vdot-540-days' results: RaceResult[] selected?: RaceResult - candidates: { result: RaceResult; ageDays: number; vdot: number; reason: 'selected' | 'lower-vdot' | 'excluded' | 'future' | 'stale' }[] + candidates: { result: RaceResult; ageDays: number; vdot: number; reason: 'selected' | 'lower-vdot' | 'excluded' | 'future' | 'stale' | 'terrain' }[] } -export function inspectCalibration(results: RaceResult[], today: string): Calibration { +export function inspectCalibration(results: RaceResult[], today: string, roadGoal = true): Calibration { const candidates: Calibration['candidates'] = results.map((result) => { const ageDays = diffDays(result.date, today) return { @@ -19,6 +19,10 @@ export function inspectCalibration(results: RaceResult[], today: string): Calibr reason: result.excluded ? 'excluded' : ageDays < 0 ? 'future' : ageDays > 540 ? 'stale' : 'lower-vdot', } }) + // Z-10: trail odpada, gdy jest wynik szosowy (ta sama reguła co w computePlan) + if (roadGoal && candidates.some((c) => c.reason === 'lower-vdot' && c.result.terrain !== 'trail')) { + for (const c of candidates) if (c.reason === 'lower-vdot' && c.result.terrain === 'trail') c.reason = 'terrain' + } const selected = candidates.filter((c) => c.reason === 'lower-vdot').sort((a, b) => b.vdot - a.vdot || a.ageDays - b.ageDays)[0] if (selected) selected.reason = 'selected' return { evaluatedAt: today, policy: 'best-vdot-540-days', results: structuredClone(results), candidates, ...(selected ? { selected: selected.result } : {}) } 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/cli-040.test.ts b/packages/cli/src/cli-040.test.ts new file mode 100644 index 0000000..f257281 --- /dev/null +++ b/packages/cli/src/cli-040.test.ts @@ -0,0 +1,381 @@ +/** + * 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, renameSync, 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, 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) +}) + +/** Zmienna klucza na czas testu — z przywróceniem wartości, którą miał programista. */ +function withKeyEnv(value: string | undefined, fn: () => void): void { + const previous = process.env['TRAINCTL_INTERVALS_API_KEY'] + if (value === undefined) delete process.env['TRAINCTL_INTERVALS_API_KEY'] + else process.env['TRAINCTL_INTERVALS_API_KEY'] = value + try { + fn() + } finally { + if (previous === undefined) delete process.env['TRAINCTL_INTERVALS_API_KEY'] + else process.env['TRAINCTL_INTERVALS_API_KEY'] = previous + } +} + +describe('status', () => { + it('pusty katalog: profil jest, planu nie ma — podpowiada plan', () => { + let r!: ReturnType + withKeyEnv(undefined, () => { 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') + // bin.ts wczytuje .env do środowiska przed komendą — tu robimy to samo + withKeyEnv('super-secret-value', () => { + 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' } }) + }) + }) + it('źródło klucza w tej samej kolejności co push: zmienna przed plikiem, pusty plik to brak klucza', () => { + withKeyEnv(undefined, () => { + writeFileSync(join(dir, '.trainctl-secret'), ' \n', 'utf-8') + expect(cmdStatus(dir).data).toMatchObject({ key: { source: null } }) + writeFileSync(join(dir, '.trainctl-secret'), 'abc', 'utf-8') + expect(cmdStatus(dir).data).toMatchObject({ key: { source: '.trainctl-secret' } }) + }) + withKeyEnv('from-env', () => { + expect(cmdStatus(dir).data).toMatchObject({ key: { source: 'environment variable' } }) + }) + }) + it('połamany log.jsonl: status mówi, co jest nie tak, zamiast rzucać wyjątkiem', () => { + cmdPlan(dir, { date: '2026-08-08' }) + writeFileSync(join(dir, 'log.jsonl'), '{"date":"2026-08-11"\n', 'utf-8') + const r = cmdStatus(dir) + expect(r.code).toBe(1) + expect(r.data).toMatchObject({ error: expect.any(String) }) + }) + it('podpowiedź commita wymienia tylko pliki treningowe, nigdy git add -A', () => { + cmdPlan(dir, { date: '2026-08-08' }) + execFileSync('git', ['init', '-q'], { cwd: dir }) + const out = cmdStatus(dir).output + expect(out).not.toContain('git add -A') + expect(out).toMatch(/git add -- .*trainctl\.yaml.* && git commit/) + }) + it('podpowiedź commita: usunięty plik wchodzi, ignorowany nie; ścieżki względem katalogu treningowego', () => { + const root = mkdtempSync(join(tmpdir(), 'trainctl-040-repo-')) + try { + const training = join(root, 'training') + mkdirSync(training) + writeFileSync(join(training, 'trainctl.yaml'), CONFIG, 'utf-8') + writeFileSync(join(training, 'AGENTS.md'), '# coach\n', 'utf-8') + writeFileSync(join(training, '.gitignore'), 'log.jsonl\n', 'utf-8') + const git = (args: string[]) => execFileSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@example.test', ...args], { cwd: training, encoding: 'utf-8' }) + execFileSync('git', ['init', '-q'], { cwd: root }) + git(['add', '-A']) + git(['commit', '-qm', 'init']) + rmSync(join(training, 'AGENTS.md')) + writeFileSync(join(training, 'trainctl.yaml'), `${CONFIG}# edited\n`, 'utf-8') + writeFileSync(join(training, 'log.jsonl'), '', 'utf-8') + const r = cmdStatus(training) + expect(r.data).toMatchObject({ git: { uncommitted: ['AGENTS.md', 'trainctl.yaml'] } }) + const paths = r.output.match(/git add -- (.*?) && git commit/)![1]!.split(' ') + expect(paths).toEqual(['AGENTS.md', 'trainctl.yaml']) + // komenda z podpowiedzi działa i zapisuje także usunięcie + git(['add', '--', ...paths]) + expect(git(['status', '--porcelain'])).toContain('D training/AGENTS.md') + } finally { + rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) + } + }) + it('rename w drzewie roboczym (git add -N): nowa i stara ścieżka, podpowiedź zapisuje cały rename', () => { + cmdPlan(dir, { date: '2026-08-08' }) + const git = (args: string[]) => execFileSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@example.test', ...args], { cwd: dir, encoding: 'utf-8' }) + git(['init', '-q']) + git(['add', '-A']) + git(['commit', '-qm', 'init']) + renameSync(join(dir, 'plan', 'PLAN.md'), join(dir, 'plan', 'PLAN-old.md')) + git(['add', '-N', 'plan/PLAN-old.md']) + const r = cmdStatus(dir) + expect(r.data).toMatchObject({ git: { uncommitted: ['plan/PLAN-old.md', 'plan/PLAN.md'] } }) + git(['add', '--', ...r.output.match(/git add -- (.*?) && git commit/)![1]!.split(' ')]) + expect(git(['status', '--porcelain'])).not.toMatch(/^ D/m) + }) + it('plik planu, którego nie da się użyć: status nie podpowiada trainctl plan (plan by odmówił)', () => { + mkdirSync(join(dir, 'plan'), { recursive: true }) + writeFileSync(join(dir, 'plan', 'plan.yaml'), '<<<<<<< HEAD\nweeks: [\n', 'utf-8') + const r = cmdStatus(dir) + expect(r.output).toContain('not valid YAML') + expect(r.output).not.toContain('next: trainctl plan') + }) + it('plan z nowszego schematu: status radzi aktualizację trainctl', () => { + cmdPlan(dir, { date: '2026-08-08' }) + const yaml = join(dir, 'plan', 'plan.yaml') + writeFileSync(yaml, readFileSync(yaml, 'utf-8').replace('schemaVersion: 1', 'schemaVersion: 2'), 'utf-8') + const r = cmdStatus(dir) + expect(r.output).toContain('upgrade trainctl') + expect(r.output).not.toContain('next: trainctl plan') + }) +}) + +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('init --commit commituje tylko to, co zapisał — nie cudze zmiany w AGENTS.md', () => { + rmSync(join(dir, 'trainctl.yaml')) + execFileSync('git', ['init', '-q'], { cwd: dir }) + writeFileSync(join(dir, 'AGENTS.md'), '# my own coach notes\n', 'utf-8') + writeFileSync(join(dir, '.gitignore'), '.env\n.env.*\n.trainctl-secret\nactivities/\n', 'utf-8') + const r = cmdInit(dir, undefined, { commit: true }) + expect(r.code).toBe(0) + expect(gitOut(['show', '--name-only', '--format=', 'HEAD']).trim().split('\n')).toEqual(['trainctl.yaml']) + }) + it('init --commit: czysty, zacommitowany .gitignore po dopisaniu wzorców trafia do commita', () => { + rmSync(join(dir, 'trainctl.yaml')) + execFileSync('git', ['init', '-q'], { cwd: dir }) + writeFileSync(join(dir, '.gitignore'), 'node_modules/\n', 'utf-8') + gitOut(['add', '.gitignore']) + gitOut(['commit', '-qm', 'ignore']) + const r = cmdInit(dir, undefined, { commit: true }) + expect(r.code).toBe(0) + expect(gitOut(['show', '--name-only', '--format=', 'HEAD']).trim().split('\n').sort()).toEqual(['.gitignore', 'AGENTS.md', 'trainctl.yaml']) + expect(gitOut(['show', 'HEAD:.gitignore'])).toContain('.env') + expect(r.output).not.toContain('commit it yourself') + }) + it('init --commit: .gitignore z cudzymi, niezacommitowanymi zmianami zostaje poza commitem — z notą', () => { + rmSync(join(dir, 'trainctl.yaml')) + execFileSync('git', ['init', '-q'], { cwd: dir }) + writeFileSync(join(dir, '.gitignore'), 'node_modules/\n', 'utf-8') + const r = cmdInit(dir, undefined, { commit: true }) + expect(r.code).toBe(0) + expect(gitOut(['show', '--name-only', '--format=', 'HEAD'])).not.toContain('.gitignore') + expect(r.output).toContain('commit it yourself') + }) + it('init --commit przy status.showUntrackedFiles=no: niezacommitowany .gitignore dalej poza commitem', () => { + rmSync(join(dir, 'trainctl.yaml')) + execFileSync('git', ['init', '-q'], { cwd: dir }) + gitOut(['config', 'status.showUntrackedFiles', 'no']) + writeFileSync(join(dir, '.gitignore'), 'my-private-notes/\n', 'utf-8') + const r = cmdInit(dir, undefined, { commit: true }) + expect(r.code).toBe(0) + expect(gitOut(['show', '--name-only', '--format=', 'HEAD'])).not.toContain('.gitignore') + expect(r.output).toContain('commit it yourself') + }) + it('init --commit poza repozytorium: bez noty o .gitignore, która nie ma sensu bez gita', () => { + rmSync(join(dir, 'trainctl.yaml')) + writeFileSync(join(dir, '.gitignore'), 'node_modules/\n', 'utf-8') + const r = cmdInit(dir, undefined, { commit: true }) + expect(r.output).toContain('Not a git repository') + expect(r.output).not.toContain('commit it yourself') + }) + 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.test.ts b/packages/cli/src/commands.test.ts index 2266669..e0da917 100644 --- a/packages/cli/src/commands.test.ts +++ b/packages/cli/src/commands.test.ts @@ -65,10 +65,11 @@ describe('trainctl plan', () => { expect(md).toContain('truchtu') }) - it('plan.yaml wczytuje się z powrotem (17 tygodni, race week na końcu)', () => { + it('plan.yaml wczytuje się z powrotem (17 tygodni do startu, potem 2 tygodnie po starcie — R-8)', () => { const plan = loadPlan(dir) - expect(plan.weeks).toHaveLength(17) - expect(plan.weeks.at(-1)!.skeleton.raceDate).toBe('2026-11-29') + expect(plan.weeks).toHaveLength(19) + expect(plan.weeks[16]!.skeleton.raceDate).toBe('2026-11-29') + expect(plan.weeks.slice(17).map((w) => w.skeleton.phase)).toEqual(['transition', 'transition']) expect(plan.vdotSource).toBe('result') }) }) diff --git a/packages/cli/src/commands.ts b/packages/cli/src/commands.ts index 8435ca5..16f88bf 100644 --- a/packages/cli/src/commands.ts +++ b/packages/cli/src/commands.ts @@ -8,16 +8,19 @@ import { getLocale, inferProfile, estimateWorkoutMinutes, + formatNumber, messages, mondayOf, parseIso, planDeskDay, + plannedWeekKm, reschedule, validatePlan, weekTotals, COACH_STYLE, INFER_WINDOW_WEEKS, type ExecutionRecord, + type ActivitySource, type InferenceOutcome, type PlanIssue, type PlannedWorkout, @@ -28,28 +31,47 @@ import { AGENTS_FILE, agentsTemplate } from './agents-md.ts' import { ENV_FILE } from './env-file.ts' import { ui } from './i18n/index.ts' import { inferredConfigYaml, loadConfig, writeConfigTemplate, CONFIG_FILE } from './config.ts' -import { appendLog, logFor, parseTime, readLog, type LogEntry } from './logfile.ts' +import { appendLog, logFor, parseTime, readLog, readStrengthLog, type LogEntry, type StrengthLogEntry } from './logfile.ts' import { computePlan, + cycleWeeksOf, + dayFingerprint, findDay, fmtTime, loadPlan, loadPlanFile, + planEnd, + readExistingPlan, readPlanDocument, shiftWorkout, + unusablePlanMessage, workoutText, + weekPosition, writePlan, PLAN_MD, 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 { clockToday } from './clock.ts' +import { rebuildPlan, type Regeneration } from './regenerate.ts' +import { commitFiles, uncommitted, type CommitOutcome } 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' 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, raceDayKm, recordedDates, type PlanProposal } from './proposals.ts' import { explainSession } from './explain-session.ts' export { buildExecution } from './execution.ts' @@ -74,6 +96,7 @@ export const kindLabel = (kind: string): string => export const phaseLabel = (phase: string): string => (messages().phase as Record)[phase] ?? phase import { + chooseSource, compare, defaultProviderFactory, defaultRange, @@ -110,12 +133,48 @@ const fail = (e: unknown): CmdResult => { return { output: message, code: 1, blocks: [b.error(message)] } } -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())}` +/** 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. + */ +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))] +} + +/** „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/… */ const weekdayShort = (day: Weekday): string => messages().weekdayShort[day] @@ -209,7 +268,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, @@ -229,45 +289,103 @@ 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; 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) + // tylko pliki, które init faktycznie zapisał — cudze zmiany w AGENTS.md czy + // .gitignore nie trafiają do commita „trainctl init" + const committed = withCommit(result, cwd, opts.commit, (result.data?.['written'] as string[] | undefined) ?? [], ui().commit.init) + // nota tylko wtedy, gdy commit naprawdę był (nie przy braku gita) — ta sama + // reguła co w withCommit: każda wartość poza undefined/false to prośba o commit + const outcome = committed.data?.['commit'] as CommitOutcome | null | undefined + if (outcome && outcome.status !== 'no-git' && result.data?.['gitignoreAppended'] && committed.blocks) { + const blocks = [...committed.blocks, b.info(ui().init.gitignoreNotCommitted)] + return { ...committed, blocks, output: renderPlain(blocks) } + } + return committed +} + +/** + * 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 | undefined, agent: AgentChoice | undefined): CmdResult { try { writeConfigTemplate(cwd, content) const agents = writeAgentsFile(cwd) + // .gitignore zapisany od zera albo czysty (zacommitowany, bez zmian) trafia do + // commita także po dopisaniu wzorców — inaczej inne klony repo zostają bez + // ochrony .env. Z cudzymi, niezacommitowanymi zmianami — nie: `git add` wziąłby je. + const hadGitignore = existsSync(join(cwd, '.gitignore')) + const gitignoreClean = hadGitignore && uncommitted(cwd, ['.gitignore'])?.length === 0 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, + written: [CONFIG_FILE, ...(agents ? [AGENTS_FILE] : []), ...(ignored.length && (!hadGitignore || gitignoreClean) ? ['.gitignore'] : []), ...integration.files], + gitignoreAppended: ignored.length > 0 && hadGitignore && !gitignoreClean, + }) } catch (e) { return fail(e) } } -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 found = readExistingPlan(cwd) + if (found.status === 'unreadable' && opts.fresh !== true) throw new Error(unusablePlanMessage(found)) + const existing = found.status === 'ok' ? found.plan : undefined + const rebuild = existing && opts.fresh !== true + ? rebuildPlan(existing, config, { today, recorded: recordedDates(cwd), raceDayKm: () => raceDayKm(cwd, existing) }) + : 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`, - `${plan.goal.date} · ${ui().plan.weeksOfPlan(weeksToRace)}`, + plan.goal.kind === 'base' ? plan.goal.name : `${plan.goal.name} · ${plan.goal.distanceKm} km`, + `${plan.goal.kind === 'base' ? ui().plan.baseUntil(plan.goal.date) : plan.goal.date} · ${ui().plan.weeksOfPlan(weeksToRace)}`, ), b.kv([ [ui().plan.volumePeak, messages().units.kmPerWeek(plan.peakKmPlanned)], - [ui().plan.recommendedForDistance, messages().units.kmPerWeek(plan.peakKmRecommended)], + ...(plan.peakKmRecommended > 0 ? ([[ui().plan.recommendedForDistance, messages().units.kmPerWeek(plan.peakKmRecommended)]] as [string, string][]) : []), [ ui().plan.vdot, `${plan.vdot} (${plan.vdotSource === 'result' ? ui().plan.vdotFromResult : ui().plan.vdotFromGoal})`, @@ -308,7 +426,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)) @@ -316,8 +434,14 @@ 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 (found.status === 'unreadable') blocks.push(b.blank(), b.warn(ui().plan.overwroteUnreadable(PLAN_YAML))) if (plan.feasibilityWarnings.length) { blocks.push(b.blank()) @@ -326,15 +450,61 @@ 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))) + if (r.mode === 'new-cycle') blocks.push(b.info(t.newCycleVolume(r.plan.loadState?.baselineWeeklyKm ?? plannedWeekKm(cycleWeeksOf(r.plan)[0]?.skeleton ?? { targetKm: 0 })))) + 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() @@ -342,7 +512,7 @@ export function cmdToday(cwd: string, opts: { date?: string | undefined } = {}): const hit = findDay(plan, date) if (!hit) { return okDoc([ - b.warn(ui().common.outsidePlan(date, plan.weeks[0]?.weekStart ?? '', plan.goal.date)), + b.warn(ui().common.outsidePlan(date, plan.weeks[0]?.weekStart ?? '', planEnd(plan))), ]) } const { week, day } = hit @@ -351,9 +521,10 @@ 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)}` + - `${sk.deload ? ` · ${ui().today.deload}` : ''} · ${ui().today.daysToRace(toRace)}`, + `${ui().today.weekOf(weekPosition(plan, week).index + 1, weekPosition(plan, week).total)} · ${phaseLabel(sk.phase)}` + + `${sk.deload ? ` · ${ui().today.deload}` : ''} · ${raceDistanceLine(plan, toRace)}`, ), + ...compatibilityNotes(plan), ] if (!day.workout) { @@ -394,9 +565,17 @@ export function cmdToday(cwd: string, opts: { date?: string | undefined } = {}): ), ) } + const strengthEntry = readStrengthLog(cwd).filter((e) => e.date === date).at(-1) + if (strengthEntry) blocks.push(b.success(ui().today.strengthLogged(strengthEntry.status))) + 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) } @@ -407,7 +586,7 @@ export function cmdWeek(cwd: string, opts: { date?: string | undefined } = {}): const date = opts.date ?? localToday() const plan = loadPlan(cwd) const hit = findDay(plan, date) - if (!hit) return ok(ui().common.outsidePlan(date, plan.weeks[0]?.weekStart ?? '', plan.goal.date)) + if (!hit) return ok(ui().common.outsidePlan(date, plan.weeks[0]?.weekStart ?? '', planEnd(plan))) const { week } = hit const sk = week.skeleton const model = messages().intensityModel[sk.intensityModel] @@ -429,10 +608,11 @@ 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.subtitle(phaseLabel(sk.phase), model, sk.targetKm, week.totalKm) + + ui().week.title(weekPosition(plan, week).index + 1, weekPosition(plan, week).total, week.weekStart), + ui().week.subtitle(phaseLabel(sk.phase), model, plannedWeekKm(sk), 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))) @@ -445,22 +625,31 @@ 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 + /** Zapis siły zamiast biegu: done | skipped. */ + strength?: string | undefined + minutes?: string | number | 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) if (!findDay(plan, date)) return fail(new Error(ui().log.outsidePlan(date))) + if (opts.strength !== undefined) return logStrength(cwd, plan, date, opts) const status = (opts.status ?? 'done') as 'done' | 'skipped' | 'modified' if (!['done', 'skipped', 'modified'].includes(status)) { return fail(new Error(ui().log.unknownStatus(String(opts.status)))) @@ -476,7 +665,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,14 +674,72 @@ 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) } } -export function cmdShift(cwd: string, opts: { from: string; to: string }): CmdResult { +/** + * Dziennik siły (E4): osobny wpis obok biegu. Bez kilometrów, tempa i RPE — + * siła to inny tor, a dziennik ma powiedzieć tylko, czy sesja się odbyła. + */ +function logStrength(cwd: string, plan: StoredPlan, date: string, opts: LogOptions): CmdResult { + const t = ui().log + if (opts.strength !== 'done' && opts.strength !== 'skipped') throw new Error(t.strengthStatus(String(opts.strength))) + if ([opts.km, opts.time, opts.testTime, opts.rpe].some((v) => v !== undefined)) throw new Error(t.strengthOnly) + const minutes = opts.minutes === undefined ? undefined : Number(opts.minutes) + if (minutes !== undefined && (!Number.isInteger(minutes) || minutes < 1 || minutes > 300)) throw new Error(t.strengthMinutes) + const entry: StrengthLogEntry = { + date, + activity: 'strength', + status: opts.strength, + ...(minutes !== undefined ? { minutes } : {}), + ...(opts.note ? { note: opts.note } : {}), + loggedAt: new Date().toISOString(), + } + appendLog(cwd, entry) + const planned = findDay(plan, date)!.day.strength + const blocks: Block[] = [ + b.success(t.strengthSaved(date, entry.status)), + b.kv([[t.planned, planned ? ui().today.strengthTitle(planned.durationMin) : ui().week.rest]]), + ] + if (!planned && entry.status === 'done') blocks.push(b.info(t.strengthUnplanned)) + return okDoc(blocks, { entry, planned: planned ?? null }) +} + +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) @@ -524,7 +771,7 @@ export function cmdWhy(cwd: string, opts: { date?: string | undefined } = {}): C parseIso(date) const plan = loadPlan(cwd) const hit = findDay(plan, date) - if (!hit) return ok(ui().common.outsidePlan(date, plan.weeks[0]?.weekStart ?? '', plan.goal.date)) + if (!hit) return ok(ui().common.outsidePlan(date, plan.weeks[0]?.weekStart ?? '', planEnd(plan))) const { week, day } = hit const sk = week.skeleton const execution = buildExecution(plan, readSnapshot(cwd)?.activities ?? [], readLog(cwd), localToday()).find(e => e.date === date) @@ -536,45 +783,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) @@ -623,6 +857,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(', ')))] : []), @@ -641,18 +876,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)) @@ -672,6 +910,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') @@ -697,7 +938,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) } @@ -713,7 +954,8 @@ function analyzeAdapt(cwd: string, opts: { date?: string | undefined } = {}): Cm const execution = buildExecution(plan, snapshot?.activities ?? [], logs, today) const currentWeek = plan.weeks.find((w) => w.days.some((d) => d.date === today)) - const currentWeeklyKm = currentWeek?.skeleton.targetKm ?? plan.peakKmPlanned + // objętość, którą biegacz faktycznie dostał (po budżecie czasu) — od niej liczą się sugestie + const currentWeeklyKm = currentWeek ? plannedWeekKm(currentWeek.skeleton) : plan.peakKmPlanned const known = new Set((plan.calibration?.results ?? []).map(resultKey)) const newResults = config.athlete.results.filter( (r) => !r.excluded && r.date <= today && (plan.calibration ? !known.has(resultKey(r)) : r.date > plan.generatedAt), @@ -799,7 +1041,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) { @@ -826,11 +1073,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() @@ -906,19 +1153,27 @@ 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) } } -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) + if (result.code !== 0) return result + 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) @@ -1109,18 +1364,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) } @@ -1133,6 +1395,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 @@ -1147,6 +1410,7 @@ export async function cmdReview( b.kv([ [ui().review.volume, ui().review.volumeValue(Math.round(actualKm), Math.round(plannedKm))], [ui().review.doneSessions, `${done}/${rows.filter((r) => r.plannedKm > 0).length}`], + ...strengthRow(plan, readStrengthLog(cwd), from, today), ...(missed.length ? ([[ui().compare.missed, missed.map((r) => r.date.slice(5)).join(', ')]] as [string, string][]) : []), @@ -1166,13 +1430,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 @@ -1207,8 +1488,11 @@ 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)], - [ui().review.toRace, ui().review.toRaceValue(diffDays(today, plan.goal.date))], + // 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)], + ...(plan.goal.kind === 'base' + ? ([[ui().review.baseEnd, plan.goal.date]] as [string, string][]) + : ([[ui().review.toRace, raceDistanceLine(plan, diffDays(today, plan.goal.date))]] as [string, string][])), ]), ) const race = upcoming.find((d) => d.workout?.kind === 'race') @@ -1236,7 +1520,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) @@ -1377,14 +1661,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], { issues: [], errors: 0, warnings: 0 }) } - 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))) @@ -1400,7 +1686,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) } @@ -1433,12 +1751,15 @@ function diffWeeks(from: StoredPlan['weeks'], to: StoredPlan['weeks']): string[] lines.push(t.weekGone(week.weekStart)) continue } - if (f.skeleton.targetKm !== week.skeleton.targetKm) { - lines.push(t.weekVolume(week.weekStart, week.skeleton.targetKm, f.skeleton.targetKm)) + const volumeChanged = plannedWeekKm(f.skeleton) !== plannedWeekKm(week.skeleton) + if (volumeChanged) { + lines.push(t.weekVolume(week.weekStart, plannedWeekKm(week.skeleton), plannedWeekKm(f.skeleton))) } - // targetKm to zamiar szkieletu, totalKm — plan faktycznie rozpisany na dni. - // Scenariusz bywa zmianą wyłącznie tego drugiego (skrócone jednostki). - if (kmDiffers(week.totalKm, f.totalKm)) { + // cel tygodnia to zamiar szkieletu (po budżecie czasu), totalKm — plan faktycznie rozpisany na dni. + // Scenariusz bywa zmianą wyłącznie tego drugiego (skrócone jednostki). Gdy sumy + // dni powtarzają cel (tydzień przycięty budżetem), druga linia byłaby echem pierwszej. + const totalsEchoTarget = !kmDiffers(week.totalKm, plannedWeekKm(week.skeleton)) && !kmDiffers(f.totalKm, plannedWeekKm(f.skeleton)) + if (kmDiffers(week.totalKm, f.totalKm) && !(volumeChanged && totalsEchoTarget)) { lines.push(t.weekTotalKm(week.weekStart, week.totalKm ?? 0, f.totalKm ?? 0)) } const fd = new Map(f.days.map((d) => [d.date, d])) @@ -1471,7 +1792,7 @@ function diffWeeks(from: StoredPlan['weeks'], to: StoredPlan['weeks']): string[] } for (const w of to) { if (!from.some((s) => s.weekStart === w.weekStart)) { - lines.push(t.weekNew(w.weekStart, w.skeleton.targetKm)) + lines.push(t.weekNew(w.weekStart, plannedWeekKm(w.skeleton))) } } return lines @@ -1517,9 +1838,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), raceDayKm: () => raceDayKm(cwd, stored) }) + 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 @@ -1531,21 +1855,50 @@ 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) } } +/** + * Siła w przeglądzie: ile zaplanowanych sesji odnotowano — liczba, bez wniosków. + * Wiersz pojawia się tylko wtedy, gdy siła była w planie albo w dzienniku. + */ +function strengthRow(plan: StoredPlan, entries: StrengthLogEntry[], from: string, to: string): [string, string][] { + const planned = plan.weeks.flatMap((w) => w.days).filter((d) => d.strength && d.date >= from && d.date <= to).length + const latest = new Map() + for (const e of entries) if (e.date >= from && e.date <= to) latest.set(e.date, e) + if (!planned && !latest.size) return [] + const done = [...latest.values()].filter((e) => e.status === 'done').length + const skipped = [...latest.values()].filter((e) => e.status === 'skipped').length + return [[ui().review.strength, ui().review.strengthValue(done, planned, skipped)]] +} + +/** „N dni do startu", „N dni po starcie" albo koniec planu bazowego (P-11). */ +function raceDistanceLine(plan: StoredPlan, toRace: number): string { + if (plan.goal.kind === 'base') return ui().plan.baseUntil(plan.goal.date) + return toRace >= 0 ? ui().today.daysToRace(toRace) : ui().today.daysAfterRace(-toRace) +} + +/** 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/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/config.ts b/packages/cli/src/config.ts index fad31b7..4d1850d 100644 --- a/packages/cli/src/config.ts +++ b/packages/cli/src/config.ts @@ -24,11 +24,29 @@ export interface StrengthConfig { days?: Weekday[] } +/** + * Czas na trening (E-2): ile minut realnie masz — razem z przygotowaniem i siłą. + * Bez tej sekcji plan liczy się w kilometrach, jak dotąd. + */ +export interface TimeConfig { + weeklyMinutes?: number + weekdayMinutes?: number + weekendMinutes?: number +} + +/** Ź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 + time?: TimeConfig /** Język interfejsu i opisów planu: 'en' (domyślny) albo 'pl'. */ language?: string } @@ -96,6 +114,12 @@ export function configTemplate(): string { pad('# strength:', t.templateStrength.section), pad('# enabled: true', t.templateStrength.enabled), pad('# days: [mon, fri]', t.templateStrength.days), + pad('# time:', t.templateTime.section), + pad('# weeklyMinutes: 300', t.templateTime.weekly), + pad('# weekdayMinutes: 60', t.templateTime.weekday), + pad('# weekendMinutes: 120', t.templateTime.weekend), + pad('# sync:', t.templateSync.section), + pad('# files: ./activities', t.templateSync.files), '', ].join('\n') } @@ -153,8 +177,19 @@ export function loadConfig(cwd: string): TrainctlConfig { }) } } + const base = (g as { kind?: unknown } | undefined)?.kind === 'base' + if (g && base) { + // P-11: plan bez zawodów — wystarczy data końca (`until`); dystans i cel czasowy nie istnieją + const until = (g as { until?: unknown }).until ?? g.date + if (!ISO_RE.test(String(until))) errors.push(v.isoDate('goal.until')) + else Object.assign(g, { date: String(until), distanceKm: 0, name: g.name || ui().configFile.baseGoalName }) + delete (g as { until?: unknown }).until + delete g.targetTimeSec + } else if ((g as { kind?: unknown } | undefined)?.kind !== undefined && (g as { kind?: unknown }).kind !== 'race') { + errors.push(v.goalKind('goal.kind')) + } if (!g) errors.push(v.missingSection('goal')) - else { + else if (!base) { if (g.targetTimeSec !== undefined && (!Number.isFinite(g.targetTimeSec) || g.targetTimeSec <= 0)) errors.push(v.seconds('goal.targetTimeSec')) if (!g.name) errors.push(v.required('goal.name')) if (!ISO_RE.test(String(g.date))) errors.push(v.isoDate('goal.date')) @@ -179,6 +214,22 @@ 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 time = raw?.time + if (time !== undefined) { + const errs: string[] = [] + if (typeof time !== 'object' || time === null) errs.push(v.required('time')) + else { + for (const key of ['weeklyMinutes', 'weekdayMinutes', 'weekendMinutes'] as const) { + const value = time[key] + if (value !== undefined && (!Number.isInteger(value) || value < 15 || value > 2000)) errs.push(v.minutes(`time.${key}`)) + } + } + if (errs.length) fail(errs) + } const athlete = a as AthleteProfile return { athlete: { @@ -192,6 +243,23 @@ export function loadConfig(cwd: string): TrainctlConfig { goal: { ...goal, priority: goal.priority ?? 'A' }, ...(desk ? { desk } : {}), ...(strength ? { strength } : {}), + ...(sync?.files ? { sync: { files: sync.files } } : {}), + ...(time ? { time } : {}), + } +} + +/** + * `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/cycle.test.ts b/packages/cli/src/cycle.test.ts new file mode 100644 index 0000000..9735c42 --- /dev/null +++ b/packages/cli/src/cycle.test.ts @@ -0,0 +1,278 @@ +/** + * Etap E (docs/PLAN-v0.4.md): życie po starcie (R-8…R-10) i plan bez startu (P-11) + * — od profilu przez plik planu do tego, co widzi biegacz. + */ +import { mkdtempSync, 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, validatePlan } from 'trainctl-core' +import { cmdCheck, cmdExport, cmdLog, cmdPlan, cmdReview, cmdToday, cmdWhy } from './commands.ts' +import { cycleWeeksOf, loadPlan } from './planfile.ts' +import { applyProposal, prepareProposal } from './proposals.ts' + +setLocale('en') + +const PROFILE = `athlete: + recentWeeklyKm: 50 + daysAvailable: [tue, wed, thu, sat, sun] + results: + - { date: "2026-03-29", distanceKm: 10, timeSec: 2580 } +strength: + enabled: true +` +const RACE = `${PROFILE}goal: + name: "Half marathon" + date: "2026-11-29" + distanceKm: 21.0975 + priority: A +` +const BASE = `${PROFILE}goal: + kind: base + until: "2026-10-25" +` + +let dir: string +beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'trainctl-cycle-')) }) +afterEach(() => { + delete process.env['TRAINCTL_TODAY'] + rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) +}) +const write = (yaml: string) => writeFileSync(join(dir, 'trainctl.yaml'), yaml, 'utf-8') + +describe('po starcie: blok przejściowy w planie i w tym, co widać', () => { + it('dwa tygodnie po półmaratonie: pierwszy spokojny, bez długiego i bez siły, bieganie od 2. dnia', () => { + write(RACE) + expect(cmdPlan(dir, { date: '2026-08-08' }).code).toBe(0) + const plan = loadPlan(dir) + const [t1, t2] = plan.weeks.filter((w) => w.skeleton.phase === 'transition') + expect(t1!.weekStart).toBe('2026-11-30') + const runs1 = t1!.days.filter((d) => d.workout) + expect(runs1.length).toBeGreaterThan(0) + expect(runs1.every((d) => d.workout!.kind === 'easy')).toBe(true) + expect(runs1.every((d) => d.date >= '2026-12-01')).toBe(true) + expect(t1!.days.some((d) => d.strength)).toBe(false) + expect(t2!.days.filter((d) => d.workout && ['quality_intervals', 'quality_continuous'].includes(d.workout.kind)).length).toBeLessThanOrEqual(1) + expect(t2!.days.filter((d) => d.strength).every((d) => d.strength!.kind === 'intro')).toBe(true) + expect(validatePlan(plan).filter((i) => i.severity === 'error')).toEqual([]) + expect(cmdCheck(dir).code).toBe(0) + }) + it('today i why po starcie mówią „po starcie", nie „poza planem"', () => { + write(RACE) + cmdPlan(dir, { date: '2026-08-08' }) + const plan = loadPlan(dir) + const day = plan.weeks.find((w) => w.skeleton.phase === 'transition')!.days.find((d) => d.workout)! + const today = cmdToday(dir, { date: day.date }) + expect(today.output).toContain('after the race') + expect(today.output).toMatch(/\d+ days? after the race/) + expect(cmdWhy(dir, { date: day.date }).output).toContain('Goal behind you') + }) + it('poza zakresem planu: koniec zakresu to koniec bloku przejściowego, nie dzień startu', () => { + write(RACE) + cmdPlan(dir, { date: '2026-08-08' }) + expect(cmdToday(dir, { date: '2027-01-20' }).output).toContain('2026-08-03 → 2026-12-13') + }) + it('w dniu startu, po zalogowaniu startu, nowy cel tego samego dystansu otwiera nowy cykl', () => { + write(RACE) + cmdPlan(dir, { date: '2026-08-08' }) + process.env['TRAINCTL_TODAY'] = '2026-11-29' + expect(cmdLog(dir, { date: '2026-11-29', km: '21.1', time: '1:35:10' }).code).toBe(0) + write(RACE.replace('2026-11-29', '2027-04-11')) + const r = cmdPlan(dir) + expect(r.code, r.output).toBe(0) + expect(r.data).toMatchObject({ regeneration: { mode: 'new-cycle' } }) + }) + it('start przełożony rano w dniu zawodów to ten sam cykl — taper się wydłuża, bez bloku po starcie', () => { + write(RACE) + cmdPlan(dir, { date: '2026-08-08' }) + process.env['TRAINCTL_TODAY'] = '2026-11-29' + write(RACE.replace('2026-11-29', '2026-12-06')) + const r = cmdPlan(dir) + expect(r.code, r.output).toBe(0) + expect(r.data).toMatchObject({ regeneration: { mode: 'same-cycle' } }) + expect(loadPlan(dir).weeks.find((w) => w.skeleton.raceDate)!.skeleton.raceDate).toBe('2026-12-06') + }) + it('rozruch rano w dniu startu i przełożenie startu: ten sam cykl, nie „start za nami"', () => { + write(RACE) + cmdPlan(dir, { date: '2026-08-08' }) + process.env['TRAINCTL_TODAY'] = '2026-11-29' + expect(cmdLog(dir, { date: '2026-11-29', km: '3' }).code).toBe(0) + write(RACE.replace('2026-11-29', '2026-12-06')) + const r = cmdPlan(dir) + expect(r.code, r.output).toBe(0) + expect(r.data).toMatchObject({ regeneration: { mode: 'same-cycle' } }) + }) + it('rozruch w dzienniku nie przykrywa startu z synchronizacji: nowy cel po starcie to nowy cykl', () => { + write(RACE) + cmdPlan(dir, { date: '2026-08-08' }) + process.env['TRAINCTL_TODAY'] = '2026-11-29' + expect(cmdLog(dir, { date: '2026-11-29', km: '3' }).code).toBe(0) + writeFileSync(join(dir, 'sync.json'), JSON.stringify({ + pulledAt: '2026-11-29T15:00:00Z', wellness: [], + activities: [{ externalId: 'race', date: '2026-11-29', type: 'Run', distanceKm: 21.2 }], + }), 'utf-8') + write(RACE.replace('2026-11-29', '2027-04-11')) + const r = cmdPlan(dir) + expect(r.code, r.output).toBe(0) + expect(r.data).toMatchObject({ regeneration: { mode: 'new-cycle' } }) + }) + it('start jawnie „pominięty" (DNS) i samotny bieg z zegarka: przełożenie to nadal ten sam cykl', () => { + write(RACE) + cmdPlan(dir, { date: '2026-08-08' }) + process.env['TRAINCTL_TODAY'] = '2026-11-29' + expect(cmdLog(dir, { date: '2026-11-29', status: 'skipped' }).code).toBe(0) + writeFileSync(join(dir, 'sync.json'), JSON.stringify({ + pulledAt: '2026-11-29T15:00:00Z', wellness: [], + activities: [{ externalId: 'solo', date: '2026-11-29', type: 'Run', distanceKm: 18 }], + }), 'utf-8') + write(RACE.replace('2026-11-29', '2026-12-06')) + const r = cmdPlan(dir) + expect(r.code, r.output).toBe(0) + expect(r.data).toMatchObject({ regeneration: { mode: 'same-cycle' } }) + }) + it('start zalogowany, cel bez zmian: plan w dniu startu działa jak zwykła regeneracja', () => { + write(RACE) + cmdPlan(dir, { date: '2026-08-08' }) + process.env['TRAINCTL_TODAY'] = '2026-11-29' + expect(cmdLog(dir, { date: '2026-11-29', km: '21.1', time: '1:35:10' }).code).toBe(0) + const r = cmdPlan(dir) + expect(r.code, r.output).toBe(0) + expect(r.data).toMatchObject({ regeneration: { mode: 'same-cycle' } }) + }) + it('w dniu startu ten sam cel to nadal ten sam cykl', () => { + write(RACE) + cmdPlan(dir, { date: '2026-08-08' }) + process.env['TRAINCTL_TODAY'] = '2026-11-29' + expect(cmdPlan(dir).data).toMatchObject({ regeneration: { mode: 'same-cycle' } }) + }) + it('nowy cel w trakcie bloku: nowy cykl zaczyna się PO bloku przejściowym, historia zostaje', () => { + write(RACE) + cmdPlan(dir, { date: '2026-08-08' }) + process.env['TRAINCTL_TODAY'] = '2026-12-02' + write(RACE.replace('"Half marathon"', '"Spring 10K"').replace('2026-11-29', '2027-03-14').replace('21.0975', '10')) + const r = cmdPlan(dir) + expect(r.code, r.output).toBe(0) + expect(r.output).toContain('New training cycle from 2026-12-14') + expect(r.output).toContain('The new cycle starts from') + const plan = loadPlan(dir) + expect(plan.cycleStart).toBe('2026-12-14') + expect(plan.weeks.filter((w) => w.skeleton.phase === 'transition' && w.weekStart < '2026-12-14')).toHaveLength(2) + expect(cycleWeeksOf(plan)[0]!.weekStart).toBe('2026-12-14') + expect(validatePlan(plan).filter((i) => i.severity === 'error')).toEqual([]) + }) +}) + +describe('regeneracja po zatwierdzonej propozycji', () => { + 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: 40, ruleRefs: [] }] } + for (const day of ['2026-08-08', '2026-09-06']) { + it(`z siłą i budżetem tygodnia, w dniu decyzji (${day}): plan odtwarza zatwierdzone dni`, () => { + write(`${RACE}time:\n weeklyMinutes: 240\n`) + process.env['TRAINCTL_TODAY'] = day + expect(cmdPlan(dir, { date: '2026-08-08' }).code).toBe(0) + applyProposal(dir, prepareProposal(dir, day, reduction).id) + const r = cmdPlan(dir, { date: day }) + expect(r.code, r.output).toBe(0) + expect(r.data).toMatchObject({ regeneration: { changedDates: [], upToDate: true } }) + }) + } + const withBudget = (yaml: string) => `${yaml}time:\n weeklyMinutes: 240\n` + const approve = (day: string) => { + process.env['TRAINCTL_TODAY'] = day + expect(cmdPlan(dir, { date: '2026-08-08' }).code).toBe(0) + applyProposal(dir, prepareProposal(dir, day, reduction).id) + } + it('start przesunięty o tydzień wcześniej po zatwierdzonej bazie: siła idzie za nowymi fazami', () => { + write(withBudget(RACE)) + approve('2026-09-06') + write(withBudget(RACE.replace('2026-11-29', '2026-11-22'))) + const r = cmdPlan(dir) + expect(r.code, r.output).toBe(0) + expect(validatePlan(loadPlan(dir)).map((i) => i.code)).not.toContain('strengthInTaper') + }) + it('zmiana strength.days po zatwierdzonej bazie przestawia siłę — plan nie jest „aktualny"', () => { + write(withBudget(RACE)) + approve('2026-09-06') + write(withBudget(RACE.replace(' enabled: true\n', ' enabled: true\n days: [mon]\n'))) + const r = cmdPlan(dir) + expect(r.code, r.output).toBe(0) + expect(r.data).toMatchObject({ regeneration: { upToDate: false } }) + const future = loadPlan(dir).weeks.flatMap((w) => w.days).filter((d) => d.date > '2026-09-07' && d.strength) + expect(future.some((d) => d.weekday === 'mon')).toBe(true) + }) + it('redukcja w taperze: kotwica to ostatni tydzień budowania, nie blok po starcie — nic nie rośnie', () => { + write(RACE) + process.env['TRAINCTL_TODAY'] = '2026-11-10' + expect(cmdPlan(dir, { date: '2026-08-08' }).code).toBe(0) + const before = loadPlan(dir) + const reduced = prepareProposal(dir, '2026-11-10', { ...reduction, actions: [{ ...reduction.actions[0]!, suggestedWeeklyKm: 35 }] }) + for (const week of reduced.plan.weeks.filter((w) => w.weekStart >= '2026-11-09')) { + expect(week.totalKm).toBeLessThanOrEqual(before.weeks.find((w) => w.weekStart === week.weekStart)!.totalKm + 0.5) + } + }) + it('po zatwierdzonej bazie dni sprzed tygodnia decyzji nie trafiają do „zachowanych" — nic by się w nich nie zmieniło', () => { + write(withBudget(RACE)) + approve('2026-09-16') + const r = cmdPlan(dir) + expect(r.code, r.output).toBe(0) + const past = (r.data as { regeneration: { protectedDays: { date: string; reason: string }[] } }).regeneration.protectedDays.filter((p) => p.reason === 'past') + // dni tygodnia decyzji sprzed niej nadal są zgłaszane — skalowanie je zmienia, ochrona trzyma + expect(past.length).toBeGreaterThan(0) + expect(past.every((p) => p.date >= '2026-09-14')).toBe(true) + }) + it('regeneracja z zatwierdzoną bazą zachowuje notatki siły tygodni (PLAN.md)', () => { + write(withBudget(RACE)) + process.env['TRAINCTL_TODAY'] = '2026-09-06' + expect(cmdPlan(dir, { date: '2026-08-08' }).code).toBe(0) + const notes = (p: ReturnType) => p.weeks.filter((w) => w.weekStart > '2026-09-13' && w.strengthNotes?.length).map((w) => w.weekStart) + const expected = notes(loadPlan(dir)) + expect(expected.length).toBeGreaterThan(0) + applyProposal(dir, prepareProposal(dir, '2026-09-06', reduction).id) + write(withBudget(RACE.replace('timeSec: 2580 }\n', 'timeSec: 2580 }\n - { date: "2026-08-01", distanceKm: 5, timeSec: 1150 }\n'))) + expect(cmdPlan(dir).code).toBe(0) + expect(notes(loadPlan(dir))).toEqual(expected) + }) + it('dzień decyzji zostaje z własnym powodem — nie „zatwierdzony wyjątek czasowy"', () => { + write(withBudget(RACE)) + approve('2026-08-08') + write(withBudget(RACE.replace('timeSec: 2580 }\n', 'timeSec: 2580 }\n - { date: "2026-08-01", distanceKm: 5, timeSec: 1150 }\n'))) + const r = cmdPlan(dir, { date: '2026-08-08' }) + expect(r.code, r.output).toBe(0) + expect((r.data as { regeneration: { protectedDays: unknown[] } }).regeneration.protectedDays).toContainEqual({ date: '2026-08-08', reason: 'baseline' }) + expect(r.output).toContain('day of the approved baseline') + }) +}) + +describe('plan bez startu (goal.kind: base)', () => { + it('generuje bazę do daty końca: bez startu, predykcji i taperu; lint bez fałszywego braku dnia startu', () => { + write(BASE) + const r = cmdPlan(dir, { date: '2026-08-08' }) + expect(r.code, r.output).toBe(0) + expect(r.output).toContain('base training until 2026-10-25') + expect(r.output).not.toContain('Predicted finish') + expect(r.output).not.toContain('Recommended for this distance') + const plan = loadPlan(dir) + expect(plan.goal).toMatchObject({ kind: 'base', distanceKm: 0, name: 'Base training' }) + expect(plan.prediction).toBeUndefined() + expect(plan.weeks.every((w) => w.skeleton.phase === 'base')).toBe(true) + expect(plan.weeks.flatMap((w) => w.days).some((d) => d.workout?.kind === 'race')).toBe(false) + expect(cmdCheck(dir).code).toBe(0) + }) + it('today, review i eksport wiedzą, że nie ma startu', async () => { + write(BASE) + cmdPlan(dir, { date: '2026-08-08' }) + expect(cmdToday(dir, { date: '2026-08-11' }).output).toContain('base training until 2026-10-25') + const review = await cmdReview(dir, { date: '2026-08-16' }) + expect(review.output).toContain('Base plan until') + expect(review.output).not.toContain('To race day') + const race = cmdExport(dir, { what: 'race' }) + expect(race.code).toBe(1) + expect(race.output).toContain('A base plan has no race') + }) + it('profil bez daty końca albo z nieznanym rodzajem celu: czytelny błąd', () => { + write(`${PROFILE}goal:\n kind: base\n`) + expect(cmdPlan(dir, { date: '2026-08-08' }).output).toContain('goal.until') + write(`${PROFILE}goal:\n kind: fun-run\n name: x\n date: "2026-10-25"\n distanceKm: 5\n`) + expect(cmdPlan(dir, { date: '2026-08-08' }).output).toContain('goal.kind: race (default) or base') + }) +}) 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/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/engine-060.test.ts b/packages/cli/src/engine-060.test.ts new file mode 100644 index 0000000..449e01e --- /dev/null +++ b/packages/cli/src/engine-060.test.ts @@ -0,0 +1,248 @@ +/** + * Etap E (docs/PLAN-v0.4.md): budżet czasu w generatorze (E-2), dziennik + * i warianty siły (F-12, F-14, F-18), wyniki z trailu w kalibracji (Z-10). + */ +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 { estimateWorkoutMinutes, setLocale, validatePlan } from 'trainctl-core' +import { cmdCheck, cmdDiff, cmdLog, cmdPlan, cmdReview, cmdToday, cmdWeek, cmdWhy } from './commands.ts' +import { computePlan, loadPlan, writePlan, PLAN_YAML, type StoredPlan } from './planfile.ts' +import type { TrainctlConfig } from './config.ts' +import { readLog, readStrengthLog } from './logfile.ts' + +setLocale('en') + +const BASE = `athlete: + recentWeeklyKm: 55 + peakWeeklyKm: 70 + 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-060-')) }) +afterEach(() => rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 })) + +const plan = (yaml: string): StoredPlan => { + writeFileSync(join(dir, 'trainctl.yaml'), yaml, 'utf-8') + const r = cmdPlan(dir, { date: '2026-08-08', fresh: true }) + expect(r.code, r.output).toBe(0) + return loadPlan(dir) +} +const minutes = (p: StoredPlan) => p.weeks.map((w) => w.days.reduce((s, d) => s + (d.workout ? estimateWorkoutMinutes(d.workout, 15) : 0) + (d.strength?.durationMin ?? 0), 0)) + +describe('E-2 · budżet czasu z profilu', () => { + it('tygodnie mieszczą się w minutach tygodnia; objętość wypłaszcza się z ostrzeżeniem', () => { + const free = plan(BASE) + const capped = plan(`${BASE}time:\n weeklyMinutes: 240\n`) + const loading = (p: StoredPlan) => p.weeks.filter((w) => !w.skeleton.raceDate) + expect(Math.max(...minutes(capped).filter((_, i) => !capped.weeks[i]!.skeleton.raceDate))).toBeLessThanOrEqual(240) + expect(Math.max(...loading(capped).map((w) => w.totalKm))).toBeLessThan(Math.max(...loading(free).map((w) => w.totalKm))) + expect(validatePlan(capped).filter((i) => i.severity === 'error')).toEqual([]) + for (const w of capped.weeks) expect(w.easyShare).toBeGreaterThanOrEqual(0.75) + }) + it('dni ponad limit dnia są skracane jawnie (timeAdjustment z profilu), why mówi o kompromisie', () => { + const p = plan(`${BASE}time:\n weekdayMinutes: 45\n`) + const adjusted = p.weeks.flatMap((w) => w.days).filter((d) => d.timeAdjustment) + expect(adjusted.length).toBeGreaterThan(0) + for (const d of adjusted) { + expect(d.timeAdjustment).toMatchObject({ origin: 'profile', budgetMinutes: 45 }) + expect(['sat', 'sun']).not.toContain(d.weekday) + expect(estimateWorkoutMinutes(d.workout!, 15) + (d.strength?.durationMin ?? 0)).toBeLessThanOrEqual(45) + } + expect(cmdWhy(dir, { date: adjusted[0]!.date }).output).toMatch(/45 min/) + }) + it('świeży plan z budżetem dnia nie łamie własnego lintu (P-3) nawet w --strict', () => { + plan(`${BASE}time:\n weekendMinutes: 90\n weekdayMinutes: 60\n`) + expect(validatePlan(loadPlan(dir)).filter((i) => i.code === 'targetKmMismatch')).toEqual([]) + expect(cmdCheck(dir).output).not.toContain('P-3') + }) + it('hojny budżet niczego nie obcina — bez fałszywego ostrzeżenia o czasie', () => { + const p = plan(`${BASE}time:\n weeklyMinutes: 2000\n weekendMinutes: 600\n`) + expect(p.feasibilityWarnings.join(' ')).not.toContain('time budget caps') + }) + it('cel tygodnia zostaje zamiarem makrocyklu; budżet zapisuje swoją objętość obok (timeCappedKm)', () => { + const free = plan(BASE) + const capped = plan(`${BASE}time:\n weeklyMinutes: 240\n weekdayMinutes: 50\n`) + const pairs = capped.weeks.map((w, i) => [w, free.weeks[i]!] as const).filter(([w]) => w.skeleton.timeCappedKm !== undefined) + expect(pairs.length).toBeGreaterThan(0) + for (const [w, f] of pairs) { + expect(w.skeleton.targetKm).toBe(f.skeleton.targetKm) + expect(w.totalKm).toBeCloseTo(w.skeleton.timeCappedKm!, 0) + } + }) + it('tydzień przycięty budżetem tygodnia przechodzi własny lint (P-3); liczby w pliku bez szumu', () => { + const capped = plan(`${BASE}time:\n weeklyMinutes: 200\n`) + expect(capped.weeks.some((w) => w.skeleton.timeCappedKm !== undefined)).toBe(true) + expect(validatePlan(capped).filter((i) => i.code === 'targetKmMismatch')).toEqual([]) + // bez budżetu plan sięgnąłby rekomendacji — to budżet go zatrzymuje, więc ostrzeżenie jest + expect(capped.feasibilityWarnings.join(' ')).toContain('time budget caps') + expect(readFileSync(join(dir, PLAN_YAML), 'utf-8')).not.toMatch(/timeCappedKm: \d+\.\d{2,}/) + }) + it('ciaśniejszy budżet tygodnia nigdy nie daje tygodnia z większą objętością', () => { + const config: TrainctlConfig = { + athlete: { recentWeeklyKm: 55, peakWeeklyKm: 70, 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' }, + } + const totals = [120, 90, 60, 45, 30, 15].map((weeklyMinutes) => + computePlan({ ...config, time: { weeklyMinutes } }, '2026-08-08').weeks.map((w) => w.totalKm)) + for (let i = 1; i < totals.length; i++) { + totals[i]!.forEach((km, k) => expect(km).toBeLessThanOrEqual(totals[i - 1]![k]! + 0.5)) + } + }) + it('dwa dni biegowe: budżet liczony od tego, co generator rozpisał — tygodnie mieszczą się w budżecie', () => { + const config: TrainctlConfig = { + athlete: { recentWeeklyKm: 55, peakWeeklyKm: 80, daysAvailable: ['sat', 'sun'], results: [{ date: '2026-03-29', distanceKm: 10, timeSec: 2580 }] }, + goal: { name: 'Half marathon', date: '2026-11-29', distanceKm: 21.0975, priority: 'A' }, + time: { weeklyMinutes: 200 }, + } + expect(computePlan(config, '2026-08-08').feasibilityWarnings.join(' ')).not.toContain('stay over the weekly time budget') + }) + it('cel szkieletu nieosiągalny przy dwóch dniach: ostrzeżenie podaje szczyt bez budżetu, nie obiecuje rekomendacji', () => { + const config: TrainctlConfig = { + athlete: { recentWeeklyKm: 80, peakWeeklyKm: 100, daysAvailable: ['sat', 'sun'], results: [{ date: '2026-03-29', distanceKm: 10, timeSec: 2580 }] }, + goal: { name: 'Marathon', date: '2026-11-29', distanceKm: 42.195, priority: 'A' }, + time: { weeklyMinutes: 300 }, + } + const free = computePlan({ ...config, time: undefined } as unknown as TrainctlConfig, '2026-08-08') + const warning = computePlan(config, '2026-08-08').feasibilityWarnings.find((w) => w.includes('time budget caps'))! + const withoutBudget = Number(warning.match(/would reach ([\d.]+) km\/week/)![1]) + expect(withoutBudget).toBeCloseTo(Math.max(...free.weeks.map((w) => w.totalKm)), 0) + expect(withoutBudget).toBeLessThan(free.peakKmRecommended) + }) + it('trzy dni, maraton i ostry budżet: ostrzeżenie mimo szczytu bez budżetu poniżej rekomendacji', () => { + const config: TrainctlConfig = { + athlete: { recentWeeklyKm: 60, peakWeeklyKm: 100, daysAvailable: ['tue', 'thu', 'sun'], results: [{ date: '2026-03-29', distanceKm: 10, timeSec: 2580 }] }, + goal: { name: 'Marathon', date: '2026-11-29', distanceKm: 42.195, priority: 'A' }, + time: { weeklyMinutes: 150 }, + } + expect(computePlan(config, '2026-08-08').feasibilityWarnings.join(' ')).toContain('time budget caps') + }) + it('diff tygodnia przyciętego budżetem: jedna linia objętości, bez echa sumy dni', () => { + plan(`${BASE}time:\n weeklyMinutes: 200\n`) + writeFileSync(join(dir, 'trainctl.yaml'), `${BASE}time:\n weeklyMinutes: 150\n`, 'utf-8') + process.env['TRAINCTL_TODAY'] = '2026-08-08' + try { + const out = cmdDiff(dir).output + // tydzień z dniami przeszłymi ma sumę inną niż cel (stare dni zostają) — tam dwie linie mają sens + const weeks = [...out.matchAll(/week (\d{4}-\d{2}-\d{2}): volume/g)].map((m) => m[1]!).filter((w) => w > '2026-08-08') + expect(weeks.length).toBeGreaterThan(0) + for (const week of weeks) expect(out).not.toContain(`week ${week}: total of the days`) + } finally { + delete process.env['TRAINCTL_TODAY'] + } + }) + it('week pokazuje cel po budżecie czasu, nie zamiar makrocyklu', () => { + const capped = plan(`${BASE}time:\n weeklyMinutes: 200\n`) + const week = capped.weeks.find((w) => w.skeleton.timeCappedKm !== undefined && w.skeleton.timeCappedKm < w.skeleton.targetKm - 5)! + const out = cmdWeek(dir, { date: week.days[0]!.date }).output + expect(out).toContain('target ') + expect(out).not.toContain(`target ${week.skeleton.targetKm} km`) + }) + it('plan z budżetem wygenerowany drugi raz bez zmian na wejściu jest „aktualny"', () => { + plan(`${BASE}time:\n weeklyMinutes: 240\n weekdayMinutes: 50\n`) + expect(cmdPlan(dir, { date: '2026-08-08' }).data).toMatchObject({ regeneration: { upToDate: true } }) + }) + it('regeneracja po zatwierdzonej bazie nadal trzyma budżet dnia (E-2)', () => { + plan(`${BASE}time:\n weekdayMinutes: 50\n`) + const stored = loadPlan(dir) + stored.loadState = { baselineWeeklyKm: 45, effectiveFrom: '2026-08-08', profileWeeklyKm: 55 } + writePlan(dir, stored) + expect(cmdPlan(dir, { date: '2026-08-08' }).code).toBe(0) + const after = loadPlan(dir) + for (const d of after.weeks.flatMap((w) => w.days)) { + if (!d.workout || ['sat', 'sun'].includes(d.weekday) || ['race', 'test'].includes(d.workout.kind)) continue + expect(estimateWorkoutMinutes(d.workout, 15) + (d.strength?.durationMin ?? 0), d.date).toBeLessThanOrEqual(50) + } + }) + it('zła wartość budżetu: czytelny błąd profilu', () => { + writeFileSync(join(dir, 'trainctl.yaml'), `${BASE}time:\n weeklyMinutes: 5\n`, 'utf-8') + const r = cmdPlan(dir, { date: '2026-08-08' }) + expect(r.code).toBe(1) + expect(r.output).toContain('time.weeklyMinutes: whole minutes between 15 and 2000') + }) +}) + +describe('siła: warianty i dziennik', () => { + const withStrength = `${BASE}strength:\n enabled: true\n` + it('wejście w blok przez dwa tygodnie, potem ciężko; szczyt raz w tygodniu (F-18, F-4, F-12)', () => { + const p = plan(withStrength) + const kinds = (phase: string) => p.weeks.filter((w) => w.skeleton.phase === phase).flatMap((w) => w.days.filter((d) => d.strength).map((d) => d.strength!.kind)) + const firstTwo = p.weeks.slice(0, 2).flatMap((w) => w.days.filter((d) => d.strength).map((d) => d.strength!.kind)) + expect(new Set(firstTwo)).toEqual(new Set(['intro'])) + expect(kinds('build')).toContain('heavy') + for (const w of p.weeks.filter((x) => x.skeleton.phase === 'peak')) { + expect(w.days.filter((d) => d.strength).length).toBeLessThanOrEqual(1) + for (const d of w.days.filter((x) => x.strength)) expect(d.strength!.kind).toBe('maintenance') + } + }) + it('log --strength: osobny wpis, nie nadpisuje biegu z tej samej daty; review liczy sesje', async () => { + const p = plan(withStrength) + const day = p.weeks[1]!.days.find((d) => d.strength)! + expect(cmdLog(dir, { date: day.date, km: '6' }).code).toBe(0) + const r = cmdLog(dir, { date: day.date, strength: 'done', minutes: '30' }) + expect(r.code).toBe(0) + expect(r.output).toContain(`Logged strength ${day.date}: done.`) + expect(readLog(dir).at(-1)).toMatchObject({ date: day.date, km: 6 }) + expect(readStrengthLog(dir)).toEqual([expect.objectContaining({ date: day.date, status: 'done', minutes: 30 })]) + expect(cmdToday(dir, { date: day.date }).output).toContain('Strength logged: done') + const review = await cmdReview(dir, { date: p.weeks[1]!.days[6]!.date }) + expect(review.output).toMatch(/Strength: 1 of \d+ planned/) + }) + it('siła nie przyjmuje kilometrów ani tempa; zły status to błąd', () => { + plan(withStrength) + expect(cmdLog(dir, { date: '2026-08-11', strength: 'done', km: '5' }).output).toContain('only --minutes and --note') + expect(cmdLog(dir, { date: '2026-08-11', strength: 'maybe' }).code).toBe(1) + expect(cmdLog(dir, { date: '2026-08-11', strength: 'done', minutes: '0' }).code).toBe(1) + }) +}) + +describe('plan.yaml, którego nie da się użyć', () => { + it('znaczniki konfliktu w pliku: bez --fresh odmowa z instrukcją (nic nie ginie po cichu), z --fresh nadpisanie z ostrzeżeniem', () => { + plan(BASE) + const broken = '<<<<<<< HEAD\nweeks: [\n=======\n>>>>>>> other\n' + writeFileSync(join(dir, PLAN_YAML), broken, 'utf-8') + const refused = cmdPlan(dir, { date: '2026-08-08' }) + expect(refused.code).toBe(1) + expect(refused.output).toContain('not valid YAML') + expect(refused.output).toContain('--fresh') + expect(readFileSync(join(dir, PLAN_YAML), 'utf-8')).toBe(broken) + const fresh = cmdPlan(dir, { date: '2026-08-08', fresh: true }) + expect(fresh.code).toBe(0) + expect(fresh.output).toContain('could not be used and was replaced') + }) + it('nowszy schemat: bez --fresh odmowa, z --fresh świadome nadpisanie', () => { + plan(BASE) + const raw = readFileSync(join(dir, PLAN_YAML), 'utf-8').replace('schemaVersion: 1', 'schemaVersion: 9') + writeFileSync(join(dir, PLAN_YAML), raw, 'utf-8') + const refused = cmdPlan(dir, { date: '2026-08-08' }) + expect(refused.code).toBe(1) + // plan z nowszego trainctl: rada to aktualizacja, nie --fresh (porzuciłoby poprawny plan) + expect(refused.output).toContain('upgrade trainctl') + expect(refused.output).not.toContain('--fresh') + expect(cmdPlan(dir, { date: '2026-08-08', fresh: true }).code).toBe(0) + }) +}) + +describe('Z-10 · wynik z trailu nie kalibruje stref szosowych', () => { + const results = (lines: string) => BASE.replace(' - { date: "2026-03-29", distanceKm: 10, timeSec: 2580 }\n', lines) + it('przy wyniku szosowym trail jest odłożony, z powodem w kalibracji', () => { + const p = plan(results(' - { date: "2026-03-29", distanceKm: 10, timeSec: 2580 }\n - { date: "2026-05-10", distanceKm: 21.1, timeSec: 7800, terrain: trail }\n')) + const road = plan(BASE) + expect(p.vdot).toBe(road.vdot) + expect(p.calibration!.candidates.find((c) => c.result.terrain === 'trail')!.reason).toBe('terrain') + }) + it('sam trail: strefy z niego, z ostrzeżeniem w planie', () => { + const p = plan(results(' - { date: "2026-05-10", distanceKm: 21.1, timeSec: 7800, terrain: trail }\n')) + expect(p.feasibilityWarnings.join(' ')).toContain('trail result') + expect(readFileSync(join(dir, 'plan/PLAN.md'), 'utf-8')).toContain('Z-10') + }) +}) 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/env-file.ts b/packages/cli/src/env-file.ts index e27a4dc..ff1f5d0 100644 --- a/packages/cli/src/env-file.ts +++ b/packages/cli/src/env-file.ts @@ -76,12 +76,41 @@ function insideGitRepo(cwd: string): boolean { } } +/** Klucze środowiska sprzed wczytania `.env` — jawny `export` wygrywa nad plikiem. */ +let shellKeys: Set | undefined + +/** + * Czy wartość zmiennej pochodzi z `.env` (a nie z eksportu w powłoce). + * `inspected` — wynik `inspectEnvFile`, jeśli wołający już go ma (bez drugiego odczytu). + */ +export function cameFromEnvFile(cwd: string, name: string, inspected?: { hasKey: boolean }): boolean { + if (shellKeys?.has(name)) return false + return (inspected ?? inspectEnvFile(cwd, name)).hasKey +} + +/** + * 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. */ export function loadEnvFile(cwd: string): EnvFileOutcome { const path = join(cwd, ENV_FILE) + shellKeys = new Set(Object.keys(process.env)) if (!existsSync(path)) return { loaded: false, unprotected: false } try { process.loadEnvFile(path) diff --git a/packages/cli/src/execution.ts b/packages/cli/src/execution.ts index a479714..8f4001a 100644 --- a/packages/cli/src/execution.ts +++ b/packages/cli/src/execution.ts @@ -6,13 +6,19 @@ export const isRunningActivity = (activity: SyncedActivity): boolean => /^(run|running|trailrun|trailrunning|virtualrun|treadmill|treadmillrunning)$/i.test(activity.type.replace(/[ _-]/g, '')) && !activity.dataWithheld -/** One interpretation for pull, review and adaptation. Latest journal entry wins. */ -export function buildExecution(plan: StoredPlan, activities: SyncedActivity[], logs: LogEntry[], today: string): ExecutionRecord[] { +/** Kilometry biegów z synchronizacji dzień po dniu — jedna reguła, co z zegarka liczy się jako bieg. */ +export function runningKmByDate(activities: SyncedActivity[]): Map { const runs = new Map() for (const a of activities) { if (!isRunningActivity(a) || a.distanceKm === undefined || !Number.isFinite(a.distanceKm) || a.distanceKm <= 0) continue runs.set(a.date, (runs.get(a.date) ?? 0) + a.distanceKm) } + return runs +} + +/** Jedna interpretacja wykonania dla pull, review i adaptacji. Wygrywa ostatni wpis dziennika. */ +export function buildExecution(plan: StoredPlan, activities: SyncedActivity[], logs: LogEntry[], today: string): ExecutionRecord[] { + const runs = runningKmByDate(activities) const journal = new Map(logs.map((entry) => [entry.date, entry])) const planned = new Map(plan.weeks.flatMap((week) => week.days).map((day) => [day.date, day])) const dates = [...new Set([...planned.keys(), ...runs.keys(), ...journal.keys()])].sort() diff --git a/packages/cli/src/explain-session.ts b/packages/cli/src/explain-session.ts index 9df778b..7756df9 100644 --- a/packages/cli/src/explain-session.ts +++ b/packages/cli/src/explain-session.ts @@ -1,4 +1,4 @@ -import { diffDays, estimateWorkoutMinutes, fmtPace, messages, type ExecutionRecord, type Microcycle, type PlannedDay } from 'trainctl-core' +import { diffDays, estimateWorkoutMinutes, fmtPace, messages, plannedWeekKm, type ExecutionRecord, type Microcycle, type PlannedDay } from 'trainctl-core' import { dayFingerprint, type StoredPlan } from './planfile.ts' import { ui } from './i18n/index.ts' import { kindPurpose } from './rules-explain.ts' @@ -13,8 +13,11 @@ export function explainSession(plan: StoredPlan, week: Microcycle, day: PlannedD const neighbor = (d: PlannedDay | undefined) => d?.workout ? { date: d.date, kind: d.workout.kind, gapDays: Math.abs(diffDays(day.date, d.date)) } : null const placement = { previous: neighbor(previous), next: neighbor(next) } const kindLabel = (kind: string) => (messages().kind as Record)[kind] ?? kind - const context = [t.goal(plan.goal.name, plan.goal.distanceKm, plan.goal.date, diffDays(day.date, plan.goal.date)), - t.weekContext(messages().phase[week.skeleton.phase], week.totalKm, week.skeleton.targetKm, Math.round(week.easyShare * 100))] + const toGoal = diffDays(day.date, plan.goal.date) + const context = [plan.goal.kind === 'base' ? t.goalBase(plan.goal.name, plan.goal.date) + : toGoal >= 0 ? t.goal(plan.goal.name, plan.goal.distanceKm, plan.goal.date, toGoal) + : t.goalBehind(plan.goal.name, plan.goal.distanceKm, plan.goal.date, -toGoal), + t.weekContext(messages().phase[week.skeleton.phase], week.totalKm, plannedWeekKm(week.skeleton), Math.round(week.easyShare * 100))] if (week.skeleton.deload) context.push(t.deload) if (week.skeleton.keepIntensity || week.skeleton.keepFrequency) context.push(t.taper) if (placement.previous) context.push(t.previous(placement.previous.date, kindLabel(placement.previous.kind), placement.previous.gapDays)) diff --git a/packages/cli/src/export.ts b/packages/cli/src/export.ts index 666039a..d309296 100644 --- a/packages/cli/src/export.ts +++ b/packages/cli/src/export.ts @@ -5,7 +5,7 @@ */ import { mkdirSync, writeFileSync } from 'node:fs' import { join } from 'node:path' -import { estimateWorkoutMinutes, getLocale, heatLadder, messages, type PlannedDay } from 'trainctl-core' +import { estimateWorkoutMinutes, getLocale, heatLadder, messages, plannedWeekKm, type PlannedDay } from 'trainctl-core' import { encodeWorkoutFit, fmtClock, @@ -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' /** @@ -206,6 +206,7 @@ export function runExport(cwd: string, req: ExportRequest): ExportedFile[] { return files } + if (req.what === 'race' && plan.goal.kind === 'base') throw new Error(t.noRaceInBase) if (req.what === 'race') { // `key` jest stabilny między językami — po nim wybieramy scenariusz na opaskę; // `label` idzie na wydruk i zmienia się z językiem. @@ -257,11 +258,13 @@ 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, + targetKm: plannedWeekKm(w.skeleton), totalKm: w.totalKm, deload: w.skeleton.deload, days: w.days.map((d) => ({ @@ -276,7 +279,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 +289,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/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/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/git.ts b/packages/cli/src/git.ts new file mode 100644 index 0000000..6f9fbe2 --- /dev/null +++ b/packages/cli/src/git.ts @@ -0,0 +1,82 @@ +/** + * `--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`) — + * ścieżki względem `cwd`, gotowe do `git add`, także gdy katalog treningowy jest + * podkatalogiem repozytorium (porcelain podaje je od korzenia repo). Pliki + * ignorowane się tu nie pojawiają, usunięte — tak. + */ +export function uncommitted(cwd: string, paths: string[]): string[] | undefined { + if (!insideGitRepo(cwd)) return undefined + const prefix = git(cwd, ['rev-parse', '--show-prefix']) + // --untracked-files=normal: `status.showUntrackedFiles=no` w konfiguracji użytkownika + // nie może ukryć nowego, niezacommitowanego pliku (init uznałby go za czysty) + const r = git(cwd, ['status', '--porcelain', '-z', '--untracked-files=normal', '--', ...paths]) + if (r.status !== 0 || prefix.status !== 0) return undefined + const root = prefix.stdout.trim() + const relative = (path: string) => (path.startsWith(root) ? path.slice(root.length) : path) + const entries = r.stdout.split('\0') + const out: string[] = [] + for (let i = 0; i < entries.length; i++) { + const entry = entries[i]! + if (entry.length < 4) continue + const xy = entry.slice(0, 2) + out.push(relative(entry.slice(3))) + // `XY nowy\0stary` (rename albo kopia): stara ścieżka to osobny token. Rename + // w drzewie roboczym (Y, po `git add -N`) zostawia usunięcie starej poza + // indeksem — ona też musi trafić do `git add`; rename w indeksie (X) ma je zapisane. + if (/[RC]/.test(xy)) { + const origin = entries[++i] + if (xy[1] === 'R' && origin) out.push(relative(origin)) + } + } + return out +} diff --git a/packages/cli/src/i18n/cli-en.ts b/packages/cli/src/i18n/cli-en.ts index 9dc5c25..362b51b 100644 --- a/packages/cli/src/i18n/cli-en.ts +++ b/packages/cli/src/i18n/cli-en.ts @@ -39,6 +39,9 @@ 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', optDateWeek: 'any date inside the week you care about', @@ -46,6 +49,8 @@ export const cliEn = { optKm: 'kilometres covered', optTime: 'time as MM:SS or HH:MM:SS', optRpe: 'session effort as a whole number 1–10 (CR-10)', + optStrength: 'log a strength session instead of a run: done | skipped', + optMinutes: 'minutes of the strength session', optNote: 'note (how it felt, conditions)', optFrom: 'source date', optTo: 'target date', @@ -53,6 +58,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', @@ -65,6 +71,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…', @@ -81,6 +99,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', @@ -110,14 +135,26 @@ 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', + 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', + gitignoreNotCommitted: '.gitignore had uncommitted changes of yours, so it was left out of the commit — review and commit it yourself.', }, plan: { weeksOfPlan: (weeks: number) => `${weeks} weeks of plan`, + baseUntil: (date: string) => `base training until ${date}`, volumePeak: 'Volume peak', recommendedForDistance: 'Recommended for this distance', vdot: 'VDOT', @@ -132,16 +169,60 @@ 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.`, + newCycleVolume: (km: number) => + `The new cycle starts from ${n(km)} km/week (athlete.recentWeeklyKm, or the approved baseline) — update the profile if your training changed.`, + 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', + baseline: 'day of the approved baseline', + 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.', + unreadable: (file: string, reason: string) => + `${file} cannot be used (${reason}) — fix it (a merge conflict?) or run trainctl plan --fresh to start over; the previous version is in git.`, + unreadableReason: { parse: 'not valid YAML', shape: 'no goal or weeks' }, + overwroteUnreadable: (file: string) => `The previous ${file} could not be used and was replaced — it is in git if you need it.`, + 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: { daysToRace: (days: number) => `${days} days to race`, + daysAfterRace: (days: number) => `${days} ${pluralEn(days, { one: 'day', other: 'days' })} after the race`, weekOf: (index: number, total: number) => `week ${index}/${total}`, deload: 'deload', restDayTitle: 'Rest day', 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}`, + strengthLogged: (status: string) => `Strength logged: ${status}`, + 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: @@ -174,6 +255,30 @@ 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.', + strengthSaved: (date: string, status: string) => `Logged strength ${date}: ${status}.`, + strengthStatus: (value: string) => `Strength status "${value}" — use done or skipped.`, + strengthOnly: 'A strength entry takes only --minutes and --note; log the run separately.', + strengthMinutes: 'Strength minutes: a whole number 1–300.', + strengthUnplanned: 'No strength was planned on this day — the entry is kept as an extra session.', + 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: { @@ -202,7 +307,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 +316,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: { @@ -226,6 +332,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 (duplicate, not an activity, unreadable or unsupported): ${sample}`, activities: 'Activities', activitiesValue: (total: number, runs: number, km: number) => `${total} (running: ${runs}, ${n(km)} km)`, @@ -281,7 +391,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: { @@ -299,7 +409,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`, @@ -316,7 +427,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', @@ -435,6 +546,7 @@ export const cliEn = { filePrintout: 'schedule', calendarEntries: (count: number) => `${count} sessions in the calendar`, printedWeeks: (weeks: number) => `${weeks} weeks to print`, + noRaceInBase: 'A base plan has no race — the race pack needs a goal race (goal.kind: race).', heat: { columns: { temperature: 'temperature', pace: 'pace', loss: 'loss' }, scenarioColumn: (label: string) => `scenario “${label}”`, @@ -456,7 +568,21 @@ 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}.`, + strength: 'Strength', + strengthValue: (done: number, planned: number, skipped: number) => + `${done} of ${planned} planned${skipped ? `, ${skipped} skipped` : ''}`, + 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) => @@ -472,9 +598,13 @@ 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`, + baseEnd: 'Base plan until', raceThisWeek: (date: string) => `Race this week: ${date} — the day before stays clear (T-10).`, timeTrialThisWeek: (date: string) => @@ -592,6 +722,136 @@ 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.`, + }, + + 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)`, + }, + + 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.', + 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"', + 'trainctl log --strength done --minutes 30', + ], + 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', 'trainctl pull --from ./activities # exported FIT/TCX/GPX, no account'], + 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} ` + @@ -609,6 +869,7 @@ export const cliEn = { /** plan/PLAN.md — the document the athlete actually reads. */ planMd: { heading: (goalName: string, date: string) => `Plan: ${goalName} — ${date}`, + headingBase: (goalName: string, date: string) => `Plan: ${goalName} — base training until ${date}`, goalTime: (time: string) => ` · target ${time}`, meta: (generatedAt: string, vdot: number, source: string, peakKm: number) => `Generated ${generatedAt} · VDOT ${n(vdot)} (${source}) · peak ${n(peakKm)} km/week.`, @@ -627,6 +888,14 @@ export const cliEn = { noCalibration: 'No race result from the last 18 months and no goal.targetTimeSec — ' + 'there is nothing to calibrate the zones from (Z-6: we calibrate from results, not from a watch).', + timeCapsVolume: (peak: number, withoutBudget: number, recommended: number) => + `Your time budget caps the plan at ${n(peak)} km/week; without it the plan would reach ${n(withoutBudget)} km/week ` + + `(${n(recommended)} km/week recommended for this distance, P-7/P-8). More minutes, or a closer goal, changes that (E-2).`, + timeDayTooShort: (dates: string) => + `These sessions do not fit the day's time budget even shortened (races and time trials are never cut): ${dates} (E-2).`, + timeWeekOver: (weeks: string) => `These weeks stay over the weekly time budget: ${weeks} (E-2).`, + trailOnlyCalibration: + 'Zones come from a trail result — terrain slows a trail race, so road paces may be too easy. Add a road result (Z-10).', zonesFromGoal: 'zones calibrated from the time goal rather than a real result — add a race to athlete.results', }, @@ -653,6 +922,17 @@ export const cliEn = { }, templateDesk: 'desk mode (trainctl desk) — optional', templateDeskPrefer: 'morning | lunch | evening', + baseGoalName: 'Base training', + templateTime: { + section: 'time you actually have, preparation and strength included (optional)', + weekly: 'minutes per week — volume levels off at what fits (E-2)', + weekday: 'minutes on Mon–Fri — longer sessions are shortened (E-1)', + weekend: 'minutes on Sat–Sun', + }, + 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)', @@ -682,6 +962,8 @@ export const cliEn = { listRequired: (path: string) => `${path}: a list is required`, isoDate: (path: string) => `${path}: format YYYY-MM-DD`, seconds: (path: string) => `${path}: a number of seconds > 0`, + goalKind: (path: string) => `${path}: race (default) or base`, + minutes: (path: string) => `${path}: whole minutes between 15 and 2000`, priorityBc: (path: string) => `${path}: B or C (A is the goal in the goal section)`, required: (path: string) => `${path}: required`, boolean: (path: string) => `${path}: true or false`, @@ -720,6 +1002,17 @@ export const cliEn = { 'F-13': 'taper: strength leaves the plan — 4 weeks of detraining does not undo the adaptation (Berryman 2020, note: n=8)', 'S-4': 'strength and running the same day: the ≥3 h gap is documented (Schumann 2022); 6 h is an engineering margin', 'S-5': 'heavy strength no later than 24 h before a quality session — the strength deficit lasts up to 48 h (de Carvalho e Silva 2022)', + 'F-12': 'strength twice a week in the base, 0–1 a week in the competition period (Haugen 2022)', + 'F-14': 'one strength session a week keeps the gains of a block (Rønnestad 2010 — data from cyclists, an extrapolation)', + 'F-18': 'the first two weeks of a strength block learn the movement at ~75% 1RM before the heavy weeks — an engineering choice, no source', + 'R-1': 'after a marathon, 48 h without running, then light running — 40 min easy at 48/96/144 h (Martínez-Navarro 2021)', + 'R-2': 'running again 48 h after a marathon does not slow recovery (Martínez-Navarro 2021)', + 'R-8': 'after a race of half marathon or longer, two transition weeks: ~50% of the pre-race volume easy only, then ~100% with one accent (coaching corpus, n=3; Martínez-Navarro 2021)', + 'R-9': 'strength returns in the second week after the race, one lighter session — an engineering choice, no source', + 'R-10': 'after a shorter goal race, one transition week at ~70% — an engineering choice; no data behind it', + 'P-11': 'a plan without a race grows to your documented peak (or +15%) and levels off there, deload every fourth week — an engineering choice', + 'E-2': 'the time budget from trainctl.yaml caps weekly volume and shortens sessions with the same rules as E-1 — an engineering choice, no source', + 'Z-10': 'a trail result does not calibrate road zones while a road result exists — an engineering choice; VDOT tables come from road and track', }, /** What each session kind is for — the physiological purpose, one sentence. */ @@ -754,7 +1047,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: @@ -768,6 +1064,8 @@ export const cliEn = { logRpe: 'session effort as a whole number 1–10 (CR-10, 10 = maximal). Ask the runner after the session — never guess it.', logNote: 'how it felt, conditions, remarks', + logStrength: 'done | skipped — records a strength session instead of a run (only minutes and note apply).', + logMinutes: 'duration of the strength session in minutes', shift: 'Week renegotiation: swap the sessions of two dates within THE SAME week ' + '(e.g. “release on Thursday — move the intervals”). Protects race day and the day before it; ' + @@ -813,6 +1111,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 ' + @@ -835,10 +1134,40 @@ 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, ' + + '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`. */ - 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. @@ -850,11 +1179,17 @@ 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 \`athlete.results\`. A measurement with no result written down changes nothing — - the zones still come from the older run. + the zones still come from the older run. After the goal race the plan continues + with transition weeks (R-8); when the user names the next goal, change \`goal\` in + \`trainctl.yaml\` → \`trainctl_diff\` → \`trainctl_plan\` — the new cycle starts + after the transition and keeps the history. - **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 @@ -868,8 +1203,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 @@ -880,7 +1216,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..a196a0f 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(), ) }) @@ -133,7 +138,7 @@ describe('reguły i cele jednostek', () => { it('każde objaśnienie cytuje źródło albo korpus', () => { // Reguły inżynierskie bez bezpośredniego źródła — wymienione jawnie, żeby // dopisanie kolejnej wymagało świadomej decyzji, nie przeoczenia. - const withoutSource = ['T-9', 'T-12', 'W-13'] + const withoutSource = ['T-9', 'T-12', 'W-13', 'F-18', 'Z-10', 'E-2', 'R-9', 'R-10', 'P-11'] // rok publikacji, odwołanie do korpusu albo nazwisko (Daniels & Gilbert, bez roku) const cites = /(19|20)\d{2}|korpus|corpus|Daniels/ for (const catalog of [cliEn.rules, cliPl.rules]) { @@ -155,8 +160,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..2df7d06 100644 --- a/packages/cli/src/i18n/cli-pl.ts +++ b/packages/cli/src/i18n/cli-pl.ts @@ -53,6 +53,9 @@ 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ś', optDateWeek: 'data w interesującym tygodniu', @@ -60,6 +63,8 @@ export const cliPl: CliMessages = { optKm: 'przebiegnięte km', optTime: 'czas MM:SS albo HH:MM:SS', optRpe: 'wysiłek sesji jako liczba całkowita 1–10 (CR-10)', + optStrength: 'zaloguj sesję siły zamiast biegu: done | skipped', + optMinutes: 'minuty sesji siłowej', optNote: 'notatka (samopoczucie, warunki)', optFrom: 'data źródłowa', optTo: 'data docelowa', @@ -67,6 +72,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ć', @@ -79,6 +85,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…', @@ -95,6 +113,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', @@ -123,13 +148,25 @@ 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', + 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', + gitignoreNotCommitted: '.gitignore miał Twoje niezacommitowane zmiany, więc nie trafił do commita — przejrzyj go i zacommituj sam.', }, plan: { + baseUntil: (date: string) => `budowanie bazy do ${date}`, weeksOfPlan: (weeks: number) => `${tygodnie(weeks)} planu`, volumePeak: 'Szczyt objętości', recommendedForDistance: 'Rekomendacja dla dystansu', @@ -145,16 +182,60 @@ 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.`, + newCycleVolume: (km: number) => + `Nowy cykl startuje od ${n(km)} km/tydz. (athlete.recentWeeklyKm albo zatwierdzona baza) — zaktualizuj profil, jeśli trening się zmienił.`, + 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', + baseline: 'dzień zatwierdzenia bazy', + 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.', + unreadable: (file: string, reason: string) => + `Nie da się użyć ${file} (${reason}) — popraw go (konflikt merge'a?) albo uruchom trainctl plan --fresh, żeby zacząć od zera; poprzednia wersja jest w gicie.`, + unreadableReason: { parse: 'to nie jest poprawny YAML', shape: 'brak celu albo tygodni' }, + overwroteUnreadable: (file: string) => `Poprzedni ${file} był nieużyteczny i został zastąpiony — jest w gicie, gdyby był potrzebny.`, + 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: { daysToRace: (days: number) => `do startu: ${dni(days)}`, + daysAfterRace: (days: number) => `${dni(days)} po starcie`, weekOf: (index: number, total: number) => `tydzień ${index}/${total}`, deload: 'odciążenie', restDayTitle: 'Dzień wolny', 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}`, + strengthLogged: (status: string) => `Siła zalogowana: ${status}`, + 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: @@ -187,6 +268,30 @@ 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.', + strengthSaved: (date: string, status: string) => `Zalogowano siłę ${date}: ${status}.`, + strengthStatus: (value: string) => `Status siły „${value}” — użyj done albo skipped.`, + strengthOnly: 'Wpis siły przyjmuje tylko --minutes i --note; bieg zaloguj osobno.', + strengthMinutes: 'Minuty siły: liczba całkowita 1–300.', + strengthUnplanned: 'Tego dnia nie było siły w planie — wpis zostaje jako sesja dodatkowa.', + 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: { @@ -215,7 +320,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 +329,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: { @@ -241,6 +347,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' })} (duplikat, to nie aktywność, nieczytelny albo nieobsługiwany): ${sample}`, activities: 'Aktywności', activitiesValue: (total: number, runs: number, km: number) => `${total} (biegowych: ${runs}, ${n(km)} km)`, @@ -296,7 +406,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: { @@ -314,7 +424,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`, @@ -331,7 +442,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', @@ -453,6 +564,7 @@ export const cliPl: CliMessages = { calendarEntries: (count: number) => `${count} ${pluralPl(count, { one: 'trening', few: 'treningi', other: 'treningów' })} w kalendarzu`, printedWeeks: (weeks: number) => `rozpiska ${tygodnie(weeks)} do wydruku`, + noRaceInBase: 'Plan bazowy nie ma startu — pakiet startowy wymaga startu docelowego (goal.kind: race).', heat: { columns: { temperature: 'temperatura', pace: 'tempo', loss: 'strata' }, scenarioColumn: (label: string) => `scenariusz „${label}”`, @@ -476,7 +588,21 @@ 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}.`, + strength: 'Siła', + strengthValue: (done: number, planned: number, skipped: number) => + `${done} z ${planned} zaplanowanych${skipped ? `, ${skipped} pominięte` : ''}`, + 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) => @@ -492,9 +618,12 @@ 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', + baseEnd: 'Plan bazowy do', toRaceValue: (days: number) => `${days} ${pluralPl(days, { one: 'dzień', few: 'dni', other: 'dni' })}`, raceThisWeek: (date: string) => @@ -617,6 +746,136 @@ 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ą.`, + }, + + 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)`, + }, + + 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.', + 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"', + 'trainctl log --strength done --minutes 30', + ], + 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', 'trainctl pull --from ./activities # eksport FIT/TCX/GPX, bez konta'], + 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} ` + @@ -632,6 +891,7 @@ export const cliPl: CliMessages = { }, planMd: { + headingBase: (goalName: string, date: string) => `Plan: ${goalName} — budowanie bazy do ${date}`, heading: (goalName: string, date: string) => `Plan: ${goalName} — ${date}`, goalTime: (time: string) => ` · cel: ${time}`, meta: (generatedAt: string, vdot: number, source: string, peakKm: number) => @@ -651,6 +911,14 @@ export const cliPl: CliMessages = { noCalibration: 'Brak wyniku startu z ostatnich 18 miesięcy i brak goal.targetTimeSec — ' + 'nie mam z czego skalibrować stref (Z-6: kalibrujemy z wyników, nie z zegarka).', + timeCapsVolume: (peak: number, withoutBudget: number, recommended: number) => + `Budżet czasu ogranicza plan do ${n(peak)} km/tydz.; bez niego plan doszedłby do ${n(withoutBudget)} km/tydz. ` + + `(rekomendowane dla tego dystansu: ${n(recommended)} km/tydz., P-7/P-8). Zmieni to więcej minut albo bliższy cel (E-2).`, + timeDayTooShort: (dates: string) => + `Te jednostki nie mieszczą się w budżecie dnia nawet po skróceniu (startów i sprawdzianów nie skracamy): ${dates} (E-2).`, + timeWeekOver: (weeks: string) => `Te tygodnie zostają ponad budżetem tygodnia: ${weeks} (E-2).`, + trailOnlyCalibration: + 'Strefy pochodzą z wyniku na trailu — teren spowalnia bieg, więc tempa szosowe mogą być za łatwe. Dopisz wynik szosowy (Z-10).', zonesFromGoal: 'strefy skalibrowane z celu czasowego, nie z realnego wyniku — dodaj start do athlete.results', }, @@ -676,6 +944,17 @@ export const cliPl: CliMessages = { }, templateDesk: 'tryb biurkowy (trainctl desk) — opcjonalny', templateDeskPrefer: 'morning | lunch | evening', + baseGoalName: 'Budowanie bazy', + templateTime: { + section: 'czas, który naprawdę masz, z przygotowaniem i siłą (opcjonalnie)', + weekly: 'minut w tygodniu — objętość wypłaszcza się na tym, co się mieści (E-2)', + weekday: 'minut od poniedziałku do piątku — dłuższe jednostki są skracane (E-1)', + weekend: 'minut w sobotę i niedzielę', + }, + 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)', @@ -705,6 +984,8 @@ export const cliPl: CliMessages = { listRequired: (path: string) => `${path}: wymagana lista`, isoDate: (path: string) => `${path}: format RRRR-MM-DD`, seconds: (path: string) => `${path}: liczba sekund > 0`, + goalKind: (path: string) => `${path}: race (domyślnie) albo base`, + minutes: (path: string) => `${path}: pełne minuty od 15 do 2000`, priorityBc: (path: string) => `${path}: B albo C (A to cel w sekcji goal)`, required: (path: string) => `${path}: wymagane`, boolean: (path: string) => `${path}: true albo false`, @@ -741,6 +1022,17 @@ export const cliPl: CliMessages = { 'F-4': 'ciężko: ≥80% 1RM, wielostawowo, wolny ciężar — im ciężej, tym większy efekt na ekonomię (Llanos-Lagos 2024)', 'F-13': 'taper: siła znika z planu — 4 tyg. detrainingu nie kasuje adaptacji (Berryman 2020, uwaga: n=8)', 'S-4': 'siła i bieg tego samego dnia: ≥3 h odstępu udokumentowane (Schumann 2022); 6 h to margines inżynierski', + 'F-12': 'siła 2× w tygodniu w bazie, 0–1× w okresie startowym (Haugen 2022)', + 'F-14': 'jedna sesja siły w tygodniu utrzymuje efekt bloku (Rønnestad 2010 — dane z kolarzy, ekstrapolacja)', + 'F-18': 'dwa pierwsze tygodnie bloku siły to nauka ruchu przy ~75% 1RM przed ciężkimi tygodniami — wybór inżynierski, bez źródła', + 'R-1': 'po maratonie 48 h bez biegania, potem lekko — 40 min spokojnie po 48/96/144 h (Martínez-Navarro 2021)', + 'R-2': 'powrót do biegania 48 h po maratonie nie spowalnia regeneracji (Martínez-Navarro 2021)', + 'R-8': 'po starcie na półmaraton i dłużej dwa tygodnie przejściowe: ~50% objętości sprzed startu wyłącznie spokojnie, potem ~100% z jednym akcentem (korpus trenerski, n=3; Martínez-Navarro 2021)', + 'R-9': 'siła wraca w drugim tygodniu po starcie, jedną lżejszą sesją — wybór inżynierski, bez źródła', + 'R-10': 'po krótszym starcie docelowym jeden tydzień przejściowy ~70% — wybór inżynierski; brak danych', + 'P-11': 'plan bez startu rośnie do udokumentowanego szczytu (albo +15%) i tam się wypłaszcza, odciążenie co czwarty tydzień — wybór inżynierski', + 'E-2': 'budżet czasu z trainctl.yaml ogranicza objętość tygodnia i skraca jednostki według zasad E-1 — wybór inżynierski, bez źródła', + 'Z-10': 'wynik z trailu nie kalibruje stref szosowych, dopóki jest wynik szosowy — wybór inżynierski; tabele VDOT pochodzą z szosy i bieżni', 'S-5': 'ciężka siła nie później niż 24 h przed sesją jakościową — deficyt siły trwa do 48 h (de Carvalho e Silva 2022)', }, @@ -774,7 +1066,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: @@ -787,6 +1082,8 @@ export const cliPl: CliMessages = { logTime: 'czas MM:SS albo HH:MM:SS', logRpe: 'wysiłek sesji jako liczba całkowita 1–10 (CR-10, 10 = maksymalny). Zapytaj biegacza po sesji — nigdy nie zgaduj.', + logStrength: 'done | skipped — zapis sesji siłowej zamiast biegu (działają tylko minutes i note).', + logMinutes: 'czas sesji siłowej w minutach', logNote: 'samopoczucie, warunki, uwagi', shift: 'Renegocjacja tygodnia: zamień treningi między dwiema datami TEGO SAMEGO tygodnia ' + @@ -835,6 +1132,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) ' + @@ -859,9 +1157,39 @@ 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, ' + + '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: (): 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. @@ -873,11 +1201,17 @@ 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 \`athlete.results\`. Pomiar bez wpisanego wyniku niczego nie zmienia — strefy - dalej liczą się ze starego biegu. + dalej liczą się ze starego biegu. Po starcie docelowym plan idzie dalej tygodniami + przejściowymi (R-8); gdy użytkownik poda następny cel, zmień \`goal\` + w \`trainctl.yaml\` → \`trainctl_diff\` → \`trainctl_plan\` — nowy cykl zaczyna się + po bloku przejściowym i zachowuje historię. - **Po zalogowanym treningu** → krótka odprawa. Zapytaj, jak było, i zapisz to w dzienniku (\`trainctl_log\` z rpe 1–10 i notatką) — ślad odczuć wraca potem w przeglądzie tygodnia. Gdy odczucie kłóci się z rolą jednostki (spokojny @@ -893,8 +1227,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 @@ -905,7 +1240,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/coach-en.ts b/packages/cli/src/i18n/coach-en.ts index 819570c..d8ecad4 100644 --- a/packages/cli/src/i18n/coach-en.ts +++ b/packages/cli/src/i18n/coach-en.ts @@ -18,6 +18,8 @@ export const coachEn = { heuristic: 'E-1: engineering choices: retain at least half of quality work, 60% of a long run, the original preparation before hills, and at least 15 min for an easy replacement. These cutoffs do not establish physiological equivalence.', context: 'How this session fits your plan', goal: (name: string, distance: number, date: string, days: number) => `Goal: ${name}, ${distance} km on ${date}; ${days} days from this session.`, + goalBehind: (name: string, distance: number, date: string, days: number) => `Goal behind you: ${name}, ${distance} km on ${date}; this session is ${days} days after it.`, + goalBase: (name: string, date: string) => `Goal: ${name} — base training without a race, until ${date} (P-11).`, weekContext: (phase: string, actual: number, target: number, share: number) => `Phase: ${phase}. Week: ${actual} km against a ${target} km target; ${share}% easy running.`, deload: 'This is a reduced-volume week in the stored plan.', taper: 'The stored taper reduces volume while aiming to retain intensity and session frequency.', diff --git a/packages/cli/src/i18n/coach-pl.ts b/packages/cli/src/i18n/coach-pl.ts index 8bfb8f6..f843177 100644 --- a/packages/cli/src/i18n/coach-pl.ts +++ b/packages/cli/src/i18n/coach-pl.ts @@ -18,6 +18,8 @@ export const coachPl: typeof coachEn = { applyHint: (id: string) => `Przejrzyj propozycję, następnie zatwierdź dokładnie te zmiany: trainctl adapt --apply ${id}`, heuristic: 'E-1: wybory inżynierskie: zachowujemy co najmniej połowę pracy jakościowej, 60% długiego biegu, pierwotne wprowadzenie przed podbiegami i co najmniej 15 min spokojnego zamiennika. Te progi nie dowodzą równoważności fizjologicznej.', context: 'Miejsce tej jednostki w Twoim planie', + goalBehind: (name: string, distance: number, date: string, days: number) => `Cel za Tobą: ${name}, ${distance} km dnia ${date}; ta jednostka wypada ${days} dni po nim.`, + goalBase: (name: string, date: string) => `Cel: ${name} — budowanie bazy bez startu, do ${date} (P-11).`, goal: (name: string, distance: number, date: string, days: number) => `Cel: ${name}, ${distance} km, ${date}; od tej jednostki pozostaje ${days} dni.`, weekContext: (phase: string, actual: number, target: number, share: number) => `Faza: ${phase}. Tydzień: ${actual} km przy celu ${target} km; ${share}% spokojnego biegania.`, deload: 'W zapisanym planie ten tydzień ma obniżoną objętość.', diff --git a/packages/cli/src/i18n/improve-en.ts b/packages/cli/src/i18n/improve-en.ts index 0813f04..b74f2af 100644 --- a/packages/cli/src/i18n/improve-en.ts +++ b/packages/cli/src/i18n/improve-en.ts @@ -32,7 +32,7 @@ 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', + terrain: 'Trail result — not used for road zones (Z-10)', 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..b19a4fa 100644 --- a/packages/cli/src/i18n/improve-pl.ts +++ b/packages/cli/src/i18n/improve-pl.ts @@ -33,7 +33,7 @@ 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', + terrain: 'Wynik z trailu — nie kalibruje stref szosowych (Z-10)', 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/interactive.test.ts b/packages/cli/src/interactive.test.ts index c2ab9dd..3df9bbe 100644 --- a/packages/cli/src/interactive.test.ts +++ b/packages/cli/src/interactive.test.ts @@ -114,7 +114,7 @@ describe('lista dni do przesunięcia', () => { it('dzień startu jest zablokowany', () => { const plan = loadPlan(dir) - const raceWeek = plan.weeks.at(-1)! + const raceWeek = plan.weeks.find((w) => w.skeleton.raceDate)! const race = dayChoices(raceWeek).find((c) => c.value === plan.goal.date)! expect(race.disabled).toBe(true) expect(race.hint).toContain('nie do przesunięcia') 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/logfile.ts b/packages/cli/src/logfile.ts index 69b95ea..c2f0626 100644 --- a/packages/cli/src/logfile.ts +++ b/packages/cli/src/logfile.ts @@ -22,17 +22,42 @@ export interface LogEntry { loggedAt: string } -export function appendLog(cwd: string, entry: LogEntry): void { +/** + * Wpis sesji siłowej — w tym samym log.jsonl, ale osobny tor (ADR-023): nie + * nadpisuje wpisu biegu z tej samej daty i nie wchodzi do porównań wykonania. + */ +export interface StrengthLogEntry { + date: string + activity: 'strength' + status: 'done' | 'skipped' + minutes?: number + note?: string + loggedAt: string +} + +export function appendLog(cwd: string, entry: LogEntry | StrengthLogEntry): void { appendFileSync(join(cwd, LOG_FILE), JSON.stringify(entry) + '\n', 'utf-8') } -export function readLog(cwd: string): LogEntry[] { +function readAll(cwd: string): (LogEntry | StrengthLogEntry)[] { const path = join(cwd, LOG_FILE) if (!existsSync(path)) return [] return readFileSync(path, 'utf-8') .split('\n') .filter((l) => l.trim()) - .map((l) => JSON.parse(l) as LogEntry) + .map((l) => JSON.parse(l) as LogEntry | StrengthLogEntry) +} + +const isStrength = (e: LogEntry | StrengthLogEntry): e is StrengthLogEntry => (e as StrengthLogEntry).activity === 'strength' + +/** Wpisy biegowe — to, z czego liczy się wykonanie planu. */ +export function readLog(cwd: string): LogEntry[] { + return readAll(cwd).filter((e): e is LogEntry => !isStrength(e)) +} + +/** Wpisy siły; ostatni wpis dnia wygrywa, jak w dzienniku biegów. */ +export function readStrengthLog(cwd: string): StrengthLogEntry[] { + return readAll(cwd).filter(isStrength) } /** Ostatni wpis dla daty (późniejszy nadpisuje wcześniejszy w interpretacji). */ diff --git a/packages/cli/src/packaging.test.ts b/packages/cli/src/packaging.test.ts index d2d7aed..c3ec70c 100644 --- a/packages/cli/src/packaging.test.ts +++ b/packages/cli/src/packaging.test.ts @@ -10,13 +10,14 @@ * * Stąd asercje na manifestach: do rejestru idą wyłącznie wejścia zbudowane. */ +import { spawnSync } from 'node:child_process' import { 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 PACKAGES = ['core', 'export', 'sync-intervalsicu', 'cli', 'mcp'] +const PACKAGES = ['core', 'export', 'sync-intervalsicu', 'sync-files', 'cli', 'mcp'] interface Manifest { name: string @@ -70,3 +71,14 @@ describe('manifesty paczek: do rejestru idzie build, nie źródło', () => { } }) }) + +describe('skrypty hooków pluginu', () => { + // Z CRLF (checkout na Windows) vitest nie zdejmuje `#!` i plugin.test.ts pada na + // imporcie — tu widać przyczynę, a nie tylko SyntaxError bez wskazówki. + it('mają LF w każdym checkoucie (.gitattributes)', () => { + for (const script of ['plugin/scripts/check-plan.mjs', 'plugin/scripts/session-start.mjs']) { + const out = spawnSync('git', ['check-attr', 'eol', '--', script], { cwd: ROOT, encoding: 'utf-8' }) + expect(out.stdout.trim(), script).toBe(`${script}: eol: lf`) + } + }) +}) diff --git a/packages/cli/src/planfile.ts b/packages/cli/src/planfile.ts index ed71eba..2939ea0 100644 --- a/packages/cli/src/planfile.ts +++ b/packages/cli/src/planfile.ts @@ -5,8 +5,11 @@ import { join } from 'node:path' import { parse, stringify } from 'yaml' import { diffDays, + mondayOf, estimateWorkoutMinutes, generateMicrocycle, + shortenWorkout, + weekTotals, getLocale, messages, paceZones, @@ -20,14 +23,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') @@ -38,7 +45,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 @@ -60,17 +74,69 @@ export interface StoredPlan { weeks: Microcycle[] } -export function computePlan(config: TrainctlConfig, today: string, calibrationDate = today): StoredPlan { +export interface ComputePlanOptions { + /** + * Zmiana tygodni PRZED budżetem czasu — skalowanie bazy (regeneracja) albo + * podmiana tygodni na tygodnie zapisanego planu (propozycja adapt). Budżet + * działa potem raz, tymi samymi strefami — dlatego regeneracja bez zmian na + * wejściu daje bajt w bajt ten sam plan. + */ + beforeTimeBudget?: (plan: StoredPlan) => void + /** + * Poniedziałek, od którego budżet czasu działa. Tygodnie wcześniejsze są gotowe + * — przeszłość przed decyzją z planu bez bazy albo z zapisanego planu, już po + * budżecie — i nie są przycinane drugi raz (przy małych celach generator nie + * jest monotoniczny, więc powtórka dałaby inne dni niż te, które biegacz miał), + * ani nie trafiają do ostrzeżeń: ich nie da się już zmienić. Z granicą siła + * zostaje na swoich dniach (plan z historią); bez niej — świeży plan — budżet + * tygodnia rozstawia ją od nowa pod nowe dni biegowe. + */ + budgetFrom?: string + /** + * Poniedziałek, od którego budżet przycina całe tygodnie (domyślnie `budgetFrom`). + * Rekalibracja zmienia w bieżącym tygodniu tylko tempa: jego przeszłe dni + * zostają, więc tydzień przycięty od nowa nie zgadzałby się z tym, co w nim jest + * — limit dnia skraca za długie dni od `budgetFrom`, tygodnie od następnego. + */ + weeklyBudgetFrom?: string + /** + * false = ostrzeżenia budżetu (`budgetWarnings`) liczy wołający na planie, który + * zapisze — po złożeniu z dni chronionych (regeneracja, propozycja). + */ + budgetWarnings?: boolean +} + +/** Tydzień sprzed granicy budżetu — gotowy, budżet go nie rusza. */ +const beforeBoundary = (week: Microcycle, boundary: string | undefined) => boundary !== undefined && week.weekStart < boundary + +/** + * Tydzień złożony z dni dwóch planów (przeszłe albo chronione zostają, reszta + * przychodzi z nowego): sumy z dni, a objętość po budżecie to to, co w nim + * faktycznie jest — z nią lint porównuje dni (P-3). Wspólne dla propozycji + * i regeneracji. + */ +export function settleMixedWeek(week: Microcycle): void { + Object.assign(week, weekTotals(week.days)) + if (week.skeleton.timeCappedKm !== undefined) week.skeleton = { ...week.skeleton, timeCappedKm: roundKm(week.totalKm) } +} + +export function computePlan(config: TrainctlConfig, today: string, calibrationDate = today, opts: ComputePlanOptions = {}): StoredPlan { const { athlete, goal } = config - const usable = athlete.results.filter( + const recent = athlete.results.filter( (r) => !r.excluded && r.date <= calibrationDate && diffDays(r.date, calibrationDate) <= 540, ) + // Z-10 (inż.): wynik z trailu nie kalibruje stref szosowych — czas w terenie mówi + // o terenie tak samo jak o formie. Gdy innych wyników brak, używamy go z ostrzeżeniem. + const roadGoal = goal.terrain !== 'trail' && goal.terrain !== 'ultra' + const road = roadGoal ? recent.filter((r) => r.terrain !== 'trail') : recent + const usable = road.length ? road : recent + const trailOnly = roadGoal && road.length === 0 && recent.length > 0 let vdot: number let vdotSource: StoredPlan['vdotSource'] if (usable.length > 0) { vdot = Math.max(...usable.map((r) => vdotFromRace(r.distanceKm, r.timeSec))) vdotSource = 'result' - } else if (goal.targetTimeSec) { + } else if (goal.targetTimeSec && goal.kind !== 'base') { vdot = vdotFromRace(goal.distanceKm, goal.targetTimeSec) vdotSource = 'goal-target' } else { @@ -87,9 +153,9 @@ 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), + calibration: inspectCalibration(athlete.results, calibrationDate, roadGoal), generatedAt: today, locale: getLocale(), vdot: Math.round(vdot * 10) / 10, @@ -101,16 +167,80 @@ export function computePlan(config: TrainctlConfig, today: string, calibrationDa changes: [], weeks, } - if (usable.length > 0) { + + // plan bazowy nie ma dystansu docelowego, więc i predykcji (P-11) + if (usable.length > 0 && goal.kind !== 'base') { plan.prediction = predictRace(usable, goal.distanceKm, { today: calibrationDate }) } if (vdotSource === 'goal-target') { plan.feasibilityWarnings.push(ui().planMd.zonesFromGoal) } + if (trailOnly) plan.feasibilityWarnings.push(ui().planMd.trailOnlyCalibration) + opts.beforeTimeBudget?.(plan) + if (config.time) { + fitTimeBudget(plan.weeks, config, zones, testDistanceKm(goal), { from: opts.budgetFrom, weeklyFrom: opts.weeklyBudgetFrom ?? opts.budgetFrom }) + plan.peakKmPlanned = Math.max(...cycleWeeksOf(plan).map((w) => w.totalKm)) + if (opts.budgetWarnings !== false) plan.feasibilityWarnings.push(...budgetWarnings(plan, config, today)) + } plan.generatedDays = Object.fromEntries(plan.weeks.flatMap((w) => w.days).map((d) => [d.date, dayFingerprint(d)])) return plan } +/** + * Skalowanie objętości do zatwierdzonej bazy — jedna arytmetyka dla propozycji + * (`adapt --prepare`, ADR-029) i regeneracji z zapisaną bazą (ADR-033), żeby + * `plan` tuż po `adapt --apply` odtwarzał zatwierdzone dni. Kotwica to pełny + * tydzień budowania (bez odpoczynkowych, taperu, startu i bloku po starcie): + * pierwszy po dacie decyzji, a gdy takiego nie ma (decyzja w taperze) — ostatni + * przed nią. Tygodnie od poniedziałku decyzji skalowane proporcjonalnie od zamiaru + * makrocyklu (budżet czasu stosuje potem computePlan, raz, od tego samego + * poniedziałku — `budgetFrom`); wcześniejsze przechodzą z `reference`. Siła to + * osobny tor: korekta objętości jej nie przestawia — też przychodzi z `reference`. + */ +export function scaleToBaseline(weeks: Microcycle[], opts: { + baselineKm: number + decidedOn: string + config: TrainctlConfig + goal: RaceGoal + vdot: number + /** + * Plan bez bazy: tygodnie sprzed decyzji przechodzą z niego bez zmian, a siła + * (sesje dni i notatki tygodnia) — do tygodni skalowanych. + */ + reference: Microcycle[] +}): Microcycle[] { + const zones = paceZones(opts.vdot) + // Kotwica to pełny tydzień budowania: nie odpoczynkowy, nie taper, start ani blok + // po starcie (połowa objętości) — inaczej „redukcja" podniosłaby resztę planu. + // Decyzja w taperze: ostatni taki tydzień przed nią. + const normal = (w: Microcycle) => !w.skeleton.deload && !['taper', 'race', 'transition'].includes(w.skeleton.phase) + const anchor = + weeks.find((w) => w.weekStart > opts.decidedOn && normal(w)) ?? + [...weeks].reverse().find((w) => w.weekStart <= opts.decidedOn && normal(w)) ?? + weeks.find((w) => w.days.some((d) => d.date > opts.decidedOn)) + const from = mondayOf(opts.decidedOn) + const strengthDays = new Map(opts.reference.flatMap((w) => w.days).map((d) => [d.date, d.strength])) + const referenceWeeks = new Map(opts.reference.map((w) => [w.weekStart, w])) + return weeks.map((week) => { + // tygodnie przed decyzją to przeszłość, której decyzja nie dotyczy — takie, jak + // w planie bez bazy (kopia: computePlan zmienia tygodnie w miejscu, a to mogą + // być tygodnie zapisanego planu) + if (week.weekStart < from) return structuredClone(referenceWeeks.get(week.weekStart) ?? week) + const skeleton = structuredClone(week.skeleton) + delete skeleton.timeCappedKm + delete skeleton.uncappedKm + skeleton.targetKm = Math.round((opts.baselineKm * skeleton.targetKm) / Math.max(1, anchor?.skeleton.targetKm ?? skeleton.targetKm)) + const generated = generateMicrocycle({ skeleton, athlete: opts.config.athlete, goal: opts.goal, zones, testDistanceKm: testDistanceKm(opts.goal) }) + for (const day of generated.days) { + const strength = strengthDays.get(day.date) + if (strength) day.strength = structuredClone(strength) + } + const notes = referenceWeeks.get(week.weekStart)?.strengthNotes + if (notes?.length) generated.strengthNotes = [...notes] + return generated + }) +} + export function writePlan(cwd: string, plan: StoredPlan): void { mkdirSync(join(cwd, PLAN_DIR), { recursive: true }) // Bez aliasów YAML (`pace: *a1`): plan jest dokumentem, który użytkownik czyta @@ -120,6 +250,144 @@ export function writePlan(cwd: string, plan: StoredPlan): void { writeFileSync(join(cwd, PLAN_MD), renderMarkdown(plan), 'utf-8') } +/** Przygotowanie wliczone w budżet czasu — to samo domyślne 15 minut co w E-1. */ +const PREPARATION_MINUTES = 15 + +const isWeekend = (wd: string) => wd === 'sat' || wd === 'sun' + +/** Plik planu czyta i edytuje człowiek — bez szumu zmiennoprzecinkowego (25.000000000000004). */ +const roundKm = (km: number) => Math.round(km * 10) / 10 + +/** + * Budżet czasu z profilu (E-2, wartość inżynierska) — dwa kroki: + * 1. tydzień ponad `weeklyMinutes` dostaje niższy cel kilometrów (nadwyżka minut + * przeliczona po wolniejszej granicy tempa spokojnego) i jest generowany + * od nowa — objętość wypłaszcza się na tym, co się mieści; + * 2. dzień ponad limitem dnia przechodzi przez to samo skracanie co `shorten` + * (E-1), z jawnym `timeAdjustment` i utratą celu, gdy wariant jej wymaga. + * Starty i sprawdziany nie są skracane; co się nie mieści, zostaje ostrzeżeniem. + */ +function fitTimeBudget( + weeks: Microcycle[], config: TrainctlConfig, zones: ReturnType, testKm: number, + bounds: { from: string | undefined; weeklyFrom: string | undefined }, +): void { + const ready = (week: Microcycle) => beforeBoundary(week, bounds.from) + const weeklyReady = (week: Microcycle) => beforeBoundary(week, bounds.weeklyFrom) + const time = config.time! + const minutesOf = (d: PlannedDay) => + (d.workout ? estimateWorkoutMinutes(d.workout, PREPARATION_MINUTES) : 0) + (d.strength?.durationMin ?? 0) + const runMinutes = (w: Microcycle) => w.days.reduce((s, d) => s + (d.workout ? estimateWorkoutMinutes(d.workout, PREPARATION_MINUTES) : 0), 0) + const easyMinPerKm = zones.easy.hiSecPerKm / 60 + if (time.weeklyMinutes) { + let capped = false + for (let i = 0; i < weeks.length; i++) { + if (weeklyReady(weeks[i]!)) continue + // Siła wraca dopiero po pętli (applyStrength) — jej minuty liczymy z tygodnia + // przed regeneracją, inaczej kolejny przebieg uznałby tydzień za zmieszczony. + const strengthMinutes = weeks[i]!.days.reduce((s, d) => s + (d.strength?.durationMin ?? 0), 0) + // Cel podawany generatorowi maleje z przebiegu na przebieg i nie przekracza + // tego, co generator faktycznie rozpisał: rozpisana objętość bywa wyższa od celu + // (minima jednostek), a cel szkieletu — nieosiągalny (mało dni, limit długiego). + // Redukcja liczona od którejś z nich mogłaby tydzień podnieść albo nie zejść + // pod budżet w czterech przebiegach. Budżet tylko obniża: tydzień przycięty + // wcześniej po szybszej rekalibracji nie rośnie — objętość podnosi `plan`. + let requested = weeks[i]!.skeleton.targetKm + const uncappedKm = weeks[i]!.skeleton.uncappedKm ?? roundKm(weeks[i]!.totalKm) + for (let pass = 0; pass < 4; pass++) { + const week = weeks[i]! + if (week.skeleton.raceDate) break + const minutes = runMinutes(week) + strengthMinutes + if (minutes <= time.weeklyMinutes) break + requested = Math.min(requested, week.totalKm) + const target = Math.max(5, Math.floor(requested - (minutes - time.weeklyMinutes) / easyMinPerKm)) + if (target >= requested) break + requested = target + const regenerated = generateMicrocycle({ skeleton: { ...week.skeleton, targetKm: target }, athlete: config.athlete, zones, goal: config.goal, testDistanceKm: testKm }) + // zamiar makrocyklu zostaje w targetKm; budżet zapisuje obok objętość, którą + // generator faktycznie rozpisał (bywa wyżej niż cel), bo z nią lint porównuje sumy (P-3) + regenerated.skeleton = { ...week.skeleton, timeCappedKm: roundKm(regenerated.totalKm), uncappedKm } + for (const day of regenerated.days) { + const session = week.days.find((d) => d.date === day.date)?.strength + if (session) day.strength = structuredClone(session) + } + // notatki siły tygodnia (PLAN.md) idą razem z sesjami — w świeżym planie i tak + // ustawi je od nowa applyStrength, w planie z historią nie ma kto + if (week.strengthNotes?.length) regenerated.strengthNotes = [...week.strengthNotes] + weeks[i] = regenerated + capped = true + } + } + // świeży plan (bez granicy): siła rozstawiona od nowa pod nowe dni biegowe; plan + // z historią — siła zostaje, korekta objętości jej nie przestawia, a applyStrength + // ruszyłby też gotowe tygodnie + if (capped && bounds.from === undefined && config.strength?.enabled) applyStrength(weeks, config.strength) + } + for (const week of weeks) { + if (ready(week)) continue + let shortened = false + const uncappedKm = week.skeleton.uncappedKm ?? roundKm(week.totalKm) + for (const day of week.days) { + const cap = isWeekend(day.weekday) ? time.weekendMinutes : time.weekdayMinutes + if (cap === undefined || !day.workout || minutesOf(day) <= cap) continue + // startów i sprawdzianów nie skracamy — zostają w ostrzeżeniu (budgetWarnings) + if (['race', 'test'].includes(day.workout.kind)) continue + const result = shortenWorkout(day.workout, cap, { preparationMinutes: PREPARATION_MINUTES, strengthMinutes: day.strength?.durationMin ?? 0 }) + if (result.workout && (result.status === 'shortened' || result.status === 'easy-alternative')) { + // ponowne skrócenie (np. po rekalibracji) nie gubi pierwotnej jednostki ani utraty celu + const earlier = day.timeAdjustment + day.timeAdjustment = { + originalKind: earlier?.originalKind ?? day.workout.kind, + originalDistanceKm: earlier?.originalDistanceKm ?? day.workout.distanceKm, + budgetMinutes: cap, + status: earlier?.status === 'easy-alternative' ? 'easy-alternative' : result.status, + origin: 'profile', + } + day.workout = result.workout + shortened = true + } + } + Object.assign(week, weekTotals(week.days)) + // Skrócone dni obniżają objętość tygodnia — zapisujemy ją obok zamiaru (targetKm), + // inaczej lint zgłaszałby P-3 na świeżo wygenerowanym planie. + if (shortened) week.skeleton = { ...week.skeleton, timeCappedKm: roundKm(week.totalKm), uncappedKm } + } +} + +/** + * Ostrzeżenia budżetu czasu (E-2) liczone na planie, który biegacz dostaje — także + * po złożeniu z dni chronionych — i tylko dla tego, co da się jeszcze zmienić: + * dni od `from` za długie na limit dnia (starty, sprawdziany, jednostki, których nie + * da się skrócić), tygodnie z takimi dniami ponad budżetem tygodnia oraz szczyt + * tygodni w całości od `from` obniżony przez budżet poniżej rekomendacji — z tym, + * ile tygodnie miałyby bez budżetu (`uncappedKm`), bo to bywa mniej niż rekomendacja + * (baza biegacza, mało dni, redukcja) i „więcej minut" da tylko tyle. Tolerancja + * P-3 (0,5 km): zaokrąglenie generatora to nie przycięcie. + */ +export function budgetWarnings(plan: StoredPlan, config: TrainctlConfig, from: string): string[] { + const time = config.time + if (!time) return [] + const minutesOf = (d: PlannedDay) => + (d.workout ? estimateWorkoutMinutes(d.workout, PREPARATION_MINUTES) : 0) + (d.strength?.durationMin ?? 0) + const weeks = cycleWeeksOf(plan) + const tooLong = weeks.flatMap((w) => w.days).filter((d) => { + const cap = isWeekend(d.weekday) ? time.weekendMinutes : time.weekdayMinutes + return d.date >= from && d.workout !== undefined && cap !== undefined && minutesOf(d) > cap + }).map((d) => d.date) + const overWeek = time.weeklyMinutes + ? weeks.filter((w) => w.days.some((d) => d.date >= from) && !w.skeleton.raceDate && + w.days.reduce((s, d) => s + (d.workout || d.strength ? minutesOf(d) : 0), 0) > time.weeklyMinutes!).map((w) => w.weekStart) + : [] + const ahead = weeks.filter((w) => w.weekStart >= from) + const peak = Math.max(0, ...ahead.map((w) => w.totalKm)) + const withoutBudget = Math.max(0, ...ahead.map((w) => w.skeleton.uncappedKm ?? w.totalKm)) + const capsVolume = ahead.some((w) => w.skeleton.timeCappedKm !== undefined) && peak < plan.peakKmRecommended && peak + 0.5 < withoutBudget + return [ + ...(tooLong.length ? [ui().planMd.timeDayTooShort(tooLong.join(', '))] : []), + ...(overWeek.length ? [ui().planMd.timeWeekOver(overWeek.join(', '))] : []), + ...(capsVolume ? [ui().planMd.timeCapsVolume(peak, withoutBudget, plan.peakKmRecommended)] : []), + ] +} + /** * Rozstawienie siły na ciągu tygodni. Ciąg, a nie tydzień po tygodniu osobno: * odstęp ≥48 h musi obowiązywać także na styku niedziela→poniedziałek. @@ -127,14 +395,18 @@ export function writePlan(cwd: string, plan: StoredPlan): void { */ export function applyStrength(weeks: Microcycle[], strength: StrengthConfig): void { let lastSessionDate: string | undefined + // tydzień bloku siły: liczymy tygodnie, w których siła w ogóle wchodzi do planu + let blockWeek = 0 for (const week of weeks) { const { byDate, notes } = planStrengthWeek({ week, phase: week.skeleton.phase, deload: week.skeleton.deload, + blockWeek, ...(strength.days?.length ? { daysPreference: strength.days } : {}), ...(lastSessionDate ? { lastSessionDate } : {}), }) + if (!['taper', 'race'].includes(week.skeleton.phase)) blockWeek++ for (const day of week.days) { const session = byDate.get(day.date) if (session) day.strength = session @@ -170,7 +442,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 +454,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 } @@ -198,6 +475,61 @@ export function loadPlanFile(path: string): StoredPlan { return doc } +export type ExistingPlan = + | { status: 'missing' } + | { status: 'ok'; plan: StoredPlan } + | { status: 'unreadable'; reason: 'parse' | 'shape' } + | { status: 'unreadable'; reason: 'schema'; version: number } + +/** + * Co powiedzieć o pliku planu, którego nie da się użyć. Nowszy schemat to plan + * z nowszego trainctl (np. od drugiej osoby z repo) — rada to aktualizacja, nie + * `--fresh`, które porzuciłoby poprawny plan z przypięciami i historią. + */ +export function unusablePlanMessage(found: Extract): string { + return found.reason === 'schema' + ? ui().common.planSchemaNewer(PLAN_YAML, found.version) + : ui().plan.unreadable(PLAN_YAML, ui().plan.unreadableReason[found.reason]) +} + +/** + * Istniejący plik planu i to, czy da się go użyć. Niesparsowalny (znaczniki + * konfliktu merge'a), bez celu i tygodni albo z nowszym schematem to + * `unreadable` — `plan` odmawia wtedy cichego nadpisania (historia, przypięcia + * i zatwierdzona baza zginęłyby bez słowa) i nadpisuje dopiero na jawne `--fresh`. + */ +export function readExistingPlan(cwd: string): ExistingPlan { + if (!existsSync(join(cwd, PLAN_YAML))) return { status: 'missing' } + let doc: unknown + try { + doc = parse(readFileSync(join(cwd, PLAN_YAML), 'utf-8')) + } catch { + return { status: 'unreadable', reason: 'parse' } + } + if (!looksLikePlan(doc)) return { status: 'unreadable', reason: 'shape' } + if (typeof doc.schemaVersion === 'number' && doc.schemaVersion > PLAN_SCHEMA_VERSION) return { status: 'unreadable', reason: 'schema', version: doc.schemaVersion } + return { status: 'ok', plan: doc } +} + +/** Ostatni dzień planu — po starcie plan trwa dalej blokiem przejściowym (R-8). */ +export const planEnd = (plan: StoredPlan): string => plan.weeks.at(-1)?.days.at(-1)?.date ?? plan.goal.date + +/** 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, @@ -240,7 +572,7 @@ export function renderMarkdown(plan: StoredPlan): string { const core = messages() const lines: string[] = [] const target = plan.goal.targetTimeSec ? m.goalTime(fmtTime(plan.goal.targetTimeSec)) : '' - lines.push(`# ${m.heading(plan.goal.name, plan.goal.date)}${target}`) + lines.push(`# ${plan.goal.kind === 'base' ? m.headingBase(plan.goal.name, plan.goal.date) : m.heading(plan.goal.name, plan.goal.date)}${target}`) lines.push('') lines.push( m.meta( @@ -269,7 +601,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/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..5d3dd29 --- /dev/null +++ b/packages/cli/src/plugin.test.ts @@ -0,0 +1,188 @@ +/** + * 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' } }) + // wartości, które przyjmuje parser Codex (0.153) — inna odrzuca cały marketplace przy `codex plugin marketplace add` + expect(['AVAILABLE', 'INSTALLED_BY_DEFAULT', 'NOT_AVAILABLE']).toContain(codex['plugins'][0]['policy']['installation']) + expect(['ON_INSTALL', 'ON_USE']).toContain(codex['plugins'][0]['policy']['authentication']) + 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/cli/src/proposals.ts b/packages/cli/src/proposals.ts index c6733d1..8d6beca 100644 --- a/packages/cli/src/proposals.ts +++ b/packages/cli/src/proposals.ts @@ -1,13 +1,14 @@ 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 { addDays, estimateWorkoutMinutes, mondayOf, validatePlan, weekTotals, withLocale, paceZones, recalibrateWorkout, parseIso, shortenWorkout, type ShortenedWorkout, type AdaptationProposal, type PlannedDay } from 'trainctl-core' import { CONFIG_FILE, loadConfig } from './config.ts' -import { readLog, LOG_FILE } from './logfile.ts' -import { computePlan, dayFingerprint, loadPlan, PLAN_YAML, writePlan, workoutText, type StoredPlan } from './planfile.ts' +import { logFor, readLog, LOG_FILE } from './logfile.ts' +import { budgetWarnings, computePlan, cycleWeeksOf, dayFingerprint, loadPlan, planEnd, scaleToBaseline, settleMixedWeek, PLAN_YAML, writePlan, workoutText, type StoredPlan } from './planfile.ts' import { ui } from './i18n/index.ts' import { readSnapshot } from './sync.ts' -import { isRunningActivity } from './execution.ts' +import { runningKmByDate } 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,12 +47,31 @@ 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) + for (const date of runningKmByDate(readSnapshot(cwd)?.activities ?? []).keys()) dates.add(date) return dates } +/** + * Kilometry zapisane w dniu startu celu (dziennik albo synchronizacja). Sygnał + * dla regeneracji, czy start się odbył — sama obecność wpisu (rozruch, „pominięte") + * tego nie mówi. + */ +export function raceDayKm(cwd: string, plan: StoredPlan): number { + const date = plan.goal.date + const entry = logFor(cwd, date) + // jawne „pominięte" (DNS) wygrywa nad zegarkiem — tak jak w buildExecution + if (entry?.status === 'skipped') return 0 + const logged = entry ? entry.km ?? (entry.status === 'done' ? plan.goal.distanceKm : 0) : 0 + const synced = runningKmByDate(readSnapshot(cwd)?.activities ?? []).get(date) ?? 0 + // Świadomie inaczej niż buildExecution (tam wpis dziennika wygrywa z zegarkiem): + // tu pytanie brzmi „czy start się odbył", a poranny rozruch w dzienniku to inna + // sesja tego dnia niż start pobrany z zegarka — liczy się większa z dwóch wartości. + return Math.max(logged, synced) +} + const describeDay = (day: PlannedDay): string => [workoutText(day), ...(day.strength ? [ui().today.strengthTitle(day.strength.durationMin) + ': ' + day.strength.description] : [])].join(' + ') /** A single explicitly selected session; all other days and profile data survive. */ @@ -65,7 +83,7 @@ export function prepareShortening(cwd: string, date: string, minutes: number): { const plan = loadPlan(cwd) const week = plan.weeks.find(w => w.days.some(d => d.date === date)) const day = week?.days.find(d => d.date === date) - if (!day) throw new Error(ui().common.outsidePlan(date, plan.weeks[0]?.weekStart ?? '', plan.goal.date)) + if (!day) throw new Error(ui().common.outsidePlan(date, plan.weeks[0]?.weekStart ?? '', planEnd(plan))) if (day.pinned) throw new Error(ui().coach.pinned) if (!day.workout) return { adjustment: null } const before = structuredClone(day) @@ -80,7 +98,7 @@ export function prepareShortening(cwd: string, date: string, minutes: number): { plan.timeBudgets = { ...plan.timeBudgets, [date]: budget } // Keep the generation fingerprint: an approved exception must survive adaptation. Object.assign(week!, weekTotals(week!.days)) - plan.peakKmPlanned = Math.max(...plan.weeks.map(w => w.totalKm)) + plan.peakKmPlanned = Math.max(...cycleWeeksOf(plan).map(w => w.totalKm)) plan.changes.push({ at: calendarToday(), action: 'shorten', detail: `${date}: ${before.workout!.distanceKm} → ${day.workout.distanceKm} km; ${budget} min; ${adjustment.status}` }) const proposal = saveProposal(cwd, { schemaVersion: 1, kind: 'shorten', preparedOn: calendarToday(), createdFor: date, baseHash, adjustment, vdotBefore: plan.vdot, plan, @@ -106,30 +124,38 @@ export function prepareProposal(cwd: string, today: string, analysis: Adaptation if (!volume && JSON.stringify(config.athlete.results.map(resultKey).sort()) === JSON.stringify(plan.calibration.results.map(resultKey).sort())) throw new Error(ui().improve.noPatch) const nextConfig = structuredClone(config) - const candidate = withLocale(plan.locale === 'pl' ? 'pl' : 'en', () => { - // Compute calibration metadata separately; never replay a new baseline from August. - const metadata = computePlan(nextConfig, plan.generatedAt, today) - const zones = paceZones(metadata.vdot) - const anchor = plan.weeks.find(w => w.weekStart > today && !w.skeleton.deload && !['taper', 'race'].includes(w.skeleton.phase)) - ?? plan.weeks.find(w => w.days.some(d => d.date > today)) - metadata.weeks = plan.weeks.map(week => { - if (!volume) { + const candidate = withLocale(plan.locale === 'pl' ? 'pl' : 'en', () => computePlan(nextConfig, plan.generatedAt, today, { + // Tygodnie zapisanego planu zamiast świeżych; budżet czasu z profilu stosuje + // potem computePlan (E-2) od tygodnia decyzji, a siła zostaje na swoich dniach. + // Rekalibracja zmienia tylko tempa: w bieżącym tygodniu limit dnia skraca za + // długie dni, całe tygodnie budżet przycina od następnego poniedziałku, a poziom + // bez budżetu tygodnie niosą z zapisanego planu (`uncappedKm`). Ostrzeżenia + // budżetu liczy budgetWarnings na planie po złożeniu, od pierwszego dnia, który + // propozycja może zmienić. + budgetFrom: mondayOf(today), + budgetWarnings: false, + ...(volume ? {} : { weeklyBudgetFrom: addDays(mondayOf(today), 7) }), + beforeTimeBudget: (metadata) => { + // Metadane kalibracji liczy computePlan; nowa baza nie sięga wstecz (tygodnie + // sprzed decyzji zostają). Bieżący cykl jak w zapisanym planie — szczyt + // i ostrzeżenia nie liczą historii poprzedniego. + if (plan.cycleStart) metadata.cycleStart = plan.cycleStart + if (volume) { + // siła to osobny tor — korekta objętości jej nie przestawia + metadata.weeks = scaleToBaseline(plan.weeks, { + baselineKm: volume.suggestedWeeklyKm!, decidedOn: today, config: nextConfig, goal: plan.goal, vdot: metadata.vdot, + reference: plan.weeks, + }) + return + } + const zones = paceZones(metadata.vdot) + metadata.weeks = plan.weeks.map((week) => { const copy = structuredClone(week) for (const day of copy.days) if (day.workout) day.workout = recalibrateWorkout(day.workout, zones, week.skeleton.intensityModel === 'polarized') return copy - } - const skeleton = structuredClone(week.skeleton) - skeleton.targetKm = Math.round(volume.suggestedWeeklyKm! * skeleton.targetKm / Math.max(1, anchor?.skeleton.targetKm ?? skeleton.targetKm)) - const generated = generateMicrocycle({ skeleton, athlete: nextConfig.athlete, goal: plan.goal, zones, testDistanceKm: testDistanceKm(plan.goal) }) - // Strength is an independent track; a volume correction does not reassign it. - 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 - }) - return metadata - }) + }) + }, + })) const candidateDays = new Map(candidate.weeks.flatMap((w) => w.days).map((day) => [day.date, day])) const recorded = recordedDates(cwd) const next = structuredClone(plan) @@ -153,19 +179,22 @@ export function prepareProposal(cwd: string, today: string, analysis: Adaptation } // Preserve the history and phase boundaries; refresh totals of changed weeks. if (changes.some((c) => week.days.some((d) => d.date === c.date))) { - Object.assign(week, weekTotals(week.days)) const skeleton = candidate.weeks.find((w) => w.weekStart === week.weekStart)?.skeleton if (skeleton) week.skeleton = structuredClone(skeleton) + settleMixedWeek(week) } } 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 else delete next.prediction - next.peakKmPlanned = Math.max(...next.weeks.map((w) => w.totalKm)) - next.feasibilityWarnings = candidate.feasibilityWarnings + next.peakKmPlanned = Math.max(...cycleWeeksOf(next).map((w) => w.totalKm)) + // ostrzeżenia budżetu na tym, co propozycja zapisze, i tylko dla dni, które może zmienić + const firstChangeable = [addDays(today, 1), calendarToday()].sort().at(-1)! + next.feasibilityWarnings = [...candidate.feasibilityWarnings, + ...withLocale(plan.locale === 'pl' ? 'pl' : 'en', () => budgetWarnings(next, nextConfig, firstChangeable))] next.changes.push({ at: today, action: 'adapt', detail: analysis.actions.map((a) => a.type).join(', ') }) // Lint remains visible in the preview; broken file invariants never reach disk. const errors = validatePlan(next).filter((issue) => issue.severity === 'error') @@ -174,6 +203,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..f39ae2b --- /dev/null +++ b/packages/cli/src/regenerate.test.ts @@ -0,0 +1,312 @@ +/** + * 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 { estimateWorkoutMinutes, 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('redukcja, którą budżet jeszcze tnie: „bez budżetu" to poziom redukcji, nie pierwotny szczyt', () => { + config.time = { weeklyMinutes: 240 } + initialize() + const reduced = prepareProposal(dir, '2026-09-06', { ...reduction, actions: [{ ...reduction.actions[0]!, suggestedWeeklyKm: 45 }] }) + const warning = reduced.plan.feasibilityWarnings.find((w) => w.includes('time budget caps')) + expect(warning).toBeDefined() + const withoutBudget = Number(warning!.match(/would reach ([\d.]+) km\/week/)![1]) + expect(withoutBudget).toBeGreaterThan(40) + expect(withoutBudget).toBeLessThanOrEqual(45.5) + }) + it('redukcja przy samych limitach dni: świeży plan bez ostrzeżenia, przycięte tygodnie pamiętają poziom redukcji', () => { + config.time = { weekdayMinutes: 60 } + const fresh = initialize() + expect(fresh.feasibilityWarnings.join('\n')).not.toContain('time budget caps') + const reduced = prepareProposal(dir, '2026-09-06', { ...reduction, actions: [{ ...reduction.actions[0]!, suggestedWeeklyKm: 30 }] }) + const future = reduced.plan.weeks.filter((w) => w.weekStart > '2026-09-06' && w.skeleton.uncappedKm !== undefined) + expect(future.length).toBeGreaterThan(0) + for (const week of future) expect(week.skeleton.uncappedKm!).toBeLessThanOrEqual(31) + const warning = reduced.plan.feasibilityWarnings.find((w) => w.includes('time budget caps')) + expect(warning).toBeDefined() + expect(Number(warning!.match(/would reach ([\d.]+) km\/week/)![1])).toBeLessThanOrEqual(30.5) + }) + it('redukcja mieszcząca się w budżecie tygodnia: bez ostrzeżenia o budżecie', () => { + config.time = { weeklyMinutes: 240 } + initialize() + const reduced = prepareProposal(dir, '2026-09-06', { ...reduction, actions: [{ ...reduction.actions[0]!, suggestedWeeklyKm: 30 }] }) + expect(reduced.plan.feasibilityWarnings.join('\n')).not.toContain('time budget caps') + }) + it('rekalibracja przy budżecie tygodnia: przycięte tygodnie znów w budżecie, ostrzeżenie zostaje', () => { + config.time = { weeklyMinutes: 240 } + const fresh = initialize() + expect(fresh.feasibilityWarnings.join('\n')).toContain('time budget caps') + config.athlete.results = [{ date: '2026-03-29', distanceKm: 10, timeSec: 2580, excluded: true }, { date: '2026-08-30', distanceKm: 10, timeSec: 2820 }] + saveConfig() + const recalibrated = prepareProposal(dir, '2026-09-06', { ...reduction, actions: [{ type: 'recalibrate-zones' as const, detail: 'recalibrate', ruleRefs: [] }] }) + const warnings = recalibrated.plan.feasibilityWarnings.join('\n') + expect(warnings).toContain('time budget caps') + expect(warnings).not.toContain('stay over the weekly time budget') + }) + it('szybsza rekalibracja przy budżecie tygodnia: przycięcie sprzed niej nadal widać w ostrzeżeniu', () => { + config.time = { weeklyMinutes: 240 } + initialize() + config.athlete.results = [{ date: '2026-03-29', distanceKm: 10, timeSec: 2580, excluded: true }, { date: '2026-08-30', distanceKm: 10, timeSec: 2450 }] + saveConfig() + const recalibrated = prepareProposal(dir, '2026-09-06', { ...reduction, actions: [{ type: 'recalibrate-zones' as const, detail: 'recalibrate', ruleRefs: [] }] }) + expect(recalibrated.plan.feasibilityWarnings.join('\n')).toContain('time budget caps') + }) + it('rekalibracja w środku tygodnia: bieżący tydzień zgadza się z własną objętością (P-3)', () => { + vi.setSystemTime(new Date('2026-09-10T12:00:00Z')) + config.time = { weeklyMinutes: 240 } + initialize() + config.athlete.results = [{ date: '2026-03-29', distanceKm: 10, timeSec: 2580, excluded: true }, { date: '2026-09-05', distanceKm: 10, timeSec: 3300 }] + saveConfig() + const recalibrated = prepareProposal(dir, '2026-09-10', { ...reduction, actions: [{ type: 'recalibrate-zones' as const, detail: 'recalibrate', ruleRefs: [] }] }) + expect(validatePlan(recalibrated.plan).filter((i) => i.code === 'targetKmMismatch')).toEqual([]) + }) + it('rekalibracja w środku tygodnia przy limitach dni: przyszłe dni bieżącego tygodnia mieszczą się w limicie', () => { + vi.setSystemTime(new Date('2026-09-10T12:00:00Z')) + config.time = { weekdayMinutes: 50, weekendMinutes: 90 } + initialize() + config.athlete.results = [{ date: '2026-03-29', distanceKm: 10, timeSec: 2580, excluded: true }, { date: '2026-09-05', distanceKm: 10, timeSec: 3300 }] + saveConfig() + const recalibrated = prepareProposal(dir, '2026-09-10', { ...reduction, actions: [{ type: 'recalibrate-zones' as const, detail: 'recalibrate', ruleRefs: [] }] }) + const tooLong = recalibrated.plan.feasibilityWarnings.join('\n') + const ahead = recalibrated.plan.weeks.flatMap((w) => w.days).filter((d) => d.date > '2026-09-10' && d.date <= '2026-09-13' && d.workout) + expect(ahead.length).toBeGreaterThan(0) + for (const day of ahead) { + const cap = ['sat', 'sun'].includes(day.weekday) ? 90 : 50 + if (estimateWorkoutMinutes(day.workout!, 15) + (day.strength?.durationMin ?? 0) > cap) expect(tooLong).toContain(day.date) + } + // dni, których propozycja nie zmieni (do dziś włącznie), nie trafiają do ostrzeżeń + expect(tooLong).not.toMatch(/2026-09-0[7-9]|2026-09-10/) + }) + it('rekalibracja po zatwierdzonej bazie: „bez budżetu" to baza, nie pierwotny szczyt', () => { + config.time = { weeklyMinutes: 240 } + initialize() + applyProposal(dir, prepareProposal(dir, '2026-09-06', { ...reduction, actions: [{ ...reduction.actions[0]!, suggestedWeeklyKm: 45 }] }).id) + config.athlete.results = [{ date: '2026-03-29', distanceKm: 10, timeSec: 2580, excluded: true }, { date: '2026-08-30', distanceKm: 10, timeSec: 2700 }] + saveConfig() + const recalibrated = prepareProposal(dir, '2026-09-06', { ...reduction, actions: [{ type: 'recalibrate-zones' as const, detail: 'recalibrate', ruleRefs: [] }] }) + const warning = recalibrated.plan.feasibilityWarnings.find((w) => w.includes('time budget caps')) + expect(warning).toBeDefined() + expect(Number(warning!.match(/would reach ([\d.]+) km\/week/)![1])).toBeLessThanOrEqual(45.5) + }) + it('redukcja w środku tygodnia, którą budżet tnie: tydzień decyzji zgadza się z własną objętością (P-3)', () => { + vi.setSystemTime(new Date('2026-09-10T12:00:00Z')) + config.time = { weeklyMinutes: 240 } + initialize() + const reduced = prepareProposal(dir, '2026-09-10', { ...reduction, actions: [{ ...reduction.actions[0]!, suggestedWeeklyKm: 45 }] }) + expect(validatePlan(reduced.plan).filter((i) => i.code === 'targetKmMismatch' && i.date === '2026-09-07')).toEqual([]) + }) + it('regeneracja po redukcji w środku tygodnia: tydzień decyzji nadal zgadza się z własną objętością (P-3)', () => { + vi.setSystemTime(new Date('2026-09-10T12:00:00Z')) + config.time = { weeklyMinutes: 240 } + initialize() + applyProposal(dir, prepareProposal(dir, '2026-09-10', { ...reduction, actions: [{ ...reduction.actions[0]!, suggestedWeeklyKm: 45 }] }).id) + config.athlete.results.push({ date: '2026-08-30', distanceKm: 5, timeSec: 1250 }) + saveConfig() + expect(cmdPlan(dir).code).toBe(0) + expect(validatePlan(loadPlan(dir)).filter((i) => i.code === 'targetKmMismatch' && i.date === '2026-09-07')).toEqual([]) + }) + it('rekalibracja w sobotę przy ciasnych limitach dni: ostrzeżenie nie wymienia minionych dni', () => { + vi.setSystemTime(new Date('2026-09-12T12:00:00Z')) + config.time = { weekdayMinutes: 30, weekendMinutes: 45 } + initialize() + config.athlete.results = [{ date: '2026-03-29', distanceKm: 10, timeSec: 2580, excluded: true }, { date: '2026-09-06', distanceKm: 10, timeSec: 3300 }] + saveConfig() + const recalibrated = prepareProposal(dir, '2026-09-12', { ...reduction, actions: [{ type: 'recalibrate-zones' as const, detail: 'recalibrate', ruleRefs: [] }] }) + expect(recalibrated.plan.feasibilityWarnings.join(' ')).not.toMatch(/2026-09-(0[7-9]|1[0-2])/) + }) + it('ręczna zmiana w tygodniu przyciętym budżetem: regeneracja jej nie wchłania, lint nadal ją pokazuje (P-3)', () => { + config.time = { weeklyMinutes: 240 } + initialize() + const plan = loadPlan(dir) + const week = plan.weeks.find((w) => w.weekStart > '2026-09-07' && w.skeleton.timeCappedKm !== undefined && w.days.some((d) => d.workout?.kind === 'long'))! + const long = week.days.find((d) => d.workout?.kind === 'long')! + long.workout!.distanceKm += 5 + const segment = long.workout!.segments.find((x) => x.distanceKm !== undefined)! + segment.distanceKm = segment.distanceKm! + 5 + writePlan(dir, plan) + config.athlete.results.push({ date: '2026-08-30', distanceKm: 5, timeSec: 1250 }) + saveConfig() + const r = cmdPlan(dir) + expect(r.code, r.output).toBe(0) + expect(validatePlan(loadPlan(dir)).some((i) => i.code === 'targetKmMismatch' && i.date === week.weekStart)).toBe(true) + }) + it('rekalibracja w ostatnim tygodniu planu: bez ostrzeżenia o „0 km/tydz."', () => { + vi.setSystemTime(new Date('2026-12-09T12:00:00Z')) + config.time = { weekdayMinutes: 30, weekendMinutes: 45 } + initialize() + config.athlete.results = [{ date: '2026-03-29', distanceKm: 10, timeSec: 2580, excluded: true }, { date: '2026-12-06', distanceKm: 10, timeSec: 3300 }] + saveConfig() + const recalibrated = prepareProposal(dir, '2026-12-09', { ...reduction, actions: [{ type: 'recalibrate-zones' as const, detail: 'recalibrate', ruleRefs: [] }] }) + expect(recalibrated.plan.feasibilityWarnings.join('\n')).not.toContain('at 0 km/week') + }) + it('wyraźnie wolniejsza rekalibracja przy budżecie tygodnia: bieżący tydzień ponad budżetem jest zgłoszony', () => { + vi.setSystemTime(new Date('2026-09-08T12:00:00Z')) + config.time = { weeklyMinutes: 240 } + initialize() + config.athlete.results = [{ date: '2026-03-29', distanceKm: 10, timeSec: 2580, excluded: true }, { date: '2026-09-06', distanceKm: 10, timeSec: 3600 }] + saveConfig() + const recalibrated = prepareProposal(dir, '2026-09-08', { ...reduction, actions: [{ type: 'recalibrate-zones' as const, detail: 'recalibrate', ruleRefs: [] }] }) + expect(recalibrated.plan.feasibilityWarnings.join('\n')).toMatch(/stay over the weekly time budget: [^\n]*2026-09-07/) + }) + it('baza zatwierdzona przy budżecie bez siły: tygodnie sprzed decyzji nie dostają fałszywego „ponad budżet"', () => { + config.time = { weeklyMinutes: 240 } + initialize() + applyProposal(dir, prepareProposal(dir, '2026-09-06', { ...reduction, actions: [{ ...reduction.actions[0]!, suggestedWeeklyKm: 45 }] }).id) + config.athlete.results.push({ date: '2026-08-30', distanceKm: 5, timeSec: 1250 }) + saveConfig() + expect(cmdPlan(dir).code).toBe(0) + expect(loadPlan(dir).feasibilityWarnings.join('\n')).not.toMatch(/stay over the weekly time budget: 2026-08-/) + }) + it('baza zatwierdzona przy budżecie dni: regeneracja nadal mówi, że budżet tnie objętość', () => { + config.time = { weekdayMinutes: 50, weekendMinutes: 90 } + initialize() + applyProposal(dir, prepareProposal(dir, '2026-09-06', { ...reduction, actions: [{ ...reduction.actions[0]!, suggestedWeeklyKm: 45 }] }).id) + config.athlete.results.push({ date: '2026-08-30', distanceKm: 5, timeSec: 1250 }) + saveConfig() + expect(cmdPlan(dir).code).toBe(0) + expect(loadPlan(dir).feasibilityWarnings.join('\n')).toContain('time budget caps') + }) + 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..62650d6 --- /dev/null +++ b/packages/cli/src/regenerate.ts @@ -0,0 +1,249 @@ +/** + * 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; dzień jej + * zatwierdzenia zostaje, jak w propozycji, która zmienia dopiero dni po nim. + */ +import { + addDays, + estimateWorkoutMinutes, + mondayOf, + weekTotals, + type Microcycle, + type PlannedDay, +} from 'trainctl-core' +import type { TrainctlConfig } from './config.ts' +import { budgetWarnings, computePlan, dayFingerprint, scaleToBaseline, settleMixedWeek, type StoredPlan } from './planfile.ts' +import { clockToday } from './clock.ts' + +export type ProtectionReason = 'past' | 'recorded' | 'pinned' | 'baseline' | '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 + +/** + * Część dystansu startu zapisana w dniu startu, od której start uznajemy za + * odbyty (wartość inżynierska): rozruch przed przełożonym startem to kilka km, + * start — prawie cały dystans, nawet z krótszym pomiarem zegarka. + */ +const RACE_DONE_SHARE = 0.8 + +export function rebuildPlan( + existing: StoredPlan, + config: TrainctlConfig, + /** `raceDayKm` — leniwie: potrzebne tylko w dniu startu, a czyta dziennik i synchronizację. */ + opts: { today: string; recorded: Set; raceDayKm?: () => number }, +): Regeneration { + const now = clockToday() + const today = opts.today + // Dzień startu jest „za nami" dopiero, gdy zapisano sam start (prawie cały + // dystans) i cel się zmienił: rozruch przed przełożonym startem to nadal ten + // sam cykl, a niezmieniony cel w dniu startu — zwykła regeneracja. + const goalUnchanged = existing.goal.date === config.goal.date && sameDistance(existing.goal.distanceKm, config.goal.distanceKm) + const raceDone = existing.goal.kind !== 'base' && existing.goal.date === now && !goalUnchanged && + (opts.raceDayKm?.() ?? 0) >= RACE_DONE_SHARE * existing.goal.distanceKm + const raceBehind = existing.goal.date < now || raceDone + 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) + // Nowy cel po starcie: pozostałe tygodnie bloku przejściowego (R-8) zostają, + // nowy cykl zaczyna się po nich — powrót do biegania nie przepada przez nowy plan. + const lastTransition = existing.weeks.filter((w) => w.skeleton.phase === 'transition').at(-1) + const afterTransition = raceBehind && lastTransition && lastTransition.weekStart >= mondayOf(today) + ? addDays(lastTransition.weekStart, 7) + : undefined + const macroStart = mode === 'same-cycle' ? existing.generatedAt : afterTransition ?? today + const loadState = keepLoad + ? { ...ls!, effectiveFrom: mode === 'same-cycle' ? ls!.effectiveFrom : today, profileWeeklyKm: config.athlete.recentWeeklyKm } + : undefined + const existingDays = new Map(existing.weeks.flatMap((w) => w.days).map((d) => [d.date, d])) + // skalowanie do zatwierdzonej bazy idzie PRZED budżetem czasu, który computePlan + // stosuje raz, tymi samymi strefami co przy pierwszym planie (E-2). Plan bez bazy + // (pełny, z budżetem) daje tygodnie sprzed decyzji — gotowe, jak w pierwotnym + // planie — i rozstawienie siły z aktualnymi fazami (przesunięty start) oraz + // `strength.days`. Propozycja przepisuje je z zapisanego planu, który ma właśnie + // to, więc regeneracja tuż po `adapt --apply` odtwarza zatwierdzone dni. + // Bez budżetu czasu tygodnie przed hakiem są tym samym planem (bez drugiego przebiegu). + const unscaled = loadState && config.time ? computePlan(config, macroStart, today) : undefined + // ostrzeżenia budżetu liczymy niżej, na planie złożonym z dni chronionych + const fresh = computePlan(config, macroStart, today, loadState + ? { + budgetWarnings: false, + budgetFrom: mondayOf(loadState.effectiveFrom), + beforeTimeBudget: (plan) => { + plan.weeks = scaleToBaseline(plan.weeks, { + baselineKm: loadState.baselineWeeklyKm, decidedOn: loadState.effectiveFrom, config, goal: plan.goal, vdot: plan.vdot, + reference: unscaled?.weeks ?? plan.weeks, + }) + }, + } + : { budgetWarnings: false }) + + 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' + // dzień zatwierdzenia bazy: propozycja zmienia dopiero dni PO nim, więc + // regeneracja w tym samym dniu też go nie rusza (inaczej „aktualny" plan by nie był) + if (mode === 'same-cycle' && keepLoad && before.date <= ls!.effectiveFrom) return 'baseline' + if (before.pinned) return 'pinned' + if (before.timeAdjustment && before.timeAdjustment.origin !== 'profile') return 'approved' + // Bez mapy odcisków (plan sprzed 0.2.0) edycji nie da się odróżnić od generacji. + // Skrócenie z budżetu w profilu to generacja, nie edycja — odcisk go obejmuje. + 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 keptFor = new Map() + 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) + keptFor.set(fd.date, reason) + 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 } + // Tydzień zmieszany przez czas (przeszłe, zalogowane, dzień decyzji) domykamy jak + // w propozycji; z ręcznymi zmianami (edycja, przypięcie, zatwierdzone skrócenie, + // budżet dnia) — nie, żeby lint nadal pokazał, że dni nie sumują się do tygodnia. + const userKept = days.some((d) => ['edited', 'pinned', 'approved', 'budget'].includes(keptFor.get(d.date) ?? '')) + if (userKept) Object.assign(week, weekTotals(days)) + else settleMixedWeek(week) + 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 + // ostrzeżenia budżetu na tym, co zapiszemy (bieżący cykl), i tylko dla dni, które + // da się jeszcze zmienić + plan.feasibilityWarnings = [...fresh.feasibilityWarnings, ...budgetWarnings(plan, config, now)] + 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) && + // notatki siły tygodni to też treść planu (PLAN.md) — plan, który je zgubił, się naprawia + JSON.stringify(weeks.map((w) => w.strengthNotes ?? null)) === JSON.stringify(existing.weeks.map((w) => w.strengthNotes ?? 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/regressions.test.ts b/packages/cli/src/regressions.test.ts index 40f7704..bc7b443 100644 --- a/packages/cli/src/regressions.test.ts +++ b/packages/cli/src/regressions.test.ts @@ -105,7 +105,7 @@ describe('plan.yaml jest czytelny dla człowieka (plan-as-code)', () => { it('każda sesja siłowa zapisana w całości, nie jako referencja', () => { setup() const yaml = readFileSync(join(dir, 'plan', 'plan.yaml'), 'utf-8') - const full = (yaml.match(/kind: heavy/g) ?? []).length + const full = (yaml.match(/kind: (heavy|intro|maintenance)/g) ?? []).length expect(full).toBe(strengthDays().length) }) }) diff --git a/packages/cli/src/rules-explain.ts b/packages/cli/src/rules-explain.ts index a5b4e47..af7aeb3 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 => @@ -15,7 +26,7 @@ export const kindPurpose = (kind: WorkoutKind): string => ui().kindPurpose[kind] /** Labels describe provenance, never numerical certainty or evidence grades. */ export function ruleEvidence(id: string): 'research' | 'corpus' | 'engineering' | 'unclassified' { - if (['E-1', 'T-9', 'T-12', 'W-13', 'R-5', 'P-3'].includes(id)) return 'engineering' - if (['T-10', 'T-11', 'W-12', 'S-9a'].includes(id)) return 'corpus' + if (['E-1', 'T-9', 'T-12', 'W-13', 'R-5', 'P-3', 'F-18', 'Z-10', 'E-2', 'R-9', 'R-10', 'P-11'].includes(id)) return 'engineering' + if (['T-10', 'T-11', 'W-12', 'S-9a', 'R-8'].includes(id)) return 'corpus' return ruleExplain(id) ? 'research' : 'unclassified' } diff --git a/packages/cli/src/status.ts b/packages/cli/src/status.ts new file mode 100644 index 0000000..2fe1d49 --- /dev/null +++ b/packages/cli/src/status.ts @@ -0,0 +1,164 @@ +/** + * `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, readExistingPlan, unusablePlanMessage, PLAN_DIR, type StoredPlan } from './planfile.ts' +import { listProposals } from './proposals.ts' +import { API_KEY_ENV, apiKeySource, readSnapshot, SYNC_FILE } from './sync.ts' +import { b, renderPlain, type Block } from './ui/blocks.ts' +import { clockToday } from './clock.ts' +import { packageVersion } from './version.ts' + +/** Ścieżka w podpowiedzi komendy — cudzysłów tylko, gdy jest potrzebny. */ +const shellArg = (path: string) => (/^[\w./-]+$/.test(path) ? path : JSON.stringify(path)) + +export interface StatusResult { + output: string + code: number + blocks: Block[] + data: Record +} + +export function cmdStatus(cwd: string): StatusResult { + try { + return statusImpl(cwd) + } catch (e) { + // status jest diagnostyką — połamany log.jsonl czy zła data symulacji to + // wiadomość, nie stack trace + const message = e instanceof Error ? e.message : String(e) + const blocks: Block[] = [b.error(message)] + return { output: renderPlain(blocks), code: 1, blocks, data: { error: message } } + } +} + +function statusImpl(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 + const found = readExistingPlan(cwd) + const plan: StoredPlan | undefined = found.status === 'ok' ? found.plan : undefined + const planError = found.status === 'unreadable' ? unusablePlanMessage(found) : undefined + 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 ?? t.noPlan)) + // plik, którego nie da się użyć, czeka na decyzję (naprawa, aktualizacja albo + // --fresh), którą opisuje komunikat — samo `trainctl plan` by odmówiło + if (hasConfig && !configErrors && !planError) next.push('trainctl plan') + } + + // dane: klucz, synchronizacja, dziennik + const env = inspectEnvFile(cwd, API_KEY_ENV) + const source = apiKeySource(cwd, env) + const keySource = source === 'environment' ? t.keyFromEnv : source + 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 TRACKED = [CONFIG_FILE, PLAN_DIR, LOG_FILE, 'AGENTS.md'] + const dirty = uncommitted(cwd, TRACKED) + blocks.push(b.section(t.git), b.text(dirty === undefined ? t.noGit : dirty.length ? t.dirty(dirty.join(', ')) : t.clean)) + // dokładnie zmienione ścieżki (względem katalogu treningowego); `git add` ze + // ścieżką zapisuje też usunięcie pliku, a ignorowanych porcelain nie zwraca + if (dirty?.length) next.push(`git add -- ${dirty.map(shellArg).join(' ')} && 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/sync.test.ts b/packages/cli/src/sync.test.ts index 9646178..cf38dc0 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 raceWeek = plan.weeks.find((w) => w.skeleton.raceDate)! 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..2033440 100644 --- a/packages/cli/src/sync.ts +++ b/packages/cli/src/sync.ts @@ -4,9 +4,12 @@ * 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 { cameFromEnvFile } from './env-file.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' @@ -23,8 +26,10 @@ export interface SyncSnapshot { wellness: SyncedWellness[] } +export const API_KEY_ENV = 'TRAINCTL_INTERVALS_API_KEY' + export function readApiKey(cwd: string): string { - const fromEnv = process.env['TRAINCTL_INTERVALS_API_KEY']?.trim() + const fromEnv = process.env[API_KEY_ENV]?.trim() if (fromEnv) return fromEnv const path = join(cwd, SECRET_FILE) if (existsSync(path)) { @@ -34,6 +39,16 @@ export function readApiKey(cwd: string): string { throw new Error(ui().sync.missingKey(SECRET_FILE)) } +/** + * Skąd przyjdzie klucz — ta sama kolejność co `readApiKey` (zmienna środowiskowa, + * także z `.env`, potem niepusty `.trainctl-secret`). Wartości nigdy nie zwraca. + */ +export function apiKeySource(cwd: string, inspected?: { hasKey: boolean }): 'environment' | '.env' | '.trainctl-secret' | undefined { + if (process.env[API_KEY_ENV]?.trim()) return cameFromEnvFile(cwd, API_KEY_ENV, inspected) ? '.env' : 'environment' + const path = join(cwd, SECRET_FILE) + return existsSync(path) && readFileSync(path, 'utf-8').trim() ? '.trainctl-secret' : undefined +} + /** Czy klucz jest osiągalny — bez rzucania (kreator pyta o pobranie historii tylko wtedy). */ export function hasApiKey(cwd: string): boolean { try { @@ -49,13 +64,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/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/package.json b/packages/core/package.json index 83ee229..38eea13 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "trainctl-core", - "version": "0.3.0", + "version": "0.4.0", "description": "Deterministic running-plan engine: pace zones from race results, macro/microcycles, week re-solver, plan lint", "keywords": [ "running", diff --git a/packages/core/src/domain/types.ts b/packages/core/src/domain/types.ts index 5da07f1..7636fcf 100644 --- a/packages/core/src/domain/types.ts +++ b/packages/core/src/domain/types.ts @@ -27,6 +27,11 @@ export interface RaceResult { export type RacePriority = 'A' | 'B' | 'C' export interface RaceGoal { + /** + * 'base' = plan bez zawodów do daty `date` (P-11): bez taperu, bez tygodnia + * startowego i bez predykcji; `distanceKm` wynosi wtedy 0. + */ + kind?: 'race' | 'base' date: string distanceKm: number name: string @@ -64,7 +69,8 @@ export interface AthleteProfile { /** Rozkład intensywności planu (FOUNDATIONS I-1/I-2). */ export type IntensityModel = 'pyramidal' | 'polarized' -export type MacroPhase = 'base' | 'build' | 'peak' | 'taper' | 'race' +/** 'transition' = blok po starcie (R-8…R-10): powrót do biegania, zanim przyjdzie następny cel. */ +export type MacroPhase = 'base' | 'build' | 'peak' | 'taper' | 'race' | 'transition' /** * Szkielet tygodnia z planera makrocyklu — wejście dla generatora mikrocykli. @@ -90,6 +96,20 @@ export interface WeekSkeleton { tuneUp?: TuneUpRace /** Sprawdzian all-out w tym tygodniu: fallback kalibracji przy pustym kalendarzu startów (W-13). */ testPlanned?: boolean + /** Najwcześniejszy dzień biegu w tygodniu — po starcie (R-1: 48 h ciszy po maratonie). */ + earliestRun?: string + /** + * Objętość po budżecie czasu z profilu (E-2). `targetKm` zostaje zamiarem + * makrocyklu — od niego liczy się skalowanie bazy (adapt, regeneracja), a lint + * porównuje sumy dni z tym, co budżet faktycznie zostawił. + */ + timeCappedKm?: number + /** + * Objętość tygodnia przed budżetem czasu, zapisana przy pierwszym przycięciu. + * Ostrzeżenie „budżet tnie objętość" mówi z niej, ile plan miałby bez budżetu — + * także przy rekalibracji, która dostaje tygodnie już przycięte. + */ + uncappedKm?: number flags: string[] ruleRefs: string[] } @@ -155,7 +175,8 @@ export interface PlannedWorkout { * na zegarek jako trening biegowy. */ export interface StrengthSession { - kind: 'heavy' + /** intro = wejście w blok (F-18, inż.), heavy = ładowanie (F-4), maintenance = szczyt (F-12/F-14). */ + kind: 'heavy' | 'intro' | 'maintenance' description: string durationMin: number ruleRefs: string[] @@ -163,7 +184,7 @@ export interface StrengthSession { export interface PlannedDay { /** Explicitly approved time adjustment; original goal remains visible in why. */ - timeAdjustment?: { originalKind: WorkoutKind; originalDistanceKm: number; budgetMinutes: number; status: 'shortened' | 'easy-alternative' } + timeAdjustment?: { originalKind: WorkoutKind; originalDistanceKm: number; budgetMinutes: number; status: 'shortened' | 'easy-alternative'; /** 'profile' = wynik budżetu czasu z trainctl.yaml (E-2), nie zatwierdzony wyjątek. */ origin?: 'profile' } date: string weekday: Weekday /** User decision: preserve this day during automatic proposals. */ diff --git a/packages/core/src/engine/macrocycle.test.ts b/packages/core/src/engine/macrocycle.test.ts index ad59d0d..42f93fd 100644 --- a/packages/core/src/engine/macrocycle.test.ts +++ b/packages/core/src/engine/macrocycle.test.ts @@ -34,7 +34,9 @@ describe('taperWeeksFor / recommendedPeakKm', () => { }) describe('planMacrocycle — maraton, 17 tygodni', () => { - const plan = planMacrocycle({ today: '2026-08-05', goal: marathon, athlete }) + const full = planMacrocycle({ today: '2026-08-05', goal: marathon, athlete }) + // cykl do startu; blok po starcie (R-8) ma własne testy niżej + const plan = { ...full, weeks: full.weeks.filter((w) => w.phase !== 'transition') } it('liczba i wyrównanie tygodni (poniedziałki)', () => { expect(plan.weeks).toHaveLength(17) @@ -120,12 +122,12 @@ describe('planMacrocycle — przypadki brzegowe', () => { goal: { ...marathon, date: '2026-08-23' }, // 3 tygodnie athlete, }) - expect(compressed.weeks).toHaveLength(3) + expect(compressed.weeks.filter((w) => w.phase !== 'transition')).toHaveLength(3) // treść ostrzeżenia zależy od języka — sprawdzamy przez katalog, nie przez literał expect( compressed.feasibilityWarnings.some((w) => w === messages().macro.compressedPlan(3)), ).toBe(true) - expect(compressed.weeks.at(-1)!.phase).toBe('race') + expect(compressed.weeks.find((w) => w.raceDate)!.phase).toBe('race') }) it('wytrenowany powyżej rekomendacji nie dostaje cięcia objętości', () => { @@ -153,3 +155,57 @@ 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')) + }) +}) + +describe('blok po starcie (R-8, R-10) i plan bez startu (P-11)', () => { + const plan = planMacrocycle({ today: '2026-08-05', goal: marathon, athlete }) + const raceIdx = plan.weeks.findIndex((w) => w.raceDate) + const transition = plan.weeks.slice(raceIdx + 1) + const before = plan.weeks.slice(raceIdx - 4, raceIdx) + const base = before.reduce((s, w) => s + w.targetKm, 0) / before.length + + it('po maratonie dwa tygodnie przejściowe: ~50%, potem ~100% średniej 4 tygodni przed tygodniem startu', () => { + expect(transition.map((w) => w.phase)).toEqual(['transition', 'transition']) + expect(transition[0]!.targetKm).toBe(Math.round(base * 0.5)) + expect(transition[1]!.targetKm).toBe(Math.round(base)) + expect(transition[0]!.weekStart).toBe('2026-11-30') + }) + it('pierwszy tydzień bez akcentu, pierwszy bieg 3. dnia po maratonie (R-1); drugi z jednym akcentem', () => { + expect(transition[0]).toMatchObject({ qualitySessions: 0, earliestRun: '2026-12-02', ruleRefs: ['R-1', 'R-2', 'R-8'] }) + expect(transition[1]).toMatchObject({ qualitySessions: 1 }) + expect(transition[1]!.earliestRun).toBeUndefined() + }) + it('po 10 km jeden tydzień ~70% (R-10), pierwszy bieg nazajutrz', () => { + const tenK = planMacrocycle({ today: '2026-08-05', goal: { ...marathon, distanceKm: 10 }, athlete }) + const after = tenK.weeks.filter((w) => w.phase === 'transition') + expect(after).toHaveLength(1) + expect(after[0]!.ruleRefs).toEqual(['R-10']) + expect(after[0]!.earliestRun).toBeUndefined() // start w niedzielę, poniedziałek to już dzień po + }) + it('plan bazowy: same tygodnie bazy z odciążeniem, bez taperu, startu i bloku po starcie', () => { + const basePlan = planMacrocycle({ today: '2026-08-05', goal: { kind: 'base', name: 'Base', date: '2026-10-25', distanceKm: 0, priority: 'A' }, athlete }) + expect(new Set(basePlan.weeks.map((w) => w.phase))).toEqual(new Set(['base'])) + expect(basePlan.weeks.some((w) => w.raceDate)).toBe(false) + expect(basePlan.weeks.some((w) => w.deload)).toBe(true) + expect(basePlan.weeks.every((w) => w.ruleRefs.includes('P-11'))).toBe(true) + expect(basePlan.peakKmRecommended).toBe(0) + expect(Math.max(...basePlan.weeks.map((w) => w.targetKm))).toBeLessThanOrEqual(athlete.peakWeeklyKm!) + }) +}) diff --git a/packages/core/src/engine/macrocycle.ts b/packages/core/src/engine/macrocycle.ts index acfbe06..8c338b3 100644 --- a/packages/core/src/engine/macrocycle.ts +++ b/packages/core/src/engine/macrocycle.ts @@ -33,6 +33,7 @@ const TAPER_MULTIPLIERS: Record = { } export function taperWeeksFor(goal: RaceGoal): { weeks: number; flags: string[] } { + if (goal.kind === 'base') return { weeks: 0, flags: [] } // P-11: plan bez zawodów nie ma taperu if (goal.distanceKm > 42.5) return { weeks: 3, flags: [messages().macro.ultraTaperExtrapolated] } if (goal.distanceKm >= 42.0) return { weeks: 3, flags: [] } // maraton: 14–21 dni if (goal.distanceKm >= 20.9) return { weeks: 2, flags: [] } // HM: 10–14 dni @@ -62,6 +63,7 @@ export function testDistanceKm(goal: RaceGoal): number { /** P-7/P-8: rekomendowana objętość szczytowa dla dystansu docelowego. */ export function recommendedPeakKm(goal: RaceGoal): number { + if (goal.kind === 'base') return 0 // bez dystansu docelowego nie ma progu P-7/P-8 if (goal.distanceKm > 42.5) return 70 // inż. — brak źródła dla ultra (T-8) if (goal.distanceKm >= 42.0) return 65 // P-8: >65 km/tydz. → −14 min if (goal.distanceKm >= 20.9) return 42 // P-7: >32 km/tydz. + długi >21 km; inż. margines @@ -74,23 +76,76 @@ 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) +/** + * R-8 (korpus, n=3: 2 starty maratońskie i dłuższe, 1 półmaraton): po starcie + * ≥HM trener rozpisywał ~50% objętości sprzed startu w pierwszym tygodniu + * (2–3 sesje, pierwszy akcent 7–8 dni po starcie) i wracał do ~100% w drugim. + * R-10 (inż., bez danych w korpusie): po krótszym celu jeden tydzień ~70%. + */ +const TRANSITION_FACTORS_LONG = [0.5, 1.0] +const TRANSITION_FACTORS_SHORT = [0.7] +/** R-1: 48 h ciszy po maratonie → pierwszy bieg 3. dnia; po HM 2. dnia, po krótszym nazajutrz (inż.). */ +const firstRunOffset = (km: number) => (km >= 42 ? 3 : km >= 20.9 ? 2 : 1) +/** + * P-11 (inż.): plan bez zawodów rośnie do udokumentowanego szczytu + * (`peakWeeklyKm`) albo +15% bieżącej objętości i tam się wypłaszcza. + */ +const BASE_GROWTH = 1.15 + +/** Tygodnie po starcie celu A — makrocykl nie kończy się w dniu zawodów. */ +function transitionWeeks(goal: RaceGoal, weeks: WeekSkeleton[]): WeekSkeleton[] { + const raceWeek = weeks.at(-1) + if (!raceWeek) return [] + const before = weeks.slice(-5, -1) + const base = before.length ? before.reduce((s, w) => s + w.targetKm, 0) / before.length : raceWeek.targetKm + const long = goal.distanceKm >= 20.9 + const factors = long ? TRANSITION_FACTORS_LONG : TRANSITION_FACTORS_SHORT + const earliestRun = addDays(goal.date, firstRunOffset(goal.distanceKm)) + return factors.map((factor, j): WeekSkeleton => { + const weekStart = addDays(raceWeek.weekStart, 7 * (j + 1)) + return { + weekStart, + index: raceWeek.index + 1 + j, + phase: 'transition', + intensityModel: 'pyramidal', + targetKm: Math.round(base * factor), + deload: false, + keepIntensity: false, + keepFrequency: false, + // pierwszy tydzień wyłącznie spokojnie; akcent wraca w drugim (R-8) + qualitySessions: j === 0 ? 0 : 1, + ...(j === 0 && earliestRun > weekStart ? { earliestRun } : {}), + flags: [messages().macro.transitionWeek(j + 1, factors.length)], + ruleRefs: long ? (j === 0 ? ['R-1', 'R-2', 'R-8'] : ['R-8', 'R-9']) : ['R-10'], + } + }) +} + +/** + * 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 { const { today, goal, athlete } = input const firstWeek = mondayOf(today) const raceWeek = mondayOf(goal.date) + const baseOnly = goal.kind === 'base' const totalWeeks = Math.floor(diffDays(firstWeek, raceWeek) / 7) + 1 - if (totalWeeks < 1) throw new Error(messages().macro.raceDateInPast) + if (totalWeeks < 1) throw new Error(baseOnly ? messages().macro.baseEndInPast : messages().macro.raceDateInPast) const feasibilityWarnings: string[] = [] const taper = taperWeeksFor(goal) - const taperWeeks = Math.min(taper.weeks, Math.max(1, totalWeeks - 1)) + const taperWeeks = baseOnly ? 0 : Math.min(taper.weeks, Math.max(1, totalWeeks - 1)) const loadWeeks = totalWeeks - taperWeeks - if (totalWeeks < 6) { + if (totalWeeks < 6 && !baseOnly) { feasibilityWarnings.push( messages().macro.compressedPlan(totalWeeks), ) @@ -104,9 +159,11 @@ export function planMacrocycle(input: MacrocycleInput): MacrocyclePlan { const reachable = start * Math.pow(RAMP_PER_LOAD_WEEK, Math.max(0, loadOnly - 1)) // P-7/P-8 to podłoga dla niedotrenowanych, nie sufit: atlecie z bazą powyżej // rekomendacji utrzymujemy (lekko rozwijamy) jego wolumen zamiast go ciąć. - const targetPeak = Math.max(recommended, Math.min(start * 1.15, cap)) + const targetPeak = baseOnly + ? Math.min(athlete.peakWeeklyKm ?? start * BASE_GROWTH, cap) + : Math.max(recommended, Math.min(start * 1.15, cap)) const peakPlanned = Math.round(Math.min(targetPeak, cap, reachable)) - if (peakPlanned < recommended) { + if (!baseOnly && peakPlanned < recommended) { feasibilityWarnings.push( messages().macro.peakBelowRecommended(peakPlanned, recommended, goal.distanceKm), ) @@ -136,19 +193,22 @@ 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 if (inTaper) { phase = i === totalWeeks - 1 ? 'race' : 'taper' intensityModel = 'polarized' // I-2 + T-1: intensywność zostaje - } else if (i < baseWeeks) { + } else if (baseOnly || i < baseWeeks) { phase = 'base' intensityModel = 'pyramidal' } else if (i < baseWeeks + buildWeeks) { @@ -240,5 +300,9 @@ export function planMacrocycle(input: MacrocycleInput): MacrocyclePlan { }) } - return { goal, weeks, peakKmPlanned: peakPlanned, peakKmRecommended: recommended, feasibilityWarnings } + if (baseOnly) { + for (const w of weeks) w.ruleRefs.push('P-11') + return { goal, weeks, peakKmPlanned: peakPlanned, peakKmRecommended: recommended, feasibilityWarnings } + } + return { goal, weeks: [...weeks, ...transitionWeeks(goal, weeks)], peakKmPlanned: peakPlanned, peakKmRecommended: recommended, feasibilityWarnings } } diff --git a/packages/core/src/engine/microcycle.ts b/packages/core/src/engine/microcycle.ts index 3c057eb..785e8fb 100644 --- a/packages/core/src/engine/microcycle.ts +++ b/packages/core/src/engine/microcycle.ts @@ -307,8 +307,9 @@ export function generateMicrocycle(input: MicrocycleInput): Microcycle { const style = athlete.longRunDay ? { ...defaults, longRunDayPreference: [athlete.longRunDay, ...defaults.longRunDayPreference.filter(d => d !== athlete.longRunDay)] } : defaults - const available = WEEKDAY_ORDER.filter((wd) => athlete.daysAvailable.includes(wd)) const dateOf = (wd: Weekday) => addDays(skeleton.weekStart, WEEKDAY_ORDER.indexOf(wd)) + // po starcie: dni przed najwcześniejszym biegiem wypadają z puli (R-1) + const available = WEEKDAY_ORDER.filter((wd) => athlete.daysAvailable.includes(wd) && (!skeleton.earliestRun || dateOf(wd) >= skeleton.earliestRun)) const plan = new Map() @@ -335,6 +336,15 @@ export function generateMicrocycle(input: MicrocycleInput): Microcycle { } } +/** + * Objętość tygodnia, którą biegacz faktycznie ma: po budżecie czasu z profilu + * (`timeCappedKm`, E-2), bez budżetu — zamiar makrocyklu (`targetKm`). Co pokazuje + * albo skaluje „bieżącą objętość", czyta ją stąd; samo `targetKm` jest wejściem + * skalowania bazy, nie tym, co rozpisano na dni. + */ +export const plannedWeekKm = (skeleton: Pick): number => + skeleton.timeCappedKm ?? skeleton.targetKm + /** * Sumy tygodnia liczone z dni — jedno źródło dla generatora, walidatora * (`trainctl check`) i `reschedule --apply`, który po przestawieniu tygodnia @@ -396,6 +406,8 @@ function planNormalWeek( const target = skeleton.targetKm const polarized = skeleton.intensityModel === 'polarized' const inTaper = skeleton.phase === 'taper' + // blok po starcie: bez podbiegów, a w pierwszym tygodniu także bez długiego (R-8) + const recovering = skeleton.phase === 'transition' const workoutsCount = Math.min( available.length, skeleton.sessionCount ?? Math.max(style.minWorkoutsPerWeek, Math.ceil(target / style.typicalKmPerSession)), @@ -421,7 +433,7 @@ function planNormalWeek( // sloty — dzień startu i dzień przed nim wypadają z puli const free = available.filter((wd) => wd !== peakWd && wd !== dayBeforePeak) // T-11: długie wybieganie ZOSTAJE po starcie (w korpusie: sobota start → niedziela long) - const longWd = inTaper + const longWd = inTaper || (recovering && skeleton.qualitySessions === 0) ? undefined : (style.longRunDayPreference.find((wd) => free.includes(wd)) ?? free.at(-1)) const qualityWds: Weekday[] = [] @@ -433,7 +445,7 @@ function planNormalWeek( ) if (okGap) qualityWds.push(wd) } - let hillsWd = inTaper + let hillsWd = inTaper || recovering ? undefined : style.hillsDayPreference.find( (wd) => free.includes(wd) && wd !== longWd && !qualityWds.includes(wd), diff --git a/packages/core/src/engine/strength.ts b/packages/core/src/engine/strength.ts index 293c96d..ce92f0f 100644 --- a/packages/core/src/engine/strength.ts +++ b/packages/core/src/engine/strength.ts @@ -17,6 +17,10 @@ import { addDays, diffDays } from '../util/dates.ts' /** F-1/F-12: 2 sesje/tydz. w ładowaniu. */ const SESSIONS_PER_WEEK = 2 +/** F-12: 0–1×/tydz. w okresie startowym; F-14: jedna sesja utrzymuje przyrost. */ +const SESSIONS_PEAK = 1 +/** F-18 (inż.): dwa pierwsze tygodnie bloku to wejście w ruch, zanim przyjdzie ≥80% 1RM. */ +const INTRO_WEEKS = 2 /** Tydzień odciążeniowy: 1 sesja — spójnie z duchem P-2 (wartość inż.). */ const SESSIONS_DELOAD = 1 /** Odstęp między sesjami siły: deficyt siły utrzymuje się do 48 h (S-5/de Carvalho). */ @@ -33,7 +37,13 @@ const QUALITY_KINDS = new Set(['quality_intervals', 'quality_continuous', 'test' * współdzielona referencja zamieniłaby 22 z 23 sesji w aliasy `*a2`, a edycja * jednego dnia zmieniłaby wszystkie. */ -export function strengthSession(): StrengthSession { +export function strengthSession(variant: StrengthSession['kind'] = 'heavy'): StrengthSession { + if (variant === 'intro') { + return { kind: 'intro', durationMin: 35, ruleRefs: ['F-1', 'F-3', 'F-18'], description: messages().strength.sessionIntro() } + } + if (variant === 'maintenance') { + return { kind: 'maintenance', durationMin: 25, ruleRefs: ['F-12', 'F-14', 'F-4'], description: messages().strength.sessionMaintenance() } + } return { kind: 'heavy', durationMin: 35, @@ -42,6 +52,12 @@ export function strengthSession(): StrengthSession { } } +/** Wariant sesji dla tygodnia: wejście w blok, ładowanie albo podtrzymanie w szczycie. */ +export function strengthVariant(phase: MacroPhase, blockWeek: number): StrengthSession['kind'] { + if (phase === 'peak') return 'maintenance' + return blockWeek < INTRO_WEEKS ? 'intro' : 'heavy' +} + export interface StrengthWeekInput { week: Microcycle phase: MacroPhase @@ -54,6 +70,8 @@ export interface StrengthWeekInput { * niedziela→poniedziałek. */ lastSessionDate?: string + /** Który to tydzień bloku siły (0 = pierwszy) — wybiera wariant sesji. */ + blockWeek?: number } export interface StrengthAssignment { @@ -84,8 +102,16 @@ export function planStrengthWeek(input: StrengthWeekInput): StrengthAssignment { notes.push(messages().strength.taperNote) return { byDate: new Map(), notes } } + // R-9 (inż.): po starcie siła wraca dopiero w drugim tygodniu bloku, jedną sesją wejścia + const firstTransitionWeek = phase === 'transition' && week.skeleton.qualitySessions === 0 + if (firstTransitionWeek) { + notes.push(messages().strength.transitionNote) + return { byDate: new Map(), notes } + } - const target = deload ? SESSIONS_DELOAD : SESSIONS_PER_WEEK + const target = phase === 'peak' || phase === 'transition' ? SESSIONS_PEAK : deload ? SESSIONS_DELOAD : SESSIONS_PER_WEEK + const variant = phase === 'transition' ? 'intro' : strengthVariant(phase, input.blockWeek ?? INTRO_WEEKS) + if (phase === 'peak') notes.push(messages().strength.peakNote) const kindOf = (d: PlannedDay) => d.workout?.kind const blocked = new Set() @@ -123,7 +149,7 @@ export function planStrengthWeek(input: StrengthWeekInput): StrengthAssignment { if (blocked.has(day.date)) continue const tooClose = placed.some((d) => Math.abs(diffDays(d, day.date)) < MIN_GAP_DAYS) if (tooClose) continue - byDate.set(day.date, strengthSession()) + byDate.set(day.date, strengthSession(variant)) placed.push(day.date) } diff --git a/packages/core/src/engine/tuneup.test.ts b/packages/core/src/engine/tuneup.test.ts index 78188b6..2c4e83c 100644 --- a/packages/core/src/engine/tuneup.test.ts +++ b/packages/core/src/engine/tuneup.test.ts @@ -45,7 +45,7 @@ describe('starty kontrolne w makrocyklu', () => { const weekOf = (date: string) => plan.weeks.find((w) => w.tuneUp?.date === date) it('start B/C ląduje w swoim tygodniu i nie zmienia liczby tygodni planu', () => { - expect(plan.weeks).toHaveLength(17) + expect(plan.weeks.filter((w) => w.phase !== 'transition')).toHaveLength(17) expect(weekOf('2026-09-05')).toBeDefined() expect(weekOf('2026-10-10')).toBeDefined() }) diff --git a/packages/core/src/engine/validate.test.ts b/packages/core/src/engine/validate.test.ts index ab00634..ebd8ffb 100644 --- a/packages/core/src/engine/validate.test.ts +++ b/packages/core/src/engine/validate.test.ts @@ -76,6 +76,8 @@ const check = (weeks: Microcycle[], goal: RaceGoal = marathon) => validatePlan({ /** Po celowej mutacji dni przywraca spójność sum — żeby test widział TYLKO badane odstępstwo. */ const resync = (week: Microcycle) => Object.assign(week, weekTotals(week.days)) +/** Tydzień startowy — od fazy przejściowej (R-8) nie jest już ostatnim tygodniem planu. */ +const raceWeekOf = (weeks: Microcycle[]) => weeks.find((w) => w.skeleton.raceDate)! describe('świeży plan zgłasza niewykonalną częstotliwość tygodnia startowego', () => { it('maraton, 17 tygodni', () => { @@ -190,9 +192,9 @@ describe('integralność pliku (error)', () => { it('raceDayMissing: plan zgubił dzień startu', () => { const weeks = buildWeeks(marathon) - const raceDay = weeks.at(-1)!.days.find((d) => d.workout?.kind === 'race')! + const raceDay = raceWeekOf(weeks).days.find((d) => d.workout?.kind === 'race')! delete raceDay.workout - resync(weeks.at(-1)!) + resync(raceWeekOf(weeks)) const hit = check(weeks).find((i) => i.code === 'raceDayMissing') expect(hit?.severity).toBe('error') expect(hit?.date).toBe(marathon.date) @@ -202,7 +204,7 @@ describe('integralność pliku (error)', () => { describe('odstępstwa od reguł (warn)', () => { it('accentGap [I-7]: akcent w przeddzień startu — także na styku jednostek race/test', () => { const weeks = buildWeeks(marathon) - const raceWeek = weeks.at(-1)! + const raceWeek = raceWeekOf(weeks) const sharpenerDay = raceWeek.days.find((d) => d.workout?.kind === 'sharpener')! const saturday = raceWeek.days[5]! saturday.workout = sharpenerDay.workout! @@ -218,7 +220,7 @@ describe('odstępstwa od reguł (warn)', () => { it('workoutBeforeRace [T-10]: bieg spokojny w przeddzień startu', () => { const weeks = buildWeeks(marathon) - const raceWeek = weeks.at(-1)! + const raceWeek = raceWeekOf(weeks) const easyDay = raceWeek.days.find((d) => d.workout?.kind === 'easy')! const saturday = raceWeek.days[5]! saturday.workout = easyDay.workout! diff --git a/packages/core/src/engine/validate.ts b/packages/core/src/engine/validate.ts index 82f7ccd..86a14ef 100644 --- a/packages/core/src/engine/validate.ts +++ b/packages/core/src/engine/validate.ts @@ -16,7 +16,7 @@ */ import type { Microcycle, RaceGoal, Weekday, WorkoutKind } from '../domain/types.ts' import { COACH_STYLE, type HouseStyle } from './house-style.ts' -import { weekTotals } from './microcycle.ts' +import { plannedWeekKm, weekTotals } from './microcycle.ts' import { addDays, diffDays, mondayOf } from '../util/dates.ts' const WEEKDAY_ORDER: Weekday[] = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] @@ -200,8 +200,9 @@ export function validatePlan(input: ValidatePlanInput): PlanIssue[] { .sort((a, b) => a.date.localeCompare(b.date)) const dayByDate = new Map(allDays.map((d) => [d.date, d])) - // --- 4. dzień startu docelowego istnieje i jest startem (tylko gdy cel ma datę) - if (goalDate) { + // --- 4. dzień startu docelowego istnieje i jest startem (tylko gdy cel ma datę + // i jest startem — plan bazowy, P-11, kończy się zwykłym tygodniem) + if (goalDate && (input.goal as { kind?: string } | undefined)?.kind !== 'base') { const raceDay = allDays.find((d) => d.date === goalDate && d.workout?.kind === 'race') if (!raceDay) { error({ code: 'raceDayMissing', ruleRefs: [], date: goalDate }) @@ -310,10 +311,11 @@ export function validatePlan(input: ValidatePlanInput): PlanIssue[] { } for (const { week, days } of cleanWeeks) { - const target = week.skeleton?.targetKm const totals = recomputed.get(week.weekStart)! - if (typeof target === 'number' && week.skeleton?.phase !== 'race' && Math.abs(totals.totalKm - target) > 0.5) { - warn({ code: 'targetKmMismatch', ruleRefs: ['P-3'], date: week.weekStart, expected: target, actual: totals.totalKm }) + // budżet czasu z profilu (E-2) świadomie obniża objętość — porównujemy z tym, co zostawił + const expected = week.skeleton ? plannedWeekKm(week.skeleton) : undefined + if (typeof expected === 'number' && week.skeleton?.phase !== 'race' && Math.abs(totals.totalKm - expected) > 0.5) { + warn({ code: 'targetKmMismatch', ruleRefs: ['P-3'], date: week.weekStart, expected, actual: totals.totalKm }) } const desired = week.skeleton?.sessionCount const actual = days.filter(d => d.workout).length diff --git a/packages/core/src/i18n/core-en.ts b/packages/core/src/i18n/core-en.ts index 2c6ca5c..776265b 100644 --- a/packages/core/src/i18n/core-en.ts +++ b/packages/core/src/i18n/core-en.ts @@ -54,6 +54,7 @@ export const coreEn = { peak: 'peak', taper: 'taper', race: 'race week', + transition: 'transition', }, intensityModel: { @@ -123,6 +124,13 @@ export const coreEn = { sharpener: 'Pre-race sharpener', test: 'Time trial', race: 'RACE', + strength: 'Strength', + }, + + syncNotice: { + raceRejected: (dates: string) => `intervals.icu did not accept the races (${dates}) in any form; they are not in the calendar.`, + 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: { @@ -131,6 +139,16 @@ export const coreEn = { }, strength: { + transitionNote: + 'First week after the race: no strength yet — it comes back next week with one lighter session (R-9).', + sessionIntro: () => + 'Strength, getting into it, ~35 min: squat or deadlift + lunges + calf raises, 3 sets × 6 reps at a weight ' + + 'you could lift 8–10 times (~75% 1RM) — learning the movement before the heavy weeks (F-18). Never to failure (S-7).', + sessionMaintenance: () => + 'Maintenance strength, ~25 min: squat or deadlift + calf raises, 2 sets × 3–5 reps HEAVY (≥80% 1RM), ' + + '2–3 min rest. One session a week keeps what the block built (F-12, F-14). Never to failure (S-7).', + peakNote: + 'Peak: one strength session a week — enough to keep the adaptation while running takes priority (F-12, F-14).', session: () => 'Heavy strength, ~35 min: squat or deadlift + lunges + calf raises, ' + '3 sets × 4–6 reps HEAVY (≥80% 1RM — the last rep is hard but the movement holds), ' + @@ -164,7 +182,9 @@ export const coreEn = { macro: { raceDurationUnknown: 'Race duration is unknown; no training window can be confirmed.', raceConflict: (date: string) => `Race calendar conflict at ${date}: multiple races in one week or a tune-up during taper. Resolve the calendar explicitly.`, - raceDateInPast: 'Race date is in the past', + raceDateInPast: 'Race date is in the past — set the next goal in trainctl.yaml', + baseEndInPast: 'The end date of the base plan (goal.until) is in the past', + transitionWeek: (week: number, total: number) => `after the race: week ${week} of ${total} back to training (R-8)`, ultraTaperExtrapolated: 'T-8: ultra — extrapolated, no direct source', compressedPlan: (weeks: number) => `only ${weeks} weeks to the race — the plan is compressed, without a full progression`, diff --git a/packages/core/src/i18n/core-pl.ts b/packages/core/src/i18n/core-pl.ts index 2f5209e..0729c2e 100644 --- a/packages/core/src/i18n/core-pl.ts +++ b/packages/core/src/i18n/core-pl.ts @@ -65,6 +65,7 @@ export const corePl: CoreMessages = { peak: 'szczyt', taper: 'taper', race: 'tydzień startowy', + transition: 'okres przejściowy', }, intensityModel: { @@ -128,6 +129,13 @@ export const corePl: CoreMessages = { sharpener: 'Rozruch przedstartowy', test: 'Sprawdzian na czas', race: 'START', + strength: 'Siła', + }, + + syncNotice: { + raceRejected: (dates: string) => `intervals.icu nie przyjęło startów (${dates}) w żadnej postaci; nie ma ich w kalendarzu.`, + 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: { @@ -136,6 +144,16 @@ export const corePl: CoreMessages = { }, strength: { + transitionNote: + 'Pierwszy tydzień po starcie: jeszcze bez siły — wraca w następnym tygodniu jedną lżejszą sesją (R-9).', + sessionIntro: () => + 'Siła na wejście ~35 min: przysiad lub martwy ciąg + wykroki + wspięcia na palce, 3 serie × 6 powtórzeń ciężarem, ' + + 'który podniósłbyś 8–10 razy (~75% 1RM) — nauka ruchu przed ciężkimi tygodniami (F-18). Nie do wyczerpania (S-7).', + sessionMaintenance: () => + 'Siła podtrzymująca ~25 min: przysiad lub martwy ciąg + wspięcia na palce, 2 serie × 3–5 powtórzeń CIĘŻKO ' + + '(≥80% 1RM), przerwy 2–3 min. Jedna sesja w tygodniu utrzymuje to, co zbudował blok (F-12, F-14). Nie do wyczerpania (S-7).', + peakNote: + 'Szczyt: jedna sesja siły w tygodniu — wystarcza, żeby utrzymać adaptację, gdy bieganie ma pierwszeństwo (F-12, F-14).', session: () => 'Siła ciężka ~35 min: przysiad lub martwy ciąg + wykroki + wspięcia na palce, ' + '3 serie × 4–6 powtórzeń CIĘŻKO (≥80% 1RM, ostatnie powtórzenie trudne, ale bez upadku ruchu), ' + @@ -170,7 +188,9 @@ export const corePl: CoreMessages = { macro: { raceDurationUnknown: 'Czas startu jest nieznany; nie można potwierdzić okna treningowego.', raceConflict: (date: string) => `Konflikt kalendarza zawodów ${date}: kilka startów w tygodniu lub start kontrolny w taperze. Jawnie rozstrzygnij konflikt w kalendarzu.`, - raceDateInPast: 'Data startu w przeszłości', + raceDateInPast: 'Data startu w przeszłości — wpisz następny cel w trainctl.yaml', + baseEndInPast: 'Data końca planu bazowego (goal.until) jest w przeszłości', + transitionWeek: (week: number, total: number) => `po starcie: tydzień ${week} z ${total} powrotu do treningu (R-8)`, ultraTaperExtrapolated: 'T-8: ultra — ekstrapolacja bez źródła', compressedPlan: (weeks: number) => `tylko ${weeks} tyg. do startu — plan skompresowany, bez pełnej progresji`, diff --git a/packages/core/src/ports/sync.ts b/packages/core/src/ports/sync.ts index 29ddf8d..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). */ @@ -63,12 +71,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/export/package.json b/packages/export/package.json index 4c2c6ea..f0bf04d 100644 --- a/packages/export/package.json +++ b/packages/export/package.json @@ -1,6 +1,6 @@ { "name": "trainctl-export", - "version": "0.3.0", + "version": "0.4.0", "description": "trainctl exports: FIT workouts for the watch, ICS calendar, printable plan and race-day pack", "keywords": [ "fit", diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 03f4359..e4c9ccc 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -13,12 +13,18 @@ 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`, `trainctl_adapt`, `trainctl_desk`, `trainctl_reschedule`, `trainctl_export`, -`trainctl_review`, `trainctl_shorten`. +`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/package.json b/packages/mcp/package.json index 2aee9c1..edee2eb 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,6 +1,6 @@ { "name": "trainctl-mcp", - "version": "0.3.0", + "version": "0.4.0", "description": "trainctl as MCP tools: a research-backed running coach for Claude Code, Codex and other MCP clients", "keywords": [ "mcp", diff --git a/packages/mcp/src/server.test.ts b/packages/mcp/src/server.test.ts index 5df3ac2..1694223 100644 --- a/packages/mcp/src/server.test.ts +++ b/packages/mcp/src/server.test.ts @@ -71,16 +71,61 @@ 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_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() + 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') @@ -137,7 +182,7 @@ describe('serwer MCP trainctl', () => { it('scenariusz renegocjacji: week → shift → week', async () => { const before = await call('trainctl_week', { date: '2026-08-04' }) - expect(before.text).toContain('Tydzień 1/17') + expect(before.text).toContain('Tydzień 1/19') expect(before.text).toMatch(/08-04.*3 kilometry/) const shift = await call('trainctl_shift', { from: '2026-08-04', to: '2026-08-05' }) diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts index ca6b7a4..f9e5ca6 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,16 @@ import { cmdPush, cmdReschedule, cmdReview, + cmdRules, cmdShift, cmdShorten, + cmdStatus, cmdToday, cmdWeek, cmdWhy, + AGENTS, defaultProviderFactory, + simulationNotice, type CmdResult, type ProviderFactory, } from 'trainctl' @@ -34,11 +40,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 +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)), + toTool(args?.fromIntervals === true ? await cmdInitFromIntervals(dir, {}, factory) : cmdInit(dir, undefined, { commit: args?.commit, agent: args?.agent })), ) server.registerTool( @@ -70,7 +83,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 +124,9 @@ 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), + strength: z.enum(['done', 'skipped']).optional().describe(t.logStrength), + minutes: z.number().int().min(1).max(300).optional().describe(t.logMinutes), + commit: commitParam(), }, }, async (args) => toTool(cmdLog(dir, args)), @@ -125,6 +141,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 +168,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 +198,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 +232,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)), @@ -239,7 +259,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)), ) @@ -272,6 +292,66 @@ 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', + { + description: t.status, + outputSchema: toolOutputSchema, + annotations: { readOnlyHint: true, openWorldHint: false }, + inputSchema: {}, + }, + async () => toTool(cmdStatus(dir)), + ) + server.registerTool( 'trainctl_check', { 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..e615983 --- /dev/null +++ b/packages/sync-files/package.json @@ -0,0 +1,55 @@ +{ + "name": "trainctl-sync-files", + "version": "0.4.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..f19c141 --- /dev/null +++ b/packages/sync-files/src/files.test.ts @@ -0,0 +1,269 @@ +/** + * 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/) + }) +}) + +describe('ten sam bieg w dwóch formatach', () => { + it('FIT i GPX z tym samym startem liczą się raz — zostaje FIT, bogatszy w dane', () => { + const twinDir = mkdtempSync(join(tmpdir(), 'trainctl-sync-files-twin-')) + try { + // GPX tego samego biegu co RUN_FIT: start 05:00Z, ~10 km na północ, punkt co 10 s + const points = Array.from({ length: 301 }, (_, i) => + ``) + writeFileSync(join(twinDir, 'strava.gpx'), `running${points.join('')}`) + writeFileSync(join(twinDir, 'garmin.fit'), RUN_FIT) + const scan = scanActivityFiles(twinDir) + expect(scan.activities).toHaveLength(1) + expect(scan.activities[0]!.name).toBe('garmin') + expect(scan.skipped).toEqual([{ file: join(twinDir, 'strava.gpx'), reason: 'duplicate' }]) + } finally { + rmSync(twinDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) + } + }) +}) + +describe('bieg w terenie i na szosie to jedna rodzina', () => { + it('FIT „trail" i GPX „running" z tym samym startem liczą się raz', () => { + const twinDir = mkdtempSync(join(tmpdir(), 'trainctl-sync-files-trail-')) + try { + const points = Array.from({ length: 181 }, (_, i) => + ``) + writeFileSync(join(twinDir, 'trail.gpx'), `running${points.join('')}`) + writeFileSync(join(twinDir, 'trail.fit'), TRAIL_FIT) + const scan = scanActivityFiles(twinDir) + expect(scan.activities).toHaveLength(1) + expect(scan.activities[0]!.type).toBe('TrailRun') + } finally { + rmSync(twinDir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) + } + }) +}) + +/** Bieg w GPX: `km` na północ, punkt co 10 s. */ +const gpxTrack = (type: string, start: string, km: number) => { + const points = Array.from({ length: 301 }, (_, i) => + ``) + return `${type}${points.join('')}` +} +const tcxRun = (start: string, meters: number) => ` + + ${start} + 3000${meters} + +` + +describe('duplikaty: okno po starcie i dystans', () => { + const scanOf = (files: Record) => { + const d = mkdtempSync(join(tmpdir(), 'trainctl-sync-files-dup-')) + try { + for (const [name, content] of Object.entries(files)) writeFileSync(join(d, name), content) + const scan = scanActivityFiles(d) + return { activities: scan.activities, skipped: scan.skipped.map((s) => ({ file: basename(s.file), reason: s.reason })) } + } finally { + rmSync(d, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) + } + } + it('łańcuch kopii przeplecionych innym sportem: bieg liczy się raz', () => { + const scan = scanOf({ + 'a-run.gpx': gpxTrack('running', '2026-09-14T05:00:00Z', 10), + 'x-ride.gpx': gpxTrack('cycling', '2026-09-14T05:00:10Z', 10), + 'b-run.tcx': tcxRun('2026-09-14T05:00:55Z', 10000), + 'c-run.gpx': gpxTrack('running', '2026-09-14T05:01:40Z', 10), + }) + expect(scan.activities.filter((a) => a.type === 'Run')).toHaveLength(1) + expect(scan.activities.find((a) => a.type === 'Run')!.name).toBe('b-run') + expect(scan.activities.filter((a) => a.type === 'Ride')).toHaveLength(1) + expect(scan.skipped.map((s) => s.file).sort()).toEqual(['a-run.gpx', 'c-run.gpx']) + }) + it('przypadkowy start zegarka 40 s przed biegiem to osobny plik, nie kopia biegu', () => { + const scan = scanOf({ + 'oops.tcx': tcxRun('2026-09-14T05:00:00Z', 50), + 'real.tcx': tcxRun('2026-09-14T05:00:40Z', 10000), + }) + expect(scan.activities.map((a) => a.distanceKm).sort((a, b) => (a ?? 0) - (b ?? 0))).toEqual([0.05, 10]) + expect(scan.skipped).toEqual([]) + }) +}) diff --git a/packages/sync-files/src/files.ts b/packages/sync-files/src/files.ts new file mode 100644 index 0000000..44ea107 --- /dev/null +++ b/packages/sync-files/src/files.ts @@ -0,0 +1,249 @@ +/** + * 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 { isRunType, 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' | 'duplicate' + +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 +} + +/** + * Ten sam bieg w dwóch formatach (eksport Garmina .fit i Stravy .gpx) ma inne + * bajty, ale ten sam start. Ta sama rodzina aktywności (bieg po szosie, trailu + * i bieżni to jedna rodzina) i start w ±60 s = duplikat; zostaje plik najbogatszy + * w dane (FIT > TCX > GPX). Do tego podobny dystans: przypadkowy start zegarka + * 40 s przed właściwym biegiem to osobny, krótki plik, nie kopia biegu. + * Wartości inżynierskie: 60 s (znaczniki czasu formatów różnią się zaokrągleniem, + * dwa różne biegi nie) i 10% albo 500 m różnicy dystansu (GPS różnych eksportów). + */ +const DUPLICATE_WINDOW_MS = 60_000 +const DUPLICATE_DISTANCE_SHARE = 0.1 +const DUPLICATE_DISTANCE_MIN_M = 500 +const FORMAT_RANK: Record = { fit: 0, tcx: 1, gpx: 2 } +const sameFamily = (a: ParsedActivity['type'], b: ParsedActivity['type']) => a === b || (isRunType(a) && isRunType(b)) +/** Dystans podobny albo nieznany w którymś pliku (wtedy rozstrzygają start i rodzina). */ +function similarDistance(a: ParsedActivity, b: ParsedActivity): boolean { + if (a.distanceM === undefined || b.distanceM === undefined) return true + const tolerance = Math.max(DUPLICATE_DISTANCE_MIN_M, DUPLICATE_DISTANCE_SHARE * Math.max(a.distanceM, b.distanceM)) + return Math.abs(a.distanceM - b.distanceM) <= tolerance +} + +/** + * 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; format: string; file: string }[] = [] + 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), format: kind.format, file }) + } + + // duplikaty między formatami: po starcie w czasie, z przesuwanym oknem — O(n log n) + const timed = found + .map((f) => ({ ...f, at: Date.parse(f.parsed.startTime) })) + .sort((a, b) => a.at - b.at || (FORMAT_RANK[a.format] ?? 9) - (FORMAT_RANK[b.format] ?? 9)) + const kept: typeof timed = [] + for (const f of timed) { + let twin = -1 + for (let k = kept.length - 1; k >= 0 && f.at - kept[k]!.at <= DUPLICATE_WINDOW_MS; k--) { + if (sameFamily(kept[k]!.parsed.type, f.parsed.type) && similarDistance(kept[k]!.parsed, f.parsed)) { + twin = k + break + } + } + if (twin === -1) { + kept.push(f) + continue + } + // zostaje bogatszy format; drugi plik jest wymieniony w pominiętych, nie znika po cichu + if ((FORMAT_RANK[f.format] ?? 9) < (FORMAT_RANK[kept[twin]!.format] ?? 9)) { + skipped.push({ file: kept[twin]!.file, reason: 'duplicate' }) + // na koniec, nie w miejsce bliźniaka: `kept` musi zostać posortowane po + // starcie, bo okno wyżej przerywa skan na pierwszym wpisie spoza 60 s + kept.splice(twin, 1) + kept.push(f) + } else { + skipped.push({ file: f.file, reason: 'duplicate' }) + } + } + + kept.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: kept.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( + /