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
', 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 run running ${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}
+ 3600 30000
+ ${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(
+ /