SLOPSHOPPER

Terminal Gym

A daily bodyweight rep goal inside Claude Code: log with /fit, quick-log band, long-turn nudges, streaks and a score grid, optional strict mode.

panebandspinnercommandtoastprompt
★ 2v0.1.6MITupdated 2026-10-23DrumAndCode/terminal-gym
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · terminal-gym
│ ┃ gym-week ✕ › fix the failing auth test and add an audit log call │ ┃ ▐█▌▐█▌ ▐█▌▐█▌ │ ┃ ━▐█▌▐█▌━━━ TERMINAL GYM ━━━▐█▌▐█▌━ ⏺ Read(src/auth.ts) │ ┃ ▐█▌▐█▌ ▐█▌▐█▌ ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ 🔥 0-day streak ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ · 10-03 ────────── 0/100 dips ⎿ 3 pass, 1 fail │ ┃ · 10-04 ────────── 0/300 squats │ ┃ · 10-05 ────────── 0/100 pushups ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ · 10-06 ────────── 0/100 pushups │ ┃ · 10-07 ────────── 0/100 dips ✻ Worked for 42s · done 4:20 PM │ ┃ · 10-08 ────────── 0/300 squats │ ┃ · 10-09 ────────── 0/100 pushups ◀ today › /fit │ ┃ ⎿ terminal-gym: 💪 ░░░░░░░░░░ 0/100 pushups │ ┃ last 4 weeks, a square a day │ ┃ ██ ██ ██ ██ ██ ██ ██ │ ┃ │ ┃ ██ ██ ██ ██ ██ ██ ██ │ ┃ │ ┃ ██ ██ ██ ██ ██ ██ ██ │ ┃ │ ┃ ██ ██ ██ ██ ██ ██ ▒▒ │ ┃ █ goal █ some reps █ none ▒ today │ ┃ │ ┃ Esc or /fit streak to close ❚█═TERMINAL-GYM═█❚ Your agent put in the reps. You next. [ Pick your training ] [ Help ] [ Just train ] ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
❚█═TERMINAL-GYM═█❚ Your agent put in the reps. You next. [ Pick your training ] [ Help ] [ Just train ]
Pane · gym-week
▐█▌▐█▌ ▐█▌▐█▌ ━▐█▌▐█▌━━━ TERMINAL GYM ━━━▐█▌▐█▌━ ▐█▌▐█▌ ▐█▌▐█▌ 🔥 0-day streak · 10-03 ────────── 0/100 dips · 10-04 ────────── 0/300 squats · 10-05 ────────── 0/100 pushups · 10-06 ────────── 0/100 pushups · 10-07 ────────── 0/100 dips · 10-08 ────────── 0/300 squats · 10-09 ────────── 0/100 pushups ◀ today last 4 weeks, a square a day ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ▒▒ █ goal █ some reps █ none ▒ today Esc or /fit streak to close [ Close ]
Pane · gym-help
Help Your agent put in the reps. You next. When a turn runs long, drop and do a set. Log a set /fit 20 adds 20 reps or press a + button above the prompt (sized to your set) Commands | Command | Does | |---|---| | /fit | today's progress | | /fit set 80 | fix today's count | | /fit reset | today back to 0 | | /fit goal 60 | change today's goal | | /fit window 3 | finish today in the next 3h | | /fit snooze 30 | put the due set off 30 min (twice a day) | | /fit swap | switch today's exercise | | /fit rest | rest day, before any reps (breaks streak) | | /fit rest off | undo today's rest day | | /fit streak | streak + grid | | /fit program | pick your training | | /fit progress | hit a goal, the next session of it goes up 5% (off to stop) | | /fit strict / /fit easy | strict mode on / off | | /fit help | this list | | /fit reload | re-read the log now (other sessions sync every 10s anyway) | | /fit start | replay the welcome | | /fit hide | close panels | Strict mode Off by default. When it's on: • today's goal is split into sets, spread over 8 hours (by default) from your first prompt • /fit window 3 spreads what's left over the next 3 hours instead (ending by midnight) • prompts before 5am count as the night before • the first set is due right away • fall behind and your prompts wait until you catch up • log a set, even a short one, and you get a breather before the rest (a few reps buy a shorter one) • just eaten? /fit snooze 30 puts the due set off, once per set and twice a day • a toast tells you when each set comes due • /fit easy stops holding prompts; /fit rest (before any reps) takes the day off Turn it on: type /fit strict Turn it off: type /fit easy Your data Stays on this machine, in ~/.claude/fitness. [ Pick your training ] [ Close ]
Pane · gym-onboard
Step 1 of 3 ● ○ ○ Your agent works the code. You work the reps. Every day has a rep goal. When Claude runs a long turn, that's your cue for a set. Log reps two ways: type /fit 20 or press a + button above your prompt [ Next ]
README

❚█═TERMINAL-GYM═█❚

Your agent put in the reps. You next.

A Claude Code mod for a daily bodyweight rep goal. While Claude works, you train: log sets from a band above your prompt, keep a streak, and let strict mode spread the reps through your day.

claude plugin marketplace add DrumAndCode/terminal-gym && claude plugin install terminal-gym@terminal-gym

Start a new Claude Code session and the welcome band appears above your prompt.

The Terminal Gym band above the Claude Code prompt: 0/100 pushups with a set due, with quick-log buttons

Demo (40 seconds)

https://github.com/user-attachments/assets/14373c7e-ad8a-4f92-812b-c93c3201b1b3

What you get

  • Tracker band above the prompt: 💪 ▓▓▓▓▓▓░░░░ 60/100 pushups next set in 23m log reps: [ +5 ] [ +10 ] [ +20 ] 🔥3d. The buttons follow your set size: a 300-squat day shows +10 +20 +30. It's grey at 0, yellow once you start, and green as you close in on the goal.
  • Walkthrough: three steps on first run: what the mod does, pick your program, how streaks and the scoreboard work.
  • Set reminders: a toast when each set comes due.
  • Cheers: a toast for every set you log, with the reps left to go.
  • Long-turn nudges (easy mode): when Claude works past 30 seconds, a toast and the spinner suggest a set.
  • Strict mode: today's goal is split into sets spread over your day. Fall behind and your prompts wait until you catch up.
  • Scoreboard (/fit streak): an ASCII barbell (in the terminal), your streak, a 28-day grid and the last week by exercise, with today marked.
  • Progressive goals (opt-in): hit a goal, and the next session of that exercise asks for about 5% more.
  • Streaks: count every day you log any reps, for as long as you keep it going. A day with none, or a rest day, resets it. The grid still marks the days you hit the full goal.

How a strict day works

Strict mode spreads today's goal into evenly spaced sets over a training window (8 hours by default) that starts with your first prompt of the day. With 100 pushups:

WhenWhat happens
First prompt (say 9:00)The day starts and the opening set is due. Your prompt waits: "Start the day with a set: 10 pushups. /fit 10 to log it, then send your prompt."
After /fit 10You're through. The band reads next set in 54m, counting down
9:53Toast: "⏱ Set due: 10 pushups. 20/100 by now." Your next prompt waits until you log it
…about every 53 minutes…Ten sets in all, the last due 8 hours after your first prompt
Goal done, or a rest dayNothing waits

You don't have to pay a debt back all at once. Log a set, even a short one, and you earn a breather of half the gap between sets (about 27 minutes with the defaults): prompts go through, the band reads 10 due · rest for 27m, and a toast calls the next set when it ends. What you didn't do stays owed. Fewer reps than the band's smallest button earn their share of it: 2 reps of a 5-rep button get about 11 minutes. A few reps never cut short a longer breather or snooze already running.

A held prompt goes back in the prompt box, so you can send it again once you've logged the set.

Just eaten, or mid-call? /fit snooze 30 puts the due set off for 30 minutes (up to 60) without logging anything: prompts go through, the band reads 20 due · back at 13:05, and a toast calls the set when time is up. Each due set can be put off once, and twice a day in all; after that it's a set, even a short one, or /fit easy. A /fit goal or /fit window meanwhile keeps the put-off: the time you asked for stands, and the set due when it ends is the new one.

Know you only have a few hours today? /fit window 3 spreads the reps you still owe over the next 3 hours, starting now. A window ends by midnight, because the day's log does. The first of those sets is due straight away. /fit window off goes back to the default window. /fit goal 60 changes today's goal and leaves your routine alone.

Only prompts you type can be held. Background tasks, /loop runs, messages from other sessions and slash commands like /fit 10 always go through. Prompts before 5am count as the night before, so a late night never leaves you a wall of overdue sets in the morning.

Easy mode (the default) shows the same schedule on the band and the same reminders, but never holds a prompt.

Progressive goals

Turn them on with /fit progress, or with Progressive goals in /config. They are off by default.

A goal moves the next time its exercise comes around, at the start of that day:

  • You hit the goal: the goal goes up one step. A step is 5% of the goal in fives, at least 5. For example, 100 → 105 and 300 → 315. From 150, a step is 10.
  • Two short sessions in a row: the goal goes back one step.
  • Anything else: the goal stays.

Only days with reps count as sessions. A rest day or a day with no reps doesn't count, so time away never lowers a goal. A /fit goal day counts only when its goal equals the routine's goal for that exercise. A /fit swap day counts for the exercise you did. A goal moves at the day's first look, before any swap.

With the default rotation, 100 pushups on Monday moves Thursday and Sunday to 105 as well. An exercise with two different goals in one routine (for example, 100 pushups on Monday and 50 on Thursday) doesn't progress. When you hit a goal, the toast tells you the next one: "Next pushups day: 105." On the day it moves, a toast says so.

The new goal is written to routine.json. Before that, the days before today are frozen at the goals they had, so the grid still shows them as hit. /fit progress off stops the changes and keeps the goals where they are.

Several sessions at once

Every Claude Code session reads the same log in ~/.claude/fitness, so a set you log in one counts in all of them. Each session checks the log every 10 seconds and redraws its band when another session, or the shell, wrote to it. /fit reload does the same read right away.

Commands

CommandDoes
/fittoday's progress, pace and streak
/fit 20log 20 reps
/fit set 80fix today's count
/fit resettoday back to 0
/fit goal 60change today's goal (your routine stays as it is)
/fit window 3spread what's left of today over the next 3 hours (/fit window off to undo)
/fit window 1240spread what's left of today between now and 12:40 (24-hour clock, 12:40 works too)
/fit snooze 30put the due set off 30 minutes (up to 60): prompts go through, the set stays owed. Once per set, twice a day
/fit swap [exercise]switch today's exercise: the next in your program, or the one you name, with that exercise's goal
/fit restrest day: no sets due, breaks your streak. Only before you've logged reps that day
/fit rest offundo today's rest day (or press Train today on the band)
/fit streakscoreboard: streak, grid and the last week (run again or press Esc to close)
/fit programpick your program (the walkthrough), or Custom goals to type each exercise's daily goal
/fit progressprogressive goals on (/fit progress off to stop)
/fit strict / /fit easystrict mode on / off
/fit helpevery command + strict-mode rules (/fit rules still works)
/fit reloadre-read today's log from disk now (/fit sync works too)
/fit startreplay the welcome
/fit hideclose panels

Settings

In /config, under terminal-gym:

SettingDefaultWhat it does
Strict modeoffHold typed prompts while you're behind pace
Progressive goalsoffRaise an exercise's goal after you hit it, and lower it after two short sessions
Training window8 hoursHow long after your first prompt the day's sets are spread over
Set sizeautoReps per set; auto is a tenth of the goal, rounded to fives
Long-turn nudgesonEasy mode: suggest a set when a turn runs long
Nudge after30 secondsHow long a turn runs before the nudge
Reps per nudge10The set the nudge suggests
Spinner takeoveronEasy mode: show the suggested set in the spinner
Quick-log bandonShow the tracker band above the prompt

Privacy and data

The mod makes no network calls and adds no hidden context for the model. /fit replies appear in your conversation like any slash command's output, so Claude can see them. Everything else stays on your machine: a few values in the mod's own store (see below), and your data in ~/.claude/fitness:

  • routine.json: the plan per weekday, for example { "mon": { "exercise": "pushups", "goal": 100 } }, with an optional "unit": "s" for timed exercises. Edit it for a custom program. With progressive goals on, the mod changes the goals in it.
  • log/YYYY-MM-DD: that day's count.
  • log/YYYY-MM-DD.skip: a rest day. If it contains off, the rest day was undone.
  • log/YYYY-MM-DD.swap: that day's plan after /fit swap or /fit goal, in the same shape as a routine day.
  • log/YYYY-MM-DD.day: that day's pace, for example { "start": 1760000000000, "window": { "from": …, "ms": …, "base": 0 }, "breather": …, "laters": 1, "putOff": 20 }: when the day started (your first prompt), a /fit window, when a breather ends (milliseconds since the epoch), and the /fit snoozes taken: how many today, and the due point the last one put off.

What it does inside Claude Code

A mod runs inside Claude Code, so here is everything Terminal Gym touches:

  • Files it writes: only its own data in ~/.claude/fitness: the routine (also when progressive goals move a goal), the daily logs listed above, and routine.json.bak (a copy of your custom routine, made before the walkthrough replaces it). It never writes settings files, instructions, build or start-up files directly.
  • Its own store: two values in the mod's per-plugin store inside Claude Code: the streak cache and whether you've seen the welcome. Everything sessions share (today's start, a /fit window, a breather) is in the day's file above, so every session reads the same one.
  • Settings it changes: /fit strict and /fit easy turn its own Strict mode setting (terminal-gym.strict) on and off. /fit progress does the same for its Progressive goals setting (terminal-gym.progress). Those are the only settings it changes. It sets no environment variables; it reads HOME to find ~/.claude/fitness.
  • Permissions: it never approves or denies a tool call, never changes your permission mode, and never runs a model or a process.
  • Events it hooks:
  • prompt.submit: in strict mode, holds a prompt you typed while you're behind pace and puts its text back in the prompt box. Easy mode lets everything through. Prompts from other sources are never touched.
  • command.run: answers its own /fit command, and nothing else.
  • session.start and the SessionStart event after /clear or /resume: load today's state and register /fit. The event passes through unchanged.
  • turn.start and turn.complete: time the easy-mode nudge and refresh the band.
  • a timer every 10 seconds: lists ~/.claude/fitness/log and re-reads it when a file changed, so sessions stay in step.
  • ui.render: draws the band, the scoreboard, the help pane and the walkthrough, and (easy mode) the suggested set in the spinner.

Requirements

Claude Code 2.1.288 or newer. The band and panes draw in the terminal and the Desktop app's Code tab. In the VS Code chat panel and claude -p, /fit still works but nothing is drawn. Mods are early access, so the API can change between Claude Code releases.

Update with claude plugin update terminal-gym@terminal-gym. From inside a chat, you can also install with /plugin install terminal-gym --marketplace DrumAndCode/terminal-gym.

Contributing

Issues and PRs welcome. Keep changes small and include a test.

claude --plugin-dir .          # load your checkout for one session
claude plugin validate --strict .
claude plugin test .

claude plugin test runs tests/*.test.tsx against the engine itself. Once the mod has loaded, tsc -p . type-checks it against the engine's types in .claude-plugin/types/.

License

MIT

Source 3 files
hooks/register.tsx 1258 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Day, OnboardPick, Pace, Today } from '../types'
5import {
6  DEFAULT_ROUTINE,
7  BARBELL,
8  HELP,
9  SNOOZE,
10  MINI_BARBELL,
11  ROUTINES,
12  SIZES,
13  bar,
14  earnedBreatherMs,
15  clockTime,
16  untilText,
17  paceAt,
18  setSizeFor,
19  stepFor,
20  buttonsWidth,
21  canProgress,
22  cells,
23  cheer,
24  customRoutine,
25  dayKey,
26  exerciseGoals,
27  fullStreak,
28  keepsStreak,
29  describeRoutine,
30  GRID_COLORS,
31  heatCells,
32  lastDays,
33  moveGoal,
34  nextGoal,
35  parseFit,
36  pickSwap,
37  progressColor,
38  repSteps,
39  scale,
40  streak,
41  weekdayKey,
42} from './lib'
43import type { Routine } from './lib'
44
45type Engine = EngineInterface
46
47const PANE = 'gym-week'
48const HELP_PANE = 'gym-help'
49const ONBOARD_PANE = 'gym-onboard'
50const HISTORY_DAYS = 28
51const TOAST_MS = 10_000
52const HOUR_MS = 60 * 60_000
53// How often a session looks for reps another session, or the shell, logged.
54const SYNC_MS = 10_000
55
56// Toasts stay up long enough to read mid-set.
57const toast = ($: Engine, text: string) => $.ui.toast(text, { timeoutMs: TOAST_MS })
58
59// The pace settings, set from the options each time the module registers.
60const paceConfig = { setSize: 0, windowMs: 8 * HOUR_MS }
61let dueTimer: { cancel: () => void } | undefined
62// Redraws the band each minute, so "rest for 13m" and "next set in 23m" count down.
63let bandTicker: { cancel: () => void } | undefined
64// Polls the log on disk, which every session and the shell script share.
65let syncTimer: { cancel: () => void } | undefined
66// The log as this session last read it: the routine's time and each day's file.
67let seenOnDisk = ''
68// Progressive goals, set from the options; and the day this session last moved
69// a goal for, so the check runs once a day.
70const progressConfig = { isOn: false }
71let progressedOn = ''
72
73const today = atom({ plugin: 'terminal-gym', key: 'today' } as const, null)
74const olderStreak = atom({ plugin: 'terminal-gym', key: 'olderStreak' } as const, 0)
75const pace = atom({ plugin: 'terminal-gym', key: 'pace' } as const, null)
76const isWaiting = atom({ plugin: 'terminal-gym', key: 'isWaiting' } as const, false)
77const history = atom({ plugin: 'terminal-gym', key: 'history' } as const, [])
78const isIntroduced = atom({ plugin: 'terminal-gym', key: 'isIntroduced' } as const, false)
79const onboardStep = atom({ plugin: 'terminal-gym', key: 'onboardStep' } as const, 0)
80const onboardPick = atom({ plugin: 'terminal-gym', key: 'onboardPick' } as const, {
81  program: 'Push · dip · squat rotation',
82  size: 'Standard',
83  hasRoutine: false,
84  base: DEFAULT_ROUTINE,
85  custom: {},
86  isCustomInvalid: false,
87})
88
89// Same files as the `fit` shell script, so both agree.
90const files = async ($: Engine) => {
91  const dir = `${(await $.env.get('HOME')) ?? ''}/.claude/fitness`
92  return { routine: `${dir}/routine.json`, log: `${dir}/log` }
93}
94
95const loadRoutine = async ($: Engine, routinePath: string): Promise<Routine> => {
96  if (!(await $.fs.exists(routinePath))) {
97    await $.fs.write(routinePath, `${JSON.stringify(DEFAULT_ROUTINE, null, 2)}\n`)
98    return DEFAULT_ROUTINE
99  }
100  return JSON.parse(await $.fs.read(routinePath)) as Routine
101}
102
103const readCount = async ($: Engine, path: string) => {
104  if (!(await $.fs.exists(path))) return 0
105  const n = parseInt(await $.fs.read(path), 10)
106  return Number.isFinite(n) ? n : 0
107}
108
109// `/fit swap` leaves the day's plan beside its count as `<date>.swap`.
110const readSwap = async ($: Engine, logDir: string, date: string): Promise<Routine[string] | undefined> => {
111  const path = `${logDir}/${date}.swap`
112  if (!(await $.fs.exists(path))) return undefined
113  // A damaged or odd file falls back to the routine instead of breaking every refresh.
114  try {
115    const plan = JSON.parse(await $.fs.read(path)) as Partial<Routine[string]>
116    return typeof plan.exercise === 'string' && typeof plan.goal === 'number'
117      ? { exercise: plan.exercise, goal: plan.goal, unit: plan.unit }
118      : undefined
119  } catch {
120    return undefined
121  }
122}
123
124// `/fit rest` leaves `<date>.skip`; `/fit rest off` writes "off" into it to undo.
125const readRest = async ($: Engine, path: string) =>
126  (await $.fs.exists(path)) && (await $.fs.read(path)).trim() !== 'off'
127
128// Progressive goals: at the day's first look, today's exercise moves on from
129// its last sessions, the next time it comes around. Days before are frozen at
130// the goals they were trained at first. Two sessions at once compute the same
131// move, and the second finds the routine already moved, so a goal moves once.
132const progress = async ($: Engine, date: string) => {
133  if (!progressConfig.isOn || progressedOn === date) return
134  progressedOn = date
135  const { routine: routinePath, log: logDir } = await files($)
136  // A day with a plan of its own (`/fit swap`, `/fit goal`) isn't the routine's.
137  if (await $.fs.exists(`${logDir}/${date}.swap`)) return
138  const routine = await loadRoutine($, routinePath)
139  const now = await $.clock.now()
140  const plan = routine[weekdayKey(now)]
141  if (plan === undefined || !canProgress(routine, plan.exercise)) return
142  const before = lastDays(now, HISTORY_DAYS).slice(0, -1).reverse()
143  const days = await Promise.all(before.map(ms => readDay($, routine, logDir, ms)))
144  const to = nextGoal(plan.goal, days.filter(day => day.exercise === plan.exercise))
145  if (to === undefined) return
146  await freezePastDays($, routine)
147  await $.fs.write(routinePath, `${JSON.stringify(moveGoal(routine, plan.exercise, plan.goal, to), null, 2)}\n`)
148  const unit = plan.unit ?? ''
149  toast($, to > plan.goal
150    ? `📈 ${plan.exercise} up to ${to}${unit}: your last session hit ${plan.goal}${unit}.`
151    : `${plan.exercise} back to ${to}${unit} after two short sessions. Rebuild.`)
152}
153
154const refreshToday = async ($: Engine): Promise<Today> => {
155  const { routine, log: logDir } = await files($)
156  const date = dayKey(await $.clock.now())
157  await progress($, date)
158  const plan =
159    (await readSwap($, logDir, date)) ?? (await loadRoutine($, routine))[weekdayKey(await $.clock.now())]
160  const next: Today = {
161    date,
162    exercise: plan?.exercise ?? 'reps',
163    goal: plan?.goal ?? 0,
164    unit: plan?.unit ?? '',
165    count: await readCount($, `${logDir}/${date}`),
166    isRest: await readRest($, `${logDir}/${date}.skip`),
167  }
168  await update($, today, () => next)
169  return next
170}
171
172const DAY_MS = 86_400_000
173
174const readDay = async ($: Engine, routine: Routine, logDir: string, ms: number): Promise<Day> => {
175  const date = dayKey(ms)
176  const plan = (await readSwap($, logDir, date)) ?? routine[weekdayKey(ms)]
177  return {
178    date,
179    count: await readCount($, `${logDir}/${date}`),
180    goal: plan?.goal ?? 0,
181    exercise: plan?.exercise ?? 'reps',
182    isSkipped: await readRest($, `${logDir}/${date}.skip`),
183  }
184}
185
186// Days with reps in a row just before the window, so a streak can outlast it.
187// Cached per window: a full walk once, then one day's step as the window slides.
188const olderRun = async ($: Engine, days: readonly Day[], routine: Routine, logDir: string) => {
189  const first = days[0]
190  if (first === undefined || !keepsStreak(first)) {
191    await $.store.delete('streakRun')
192    return 0
193  }
194  const oldest = lastDays(await $.clock.now(), HISTORY_DAYS)[0] ?? 0
195  const asOf = dayKey(oldest)
196  const cache = (await $.store.get('streakRun')) as { asOf?: string; older?: number } | undefined
197  let older: number
198  if (cache?.asOf === asOf && typeof cache.older === 'number') {
199    older = cache.older
200  } else if (cache?.asOf === dayKey(oldest - DAY_MS) && typeof cache.older === 'number') {
201    // The window moved on a day: the day that left it joins the older run.
202    older = keepsStreak(await readDay($, routine, logDir, oldest - DAY_MS)) ? cache.older + 1 : 0
203  } else {
204    older = 0
205    for (let back = 1; back <= 366; back++) {
206      if (!keepsStreak(await readDay($, routine, logDir, oldest - back * DAY_MS))) break
207      older++
208    }
209  }
210  await $.store.set('streakRun', { asOf, older })
211  return older
212}
213
214const refreshHistory = async ($: Engine) => {
215  const { routine: routinePath, log: logDir } = await files($)
216  const routine = await loadRoutine($, routinePath)
217  const days: Day[] = await Promise.all(
218    lastDays(await $.clock.now(), HISTORY_DAYS).map(async ms => {
219      const date = dayKey(ms)
220      const plan = (await readSwap($, logDir, date)) ?? routine[weekdayKey(ms)]
221      return {
222        date,
223        count: await readCount($, `${logDir}/${date}`),
224        goal: plan?.goal ?? 0,
225        exercise: plan?.exercise ?? 'reps',
226        isSkipped: await readRest($, `${logDir}/${date}.skip`),
227      }
228    }),
229  )
230  await update($, history, () => days)
231  const older = await olderRun($, days, routine, logDir)
232  await update($, olderStreak, () => older)
233  return days
234}
235
236type Schedule = { from: number; ms: number; base: number }
237
238// The day's pace, kept in `<date>.day` beside its count so every session reads
239// the same one: when the day started, a `/fit window`, a breather's end, and
240// the `/fit snooze`s taken (how many today, and the due point the last put off).
241type DayState = { start?: number; window?: Schedule; breather?: number; laters?: number; putOff?: number }
242
243const dayPath = async ($: Engine, date: string) => `${(await files($)).log}/${date}.day`
244
245const isSchedule = (w: unknown): w is Schedule =>
246  typeof w === 'object' && w !== null && ['from', 'ms', 'base'].every(k => typeof (w as Record<string, unknown>)[k] === 'number')
247
248// Only the fields of the right shape: a damaged file reads as an empty day.
249const asDayState = (raw: unknown): DayState => {
250  const r = (typeof raw === 'object' && raw !== null ? raw : {}) as Record<string, unknown>
251  return {
252    ...(typeof r.start === 'number' ? { start: r.start } : {}),
253    ...(isSchedule(r.window) ? { window: r.window } : {}),
254    ...(typeof r.breather === 'number' ? { breather: r.breather } : {}),
255    ...(typeof r.laters === 'number' ? { laters: r.laters } : {}),
256    ...(typeof r.putOff === 'number' ? { putOff: r.putOff } : {}),
257  }
258}
259
260// Up to 0.1.4 these sat in the plugin store, which a session may cache. A day
261// started before the update still reads from there until its file is written.
262const legacyDayState = async ($: Engine, date: string): Promise<DayState> => {
263  const dated = (key: string) => $.store.get(key) as Promise<{ date?: string; [k: string]: unknown } | undefined>
264  const [start, window, breather] = await Promise.all([dated('dayStart'), dated('window'), dated('breather')])
265  return asDayState({
266    start: start?.date === date ? start.at : undefined,
267    window: window?.date === date ? { from: window.from, ms: window.ms, base: window.base } : undefined,
268    breather: breather?.date === date ? breather.until : undefined,
269  })
270}
271
272// The file's state, or null when it doesn't parse: another session may be
273// mid-write, so a damaged file is read once more before giving up.
274const readDayFile = async ($: Engine, path: string): Promise<DayState | null> => {
275  for (let attempt = 0; attempt < 2; attempt++) {
276    try {
277      return asDayState(JSON.parse(await $.fs.read(path)))
278    } catch {
279      // Read it again.
280    }
281  }
282  return null
283}
284
285const readDayState = async ($: Engine, date: string): Promise<DayState> => {
286  const path = await dayPath($, date)
287  if (!(await $.fs.exists(path))) return legacyDayState($, date)
288  return (await readDayFile($, path)) ?? {}
289}
290
291// A damaged file is never written over: that would make the other session's
292// loss permanent. The change is skipped, and the next one finds the file whole.
293const writeDayState = async ($: Engine, date: string, change: (state: DayState) => DayState) => {
294  const path = await dayPath($, date)
295  const state = (await $.fs.exists(path)) ? await readDayFile($, path) : await legacyDayState($, date)
296  if (state === null) return false
297  await $.fs.write(path, `${JSON.stringify(change(state))}\n`)
298  return true
299}
300
301// The day starts at the person's first prompt; sets are spread from there.
302const dayStart = async ($: Engine, date: string) => (await readDayState($, date)).start
303
304// Prompts before this hour belong to the night before: they never start the
305// day, or a 00:30 prompt would leave every set overdue by morning.
306const DAY_BEGINS_HOUR = 5
307
308const startDay = async ($: Engine) => {
309  const now = await $.clock.now()
310  if (new Date(now).getHours() < DAY_BEGINS_HOUR) return
311  const date = dayKey(now)
312  if ((await dayStart($, date)) === undefined) await writeDayState($, date, s => ({ ...s, start: now }))
313}
314
315// Ends a breather, and forgets which set a `/fit snooze` put off: with the debt
316// cleared or the count lowered, that set is no longer the one due.
317const endBreather = ($: Engine, date: string) =>
318  writeDayState($, date, ({ breather: _b, putOff: _p, ...rest }) => rest)
319
320// `/fit goal` and `/fit window` change which set is due. A breather sized for
321// the old schedule ends. A put-off keeps its time, since the person's minutes
322// set it, not the goal, and it now names the new due point.
323const reschedule = async ($: Engine, date: string): Promise<Pace | null> => {
324  const now = await $.clock.now()
325  const { breather, putOff } = await readDayState($, date)
326  const kept = putOff !== undefined && breather !== undefined && breather > now
327  await writeDayState($, date, ({ breather: b, putOff: _, ...rest }) => (kept ? { ...rest, breather: b } : rest))
328  const p = await refreshPace($)
329  if (!kept || p === null) return p
330  await writeDayState($, date, s => ({ ...s, putOff: p.required }))
331  return refreshPace($)
332}
333
334// The span today's sets are spread over: the configured window from the first
335// prompt, or after `/fit window`, the reps left then (above `base`) over the hours named.
336const scheduleOf = ({ window, start }: DayState): Schedule | undefined => {
337  if (window !== undefined) return window
338  return start === undefined ? undefined : { from: start, ms: paceConfig.windowMs, base: 0 }
339}
340
341const schedule = async ($: Engine, date: string) => scheduleOf(await readDayState($, date))
342
343// Recomputes the pace and arms a timer for the next set or breather's end.
344const refreshPace = async ($: Engine): Promise<Pace | null> => {
345  dueTimer?.cancel()
346  dueTimer = undefined
347  // Re-read today: the date may have rolled over, or the shell script logged reps.
348  const t = await refreshToday($)
349  const day = t === null ? {} : await readDayState($, t.date)
350  const s = scheduleOf(day)
351  const now = await $.clock.now()
352  let next: Pace | null = null
353  if (t !== null && !t.isRest && s !== undefined) {
354    const left = paceAt(Math.max(0, t.goal - s.base), t.count - s.base, setSizeFor(t.goal, paceConfig.setSize), s.from, now, s.ms)
355    next = {
356      ...left,
357      // Goal met: the schedule may still hold sets, but none are due.
358      nextDueAt: t.goal > 0 && t.count >= t.goal ? null : left.nextDueAt,
359      required: left.required + s.base,
360      // A breather still running: catch-up reps owed, but prompts not held.
361      restUntil: day.breather !== undefined && day.breather > now ? day.breather : null,
362      isPutOff: day.putOff !== undefined && day.putOff === left.required + s.base,
363      // A window set mid-day (base > 0) is never the day's opener, even after a reset.
364      isOpening: s.base === 0 && t.count === 0 && left.behind > 0 && left.required <= left.setSize,
365    }
366  }
367  await update($, pace, () => next)
368  bandTicker?.cancel()
369  bandTicker = undefined
370  // Only the countdowns paceText draws: "rest for 13m" and "next set in 23m".
371  const countdownTo = next === null ? null
372    : next.behind > 0 ? (next.isPutOff !== true ? next.restUntil : null)
373    : next.nextDueAt
374  if (countdownTo !== null) {
375    // Wake when the minute shown changes, so a re-arm (a sync, a prompt) never delays it.
376    // Each wait is measured from the clock, so an early timer or a sleep corrects itself.
377    const tick = (at: number) => {
378      const left = countdownTo - at
379      if (left <= 0) return
380      const timer = $.clock.after(left % 60_000 || 60_000, async () => {
381        $.ui.invalidate('ui.render')
382        const at = await $.clock.now()
383        // A refreshPace while this waited has armed its own ticker: leave it be.
384        if (bandTicker === timer) tick(at)
385      })
386      bandTicker = timer
387    }
388    tick(now)
389  }
390  const wakeAt = Math.min(next?.nextDueAt ?? Infinity, next?.restUntil ?? Infinity)
391  if (wakeAt !== Infinity && t !== null && t.count < t.goal) {
392    dueTimer = $.clock.after(Math.max(1, wakeAt - now), () => void setDue($))
393  }
394  return next
395}
396
397const setDue = async ($: Engine) => {
398  const p = await refreshPace($)
399  const t = await read($, today)
400  if (p === null || t === null || p.behind <= 0 || p.restUntil !== null) return
401  toast($, p.isOpening === true
402    ? `🏁 First set: ${p.behind} ${t.exercise} to start the day.`
403    : `⏱ Set due: ${p.behind} ${t.exercise}. ${p.required}/${t.goal} by now.`)
404}
405
406// A Close button's press: a refused close says why instead of doing nothing.
407const closePane = async ($: Engine, id: string) => {
408  try {
409    await $.ui.close({ id })
410  } catch (err) {
411    toast($, `Couldn't close the panel (${err instanceof Error ? err.message : String(err)}). Try Esc or /fit hide.`)
412  }
413}
414
415// Owed reps read as a set that's due, not a debt; a breather as rest left.
416const paceText = (p: Pace | null, isStrict: boolean, now: number) => {
417  if (p === null) return ''
418  if (p.isOpening === true) return `  🏁 first set: ${p.behind} to start the day`
419  if (p.behind > 0 && p.restUntil !== null) {
420    if (p.isPutOff === true) return `  ${p.behind} due · back at ${clockTime(p.restUntil)}`
421    return `  ${p.behind} due · rest for ${untilText(p.restUntil - now)}`
422  }
423  if (p.behind > 0) return `  ${p.behind} due now${isStrict ? ' · log it to keep prompting' : ''}`
424  return p.nextDueAt === null ? '' : `  next set in ${untilText(p.nextDueAt - now)}`
425}
426
427const line = (t: Today) => {
428  const isDone = t.goal > 0 && t.count >= t.goal
429  return `${isDone ? '✅' : '💪'} ${bar(t.count, t.goal)} ${t.count}/${t.goal}${t.unit} ${t.exercise}`
430}
431
432const withStreak = (t: Today, days: readonly Day[], older = 0) => {
433  const run = fullStreak(days, older)
434  return run > 0 ? `${line(t)}  🔥${run}d` : line(t)
435}
436
437const logReps = async ($: Engine, change: (count: number) => number) => {
438  const owed = await refreshPace($)
439  const before = await refreshToday($)
440  const count = Math.max(0, change(before.count))
441  await $.fs.write(`${(await files($)).log}/${before.date}`, `${count}\n`)
442
443  const after = { ...before, count }
444  await update($, today, () => after)
445  await update($, history, days =>
446    days.map(day => (day.date === after.date ? { ...day, count } : day)),
447  )
448
449  // A set that still leaves reps owed earns a breather before the rest: a short
450  // one counts, and fewer reps than the band's smallest button earn a shorter
451  // one. Clearing the debt or lowering the count ends one, so later sets aren't hidden.
452  const added = count - before.count
453  const stillOwed = owed === null ? 0 : owed.behind - added
454  const s = await schedule($, after.date)
455  if (owed !== null && s !== undefined && stillOwed > 0 && added > 0) {
456    const until = (await $.clock.now()) + earnedBreatherMs(added, after.goal - s.base, owed.setSize, s.ms)
457    const isFullSet = added >= (repSteps(owed.setSize)[0] ?? owed.setSize)
458    // Reps never cut short a longer breather or put-off already running. A
459    // full set means it's no longer the set that was put off; a few reps under
460    // a put-off that ends later leave its hold and its mark alone.
461    await writeDayState($, after.date, state => {
462      const isLater = state.breather !== undefined && state.breather > until
463      if (isLater && !isFullSet) return state
464      const { putOff: _, ...rest } = state
465      return { ...rest, breather: isLater ? state.breather : until }
466    })
467  } else if (stillOwed <= 0 || added < 0) {
468    await endBreather($, after.date)
469  }
470  await refreshPace($)
471  if (after.goal > 0 && before.count < after.goal && count >= after.goal) {
472    // The routine's goal hit, by the rule `nextGoal` moves it on: say where the
473    // next session of it goes. A swap counts; a goal of its own does not.
474    const routine = await loadRoutine($, (await files($)).routine)
475    const isPlanned = progressConfig.isOn && canProgress(routine, after.exercise) &&
476      Object.values(routine).some(plan => plan.exercise === after.exercise && plan.goal === after.goal)
477    const next = isPlanned ? ` Next ${after.exercise} day: ${after.goal + stepFor(after.goal)}${after.unit}.` : ''
478    toast($, `✅ Done. ${count}/${after.goal}${after.unit} ${after.exercise}. That's the work.${next}`)
479  } else if (added > 0) {
480    toast($, cheer(added, count, after.goal, after.exercise, after.unit))
481  }
482  return after
483}
484
485// Everything on disk another session can change, as one string: the routine's
486// modification time, then each log file's name, size and time. A directory's
487// own time only moves when a file is added, not when today's count is rewritten.
488const diskFingerprint = async ($: Engine) => {
489  const { routine, log: logDir } = await files($)
490  const routineAt = (await $.fs.exists(routine)) ? (await $.fs.stat(routine)).mtimeMs : 0
491  const entries = (await $.fs.exists(logDir)) ? await $.fs.list(logDir) : []
492  return [routineAt, ...entries.map(entry => `${entry.name}:${entry.size}:${entry.mtimeMs}`)].join('|')
493}
494
495// Re-reads today, the history and the pace when the files changed since this
496// session last looked (or always, when forced). Two sessions share one log:
497// a set logged in one shows in the other's band within a poll.
498const syncFromDisk = async ($: Engine, isForced = false) => {
499  let now: string
500  try {
501    now = await diskFingerprint($)
502  } catch {
503    // A missing or unreadable directory: nothing to catch up on this time.
504    return false
505  }
506  if (!isForced && now === seenOnDisk) return false
507  seenOnDisk = now
508  await refreshHistory($)
509  await refreshPace($)
510  return true
511}
512
513// The reps the last nudge suggested, for the spinner.
514let nudgeReps = 0
515
516// Easy mode: a suggestion once a turn runs long, sized to the set that's due.
517// On pace or in a breather there's nothing owed, so nothing to suggest.
518const nudge = async ($: Engine) => {
519  const p = await refreshPace($)
520  const t = await read($, today)
521  if (t === null || t.isRest || (t.goal > 0 && t.count >= t.goal)) return
522  if (p !== null && (p.behind <= 0 || p.restUntil !== null)) return
523  nudgeReps = p === null ? setSizeFor(t.goal, paceConfig.setSize) : Math.min(p.behind, p.setSize)
524  if (nudgeReps <= 0) return
525  await update($, isWaiting, () => true)
526  toast($, `Your agent's mid-set. You next: ${nudgeReps} ${t.exercise}.`)
527}
528
529const endRest = async ($: Engine) => {
530  const t = await refreshToday($)
531  if (!t.isRest) return { text: `Today isn't a rest day. ${line(t)}` }
532  await $.fs.write(`${(await files($)).log}/${t.date}.skip`, 'off\n')
533  const back = await refreshToday($)
534  await refreshHistory($)
535  await refreshPace($)
536  return { text: `Rest day undone. Back to work. ${line(back)}` }
537}
538
539const markIntroduced = async ($: Engine) => {
540  await $.store.set('introduced', true)
541  await update($, isIntroduced, () => true)
542}
543
544const KEEP = 'Keep my current routine'
545const CUSTOM = 'Custom goals'
546const DEFAULT_PROGRAM = 'Push · dip · squat rotation'
547
548const openOnboarding = async ($: Engine) => {
549  // Open first: a pane counts as asked for only while the press or command that
550  // asked is still being answered. Opened after other awaits, the engine treats
551  // it as unasked and leaves it undrawn below 144 columns.
552  await update($, onboardStep, () => 0)
553  const opened = await $.ui.open({ id: ONBOARD_PANE, title: 'TERMINAL GYM', focus: true, closeOnEscape: true })
554  if (!opened.isPlaced) toast($, 'Widen the terminal to see the walkthrough, or type /fit program.')
555  // A seeded default counts as no routine of their own; only custom ones get "keep".
556  const { routine: routinePath } = await files($)
557  const base = await loadRoutine($, routinePath)
558  const hasRoutine = JSON.stringify(base) !== JSON.stringify(DEFAULT_ROUTINE)
559  // Custom starts from the current routine's days and goals.
560  const custom = Object.fromEntries(Object.entries(exerciseGoals(base)).map(([name, goal]) => [name, String(goal)]))
561  await update($, onboardPick, () => ({
562    program: hasRoutine ? KEEP : DEFAULT_PROGRAM,
563    size: 'Standard',
564    hasRoutine,
565    base,
566    custom,
567    isCustomInvalid: false,
568  }))
569}
570
571const pickedRoutine = (p: OnboardPick): Routine | undefined => {
572  if (p.program === CUSTOM) return customRoutine(p.base, p.custom)
573  const preset = ROUTINES[p.program as keyof typeof ROUTINES] as Routine | undefined
574  return preset === undefined ? undefined : scale(preset, SIZES[p.size as keyof typeof SIZES] ?? 1)
575}
576
577// A new program changes today on; the days before keep the plan they were
578// trained against, written down as their own plan the way `/fit swap` does.
579const freezePastDays = async ($: Engine, old: Routine) => {
580  const { log: logDir } = await files($)
581  for (const ms of lastDays(await $.clock.now(), HISTORY_DAYS).slice(0, -1)) {
582    const path = `${logDir}/${dayKey(ms)}.swap`
583    const plan = old[weekdayKey(ms)]
584    if (plan !== undefined && !(await $.fs.exists(path))) await $.fs.write(path, `${JSON.stringify(plan)}\n`)
585  }
586}
587
588const finishOnboarding = async ($: Engine) => {
589  const p = await read($, onboardPick)
590  const { routine: routinePath } = await files($)
591  const routine = pickedRoutine(p)
592  // A custom goal that isn't a number sends the person back to fix it.
593  if (p.program === CUSTOM && routine === undefined) {
594    await update($, onboardPick, now => ({ ...now, isCustomInvalid: true }))
595    await update($, onboardStep, () => 1)
596    return
597  }
598  if (routine !== undefined) {
599    const old = await loadRoutine($, routinePath)
600    if (JSON.stringify(old) !== JSON.stringify(routine)) await freezePastDays($, old)
601    if (p.hasRoutine) await $.fs.write(`${routinePath}.bak`, await $.fs.read(routinePath))
602    await $.fs.write(routinePath, `${JSON.stringify(routine, null, 2)}\n`)
603  }
604  await markIntroduced($)
605  await refreshToday($)
606  await refreshHistory($)
607  await refreshPace($)
608  await $.ui.close({ id: ONBOARD_PANE })
609  const plan = routine ?? (JSON.parse(await $.fs.read(routinePath)) as Routine)
610  toast($, `Program set: ${describeRoutine(plan)}. Get to work.`)
611}
612
613// A made-up fortnight for the walkthrough's example grid.
614const SAMPLE_DAYS: Day[] = [1, 1, 0.4, 1, 1, 0, 1, 1, 1, 0.6, 1, 1, 1, 0.3].map((share, i) => ({
615  date: `sample-${i}`,
616  count: Math.round(share * 100),
617  goal: 100,
618  exercise: 'pushups',
619  isSkipped: false,
620}))
621
622// Everything a conversation needs: the /fit command and today's state.
623const boot = async ($: Engine) => {
624  const introduced = (await $.store.get('introduced')) === true
625  await update($, isIntroduced, () => introduced)
626  // A new conversation looks again: the routine may have moved since.
627  progressedOn = ''
628  await refreshToday($)
629  await refreshHistory($)
630  // Re-arms the due timer, which a restart or reload drops.
631  await refreshPace($)
632  // Remember the log as read, then watch it for what other sessions log.
633  try {
634    seenOnDisk = await diskFingerprint($)
635  } catch {
636    seenOnDisk = ''
637  }
638  syncTimer?.cancel()
639  syncTimer = $.clock.every(SYNC_MS, () => void syncFromDisk($))
640  // Last, so a refused registration can't leave the band without its state.
641  await $.command.register({
642    name: 'fit',
643    description: "Log reps toward today's goal",
644    argumentHint: '[n | snooze [min] | goal n | window hours | swap | streak | strict | easy | help]',
645    immediate: true,
646  })
647}
648
649export const register: Register = (on, options) => {
650  const isStrict = options.strict === true
651  const nudgeMs = Number(options.nudgeSeconds ?? 30) * 1000
652  // Whole reps only: a fractional set would make fractional buttons.
653  paceConfig.setSize = Math.max(0, Math.round(Number(options.setSize ?? 0)) || 0)
654  paceConfig.windowMs = Math.max(1, Number(options.windowHours ?? 8)) * HOUR_MS
655  progressConfig.isOn = options.progress === true
656  let timer: { cancel: () => void } | undefined
657
658  on('session.start', async ($, e, next) => {
659    await boot($)
660    return next(e)
661  })
662
663  // /clear and an in-session /resume switch to another conversation in the
664  // same process without another session.start, so the setup runs again here.
665  on('classic.SessionStart', async ($, e, next) => {
666    if (e.source === 'clear' || e.source === 'resume') await boot($)
667    return next(e)
668  })
669
670  on('command.run', { command: 'fit' }, async ($, e) => {
671    const cmd = parseFit(e.args)
672    switch (cmd.kind) {
673      case 'error':
674        return { text: cmd.text }
675      case 'add':
676      case 'set': {
677        if ((await refreshToday($)).isRest) return { text: "Today's a rest day. /fit rest off to train." }
678        const n = cmd.n
679        const t = await logReps($, count => (cmd.kind === 'add' ? count + n : n))
680        return { text: `${line(t)}${paceText(await read($, pace), isStrict, await $.clock.now())}` }
681      }
682      case 'skip': {
683        const t = await refreshToday($)
684        if (t.isRest) return { text: 'Already a rest day. /fit rest off to train.' }
685        // Reps logged means a training day: a rest day would wipe the streak.
686        if (t.count > 0) {
687          return { text: `You've logged ${t.count}${t.unit} ${t.exercise} today, so it's a training day. /fit rest is for a day off; it resets your streak.` }
688        }
689        await $.fs.write(`${(await files($)).log}/${t.date}.skip`, '')
690        await refreshToday($)
691        await refreshHistory($)
692        await refreshPace($)
693        return { text: `Rest day logged. Streak resets, no sets due today. Back at it tomorrow. (/fit rest off to undo)` }
694      }
695      case 'unskip':
696        return endRest($)
697      case 'week': {
698        if ((await $.ui.panes()).some(pane => pane.id === PANE)) {
699          await $.ui.close({ id: PANE })
700          return { text: 'Scoreboard closed.' }
701        }
702        const days = await refreshHistory($)
703        await $.ui.open({ id: PANE, title: 'TERMINAL GYM', focus: true, closeOnEscape: true })
704        return { text: `🔥 ${fullStreak(days, await read($, olderStreak))}-day streak · Esc or /fit streak to close` }
705      }
706      case 'swap': {
707        const before = await refreshToday($)
708        const { routine: routinePath, log: logDir } = await files($)
709        const routine = await loadRoutine($, routinePath)
710        const names = [...new Set(Object.values(routine).map(p => p.exercise))]
711        if (names.length === 0) return { text: 'Your program has no exercises. /fit program to pick one.' }
712        const plan = pickSwap(routine, before.exercise, cmd.exercise)
713        if (plan === undefined) {
714          return { text: `No ${cmd.exercise} in your program. Pick one of: ${names.join(', ')}.` }
715        }
716        if (plan.exercise === before.exercise) return { text: `Already on ${plan.exercise} today.` }
717        await $.fs.write(`${logDir}/${before.date}.swap`, `${JSON.stringify(plan)}\n`)
718        await refreshHistory($)
719        const amount = before.unit === '' ? `${before.count} reps` : `${before.count}${before.unit}`
720        const carried = before.count > 0 ? ` Your ${amount} carry over.` : ''
721        const swapped = await refreshToday($)
722        await refreshPace($)
723        return { text: `Swapped to ${plan.exercise} today.${carried} ${line(swapped)}` }
724      }
725      case 'goal': {
726        // Today's plan with a new goal, in the same file `/fit swap` writes.
727        const before = await refreshToday($)
728        if (before.isRest) return { text: "Today's a rest day. /fit rest off to train." }
729        const plan = { exercise: before.exercise, goal: cmd.n, ...(before.unit === '' ? {} : { unit: before.unit }) }
730        await $.fs.write(`${(await files($)).log}/${before.date}.swap`, `${JSON.stringify(plan)}\n`)
731        await refreshHistory($)
732        const after = await refreshToday($)
733        return { text: `Today's goal is ${cmd.n}${after.unit} ${after.exercise}. ${line(after)}${paceText(await reschedule($, before.date), isStrict, await $.clock.now())}` }
734      }
735      case 'window': {
736        const t = await refreshToday($)
737        if (cmd.hours === null) {
738          await writeDayState($, t.date, ({ window: _, ...rest }) => rest)
739          return {
740            text: `Back to ${paceConfig.windowMs / HOUR_MS}h from your first prompt. ${line(t)}${paceText(await reschedule($, t.date), isStrict, await $.clock.now())}`,
741          }
742        }
743        if (t.isRest) return { text: "Today's a rest day. /fit rest off to train." }
744        if (t.goal <= 0) return { text: 'No goal today. /fit goal 60 to set one.' }
745        if (t.count >= t.goal) return { text: `Today's goal is done. ${line(t)}` }
746        const now = await $.clock.now()
747        // Today ends at midnight: a window can't run into tomorrow's log. It ends a
748        // minute early so its last set comes due today, not on the stroke of midnight.
749        const d = new Date(now)
750        const midnight = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1).getTime()
751        const ms = Math.max(1, Math.min(cmd.hours * HOUR_MS, midnight - now - 60_000))
752        await writeDayState($, t.date, s => ({ ...s, window: { from: now, ms, base: t.count } }))
753        const span = ms < cmd.hours * HOUR_MS ? 'between now and midnight' : `over the next ${cmd.hours}h (done by ${clockTime(now + ms)})`
754        return {
755          text: `${t.goal - t.count}${t.unit} ${t.exercise} left, spread ${span}. ${line(t)}${paceText(await reschedule($, t.date), isStrict, await $.clock.now())}`,
756        }
757      }
758      case 'window-until': {
759        const t = await refreshToday($)
760        if (t.isRest) return { text: "Today's a rest day. /fit rest off to train." }
761        if (t.goal <= 0) return { text: 'No goal today. /fit goal 60 to set one.' }
762        if (t.count >= t.goal) return { text: `Today's goal is done. ${line(t)}` }
763        const now = await $.clock.now()
764        const d = new Date(now)
765        const end = new Date(d.getFullYear(), d.getMonth(), d.getDate(), cmd.hour, cmd.minute).getTime()
766        const named = `${String(cmd.hour).padStart(2, '0')}:${String(cmd.minute).padStart(2, '0')}`
767        if (end <= now) return { text: `${named} has already passed today. 3–4 digits are a clock time (1240 = 12:40); for hours from now, use 1–2 digits like /fit window 2.` }
768        // The same window `/fit window <hours>` sets, ending at the time named.
769        await writeDayState($, t.date, s => ({ ...s, window: { from: now, ms: end - now, base: t.count } }))
770        return {
771          text: `${t.goal - t.count}${t.unit} ${t.exercise} left, spread between now and ${named}. ${line(t)}${paceText(await reschedule($, t.date), isStrict, await $.clock.now())}`,
772        }
773      }
774      case 'snooze': {
775        // A breather with no reps logged: the set stays owed, prompts go through
776        // until the time is up. Once per due set and twice a day, so strict stays strict.
777        const p = await refreshPace($)
778        const t = await read($, today)
779        if (t === null || t.isRest) return { text: "Today's a rest day. Nothing to put off." }
780        if (t.goal > 0 && t.count >= t.goal) return { text: `Today's goal is done. ${line(t)}` }
781        if (p === null) return { text: 'Nothing is due yet. The day starts with your first prompt.' }
782        if (p.behind <= 0) {
783          return { text: p.nextDueAt === null ? 'Nothing is due.' : `Nothing is due until ${clockTime(p.nextDueAt)}. Put it off then.` }
784        }
785        if (p.restUntil !== null) {
786          return { text: `Already ${p.isPutOff === true ? 'put off' : 'resting'} until ${clockTime(p.restUntil)}. Log a set, even a short one, when it ends.` }
787        }
788        const day = await readDayState($, t.date)
789        if (day.putOff === p.required) {
790          return { text: `This set was already put off once. Log it, even a short one (/fit ${repSteps(p.setSize)[0] ?? p.setSize} earns a breather).` }
791        }
792        if ((day.laters ?? 0) >= SNOOZE.perDay) {
793          return { text: `That's ${SNOOZE.perDay} put off today already. Log a set, even a short one, or /fit easy stops holding prompts.` }
794        }
795        const until = (await $.clock.now()) + cmd.minutes * 60_000
796        await writeDayState($, t.date, s => ({ ...s, breather: until, laters: (s.laters ?? 0) + 1, putOff: p.required }))
797        return {
798          text: `${p.behind} ${t.exercise} put off until ${clockTime(until)}. ${line(t)}${paceText(await refreshPace($), isStrict, await $.clock.now())}`,
799        }
800      }
801      case 'program':
802        await openOnboarding($)
803        return { text: 'Pick your program.' }
804      case 'intro':
805        await $.store.delete('introduced')
806        await update($, isIntroduced, () => false)
807        return { text: 'Welcome is back above your prompt.' }
808      case 'reset':
809        return { text: `Reset. ${line(await logReps($, () => 0))}${paceText(await read($, pace), isStrict, await $.clock.now())}` }
810      case 'help':
811        await markIntroduced($)
812        await $.ui.open({ id: HELP_PANE, title: 'HELP' })
813        return { text: 'Help opened · /fit hide to close' }
814      case 'strict': {
815        const { deny } = await $.config.set({ key: 'terminal-gym.strict', value: cmd.isOn })
816        if (deny !== undefined) return { text: `Couldn't change strict mode: ${deny}` }
817        return {
818          text: cmd.isOn
819            ? `Coach is strict. Today's goal is spread into sets over ${paceConfig.windowMs / HOUR_MS}h from your first prompt; fall behind and prompts wait until you catch up.`
820            : 'Coach is easy. Same schedule on the band, nudges only, nothing held.',
821        }
822      }
823      case 'progress': {
824        const { deny } = await $.config.set({ key: 'terminal-gym.progress', value: cmd.isOn })
825        if (deny !== undefined) return { text: `Couldn't change progressive goals: ${deny}` }
826        return {
827          text: cmd.isOn
828            ? 'Progressive goals on. Hit a goal, and the next session of that exercise is about 5% more. Two short sessions in a row step it back.'
829            : 'Progressive goals off. Goals stay where they are now.',
830        }
831      }
832      case 'hide':
833        await $.ui.close({ id: PANE })
834        await $.ui.close({ id: HELP_PANE })
835        return { text: 'Terminal Gym panels closed.' }
836      case 'status': {
837        const t = await refreshToday($)
838        const shown = withStreak(t, await refreshHistory($), await read($, olderStreak))
839        return { text: `${shown}${paceText(await refreshPace($), isStrict, await $.clock.now())}` }
840      }
841      case 'reload': {
842        // Every session reads the same files, so a reload is a fresh read of them.
843        if (!(await syncFromDisk($, true))) return { text: "Couldn't read ~/.claude/fitness just now. Nothing changed; try again." }
844        const t = await read($, today)
845        if (t === null) return { text: 'Reloaded from disk.' }
846        const shown = withStreak(t, await read($, history), await read($, olderStreak))
847        return { text: `Reloaded from disk. ${shown}${paceText(await read($, pace), isStrict, await $.clock.now())}` }
848      }
849    }
850  })
851
852  on('prompt.submit', async ($, e, next) => {
853    // Only prompts the person typed count: background tasks, loops and other
854    // sessions start turns too. Slash commands (like /fit 10) always pass.
855    const isTyped = e.origin.kind === 'composer' && !e.text.trimStart().startsWith('/')
856    if (!isTyped) return next(e)
857    await startDay($)
858    const p = await refreshPace($)
859    const t = await read($, today)
860    // Claude Code puts a dropped prompt back in the box itself; a fill here
861    // as well left it there twice.
862    if (isStrict && p !== null && p.behind > 0 && p.restUntil === null) {
863      if (p.isOpening === true) {
864        return {
865          drop: `Start the day with a set: ${p.behind} ${t?.exercise ?? 'reps'}. /fit ${p.behind} to log it, then send your prompt. /fit rest skips the day (breaks streak).`,
866        }
867      }
868      return {
869        drop: `${p.behind} ${t?.exercise ?? 'reps'} due now (${p.required}/${t?.goal ?? 0} by now). /fit ${p.behind} to log it, then send your prompt. /fit snooze 30 puts it off; /fit easy stops holding prompts.`,
870      }
871    }
872    return next(e)
873  })
874
875  on('turn.start', async ($, e, next) => {
876    timer?.cancel()
877    if (!isStrict && options.nudges !== false) timer = $.clock.after(nudgeMs, () => void nudge($))
878    return next(e)
879  })
880
881  on('turn.complete', async ($, e, next) => {
882    if (e.agentId === undefined) {
883      timer?.cancel()
884      timer = undefined
885      await update($, isWaiting, () => false)
886      await refreshToday($)
887      await refreshPace($)
888    }
889    return next(e)
890  })
891
892  on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
893    const t = await read($, today)
894    if (options.spinner === false || t === null || !(await read($, isWaiting))) return next(e)
895    return next({ ...e, props: { ...e.props, message: `${nudgeReps} ${t.exercise} while Claude works` } })
896  })
897
898  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
899    const t = await read($, today)
900    if (options.band === false || e.props.hasSurvey || t === null) return next(e)
901
902    const { Box, Button, Text } = $.ui.resolve(e)
903
904    // Lay the band out in rows that fit, widest first: one line, then the
905    // header over the buttons, then every piece on its own line.
906    const cols = e.props.bodyColumns
907    const WORDMARK = MINI_BARBELL.small + MINI_BARBELL.plate + MINI_BARBELL.name + MINI_BARBELL.plateRight + MINI_BARBELL.small
908    const TAGLINE = 'Your agent put in the reps. You next.'
909    const BUTTONS_WIDTH = buttonsWidth(['Pick your training', 'Help', 'Just train'])
910    const HEADER_WIDTH = cells(WORDMARK) + 2 + cells(TAGLINE)
911
912    if (!(await read($, isIntroduced))) {
913      const buttons = (
914        <Box key="buttons" flexDirection={cols >= BUTTONS_WIDTH ? 'row' : 'column'}>
915          <Button key="setup" label="Pick your training" variant="primary" onPress={() => openOnboarding($)} />
916          {cols >= BUTTONS_WIDTH && <Text> </Text>}
917          <Button key="help" label="Help" onPress={() => $.ui.open({ id: HELP_PANE, title: 'HELP' })} />
918          {cols >= BUTTONS_WIDTH && <Text> </Text>}
919          <Button key="dismiss" label="Just train" onPress={() => markIntroduced($)} />
920        </Box>
921      )
922      const header = (
923        <Box key="header" flexDirection={cols >= HEADER_WIDTH ? 'row' : 'column'}>
924          {cols >= cells(WORDMARK) ? (
925            <Box>
926              <Text dimColor>{MINI_BARBELL.small}</Text>
927              <Text color="#d7af5f">{MINI_BARBELL.plate}</Text>
928              <Text bold>{MINI_BARBELL.name}</Text>
929              <Text color="#d7af5f">{MINI_BARBELL.plateRight}</Text>
930              <Text dimColor>{MINI_BARBELL.small}</Text>
931              {cols >= HEADER_WIDTH && <Text>  </Text>}
932            </Box>
933          ) : (
934            <Text bold wrap="truncate-end">
935              {MINI_BARBELL.name}
936            </Text>
937          )}
938          <Text dimColor wrap="truncate-end">{TAGLINE}</Text>
939        </Box>
940      )
941      const isOneLine = cols >= HEADER_WIDTH + 1 + BUTTONS_WIDTH
942      return (
943        <Box key="band" flexDirection={isOneLine ? 'row' : 'column'}>
944          {header}
945          {isOneLine && <Text> </Text>}
946          {buttons}
947        </Box>
948      )
949    }
950
951    // A rest day is deliberate, not a miss: no rep buttons, just a way back.
952    if (t.isRest) {
953      const REST = `😴 Rest day · ${t.exercise} back tomorrow`
954      const TRAIN = 'Train today'
955      return (
956        <Box key="rest" flexDirection={cols >= cells(REST) + 2 + buttonsWidth([TRAIN]) ? 'row' : 'column'}>
957          <Text dimColor wrap="truncate-end">
958            {REST}
959            {'  '}
960          </Text>
961          <Button key="train" label={TRAIN} onPress={() => endRest($)} />
962        </Box>
963      )
964    }
965
966    const days = await read($, history)
967    const color = progressColor(t.count, t.goal)
968    const add = (n: number) => () => void logReps($, count => count + n)
969    const progress = `${line(t)}${paceText(await read($, pace), isStrict, await $.clock.now())}`
970    const run = fullStreak(days, await read($, olderStreak))
971    const streakText = run > 0 ? `  🔥${run}d` : ''
972    const LOG_LABEL = 'log reps: '
973    // Buttons sized to today's set: a 300 goal's 30-rep sets get +10 +20 +30.
974    const steps = repSteps(setSizeFor(t.goal, paceConfig.setSize))
975    const logWidth = cells(LOG_LABEL) + buttonsWidth(steps.map(n => `+${n}`)) + cells(streakText)
976
977    return (
978      <Box key="tracker" flexDirection={cols >= cells(progress) + 2 + logWidth ? 'row' : 'column'}>
979        <Text color={color} dimColor={color === undefined} wrap="truncate-end">
980          {progress}
981          {'  '}
982        </Text>
983        <Box>
984          <Text dimColor>{LOG_LABEL}</Text>
985          {steps.map((n, i) => (
986            <Box key={`step${i}`}>
987              {i > 0 && <Text> </Text>}
988              <Button key={`add${n}`} label={`+${n}`} onPress={add(n)} />
989            </Box>
990          ))}
991          {streakText !== '' && <Text>{streakText}</Text>}
992        </Box>
993      </Box>
994    )
995  })
996
997  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
998    const days = await read($, history)
999    const run = fullStreak(days, await read($, olderStreak))
1000    const heat = heatCells(days)
1001    const week = days.slice(-7)
1002
1003    const { Box, Text } = $.ui.resolve(e)
1004    // The bar needs a monospace grid of BARBELL.width cells: the terminal's.
1005    // Elsewhere, or too narrow, the name alone.
1006    const barbell =
1007      e.surface === 'terminal' && e.props.bodyColumns >= BARBELL.width ? (
1008        <Box flexDirection="column">
1009          <Text>{BARBELL.plates}</Text>
1010          <Box>
1011            <Text>{BARBELL.left}</Text>
1012            <Text bold>{BARBELL.name}</Text>
1013            <Text>{BARBELL.right}</Text>
1014          </Box>
1015          <Text>{BARBELL.plates}</Text>
1016          <Text> </Text>
1017        </Box>
1018      ) : (
1019        <Text bold>{BARBELL.name}</Text>
1020      )
1021
1022    // One row a day: date, its progress bar in the band's colors, then the count.
1023    // Counts padded to one width so the exercise names line up.
1024    const counts = week.map(day => (day.isSkipped ? 'rest' : `${day.count}/${day.goal}`))
1025    const countWidth = Math.max(0, ...counts.map(count => count.length))
1026    const filled = (day: Day) => (day.goal > 0 ? Math.min(10, Math.floor((day.count / day.goal) * 10)) : 0)
1027    const summary = week.map((day, i) => {
1028      const mark = day.isSkipped ? '–' : day.goal > 0 && day.count >= day.goal ? '✓' : '·'
1029      const isToday = i === week.length - 1
1030      const color = day.isSkipped ? undefined : progressColor(day.count, day.goal)
1031      return (
1032        <Box key={`day-${day.date}`}>
1033          <Text dimColor={!isToday} bold={isToday}>{`${mark} ${day.date.slice(5)}  `}</Text>
1034          {/* Thin lines, not shaded blocks: blocks on stacked rows merge into slabs. */}
1035          <Text color={color ?? GRID_COLORS.none}>{'━'.repeat(day.isSkipped ? 0 : filled(day))}</Text>
1036          <Text dimColor>{(day.isSkipped ? '╌' : '─').repeat(10 - (day.isSkipped ? 0 : filled(day)))}</Text>
1037          <Text dimColor={!isToday} bold={isToday}>
1038            {`  ${(counts[i] ?? '').padEnd(countWidth)}  ${day.exercise}${isToday ? '  ◀ today' : ''}`}
1039          </Text>
1040        </Box>
1041      )
1042    })
1043
1044    if (e.surface === 'terminal') {
1045      const { Button, Raster } = $.ui.resolve(e)
1046      return (
1047        <Box flexDirection="column">
1048          {barbell}
1049          <Text bold>🔥 {run}-day streak</Text>
1050          <Text> </Text>
1051          {summary}
1052          <Text> </Text>
1053          <Text dimColor>last {HISTORY_DAYS / 7} weeks, a square a day</Text>
1054          <Raster key="heat" {...heat} />
1055          <Box>
1056            <Text color={GRID_COLORS.goal}>█ </Text>
1057            <Text dimColor>goal  </Text>
1058            <Text color={GRID_COLORS.some}>█ </Text>
1059            <Text dimColor>some reps  </Text>
1060            <Text color={GRID_COLORS.none}>█ </Text>
1061            <Text dimColor>none  ▒ today</Text>
1062          </Box>
1063          <Text> </Text>
1064          <Text dimColor>Esc or /fit streak to close</Text>
1065          <Button key="close" label="Close" onPress={() => closePane($, PANE)} />
1066        </Box>
1067      )
1068    }
1069
1070    const { Button } = $.ui.resolve(e)
1071    return (
1072      <Box flexDirection="column">
1073        {barbell}
1074        <Text bold>🔥 {run}-day streak</Text>
1075        {summary}
1076        <Button key="close" label="Close" onPress={() => closePane($, PANE)} />
1077      </Box>
1078    )
1079  })
1080
1081  on('ui.render', { component: 'Pane', requestId: HELP_PANE }, async ($, e) => {
1082    const { Box, Button, Markdown, Text } = $.ui.resolve(e)
1083    return (
1084      <Box flexDirection="column">
1085        <Markdown text={HELP} />
1086        <Text> </Text>
1087        <Box>
1088          <Button key="setup" label="Pick your training" variant="primary" onPress={() => openOnboarding($)} />
1089          <Text> </Text>
1090          <Button key="close" label="Close" onPress={() => closePane($, HELP_PANE)} />
1091        </Box>
1092      </Box>
1093    )
1094  })
1095
1096  on('ui.render', { component: 'Pane', requestId: ONBOARD_PANE }, async ($, e) => {
1097    const { Box, Button, Text } = $.ui.resolve(e)
1098    const step = await read($, onboardStep)
1099    const p = await read($, onboardPick)
1100    const go = (to: number) => async () => {
1101      // Custom goals must all be numbers before leaving the program step.
1102      if (step === 1 && to > step && p.program === CUSTOM && pickedRoutine(p) === undefined) {
1103        await update($, onboardPick, now => ({ ...now, isCustomInvalid: true }))
1104        return
1105      }
1106      await update($, onboardStep, () => to)
1107    }
1108    const choose = (patch: Partial<OnboardPick>) => () => void update($, onboardPick, now => ({ ...now, ...patch }))
1109    const dots = [0, 1, 2].map(i => (i === step ? '●' : '○')).join(' ')
1110
1111    const header = (title: string) => (
1112      <Box flexDirection="column">
1113        <Text dimColor>
1114          Step {step + 1} of 3 {dots}
1115        </Text>
1116        <Text bold>{title}</Text>
1117        <Text> </Text>
1118      </Box>
1119    )
1120
1121    const nav = (
1122      <Box>
1123        {step > 0 && <Button key="back" label="Back" onPress={go(step - 1)} />}
1124        {step > 0 && <Text> </Text>}
1125        {step < 2 ? (
1126          <Button key="next" label="Next" variant="primary" onPress={go(step + 1)} />
1127        ) : (
1128          <Button key="finish" label="Let's go" variant="primary" onPress={() => finishOnboarding($)} />
1129        )}
1130      </Box>
1131    )
1132
1133    if (step === 0) {
1134      return (
1135        <Box flexDirection="column">
1136          {header('Your agent works the code. You work the reps.')}
1137          <Text>Every day has a rep goal.</Text>
1138          <Text>When Claude runs a long turn, that's your cue for a set.</Text>
1139          <Text> </Text>
1140          <Text>Log reps two ways:</Text>
1141          <Text dimColor>  type /fit 20</Text>
1142          <Text dimColor>  or press a + button above your prompt</Text>
1143          <Text> </Text>
1144          {nav}
1145        </Box>
1146      )
1147    }
1148
1149    if (step === 1) {
1150      // The mobile app draws no Input, so Custom needs another surface there.
1151      const elements = $.ui.resolve(e)
1152      const Input = e.surface !== 'mobile' && 'Input' in elements ? elements.Input : undefined
1153      const programs = [...(p.hasRoutine ? [KEEP] : []), ...Object.keys(ROUTINES), ...(Input === undefined ? [] : [CUSTOM])]
1154      const routine = pickedRoutine(p)
1155      const isCustom = p.program === CUSTOM
1156      const setGoal = (exercise: string) => (value: string) =>
1157        void update($, onboardPick, now => ({ ...now, custom: { ...now.custom, [exercise]: value }, isCustomInvalid: false }))
1158      const fields = Input !== undefined && isCustom && (
1159        <Box flexDirection="column">
1160          <Text> </Text>
1161          <Text dimColor>Daily goal per exercise</Text>
1162          {Object.entries(exerciseGoals(p.base)).map(([exercise, goal]) => (
1163            <Input
1164              key={`goal-${exercise}`}
1165              label={`${exercise} `}
1166              placeholder={String(goal)}
1167              value={p.custom[exercise] ?? ''}
1168              submitLabel="set"
1169              onInput={setGoal(exercise)}
1170              onSubmit={setGoal(exercise)}
1171            />
1172          ))}
1173          {p.isCustomInvalid && <Text color="#d75f5f">Every goal needs a whole number above 0.</Text>}
1174        </Box>
1175      )
1176      return (
1177        <Box flexDirection="column">
1178          {header('Pick your program')}
1179          {programs.map((name, i) => (
1180            <Button
1181              key={`program-${i}`}
1182              label={`${name === p.program ? '●' : '○'} ${name}`}
1183              plain
1184              onPress={choose({ program: name })}
1185            />
1186          ))}
1187          {fields}
1188          {routine !== undefined && !isCustom && (
1189            <Box flexDirection="column">
1190              <Text> </Text>
1191              <Text dimColor>Goal size</Text>
1192              <Box>
1193                {Object.keys(SIZES).map(size => (
1194                  <Box>
1195                    <Button
1196                      key={`size-${size}`}
1197                      label={`${size === p.size ? '●' : '○'} ${size}`}
1198                      plain
1199                      onPress={choose({ size })}
1200                    />
hooks/lib.ts 450 lines
1import type { Day, Pace } from '../types'
2
3export type Routine = Record<string, { exercise: string; goal: number; unit?: string }>
4
5export const DEFAULT_ROUTINE: Routine = {
6  mon: { exercise: 'pushups', goal: 100 },
7  tue: { exercise: 'dips', goal: 100 },
8  wed: { exercise: 'squats', goal: 300 },
9  thu: { exercise: 'pushups', goal: 100 },
10  fri: { exercise: 'dips', goal: 100 },
11  sat: { exercise: 'squats', goal: 300 },
12  sun: { exercise: 'pushups', goal: 100 },
13}
14
15const WEEKDAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']
16const DAY_MS = 86_400_000
17
18const pad = (n: number) => String(n).padStart(2, '0')
19
20export const dayKey = (ms: number) => {
21  const d = new Date(ms)
22  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
23}
24
25export const weekdayKey = (ms: number) => WEEKDAYS[new Date(ms).getDay()] ?? 'sun'
26
27// Noon anchors keep day arithmetic clear of DST shifts.
28export const lastDays = (ms: number, n: number) => {
29  const d = new Date(ms)
30  const noon = new Date(d.getFullYear(), d.getMonth(), d.getDate(), 12).getTime()
31  return Array.from({ length: n }, (_, i) => noon - (n - 1 - i) * DAY_MS)
32}
33
34export const bar = (count: number, goal: number, width = 10) => {
35  const filled = goal > 0 ? Math.min(width, Math.floor((count / goal) * width)) : 0
36  return '▓'.repeat(filled) + '░'.repeat(width - filled)
37}
38
39export type FitCommand =
40  | { kind: 'status' }
41  | { kind: 'week' }
42  | { kind: 'skip' }
43  | { kind: 'unskip' }
44  | { kind: 'help' }
45  | { kind: 'hide' }
46  | { kind: 'reload' }
47  | { kind: 'reset' }
48  | { kind: 'intro' }
49  | { kind: 'program' }
50  | { kind: 'swap'; exercise?: string }
51  | { kind: 'strict'; isOn: boolean }
52  | { kind: 'progress'; isOn: boolean }
53  | { kind: 'add'; n: number }
54  | { kind: 'set'; n: number }
55  | { kind: 'goal'; n: number }
56  // null: back to the configured window from the first prompt.
57  | { kind: 'window'; hours: number | null }
58  | { kind: 'window-until'; hour: number; minute: number }
59  | { kind: 'snooze'; minutes: number }
60  | { kind: 'error'; text: string }
61
62// How long a set can be put off, and how often.
63export const SNOOZE = { defaultMinutes: 30, maxMinutes: 60, perDay: 2 } as const
64
65const USAGE = 'usage: /fit [<n> | set <n> | reset | goal <n> | window <hours>|<hhmm>|off | snooze [minutes] | swap [exercise] | rest [off] | streak | program | progress [off] | help | strict | easy | reload | start | hide]'
66
67export const parseFit = (args: string): FitCommand => {
68  const [head = '', value] = args.trim().split(/\s+/)
69  if (head === '' || head === 'status') return { kind: 'status' }
70  if (head === 'streak') return { kind: 'week' }
71  if (head === 'rest') return value === 'off' ? { kind: 'unskip' } : { kind: 'skip' }
72  if (head === 'program') return { kind: 'program' }
73  if (head === 'swap') {
74    // Names may be several words ("jumping jacks"): keep everything after "swap".
75    const name = args.trim().replace(/^swap\s*/, '').replace(/\s+/g, ' ').toLowerCase()
76    return name === '' ? { kind: 'swap' } : { kind: 'swap', exercise: name }
77  }
78  if (head === 'help' || head === 'rules') return { kind: 'help' }
79  if (head === 'hide') return { kind: 'hide' }
80  if (head === 'reload' || head === 'sync') return { kind: 'reload' }
81  if (head === 'reset') return { kind: 'reset' }
82  if (head === 'start') return { kind: 'intro' }
83  if (head === 'strict') return { kind: 'strict', isOn: value !== 'off' }
84  if (head === 'easy') return { kind: 'strict', isOn: false }
85  if (head === 'progress') return { kind: 'progress', isOn: value !== 'off' }
86  if (head === 'set') {
87    return value !== undefined && /^\d+$/.test(value)
88      ? { kind: 'set', n: Number(value) }
89      : { kind: 'error', text: 'fit: set needs a number' }
90  }
91  if (head === 'goal') {
92    return value !== undefined && /^\d+$/.test(value) && Number(value) > 0
93      ? { kind: 'goal', n: Number(value) }
94      : { kind: 'error', text: 'fit: goal needs a number of reps, like /fit goal 60' }
95  }
96  if (head === 'window') {
97    if (value === 'off') return { kind: 'window', hours: null }
98    // "1240", "940" or "12:40": an end time today, on the 24-hour clock.
99    const clock = value === undefined ? null : /^(\d{1,2}):?(\d{2})$/.exec(value)
100    if (clock !== null && (value?.includes(':') === true || (value?.length ?? 0) >= 3)) {
101      const hour = Number(clock[1])
102      const minute = Number(clock[2])
103      return hour < 24 && minute < 60
104        ? { kind: 'window-until', hour, minute }
105        : { kind: 'error', text: 'fit: window needs a time like 1240 or 12:40 (24-hour clock)' }
106    }
107    // "3", "1.5" or "3h": hours from now, up to a day.
108    const hours = value !== undefined && /^\d+(\.\d+)?h?$/.test(value) ? parseFloat(value) : NaN
109    return hours > 0 && hours <= 24
110      ? { kind: 'window', hours }
111      : { kind: 'error', text: 'fit: window needs hours from now (up to 24) like /fit window 3, an end time like 1240, or off' }
112  }
113  if (head === 'snooze' || head === 'later') {
114    // "30" or "30m": minutes from now, within the cap.
115    const minutes = value === undefined ? SNOOZE.defaultMinutes : /^\d+m?$/.test(value) ? parseInt(value, 10) : NaN
116    return minutes > 0 && minutes <= SNOOZE.maxMinutes
117      ? { kind: 'snooze', minutes }
118      : { kind: 'error', text: `fit: snooze takes minutes from now, up to ${SNOOZE.maxMinutes}, like /fit snooze 30` }
119  }
120  if (/^-?\d+$/.test(head)) return { kind: 'add', n: Number(head) }
121  return { kind: 'error', text: USAGE }
122}
123
124export const isDone = (day: Day) => !day.isSkipped && day.goal > 0 && day.count >= day.goal
125
126// Any reps keep a streak alive; only a day with none, or a rest day, breaks it.
127export const keepsStreak = (day: Day) => !day.isSkipped && day.count > 0
128
129// Today counts once it has reps; an empty today does not break the run yet,
130// but a rest day taken today does.
131export const streak = (history: readonly Day[]) => {
132  let run = 0
133  for (let i = history.length - 1; i >= 0; i--) {
134    const day = history[i]
135    if (day === undefined) break
136    if (keepsStreak(day)) run++
137    else if (i !== history.length - 1 || day.isSkipped) break
138  }
139  return run
140}
141
142// The engine environment has Uint8Array#toBase64; es2023 typings do not.
143type Base64Bytes = Uint8Array & { toBase64: () => string }
144
145const ACCENT = 0xc8a86b
146const PARTIAL = 0x6b5d3f
147const EMPTY = 0x343434
148const DEFAULT = 0x01000000
149
150// The streak, counting days older than the window when every day in it has reps.
151export const fullStreak = (history: readonly Day[], older: number) => {
152  const run = streak(history)
153  const last = history[history.length - 1]
154  const coversWindow = run === history.length || (run === history.length - 1 && last !== undefined && !keepsStreak(last) && !last.isSkipped)
155  return coversWindow ? run + older : run
156}
157
158// The grid's colors as text colors, for its legend.
159export const GRID_COLORS = {
160  goal: `#${ACCENT.toString(16)}`,
161  some: `#${PARTIAL.toString(16)}`,
162  none: `#${EMPTY.toString(16)}`,
163} as const
164
165// One row per week, seven 2-cell days with a gap: 20 columns. A blank row
166// between weeks keeps the days square, so it reads as a grid, not bars.
167export const heatCells = (history: readonly Day[]) => {
168  const weeks = Math.ceil(history.length / 7)
169  const columns = 20
170  const rows = Math.max(1, weeks * 2 - 1)
171  const words = new Uint32Array(columns * rows * 3)
172  for (let row = 0; row < rows; row++) {
173    const week = row / 2
174    for (let col = 0; col < columns; col++) {
175      const day = row % 2 === 1 ? undefined : history[week * 7 + Math.floor(col / 3)]
176      const isGap = col % 3 === 2 || day === undefined
177      const color = isGap
178        ? DEFAULT
179        : isDone(day)
180          ? ACCENT
181          : day.count > 0
182            ? PARTIAL
183            : EMPTY
184      const at = (row * columns + col) * 3
185      // Today, the last day, is drawn shaded so it stands out from finished days.
186      const isToday = row % 2 === 0 && week * 7 + Math.floor(col / 3) === history.length - 1
187      words[at] = isGap ? 0x20 : isToday ? 0x2592 : 0x2588
188      words[at + 1] = color
189      words[at + 2] = DEFAULT
190    }
191  }
192  return { columns, rows, cells: (new Uint8Array(words.buffer) as Base64Bytes).toBase64() }
193}
194
195// Grey until the first rep, then yellow on the way and green for the last fifth.
196// No red: an unfinished day is work in progress, not an error. No goal: undefined draws dim.
197export const progressColor = (count: number, goal: number) => {
198  if (goal <= 0 || count <= 0) return undefined
199  const share = count / goal
200  return share >= 0.8 ? '#87af87' : '#d7af5f'
201}
202
203export const daily = (exercise: string, goal: number): Routine =>
204  Object.fromEntries(WEEKDAYS.map(day => [day, { exercise, goal }]))
205
206export const ROUTINES = {
207  'Push · dip · squat rotation': DEFAULT_ROUTINE,
208  'Daily pushups': daily('pushups', 100),
209  'Daily squats': daily('squats', 200),
210} as const satisfies Record<string, Routine>
211
212export const SIZES = { Light: 0.5, Standard: 1, Heavy: 2 } as const satisfies Record<string, number>
213
214export const scale = (routine: Routine, factor: number): Routine =>
215  Object.fromEntries(
216    Object.entries(routine).map(([day, plan]) => [
217      day,
218      { ...plan, goal: Math.max(5, Math.round((plan.goal * factor) / 5) * 5) },
219    ]),
220  )
221
222// Each exercise in a routine once, with its first day's goal.
223export const exerciseGoals = (routine: Routine) => {
224  const goals: Record<string, number> = {}
225  for (const plan of Object.values(routine)) goals[plan.exercise] ??= plan.goal
226  return goals
227}
228
229// A custom program: the base routine's days, each exercise at the goal typed
230// for it. A field left at its prefill changes nothing, so days that differ keep
231// their own goals. Undefined while any goal isn't a whole number above zero.
232export const customRoutine = (base: Routine, goals: Record<string, string>): Routine | undefined => {
233  const parsed = new Map<string, number>()
234  for (const [exercise, prefill] of Object.entries(exerciseGoals(base))) {
235    const text = (goals[exercise] ?? '').trim()
236    if (!/^\d+$/.test(text) || Number(text) <= 0) return undefined
237    if (Number(text) !== prefill) parsed.set(exercise, Number(text))
238  }
239  return Object.fromEntries(
240    Object.entries(base).map(([day, plan]) => [day, { ...plan, goal: parsed.get(plan.exercise) ?? plan.goal }]),
241  )
242}
243
244// "30 burpees" typed under Other: one exercise every day.
245export const parseCustom = (text: string): Routine | undefined => {
246  const match = /^\s*(\d+)\s+([a-z][a-z -]*?)\s*$/i.exec(text)
247  if (match === null) return undefined
248  const [, goal = '0', exercise = ''] = match
249  return Number(goal) > 0 ? daily(exercise.toLowerCase(), Number(goal)) : undefined
250}
251
252// A goal's step: a twentieth (5%) in fives, at least 5.
253export const stepFor = (goal: number) => Math.max(5, Math.round(goal / 20 / 5) * 5)
254
255// Where an exercise's goal goes next, from its days before today, newest first.
256// Only days with reps count as sessions: rest days and empty days are passed
257// over. The last session must have been trained at `goal`, so a day with a goal
258// of its own (`/fit goal`) or one already counted moves nothing. A hit steps up;
259// two short sessions in a row step back. Undefined: the goal stays.
260export const nextGoal = (goal: number, past: readonly Day[]) => {
261  const [last, before] = past.filter(day => !day.isSkipped && day.count > 0)
262  if (last === undefined || goal <= 0 || last.goal !== goal) return undefined
263  if (last.count >= goal) return goal + stepFor(goal)
264  if (before === undefined || before.goal !== goal || before.count >= goal) return undefined
265  // Never below 5, and a goal already there stays.
266  const down = Math.max(5, goal - stepFor(goal))
267  return down < goal ? down : undefined
268}
269
270// Whether an exercise's goal can move: every routine day of it at one goal. A
271// routine that sets two goals for one exercise trades sessions between them,
272// so neither is the last session of the other.
273export const canProgress = (routine: Routine, exercise: string) =>
274  new Set(Object.values(routine).filter(plan => plan.exercise === exercise).map(plan => plan.goal)).size === 1
275
276// The routine with an exercise's goal moved: only the days at the old goal, so
277// days a custom program set apart keep theirs.
278export const moveGoal = (routine: Routine, exercise: string, from: number, to: number): Routine =>
279  Object.fromEntries(
280    Object.entries(routine).map(([day, plan]) => [
281      day,
282      plan.exercise === exercise && plan.goal === from ? { ...plan, goal: to } : plan,
283    ]),
284  )
285
286// Today's exercise, swapped: the next one in the routine, or the one named.
287export const pickSwap = (routine: Routine, current: string, wanted?: string) => {
288  const plans = [...new Map(Object.values(routine).map(plan => [plan.exercise, plan])).values()]
289  if (wanted !== undefined) return plans.find(plan => plan.exercise.toLowerCase() === wanted)
290  if (plans.length === 0) return undefined
291  const at = plans.findIndex(plan => plan.exercise === current)
292  return plans[(at + 1) % plans.length]
293}
294
295// The scoreboard's barbell, the name across the bar. 34 columns wide.
296export const BARBELL = {
297  plates: ' ▐█▌▐█▌                    ▐█▌▐█▌ ',
298  left: '━▐█▌▐█▌━━━ ',
299  name: 'TERMINAL GYM',
300  right: ' ━━━▐█▌▐█▌━',
301  width: 34,
302} as const
303
304// Terminal cells a string takes: emoji draw two cells wide.
305export const cells = (text: string) =>
306  [...text].reduce((w, ch) => w + ((ch.codePointAt(0) ?? 0) >= 0x1f000 || ch === '✅' ? 2 : 1), 0)
307
308// The terminal draws a Button as `[ label ]`, and a row puts one cell between buttons.
309export const buttonsWidth = (labels: readonly string[]) =>
310  labels.reduce((w, label) => w + cells(label) + 4, 0) + labels.length - 1
311
312// The band's one-line barbell wordmark.
313// Small plate, big plate, bar: ❚█═TERMINAL-GYM═█❚
314export const MINI_BARBELL = { small: '❚', plate: '█═', name: 'TERMINAL-GYM', plateRight: '═█' } as const
315
316// A set is a tenth of the goal, rounded to fives, unless the person picked a size.
317export const setSizeFor = (goal: number, setting: number) => {
318  if (goal <= 0) return 0
319  if (setting > 0) return Math.min(setting, goal)
320  return Math.min(goal, Math.max(5, Math.round(goal / 10 / 5) * 5))
321}
322
323// The band's quick-log buttons: a third, two thirds and a whole set, in fives
324// (tens from a 60-rep set); the last is the set exactly. A set too small for
325// three steps gets half, one and two, without repeats.
326export const repSteps = (setSize: number) => {
327  if (setSize <= 0) return [5, 10, 25]
328  const step = setSize >= 60 ? 10 : 5
329  const [third, twoThirds] = [1, 2].map(i => Math.round((setSize * i) / 3 / step) * step) as [number, number]
330  if (third > 0 && third < twoThirds && twoThirds < setSize) return [third, twoThirds, setSize]
331  return [...new Set([Math.ceil(setSize / 2), setSize, setSize * 2])]
332}
333
334// The goal as evenly spaced sets: the first due at the start, the last at the
335// end of the window. `required` is what should be done by `now`.
336const setGap = (goal: number, setSize: number, windowMs: number) => {
337  const sets = Math.ceil(goal / setSize)
338  return sets > 1 ? windowMs / (sets - 1) : windowMs
339}
340
341export const paceAt = (
342  goal: number,
343  count: number,
344  setSize: number,
345  startedAt: number,
346  now: number,
347  windowMs: number,
348): Pace => {
349  if (goal <= 0 || setSize <= 0) return { required: 0, behind: 0, setSize, nextDueAt: null, restUntil: null }
350  const sets = Math.ceil(goal / setSize)
351  const gap = setGap(goal, setSize, windowMs)
352  const due = Math.min(sets, 1 + Math.floor(Math.max(0, now - startedAt) / gap))
353  const required = Math.min(goal, due * setSize)
354  return {
355    required,
356    behind: Math.max(0, required - count),
357    setSize,
358    nextDueAt: due < sets ? startedAt + due * gap : null,
359    restUntil: null,
360  }
361}
362
363// Behind, a set logged (a short one counts) earns a breather of half the gap
364// between sets before the rest is due: catching up never means back-to-back sets.
365export const breatherMs = (goal: number, setSize: number, windowMs: number) =>
366  goal <= 0 || setSize <= 0 ? 0 : setGap(goal, setSize, windowMs) / 2
367
368// Fewer reps than the band's smallest button earn their share of the breather:
369// 2 of a 5-rep button, two fifths. A full button or more earns it all.
370export const earnedBreatherMs = (added: number, goal: number, setSize: number, windowMs: number) => {
371  if (added <= 0) return 0
372  const smallest = repSteps(setSize)[0] ?? setSize
373  return breatherMs(goal, setSize, windowMs) * Math.min(1, added / Math.max(1, smallest))
374}
375
376// Time left, rounded up to the minute: "23m", "1h", "1h 5m".
377export const untilText = (ms: number) => {
378  const minutes = Math.max(1, Math.ceil(ms / 60_000))
379  const h = Math.floor(minutes / 60)
380  const m = minutes % 60
381  return h === 0 ? `${m}m` : m === 0 ? `${h}h` : `${h}h ${m}m`
382}
383
384export const clockTime = (ms: number) => {
385  const d = new Date(ms)
386  return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
387}
388
389const CHEERS = ['Good set.', 'Strong set.', 'Reps in the bank.', 'Keep stacking.', 'Clean work.', "That's how it's built."]
390
391// The toast for a logged set short of the goal. The line turns with the set's
392// number, not the rep count: sets come in fives, so a count like 30, 60, 90
393// would land on one line every time.
394export const cheer = (added: number, count: number, goal: number, exercise: string, unit = '') => {
395  const line = CHEERS[Math.floor(count / Math.max(1, added)) % CHEERS.length] ?? CHEERS[0]
396  const left = goal > count ? ` ${goal - count}${unit} to go.` : ''
397  return `💪 +${added}${unit} ${exercise}. ${line}${left}`
398}
399
400export const describeRoutine = (routine: Routine) =>
401  [...new Set(Object.values(routine).map(p => `${p.goal}${p.unit ?? ''} ${p.exercise}`))].join(' / ')
402
403export const HELP = `## Help
404
405**Your agent put in the reps. You next.**
406When a turn runs long, drop and do a set.
407
408### Log a set
409\`/fit 20\` adds 20 reps
410or press a **+** button above the prompt (sized to your set)
411
412### Commands
413| Command | Does |
414|---|---|
415| \`/fit\` | today's progress |
416| \`/fit set 80\` | fix today's count |
417| \`/fit reset\` | today back to 0 |
418| \`/fit goal 60\` | change today's goal |
419| \`/fit window 3\` | finish today in the next 3h |
420| \`/fit snooze 30\` | put the due set off 30 min (twice a day) |
421| \`/fit swap\` | switch today's exercise |
422| \`/fit rest\` | rest day, before any reps (breaks streak) |
423| \`/fit rest off\` | undo today's rest day |
424| \`/fit streak\` | streak + grid |
425| \`/fit program\` | pick your training |
426| \`/fit progress\` | hit a goal, the next session of it goes up 5% (\`off\` to stop) |
427| \`/fit strict\` / \`/fit easy\` | strict mode on / off |
428| \`/fit help\` | this list |
429| \`/fit reload\` | re-read the log now (other sessions sync every 10s anyway) |
430| \`/fit start\` | replay the welcome |
431| \`/fit hide\` | close panels |
432
433### Strict mode
434Off by default. When it's on:
435- today's goal is split into sets, spread over 8 hours (by default) from your first prompt
436- \`/fit window 3\` spreads what's left over the next 3 hours instead (ending by midnight)
437- prompts before 5am count as the night before
438- the first set is due right away
439- fall behind and your prompts wait until you catch up
440- log a set, even a short one, and you get a breather before the rest (a few reps buy a shorter one)
441- just eaten? \`/fit snooze 30\` puts the due set off, once per set and twice a day
442- a toast tells you when each set comes due
443- \`/fit easy\` stops holding prompts; \`/fit rest\` (before any reps) takes the day off
444
445**Turn it on:** type \`/fit strict\`
446**Turn it off:** type \`/fit easy\`
447
448### Your data
449Stays on this machine, in \`~/.claude/fitness\`.`
450
types/index.d.ts 56 lines
1export type Today = {
2  date: string
3  exercise: string
4  goal: number
5  unit: string
6  count: number
7  isRest: boolean
8}
9
10export type Day = {
11  date: string
12  count: number
13  goal: number
14  exercise: string
15  isSkipped: boolean
16}
17
18export type OnboardPick = {
19  program: string
20  size: string
21  hasRoutine: boolean
22  // Custom: the routine whose days it keeps, and each exercise's goal as typed.
23  base: Record<string, { exercise: string; goal: number; unit?: string }>
24  custom: Record<string, string>
25  isCustomInvalid: boolean
26}
27
28// Where today stands against the schedule of sets.
29export type Pace = {
30  required: number
31  behind: number
32  setSize: number
33  nextDueAt: number | null
34  // While a breather runs, catch-up reps are owed but prompts are not held.
35  restUntil: number | null
36  // The day's first set, before any reps: an opener, not a debt.
37  isOpening?: boolean
38  // The breather is a `/fit snooze`: the set was put off, not partly done.
39  isPutOff?: boolean
40}
41
42declare module 'claude-code' {
43  interface PluginState {
44    'terminal-gym': {
45      today: Today | null
46      pace: Pace | null
47      isWaiting: boolean
48      isIntroduced: boolean
49      onboardStep: number
50      onboardPick: OnboardPick
51      history: Day[]
52      olderStreak: number
53    }
54  }
55}
56