diff --git a/.env.example b/.env.example index dc9f839..c63b767 100644 --- a/.env.example +++ b/.env.example @@ -64,6 +64,14 @@ FAST_TIER_ENABLED=false # Lower is faster and cheaper with less deep thinking. Default medium. REASONING_EFFORT=medium +# On long runs, show one short status message ("Checking your training log...") +# that is edited in place and removed when the reply lands. Set false to disable. +PROGRESS_UPDATES=true + +# Let the host refresh the Dashboard data tiles after a run that logged rows, +# instead of the agent doing it before it replies. Set false to disable. +HOST_DASHBOARD_SYNC=true + # ── Storage paths ───────────────────────────────────────────────────── # Local defaults work out of the box. In Docker these point at a mounted volume. SESSION_FILE=./data/sessions.json diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..5a04c6f --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +# Shell scripts must stay LF: a CRLF entrypoint.sh will not start in the container. +*.sh text eol=lf diff --git a/CLAUDE.md b/CLAUDE.md index 60e55bd..2efdcad 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -82,19 +82,19 @@ The user can dump raw training programs and reference material into the repo's ` Always read recent log rows and current goals before recommending or planning, so your advice reflects what they have actually been doing. After a session is logged, a recommendation given, or a plan built, write it back to Notion so nothing is lost. If the workspace does not exist yet, run the setup-notion skill first. If Notion is not configured (no token), say so plainly and offer to coach without persistence for now. -When answering any question about past lifts, sessions, or training history, always fetch the full page body (blocks) of the relevant Workout Log entries, not just the database row properties. The blocks contain the actual sets, reps, weights, and notes; the properties hold only the summary. Pull the blocks with `node scripts/notion.ts get-page-blocks `, then explain in chat what concretely happened in that session (exercises done, loads used, key notes), rather than only reporting top-level fields. +When answering any question about past lifts, sessions, or training history, always fetch the full page body (blocks) of the relevant Workout Log entries, not just the database row properties. The blocks contain the actual sets, reps, weights, and notes; the properties hold only the summary. Pull them in one call: `node scripts/notion.ts query-recent --db "Workout Log" --limit 3 --with-blocks` returns recent rows with their bodies, and `node scripts/notion.ts get-page-blocks ...` reads specific pages (every `query-recent` row ends with its `id:`). Then explain in chat what concretely happened in that session (exercises done, loads used, key notes), rather than only reporting top-level fields. -All Notion work goes through the bundled helper `scripts/notion.ts` (run via Bash), which wraps the REST API: `log` to add a Workout Log row, `query-recent` to pull the last sessions, `append` to write rich blocks (headings, callouts, dividers, tables, columns, with inline **bold**, _italic_, `code`, and [links](url) rendered as rich text), `create-page` to add a child page, `refresh-tile` to update a Dashboard tile, and `resolve-db` to resolve and cache a database id. The helper retries automatically on Notion's rate limit, and its id cache self-heals if a database is deleted and recreated. The notion-formatting and log-workout skills show the exact commands. Note: Notion's public API cannot configure database views, so default views are still set by hand once. +All Notion work goes through the bundled helper `scripts/notion.ts` (run via Bash), which wraps the REST API: `log` to add a Workout Log row, `query-recent` to pull the last sessions, `get-page-blocks` to read page bodies, `append` to write rich blocks (headings, callouts, dividers, tables, columns, with inline **bold**, _italic_, `code`, and [links](url) rendered as rich text), `create-page` to add a child page, `refresh-tile` to update a Dashboard tile, and `resolve-db` to resolve and cache a database id (`node scripts/notion.ts --help` lists every command). The helper retries automatically on Notion's rate limit, and its id cache self-heals if a database is deleted and recreated. Run it from the project root as `node scripts/notion.ts ...` (no `cd /data`), and pass several page ids to one `get-page-blocks` call rather than one call per page. The notion-formatting and log-workout skills show the exact commands. Note: Notion's public API cannot configure database views, so default views are still set by hand once. ### Keep the Dashboard current -The Dashboard page is a live snapshot and summary of what is happening: current program and week, active goals, this week's training, latest body stats, and the next session. It also doubles as the central index of the workspace: keep a small, tasteful set of links near the top to the key pages and databases (Programs, Goals, Body Stats, Workout Log, Knowledge Base) so the user can jump anywhere from one place. Keep that index compact (a single linked row or a small callout), never a cluttered wall of links. Treat the whole page as something you keep in sync, not a one-off build. Whenever you change the underlying data, refresh the affected tile in the same turn, before you reply, so the Dashboard never goes stale: +The Dashboard page is a live snapshot and summary of what is happening: current program and week, active goals, this week's training, latest body stats, and the next session. It also doubles as the central index of the workspace: keep a small, tasteful set of links near the top to the key pages and databases (Programs, Goals, Body Stats, Workout Log, Knowledge Base) so the user can jump anywhere from one place. Keep that index compact (a single linked row or a small callout), never a cluttered wall of links. Treat the whole page as something you keep in sync, not a one-off build. Whenever you change the underlying data, refresh the affected tile in the same turn, before you reply, so the Dashboard never goes stale (the three data tiles are the exception, see the first point): -- Logged a session, changed a goal, or logged body weight or measurements: run `node scripts/notion.ts sync-dashboard` once. It re-derives the `thisWeek`, `goals`, and `bodyStats` tiles straight from the databases (counts and values come from queries, never hand-typed), so it is the preferred, fabrication-proof way to keep those three tiles current. Pass `--now ` (the date from the Telegram header) so "this week" is correct in the user's timezone. +- Logged a session, changed a goal, or logged body weight or measurements with the helper's `log` command: do not run `sync-dashboard` yourself (unless the `[context]` line says "host Dashboard sync is off", then run it once yourself). The host runs it right after your reply, re-deriving the `thisWeek`, `goals`, and `bodyStats` tiles straight from the databases (counts and values come from queries, never hand-typed), so the user gets their reply without waiting on it. Only if you changed those rows some other way (not through `log`), run `node scripts/notion.ts sync-dashboard --now ` once yourself, with the date from the Telegram header. - Changed the program, started a new week, or anything that touches the hero (program, week, dates): rebuild the relevant tile, or rebuild the whole Dashboard if several tiles are affected at once (`node scripts/setup-workspace.ts --rebuild-dashboard`). - The prose tiles (Next Session, Active Program, Nutrition) are yours to maintain with the same care a person would give their own board. Update them when the conversation gives you the material, without being asked: recommended or planned a session, refresh Next Session; agreed macros or nutrition targets, refresh Nutrition; program or focus shifted, refresh Active Program. Likewise, if you happen to read the Dashboard and a tile is visibly stale against what you know (Next Session shows a workout that was already logged, the hero shows last week), fix it in the same turn. -For one-off or prose tiles use `scripts/notion.ts refresh-tile --tile ` with tile ids resolved from `data/notion-ids.json` (`__dashboard.columns`); for the three data tiles prefer `sync-dashboard`. Never edit blocks in place; replace the whole tile (both commands do). The notion-formatting skill has the commands and the recommended tile content. If no Dashboard exists yet, run setup-notion. Do not announce the Dashboard update to the user unless they ask; just keep it accurate. +For one-off or prose tiles use `scripts/notion.ts refresh-tile --tile ` with tile ids resolved from `data/notion-ids.json` (`__dashboard.columns`); never hand-write the three data tiles, `sync-dashboard` owns them. Never edit blocks in place; replace the whole tile (both commands do). The notion-formatting skill has the commands and the recommended tile content. If no Dashboard exists yet, run setup-notion. Do not announce the Dashboard update to the user unless they ask; just keep it accurate. ## Workflow diff --git a/Dockerfile b/Dockerfile index 5ce50d5..180a1a0 100644 --- a/Dockerfile +++ b/Dockerfile @@ -57,6 +57,13 @@ RUN chmod +x entrypoint.sh # harmlessly (agent treats PERSONAL.md as missing) when the volume has no copy. RUN ln -sf /data/PERSONAL.md /app/PERSONAL.md +# One canonical data dir: /app/data (what the scripts and the app resolve, as +# ./data does locally) points into the volume, so caches like notion-ids.json +# survive restarts. It targets /data/data, not /data, because earlier deploys +# already wrote their newest caches there. entrypoint.sh creates it on a fresh +# volume, since a mount hides anything built into the image under /data. +RUN ln -sfn /data/data /app/data + # /data is the mountpoint for the persistent volume (sessions + schedule). RUN chown -R node:node /app/dist /app/node_modules /app/package.json /app/entrypoint.sh && \ mkdir -p /home/node/.claude && chown -R node:node /home/node && \ diff --git a/coach-plugin/skills/log-workout/SKILL.md b/coach-plugin/skills/log-workout/SKILL.md index 9ec2eba..c2857b5 100644 --- a/coach-plugin/skills/log-workout/SKILL.md +++ b/coach-plugin/skills/log-workout/SKILL.md @@ -70,12 +70,11 @@ If the user flags an injury or pain while logging (not normal training soreness) ## 3. Keep the Dashboard current -Do both of these in the same turn, before replying: +Do not run `sync-dashboard` yourself: after a `log` write the host re-derives the This Week, Goals, and Body Stats tiles right after your reply. The one exception: if the `[context]` line says "host Dashboard sync is off", run it once yourself after logging. -1. Run `node scripts/notion.ts sync-dashboard --now ` to re-derive the This Week, Goals, and Body Stats tiles from the databases. -2. Refresh the **Next Session** tile. The session just logged is no longer "next": work out what actually comes next from the weekly plan (or the active program's schedule) and rewrite the tile with `node scripts/notion.ts refresh-tile` (tile ids in `data/notion-ids.json` under `__dashboard.columns`; content format in the notion-formatting skill). If no plan tells you what is next, put a short honest placeholder ("Next session not planned yet, ask me to plan the week") rather than leaving the completed session showing. +In the same turn, before replying, refresh the **Next Session** tile. The session just logged is no longer "next": work out what actually comes next from the weekly plan (or the active program's schedule) and rewrite the tile with `node scripts/notion.ts refresh-tile` (tile ids in `data/notion-ids.json` under `__dashboard.columns`; content format in the notion-formatting skill). If no plan tells you what is next, put a short honest placeholder ("Next session not planned yet, ask me to plan the week") rather than leaving the completed session showing. -`sync-dashboard` alone is not enough: it does not touch the prose tiles, and a Next Session tile still showing the workout that was just logged is exactly the staleness to avoid. +The host sync does not touch the prose tiles, and a Next Session tile still showing the workout that was just logged is exactly the staleness to avoid. ## 4. Confirm and encourage diff --git a/coach-plugin/skills/notion-formatting/SKILL.md b/coach-plugin/skills/notion-formatting/SKILL.md index b17890b..ff37d5b 100644 --- a/coach-plugin/skills/notion-formatting/SKILL.md +++ b/coach-plugin/skills/notion-formatting/SKILL.md @@ -70,14 +70,12 @@ Note: Notion's public API cannot create or configure database *views* (grouping, If the workspace has a Dashboard page (built by setup-notion), keep its tiles current after you change the underlying data, so the user never has to ask. -**Preferred for the three data tiles (This Week, Goals, Body Stats):** run one command. +**The three data tiles (This Week, Goals, Body Stats)** come from `sync-dashboard`, which re-derives them directly from the databases (session counts, goal progress, latest body stats), so the numbers are always consistent with the data and never hand-typed. After you log a session, a goal, or body stats with the helper's `log` command, the host runs it for you right after your reply, so do not run it yourself. Run it once yourself only if you changed those rows some other way, or if the `[context]` line says "host Dashboard sync is off": ```bash node scripts/notion.ts sync-dashboard --now 2026-06-30 # --now is the date from the Telegram header ``` -`sync-dashboard` re-derives all three tiles directly from the databases (session counts, goal progress, latest body stats), so the numbers are always consistent with the data and never hand-typed. Run it after logging a session, changing a goal, or logging body stats. - For one-off or prose tiles, `refresh-tile` replaces a single tile from your own markdown (never edit blocks in place; their ids shift). Tile ids are cached in `data/notion-ids.json` and self-heal from the live page, so refer to tiles by name: `thisWeek`, `goals`, `bodyStats`, `nextSession`, `activeProgram`, `nutrition`, `quickCommands`. ```bash diff --git a/coach-plugin/skills/progress-report/SKILL.md b/coach-plugin/skills/progress-report/SKILL.md index ae3e4df..865c2a2 100644 --- a/coach-plugin/skills/progress-report/SKILL.md +++ b/coach-plugin/skills/progress-report/SKILL.md @@ -10,7 +10,7 @@ Turn the Notion Workout Log into an honest, motivating read on how the user is d ## 1. Pull the data - Decide the window from the request (this week, last month, or a sensible default like the last 4 weeks). -- Query the Notion Workout Log with `node scripts/notion.ts query-recent --db "Workout Log"` for sessions in that window. Read current Goals and `PERSONAL.md` for what success looks like. +- Query the Notion Workout Log with `node scripts/notion.ts query-recent --db "Workout Log"` for sessions in that window (add `--with-blocks` to get each session's sets and loads in the same call). Read current Goals and `PERSONAL.md` for what success looks like. ## 2. Analyse diff --git a/coach-plugin/skills/recommend-workout/SKILL.md b/coach-plugin/skills/recommend-workout/SKILL.md index 14b54e8..1378c1c 100644 --- a/coach-plugin/skills/recommend-workout/SKILL.md +++ b/coach-plugin/skills/recommend-workout/SKILL.md @@ -20,8 +20,8 @@ On the first message of a new conversation, check that `PERSONAL.md` has real go ```bash # Last 3 sessions overall, or for a specific Focus you are about to train - node scripts/notion.ts query-recent --db "Workout Log" --limit 3 - node scripts/notion.ts query-recent --db "Workout Log" --focus Push --limit 3 + node scripts/notion.ts query-recent --db "Workout Log" --limit 3 --with-blocks + node scripts/notion.ts query-recent --db "Workout Log" --focus Push --limit 3 --with-blocks ``` Use the returned loads and RPE as the reference point for today's prescription. The helper is one call and already sorted by date. Check the current week's plan if one exists. diff --git a/coach-plugin/skills/setup-notion/SKILL.md b/coach-plugin/skills/setup-notion/SKILL.md index 247df01..59c7f08 100644 --- a/coach-plugin/skills/setup-notion/SKILL.md +++ b/coach-plugin/skills/setup-notion/SKILL.md @@ -40,8 +40,9 @@ read it if you need to extend the workspace. ## 3. Seed goals and confirm If `PERSONAL.md` lists real goals, offer to add them to the Goals database (ask -before writing), and refresh the Dashboard Goals tile afterwards (see the -notion-formatting skill). Then confirm what now exists and tell the user they can +before writing). Goals added with the helper's `log` command reach the Dashboard +Goals tile on their own: the host syncs it right after your reply, unless the +`[context]` line says host Dashboard sync is off (see the notion-formatting skill). Then confirm what now exists and tell the user they can log workouts in plain language and ask for plans, recommendations, and progress. ## Note on views diff --git a/docs/architecture.md b/docs/architecture.md index 2c912b4..d7d74f7 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -13,7 +13,11 @@ grammy bot (src/index.ts) ── allowlist, dedupe, attachments, ├─ voice note ─► local Whisper (src/media/transcribe.ts) ─► text │ ▼ +chat queue (src/channel/chat-queue.ts) ── one turn at a time per chat; messages that + │ wait behind a turn are merged into the next + ▼ runAgent (src/agent/runner.ts) ── Claude Agent SDK query() + │ • tool activity ─► status message (src/channel/progress.ts), long runs only │ • persona overlay (src/agent/personalities.ts) │ • session resume (src/agent/sessions.ts) │ • CLAUDE.md persona + coach-plugin skills @@ -38,12 +42,44 @@ generic while the running agent is personalised to you. | `src/index.ts` | Entry point and composition root: wires the bot, scheduler, and HTTP servers. | | `src/config.ts` | Central env-driven configuration. | | `src/agent/` | The agent loop (`runner.ts`), persona overlays (`personalities.ts`), and per-chat session store (`sessions.ts`). | -| `src/channel/` | Telegram transport: `notify.ts` (send), `format.ts` (markdown→HTML, em-dash strip), `webhook-server.ts`, `permissions.ts` (allowlist). | +| `src/channel/` | Telegram transport: `notify.ts` (send), `format.ts` (markdown→HTML, em-dash strip), `webhook-server.ts`, `permissions.ts` (allowlist), `chat-queue.ts` (per-chat serialisation and message coalescing), `progress.ts` (the status message shown during long runs). | | `src/media/` | Inbound media: `attachments.ts` (images/PDFs → content blocks), `transcribe.ts` (voice notes → text). | | `src/notion/` | `status.ts` reports whether Notion is configured (a `NOTION_TOKEN` is set). All Notion I/O goes through `scripts/notion.ts` via Bash. | | `src/scheduler/` | `scheduler.ts` (croner reminders) and `server.ts` (the localhost control plane). | | `src/util/` | `redact.ts` (secret scrubbing) and `dedupe.ts` (webhook idempotency). | +## Concurrency and progress + +Chat messages for the same chat never run in parallel. Two overlapping runs would +either start two Claude sessions (each redoing onboarding) or race to resume the +same one. Every +inbound message takes its place in the chat's queue on arrival, before attachments +download or a voice note is transcribed, so arrival order holds even when one +message prepares slowly. Messages that pile up behind a running turn are handed to +the next turn together, joined in order with their attachments, so three quick +messages cost one extra run rather than three. When merged messages carry photos +or PDFs, each text is tagged with its attachment numbers ("lunch (attachment 2)") +so a caption stays with its photo; an album counts as one message. `/new` waits +its turn in the same queue. Different chats run in parallel, up to a global cap of +two agent processes for chat messages. Scheduled reminders go through the +same per-chat queue, so a reminder never runs alongside a message for its chat; +they sit outside the global cap. + +There is no overall time limit on a run, so a run that never returns holds up its +chat's queue, `/new` included, until the instance restarts or scales to zero. +Other chats are unaffected. This is accepted for now: Bash calls have their own +tool timeout and a run stops after at most 60 turns, so a true hang is unlikely. + +The Telegram handler does not wait for the run, so in polling mode one long turn no +longer holds up updates for other chats. + +While a run is going, the runner reports each tool call. If the run passes about +9 seconds, the chat gets one silent status message ("Checking your training +log...", "Writing it up in Notion...") that is edited in place as the phase +changes, at most once every few seconds, and deleted when the reply arrives. The +labels come from a fixed table and never include the command. Set +`PROGRESS_UPDATES=false` to turn this off. + ## Bundled scripts `scripts/` holds Node CLIs the agent calls via Bash (the "bundled-CLI" pattern), @@ -51,7 +87,7 @@ plus deploy helpers: | Script | Purpose | |---|---| -| `scripts/notion.ts` | Notion REST helper: `log`, `query-recent`, `append` (rich blocks + columns + inline formatting), `create-page`, `refresh-tile`, `resolve-db`. Retries on rate limits; self-heals a stale id cache. Unit-tested by `scripts/notion.test.ts` (`npm test`). | +| `scripts/notion.ts` | Notion REST helper: `log`, `query-recent` (`--with-blocks` adds each row's page body), `get-page-blocks`, `resolve-workspace`, `append` (rich blocks + columns + inline formatting), `create-page`, `refresh-tile`, `resolve-db`. Retries on rate limits; self-heals a stale id cache. Unit-tested by `scripts/notion.test.ts` (`npm test`). | | `scripts/setup-workspace.ts` | Idempotent builder for the full Notion workspace (databases + Dashboard). See [notion-architecture.md](./notion-architecture.md). | | `scripts/exercise-db.ts` | Queries the free, keyless exercise dataset (see [capabilities.md](./capabilities.md)). | | `scripts/deploy-cloudrun.sh` | Google Cloud Run deploy (see [deployment.md](./deployment.md)). | diff --git a/docs/configuration.md b/docs/configuration.md index d4125fe..18405b4 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -52,6 +52,8 @@ After setting the client id and secret, authorise once with | `CLAUDE_MODEL_FAST` | `claude-haiku-4-5` | Cheaper model used for trivial logging messages, only when `FAST_TIER_ENABLED=true`. | | `FAST_TIER_ENABLED` | `false` | When `true`, short transactional logging messages on new chats route to `CLAUDE_MODEL_FAST` to save subscription usage. Off by default so every message uses `CLAUDE_MODEL` for consistent behaviour. | | `REASONING_EFFORT` | `medium` | Thinking depth for the standard model: `low \| medium \| high \| xhigh \| max`. Lower is faster and cheaper. | +| `PROGRESS_UPDATES` | `true` | On runs that take more than a few seconds, post one short status message ("Logging your session...") that is edited as the run moves on and removed when the reply lands. Quick runs show nothing. `false` (or `0`, `off`, `no`) disables it. | +| `HOST_DASHBOARD_SYNC` | `true` | After a run that logged rows with the Notion helper's `log` command, the host runs `scripts/notion.ts sync-dashboard` in the background once the reply is sent, instead of the agent doing it inside its turn (which added 9 to 17 seconds to every logging reply). Overlapping syncs are collapsed into one. `false` (or `0`, `off`, `no`) hands the job back to the agent: the session context then tells it to run the sync itself. See [observability.md](./observability.md#host-dashboard-sync). | | `PERSONALITIES_ENABLED` | `true` | Persona overlays (owner gets Arnold, others a stable random character). `false` keeps everyone on the plain coach. See [customization.md](./customization.md). | ## Storage diff --git a/docs/deployment.md b/docs/deployment.md index 1db8ae2..969b456 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -21,6 +21,31 @@ docker run -d --name fitcoach --env-file .env -v fitcoach-data:/data -p 8080:808 `/data` holds sessions, the schedule, and the Notion id cache; mount it as a volume so they survive restarts. `/healthz` on port 8080 reports health. +### Where the data directory lives + +There is one data directory, `data/` next to `scripts/`. Locally that is +`./data`. In the image, `/app/data` is a symlink to `/data/data` on the volume, +and `entrypoint.sh` creates `/data/data` at startup (the mount hides anything +built into the image). So the bundled scripts, the app, and the agent all see +the same `notion-ids.json`, `google-token.json` and `exercises.json` from the +default working directory `/app`. The scripts resolve `data/` from their own +location, not the working directory, so running them from somewhere else +still finds the same cache. + +It is `/data/data` rather than the volume root because that is where earlier +versions wrote their newest caches, so an existing volume keeps them with no +migration. If a volume only has a copy at the root (for example +`/data/notion-ids.json`), the entrypoint copies it into `/data/data` once +without overwriting anything. Leftover copies at the root are unused and +safe to delete. Sessions and the schedule stay at `/data/sessions.json` and +`/data/schedule.json` (`SESSION_FILE`, `SCHEDULE_FILE`). + +The app's own `./data` defaults land there too: the run log +(`agent-runs.jsonl`, which `/stats` reads; set `RUN_LOG_FILE` to move it) and +the Google token. Before this the container could not write `/app/data`, so +expect the run log to start growing in the bucket and calendar status to report +"configured" once a token is present there. + > Only one instance may poll a given bot token at a time. If you also run it > locally while a deployed copy is up, Telegram returns a 409 conflict. Stop one, > or use a separate bot token for local development. diff --git a/docs/notion-architecture.md b/docs/notion-architecture.md index f83f956..9563b3d 100644 --- a/docs/notion-architecture.md +++ b/docs/notion-architecture.md @@ -8,7 +8,10 @@ by `scripts/setup-workspace.ts` and maintained through `scripts/notion.ts`. Instance-specific ids (Hub, each database, the Dashboard page, and its column ids) are **not hardcoded** anywhere in the repo. They are discovered at build time and cached in `data/notion-ids.json` (gitignored). Resolve ids from that -cache or by name lookup, never from a literal in code. +cache or by name lookup, never from a literal in code. The scripts resolve +`data/` from their own location, not the working directory, so the cache is the +same file wherever they are run from (in the container it lives on the volume, +see [deployment.md](./deployment.md#where-the-data-directory-lives)). ## Build order (strict) @@ -45,6 +48,17 @@ databases/pages are detected by title and reused, never duplicated). Add `node scripts/notion.ts log --db "Workout Log" --set "Name=value" ...`. - **Child pages:** `POST /v1/pages` with `parent:{ page_id }`. Use `node scripts/notion.ts create-page --parent --title "..." --file x.md`. +- **Reading rows:** `node scripts/notion.ts query-recent --db "Workout Log" --limit 3` + prints the newest rows, each ending in `id: `. The properties are only + a summary; the sets, loads and notes live in the page body. +- **Reading page bodies:** `node scripts/notion.ts get-page-blocks [ ...]` + prints each page's blocks as compact text (headings, bullets, to-dos, table + rows, callouts), several pages per call. It recurses into children (tables, + columns, toggles) up to `--depth` levels (default 4) and prints a marker where + it stops, but never into child pages or databases. `--json` gives the raw + block tree. To get recent rows and their bodies in one call, add + `--with-blocks` to `query-recent`. +- **Help:** `node scripts/notion.ts --help` lists every command and the id cache path. ## Database schemas diff --git a/docs/observability.md b/docs/observability.md index dd69c5e..6ee355f 100644 --- a/docs/observability.md +++ b/docs/observability.md @@ -66,6 +66,35 @@ case under `CLAUDE_CODE_OAUTH_TOKEN`. When some runs do report a cost, the summa sums those and says how many runs had none, rather than implying the total is complete. +## Host Dashboard sync + +The three Dashboard data tiles (This Week, Goals, Body Stats) are re-derived by +`scripts/notion.ts sync-dashboard`, which is deterministic. Rather than having the +model run it inside its turn, the runner watches the stream for top-level Bash calls +to the helper's `log` command (not `--dry-run` or `--help`). When the run ends +(including with an error, since the rows are already written) and the agent did not +already sync after its last write, it +starts `node scripts/notion.ts sync-dashboard --now ` from the +project root as a child process and returns the reply without waiting for it +(`src/notion/dashboard-sync.ts`). + +- At most one sync runs at a time. Requests that arrive meanwhile collapse into one + follow-up run. +- A sync is killed after 60 seconds. Failures are logged and never reach the chat. +- Its output, and a final `sync done`, `sync exited with ` or `sync timed out` + line with the duration, go to stdout with a `[dashboard]` prefix. +- The coalescing only covers host syncs. If the agent rewrites the same tile (for + example its own `sync-dashboard` after editing a row without `log`) while a host + sync is still running, both append before deleting the old blocks, so the tile can + briefly show its content twice. The next sync of that tile clears it. + +On Cloud Run this relies on CPU always being allocated: the instance keeps running +after the webhook is acknowledged, so a child that finishes a few seconds after the +reply completes normally. On a host that throttles CPU between requests, or to +debug, set `HOST_DASHBOARD_SYNC=false` (or `0`, `off`, `no`). The session context +then tells the agent the host sync is off, and CLAUDE.md and the skills tell it to +run the sync itself in its turn, as before. + ## Samples A line from `data/agent-runs.jsonl` (wrapped here for reading; it is one line): diff --git a/entrypoint.sh b/entrypoint.sh index 3ba56f4..46617ed 100644 --- a/entrypoint.sh +++ b/entrypoint.sh @@ -5,5 +5,20 @@ set -e export SESSION_FILE="${SESSION_FILE:-/data/sessions.json}" export SCHEDULE_FILE="${SCHEDULE_FILE:-/data/schedule.json}" +# /app/data links to /data/data (see Dockerfile). Create it here because the +# volume mount hides anything the image put under /data. Non-fatal: the bot +# still answers without it, only the script caches would not persist. +if mkdir -p /data/data; then + # Some older deploys wrote caches to the volume root instead. Seed any the + # data dir lacks, never overwriting a copy already there (that one is newer). + for f in notion-ids.json google-token.json google-calendar.json; do + if [ -f "/data/$f" ] && [ ! -e "/data/data/$f" ]; then + cp -p "/data/$f" "/data/data/$f" || true + fi + done +else + echo "[entrypoint] warning: could not create /data/data; script caches will not persist" >&2 +fi + # Start the agent. exec node dist/index.js diff --git a/scripts/calendar.ts b/scripts/calendar.ts index 3609808..736fe7a 100644 --- a/scripts/calendar.ts +++ b/scripts/calendar.ts @@ -48,11 +48,13 @@ const CLIENT_SECRET = process.env.GOOGLE_CLIENT_SECRET; const TIMEZONE = process.env.TIMEZONE ?? "Europe/London"; const API = "https://www.googleapis.com/calendar/v3"; const TOKEN_URL = "https://oauth2.googleapis.com/token"; -const TOKEN_FILE = path.resolve( - process.cwd(), - process.env.GOOGLE_TOKEN_FILE ?? path.join("data", "google-token.json"), -); -const CALENDAR_FILE = path.resolve(process.cwd(), "data", "google-calendar.json"); +// The data dir is resolved from this file, not cwd, so the agent hits the same +// cache whatever directory it runs the script from (see docs/deployment.md). +const DATA_DIR = path.resolve(import.meta.dirname, "..", "data"); +const TOKEN_FILE = process.env.GOOGLE_TOKEN_FILE + ? path.resolve(process.env.GOOGLE_TOKEN_FILE) + : path.join(DATA_DIR, "google-token.json"); +const CALENDAR_FILE = path.join(DATA_DIR, "google-calendar.json"); const MAX_RETRIES = 5; const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); diff --git a/scripts/exercise-db.ts b/scripts/exercise-db.ts index 968b661..c7b1c53 100644 --- a/scripts/exercise-db.ts +++ b/scripts/exercise-db.ts @@ -26,7 +26,8 @@ const DATA_URL = const IMAGE_BASE = process.env.EXERCISE_DB_IMAGE_BASE ?? "https://raw.githubusercontent.com/yuhonas/free-exercise-db/main/exercises/"; -const CACHE_FILE = path.resolve(process.cwd(), "data", "exercises.json"); +// Resolved from this file, not cwd, so every run shares one cache (see docs/deployment.md). +const CACHE_FILE = path.resolve(import.meta.dirname, "..", "data", "exercises.json"); const CACHE_TTL_MS = 1000 * 60 * 60 * 24 * 30; // 30 days /** One record from the free-exercise-db dataset. */ diff --git a/scripts/notion.test.ts b/scripts/notion.test.ts index f24dafe..c61be9b 100644 --- a/scripts/notion.test.ts +++ b/scripts/notion.test.ts @@ -1,13 +1,21 @@ import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import os from "node:os"; +import path from "node:path"; import { test } from "node:test"; import { + CACHE_FILE, buildPropertyValue, + fetchBlockTree, markdownToBlocks, optionNames, + parseArgs, parseInline, + renderBlocks, renderBodyStatsTile, renderGoalsTile, renderThisWeekTile, + rowIcon, startOfWeekUTC, validateValue, } from "./notion.ts"; @@ -233,3 +241,150 @@ test("renderBodyStatsTile: shows latest weight and waist, or empty state", () => ); assert.match(renderBodyStatsTile(null), /No check-ins logged yet/); }); + +// ─── data dir and arg parsing ────────────────────────────────────────────────── + +test("CACHE_FILE: resolved from the script location, not the cwd", () => { + // npm test runs from the repo root, where a cwd-based path would match too, so + // run the CLI from elsewhere. In the container the agent sometimes cd's away + // from /app and must still hit the same cache file. + const expected = path.resolve(import.meta.dirname, "..", "data", "notion-ids.json"); + assert.equal(CACHE_FILE, expected); + const { NOTION_TOKEN: _token, ...env } = process.env; + const out = execFileSync( + process.execPath, + [path.join(import.meta.dirname, "notion.ts"), "--help"], + { + cwd: os.tmpdir(), + env, + encoding: "utf8", + }, + ); + assert.ok(out.includes(`Id cache: ${expected}`), out); +}); + +test("parseArgs: bare words collect as positionals", () => { + const args = parseArgs(["id-one", "id-two", "--depth", "2"]); + assert.deepEqual(args._, ["id-one", "id-two"]); + assert.equal(args.depth, "2"); +}); + +test("parseArgs: boolean flags never swallow the next word", () => { + const args = parseArgs(["--json", "id-one", "--with-blocks", "--db", "Workout Log"]); + assert.equal(args.json, true); + assert.equal(args["with-blocks"], true); + assert.deepEqual(args._, ["id-one"]); + assert.equal(args.db, "Workout Log"); +}); + +// ─── page bodies ─────────────────────────────────────────────────────────────── + +const txt = (s: string) => [{ plain_text: s }]; +const blk = ( + id: string, + type: string, + payload: Record = {}, + hasChildren = false, +) => ({ + id, + type, + has_children: hasChildren, + [type]: payload, +}); + +test("fetchBlockTree: recurses into children but not into child pages", async () => { + const tree: Record = { + page: [ + blk("t", "table", { table_width: 2, has_column_header: true }, true), + blk("sub", "child_page", { title: "Old program" }, true), + ], + t: [ + blk("r1", "table_row", { cells: [txt("Exercise"), txt("Sets")] }), + blk("r2", "table_row", { cells: [txt("Bench"), txt("5x5 @60kg")] }), + ], + }; + const asked: string[] = []; + const blocks = await fetchBlockTree("page", 4, async (id) => { + asked.push(id); + return structuredClone(tree[id] ?? []); + }); + assert.deepEqual(asked, ["page", "t"]); + assert.equal(blocks[0].children?.length, 2); + assert.equal(blocks[1].children, undefined); +}); + +test("fetchBlockTree: marks children beyond the depth cap as truncated", async () => { + const blocks = await fetchBlockTree("page", 1, async () => [ + blk("tog", "toggle", { rich_text: txt("Warm-up") }, true), + ]); + assert.equal(blocks[0].truncated, true); + assert.equal(blocks[0].children, undefined); + assert.match(renderBlocks(blocks).join("\n"), /nested content not fetched/); +}); + +test("renderBlocks: a typical session body reads as compact text", () => { + const lines = renderBlocks([ + blk("h", "heading_2", { rich_text: txt("Push A") }), + blk("c", "callout", { rich_text: txt("Felt strong"), icon: { emoji: "💪" } }), + { + ...blk("t", "table", { table_width: 2, has_column_header: true }, true), + children: [ + blk("r1", "table_row", { cells: [txt("Exercise"), txt("Sets")] }), + blk("r2", "table_row", { cells: [txt("Bench"), txt("5x5 @60kg")] }), + ], + }, + { + ...blk("b", "bulleted_list_item", { rich_text: txt("Accessories") }, true), + children: [blk("b2", "bulleted_list_item", { rich_text: txt("Dips 3x10") })], + }, + blk("n1", "numbered_list_item", { rich_text: txt("first") }), + blk("n2", "numbered_list_item", { rich_text: txt("second") }), + blk("td", "to_do", { rich_text: txt("Stretch"), checked: true }), + blk("e", "paragraph", { rich_text: [] }), + blk("d", "divider"), + blk("sub", "child_page", { title: "Notes" }, true), + blk("x", "some_new_type"), + ]); + assert.deepEqual(lines, [ + "## Push A", + "> 💪 Felt strong", + "| Exercise | Sets |", + "| --- | --- |", + "| Bench | 5x5 @60kg |", + "- Accessories", + " - Dips 3x10", + "1. first", + "2. second", + "- [x] Stretch", + "---", + "[page] Notes (sub)", + "[some_new_type]", + ]); +}); + +test("renderBlocks: column layouts flatten without extra indentation", () => { + const lines = renderBlocks([ + { + ...blk("cl", "column_list", {}, true), + children: [ + { + ...blk("c1", "column", {}, true), + children: [blk("p1", "paragraph", { rich_text: txt("left") })], + }, + { + ...blk("c2", "column", {}, true), + children: [blk("p2", "paragraph", { rich_text: txt("right") })], + }, + ], + }, + ]); + assert.deepEqual(lines, ["left", "right"]); +}); + +test("rowIcon: Workout Log rows get the notepad icon unless --icon overrides it", () => { + assert.equal(rowIcon("Workout Log"), "🗒️"); + assert.equal(rowIcon(" workout log "), "🗒️"); + assert.equal(rowIcon("Workout Log", "🏋️"), "🏋️"); + assert.equal(rowIcon("Goals"), undefined); + assert.equal(rowIcon(undefined), undefined); +}); diff --git a/scripts/notion.ts b/scripts/notion.ts index 5825285..08d5afe 100644 --- a/scripts/notion.ts +++ b/scripts/notion.ts @@ -27,6 +27,8 @@ * node scripts/notion.ts resolve-workspace # rebuild the id cache from the pinned Hub * node scripts/notion.ts resolve-db --name "Workout Log" * node scripts/notion.ts query-recent --db "Workout Log" --focus Push --limit 3 + * node scripts/notion.ts query-recent --db "Workout Log" --limit 3 --with-blocks + * node scripts/notion.ts get-page-blocks [ ...] [--json] * node scripts/notion.ts log --db "Workout Log" \ * --set "Session=Push A" --set "Focus=Push" --set "Date=2026-06-23" \ * --set "RPE=8" --set "Exercises=Bench 5x5 @60kg; OHP 3x8 @40kg" @@ -43,7 +45,11 @@ import { pathToFileURL } from "node:url"; const TOKEN = process.env.NOTION_TOKEN; const NOTION_VERSION = process.env.NOTION_VERSION ?? "2022-06-28"; const API = "https://api.notion.com/v1"; -const CACHE_FILE = path.resolve(process.cwd(), "data", "notion-ids.json"); +// Paths are resolved from this file, not cwd, so the agent finds the same id +// cache whatever directory it runs the script from. In the container +// /app/data links into the durable volume (see docs/deployment.md). +const ROOT = path.resolve(import.meta.dirname, ".."); +const CACHE_FILE = path.join(ROOT, "data", "notion-ids.json"); // Retry tuning for rate limits (429) and transient 5xx responses. const MAX_RETRIES = 5; @@ -51,9 +57,11 @@ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms)); // ─── arg parsing (supports repeated --set) ────────────────────────────────── -/** Parsed CLI flags. A bare flag with no value (e.g. --dry-run) parses as `true`. */ +/** Parsed CLI flags. A bare flag with no value (e.g. --dry-run) parses as `true`. + * Bare words (not flags or flag values) collect in `_`, e.g. page ids. */ type Args = { set: string[]; + _: string[]; name?: string; db?: string; focus?: string; @@ -67,17 +75,27 @@ type Args = { tile?: string; column?: string; now?: string; + depth?: string; "dry-run"?: string | true; + json?: string | true; + "with-blocks"?: string | true; }; +// Flags that never take a value, so "--json " keeps the id as a bare word. +const BOOLEAN_FLAGS = new Set(["dry-run", "json", "with-blocks"]); + function parseArgs(argv: string[]): Args { - const args: Args = { set: [] }; + const args: Args = { set: [], _: [] }; for (let i = 0; i < argv.length; i++) { const a = argv[i]; - if (!a.startsWith("--")) continue; + if (!a.startsWith("--")) { + args._.push(a); + continue; + } const key = a.slice(2); const next = argv[i + 1]; - const val = next === undefined || next.startsWith("--") ? true : (i++, next); + const val = + BOOLEAN_FLAGS.has(key) || next === undefined || next.startsWith("--") ? true : (i++, next); if (key === "set") args.set.push(val as string); else (args as Record)[key] = val; } @@ -114,7 +132,9 @@ async function notion(pathname: string, method?: string, body?: unknown): Promis const json = await res.json().catch(() => ({})); if (!res.ok) { - throw new Error(`Notion ${method} ${pathname} -> ${res.status}: ${json.message ?? ""}`); + throw new Error( + `Notion ${method ?? "GET"} ${pathname} -> ${res.status}: ${json.message ?? ""}`, + ); } return json; } @@ -167,7 +187,7 @@ const normId = (id?: string) => (id ?? "").replace(/-/g, "").toLowerCase(); // stranger's database of the same name. Resolution order: id cache, then the // NOTION_PARENT_PAGE_ID env var, then config/notion-hub.json (a gitignored local // pin, copied from its .example, that survives restarts where the data/ cache starts empty). -const HUB_PIN_FILE = path.resolve(process.cwd(), "config", "notion-hub.json"); +const HUB_PIN_FILE = path.join(ROOT, "config", "notion-hub.json"); function hubId() { const cache = readCache(); let pinned: string | undefined; @@ -839,6 +859,153 @@ async function replaceTileContent(columnId: string, md: string, forceColor?: str return blocks.length; } +// ─── reading page bodies ───────────────────────────────────────────────────── + +/** A block as the API returns it, with its fetched children attached. */ +interface BlockNode { + id: string; + type: string; + has_children?: boolean; + children?: BlockNode[]; + /** Set when the block has children that the depth cap left unfetched. */ + truncated?: boolean; + [payload: string]: any; +} + +// Enough for column_list > column > table > table_row, the deepest shape the +// coach writes, plus one spare level for a nested list or toggle. +const DEFAULT_DEPTH = 4; + +// Child pages and databases report has_children too, but they are separate +// documents: recursing into them from the Hub would crawl the whole workspace. +const NO_RECURSE = new Set(["child_page", "child_database"]); + +/** + * Fetch a page's blocks, recursing into children up to `depth` levels (the + * page's own children are level 1). The lister is injectable for tests. + */ +async function fetchBlockTree( + blockId: string, + depth = DEFAULT_DEPTH, + list: (id: string) => Promise = listChildren, +): Promise { + const blocks: BlockNode[] = await list(blockId); + for (const b of blocks) { + if (!b.has_children || NO_RECURSE.has(b.type)) continue; + if (depth > 1) b.children = await fetchBlockTree(b.id, depth - 1, list); + else b.truncated = true; + } + return blocks; +} + +const richPlain = (rich?: any[]) => (rich ?? []).map((t: any) => t.plain_text ?? "").join(""); + +/** + * Render a block tree as compact markdown-ish text for the model to read. + * Unknown types print as a "[type]" placeholder and depth-capped children + * print a marker, so the reader never mistakes a partial body for a whole one. + */ +function renderBlocks(blocks: BlockNode[], indent = ""): string[] { + const out: string[] = []; + const nested = `${indent} `; + let num = 0; + for (const b of blocks) { + const data = b[b.type] ?? {}; + const text = richPlain(data.rich_text); + num = b.type === "numbered_list_item" ? num + 1 : 0; + // Layout wrappers add no text of their own; their children stay at this level. + let childIndent = nested; + let line: string | undefined; + + switch (b.type) { + case "paragraph": + line = text || undefined; + break; + case "heading_1": + case "heading_2": + case "heading_3": + line = `${"#".repeat(Number(b.type.slice(-1)))} ${text}`; + break; + case "bulleted_list_item": + case "toggle": + line = `- ${text}`; + break; + case "numbered_list_item": + line = `${num}. ${text}`; + break; + case "to_do": + line = `- [${data.checked ? "x" : " "}] ${text}`; + break; + case "quote": + line = `> ${text}`; + break; + case "callout": + line = `> ${data.icon?.emoji ? `${data.icon.emoji} ` : ""}${text}`; + break; + case "code": + line = `\`\`\`${data.language ?? ""}\n${text}\n\`\`\``; + break; + case "divider": + line = "---"; + break; + case "equation": + line = data.expression ?? ""; + break; + case "table": { + const rows = (b.children ?? []) + .filter((r) => r.type === "table_row") + .map((r) => `| ${(r.table_row?.cells ?? []).map(richPlain).join(" | ")} |`); + if (data.has_column_header && rows.length) { + const width = b.children?.[0]?.table_row?.cells?.length ?? 1; + rows.splice(1, 0, `|${" --- |".repeat(width)}`); + } + out.push(...rows.map((r) => indent + r)); + if (b.truncated) out.push(`${indent}(table rows not fetched; raise --depth)`); + continue; + } + case "column_list": + case "column": + case "synced_block": + childIndent = indent; + break; + case "child_page": + case "child_database": + line = `[${b.type === "child_page" ? "page" : "database"}] ${data.title ?? ""} (${b.id})`; + break; + case "image": + case "video": + case "audio": + case "file": + case "pdf": + line = `[${b.type}] ${richPlain(data.caption) || data.name || data.external?.url || data.file?.url || ""}`; + break; + case "bookmark": + case "embed": + case "link_preview": + line = `[link] ${data.url ?? ""}`; + break; + case "table_of_contents": + case "breadcrumb": + break; + default: + line = `[${b.type}]${text ? ` ${text}` : ""}`; + } + + if (line !== undefined) out.push(...line.split("\n").map((l) => indent + l)); + if (b.children) out.push(...renderBlocks(b.children, childIndent)); + if (b.truncated) out.push(`${childIndent}(nested content not fetched; raise --depth)`); + } + return out; +} + +function parseDepth(raw?: string) { + if (raw === undefined) return DEFAULT_DEPTH; + const n = Number.parseInt(raw, 10); + if (!Number.isInteger(n) || n < 1) + throw new Error(`--depth must be a positive integer, got "${raw}"`); + return n; +} + // ─── commands ──────────────────────────────────────────────────────────────── /** Body of a database query request. */ interface QueryBody { @@ -877,6 +1044,7 @@ async function cmdQueryRecent(args: Args) { const rpeProp = byName("rpe"); const exProp = byName("exercise"); + const depth = parseDepth(args.depth); let p: Record; const get = (name?: string) => readProp(name ? p[name] : null); for (const page of res.results) { @@ -884,11 +1052,60 @@ async function cmdQueryRecent(args: Args) { const parts = [get(dateProp), get(titleProp)]; if (focusProp) parts.push(`Focus: ${get(focusProp)}`); if (rpeProp) parts.push(`RPE: ${get(rpeProp)}`); + // The id lets the caller read a row's body with get-page-blocks without + // another lookup. + parts.push(`id: ${page.id}`); console.log(`- ${parts.filter(Boolean).join(" | ")}`); if (exProp && get(exProp)) console.log(` ${get(exProp)}`); + // --with-blocks inlines each row's page body, since the sets and notes live + // there, so "recent sessions in full" is one command instead of 1 + N. + if (args["with-blocks"]) { + try { + const lines = renderBlocks(await fetchBlockTree(page.id, depth)); + for (const l of lines.length ? lines : ["(empty page)"]) console.log(` ${l}`); + } catch (err) { + console.log(` (could not read page body: ${(err as Error).message})`); + process.exitCode = 1; + } + } } } +/** + * Print the body of one or more pages (e.g. Workout Log entries, whose sets, + * loads, and notes live in the blocks, not the row properties). Accepts several + * ids so a few sessions can be read in one call. One bad id prints an error + * under its header and fails the exit code without losing the other pages. + */ +async function cmdGetPageBlocks(args: Args) { + const ids = [...args._, ...(typeof args.page === "string" ? [args.page] : [])] + .flatMap((s) => s.split(",")) + .map((s) => s.trim()) + .filter(Boolean); + if (!ids.length) { + throw new Error("Pass one or more page ids: get-page-blocks [ ...]"); + } + const depth = parseDepth(args.depth); + const json: { pageId: string; blocks?: BlockNode[]; error?: string }[] = []; + for (const id of ids) { + try { + const blocks = await fetchBlockTree(id, depth); + if (args.json) { + json.push({ pageId: id, blocks }); + continue; + } + const lines = renderBlocks(blocks); + console.log(`### Page ${id}\n${lines.length ? lines.join("\n") : "(empty page)"}\n`); + } catch (err) { + process.exitCode = 1; + const message = (err as Error).message; + if (args.json) json.push({ pageId: id, error: message }); + else console.log(`### Page ${id}\n(error: ${message})\n`); + } + } + if (args.json) console.log(JSON.stringify(json, null, 2)); +} + async function cmdLog(args: Args) { const dbId = await resolveDbId(args.db); const properties = await buildProperties(dbId, args.set); @@ -899,10 +1116,23 @@ async function cmdLog(args: Args) { console.log(JSON.stringify(properties, null, 2)); return; } - const page = await notion("/pages", "POST", { parent: { database_id: dbId }, properties }); + const body: Record = { parent: { database_id: dbId }, properties }; + const icon = rowIcon(args.db, args.icon); + if (icon) body.icon = { type: "emoji", emoji: icon }; + const page = await notion("/pages", "POST", body); console.log(`Logged row ${page.id}`); } +/** Page icon new rows get per database, so nobody has to set it by hand in Notion. */ +const DEFAULT_ROW_ICONS: Record = { "workout log": "🗒️" }; + +/** Icon for a new row: an explicit --icon wins, otherwise the database's default (if any). */ +export function rowIcon(db: string | undefined, explicit?: string): string | undefined { + const chosen = explicit?.trim(); + if (chosen) return chosen; + return DEFAULT_ROW_ICONS[(db ?? "").trim().toLowerCase()]; +} + async function cmdAppend(args: Args) { if (!args.page) throw new Error("--page is required"); const md = args.file ? fs.readFileSync(args.file, "utf8") : (args.md ?? ""); @@ -950,8 +1180,9 @@ async function cmdRefreshTile(args: Args) { /** * Rebuild the three Row 1 Dashboard tiles (This Week, Goals, Body Stats) directly * from the databases, so they are always consistent with the data and never carry - * hand-written (fabricated) numbers. The agent calls this once after any data - * change instead of hand-building each tile. --now sets "this week" + * hand-written (fabricated) numbers. The host runs this after a run that + * wrote rows (the agent does when HOST_DASHBOARD_SYNC is off), so tiles are never + * hand-built. --now sets "this week" * from the chat header date (defaults to the system date). */ async function cmdSyncDashboard(args: Args) { @@ -1091,13 +1322,14 @@ async function cmdResolveWorkspace() { console.log(`Databases: ${dbs.join(", ") || "none"}`); console.log(`Knowledge Base: ${cache.__knowledgeBase ?? "not found"}`); console.log(`Dashboard: ${dashboard}`); - console.log("Ids cached to data/notion-ids.json"); + console.log(`Ids cached to ${CACHE_FILE}`); } const COMMANDS: Record Promise> = { "resolve-db": cmdResolveDb, "resolve-workspace": cmdResolveWorkspace, "query-recent": cmdQueryRecent, + "get-page-blocks": cmdGetPageBlocks, log: cmdLog, append: cmdAppend, "refresh-tile": cmdRefreshTile, @@ -1105,16 +1337,40 @@ const COMMANDS: Record Promise> = { "create-page": cmdCreatePage, }; +const USAGE = `Usage: node scripts/notion.ts [flags] + + resolve-workspace rebuild the id cache from the pinned Hub + resolve-db --name "Workout Log" print (and cache) a database id + query-recent --db "Workout Log" [--focus Push] [--limit 3] [--with-blocks] [--depth 4] + recent rows, newest first, each with its page id; + --with-blocks also prints each row's page body + get-page-blocks [ ...] [--json] [--depth 4] + print page bodies (sets, loads, notes) as text + log --db "Workout Log" --set "Prop=value" ... [--icon 🗒️] [--dry-run] + (Workout Log rows get the 🗒️ page icon by default) + append --page (--md "..." | --file x.md) + create-page --parent --title "..." [--icon 🏋️] [--md "..." | --file x.md] + refresh-tile (--tile | --column ) (--md "..." | --file x.md) + sync-dashboard [--now YYYY-MM-DD] + +Id cache: ${CACHE_FILE}`; + async function main() { - if (!TOKEN) { - console.error("NOTION_TOKEN is not set. Notion is not configured."); - process.exitCode = 1; + const [command, ...rest] = process.argv.slice(2); + // Help works without a token so the usage is always discoverable, and + // " --help" must print it rather than run the command. + if (!command || ["help", "--help", "-h"].includes(command) || rest.includes("--help")) { + console.log(USAGE); return; } - const [command, ...rest] = process.argv.slice(2); const fn = COMMANDS[command]; if (!fn) { - console.error(`Unknown command "${command}". Use one of: ${Object.keys(COMMANDS).join(", ")}`); + console.error(`Unknown command "${command}".\n\n${USAGE}`); + process.exitCode = 1; + return; + } + if (!TOKEN) { + console.error("NOTION_TOKEN is not set. Notion is not configured."); process.exitCode = 1; return; } @@ -1131,6 +1387,10 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) } export { + CACHE_FILE, + parseArgs, + fetchBlockTree, + renderBlocks, parseInline, markdownToBlocks, buildPropertyValue, diff --git a/scripts/setup-workspace.ts b/scripts/setup-workspace.ts index bfe924b..a828478 100644 --- a/scripts/setup-workspace.ts +++ b/scripts/setup-workspace.ts @@ -28,7 +28,10 @@ import path from "node:path"; const TOKEN = process.env.NOTION_TOKEN; const API = "https://api.notion.com/v1"; -const CACHE_FILE = path.resolve(process.cwd(), "data", "notion-ids.json"); +// Paths are resolved from this file, not cwd, so the cache is the same one +// notion.ts reads wherever the script is run from (see docs/deployment.md). +const ROOT = path.resolve(import.meta.dirname, ".."); +const CACHE_FILE = path.join(ROOT, "data", "notion-ids.json"); if (!TOKEN) { console.error("NOTION_TOKEN is not set. Notion is not configured."); @@ -47,9 +50,8 @@ const opt = (name: string): string | undefined => { // with an empty data/ mount can still rebuild against the right workspace. function pinnedHub(): string | undefined { try { - return JSON.parse( - fs.readFileSync(path.resolve(process.cwd(), "config", "notion-hub.json"), "utf8"), - ).hubPageId; + return JSON.parse(fs.readFileSync(path.join(ROOT, "config", "notion-hub.json"), "utf8")) + .hubPageId; } catch { return undefined; } diff --git a/src/agent/runner.ts b/src/agent/runner.ts index 65a8ee8..5d6d287 100644 --- a/src/agent/runner.ts +++ b/src/agent/runner.ts @@ -5,6 +5,11 @@ import { type SDKUserMessage, query } from "@anthropic-ai/claude-agent-sdk"; import { googleCalendarConfigured } from "../calendar/status.js"; import { config } from "../config.js"; import { type Attachment, buildUserContent } from "../media/attachments.js"; +import { + createDashboardSyncer, + dashboardSyncEffect, + localIsoDate, +} from "../notion/dashboard-sync.js"; import { notionConfigured } from "../notion/status.js"; import { personaSystemPrompt, pickPersonality } from "./personalities.js"; import { type RunRecord, appendRunRecord, summariseModelUsage, summariseUsage } from "./runlog.js"; @@ -34,6 +39,35 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url)); // runner.ts lives at src/agent/, so the repo root is two levels up. const PROJECT_ROOT = path.resolve(__dirname, "..", ".."); +// One syncer per process, so syncs from overlapping chats are coalesced. +const dashboardSync = createDashboardSyncer({ cwd: PROJECT_ROOT }); + +/** Activity events never break a run: thrown errors and rejected promises are both swallowed. */ +function emitActivity( + onActivity: ((event: { tool: string; command?: string }) => void) | undefined, + block: any, +): void { + if (!onActivity) return; + try { + const input = block.input ?? {}; + const raw = + block.name === "Bash" + ? input.command + : block.name === "Skill" + ? (input.skill ?? input.command) + : undefined; + const command = typeof raw === "string" ? raw.slice(0, 200) : undefined; + const ret: unknown = onActivity( + command === undefined ? { tool: block.name } : { tool: block.name, command }, + ); + if (ret && typeof (ret as Promise).catch === "function") { + (ret as Promise).catch(() => {}); + } + } catch { + /* a progress callback must not affect the reply */ + } +} + export type ModelTier = "fast" | "standard"; // ─── Lightweight query classifier ───────────────────────────────────────────── @@ -103,6 +137,13 @@ function buildSessionContext(): string { const parts: string[] = []; if (notionConfigured()) { parts.push("Notion configured"); + // CLAUDE.md says the host syncs the data tiles; when that is turned off the + // agent has to do it, or nobody does. + if (!config.hostDashboardSync) { + parts.push( + "host Dashboard sync is off: after writing Workout Log, Goals or Body Stats rows, run `node scripts/notion.ts sync-dashboard --now ` yourself once", + ); + } const idsPath = path.join(PROJECT_ROOT, "data", "notion-ids.json"); if (fs.existsSync(idsPath)) { parts.push("workspace built"); @@ -170,8 +211,9 @@ export async function runAgent(opts: { modelTier?: ModelTier; attachments?: Attachment[]; onProgress?: (text: string) => void; + onActivity?: (event: { tool: string; command?: string }) => void; }): Promise { - const { userMessage, chatId, userLabel, attachments, onProgress } = opts; + const { userMessage, chatId, userLabel, attachments, onProgress, onActivity } = opts; const modelTier = opts.modelTier ?? "standard"; const existingSession = getSession(chatId); @@ -201,6 +243,26 @@ export async function runAgent(opts: { const startedAt = Date.now(); const toolCounts: Record = {}; let resultMessage: any; + // True when the run wrote Dashboard-feeding rows and has not synced since. + let dashboardDirty = false; + + /** + * Start the host Dashboard sync if this attempt wrote rows and did not sync + * afterwards. Also called when the run fails: the rows are already in Notion + * and the agent is told not to sync after a write. Not awaited, so the reply + * goes out while the helper re-derives the tiles. + */ + const syncDashboardIfDirty = () => { + if (!dashboardDirty) return; + dashboardDirty = false; + try { + if (config.hostDashboardSync && notionConfigured()) { + dashboardSync.request(localIsoDate(config.timezone)); + } + } catch (syncErr) { + console.warn("[dashboard] could not start sync:", (syncErr as Error).message); + } + }; /** Fire-and-forget run record. Never awaited, never allowed to throw. */ const logRun = (isError: boolean, errorMessage?: string) => { @@ -289,6 +351,17 @@ export async function runAgent(opts: { } } + if (message.type === "assistant" && (message as any).parent_tool_use_id == null) { + for (const block of (message as any).message?.content ?? []) { + if (block?.type !== "tool_use" || typeof block.name !== "string") continue; + emitActivity(onActivity, block); + if (block.name === "Bash" && typeof block.input?.command === "string") { + const effect = dashboardSyncEffect(block.input.command); + if (effect) dashboardDirty = effect === "dirty"; + } + } + } + if ( onProgress && message.type === "assistant" && @@ -317,11 +390,13 @@ export async function runAgent(opts: { } logRun(Boolean(resultMessage?.is_error)); + syncDashboardIfDirty(); return { text: resultText, sessionId }; } catch (err: any) { const msg = err?.message ?? String(err); console.error("[agent] query() threw:", msg); logRun(true, msg); + syncDashboardIfDirty(); // Subscription usage limit hit. Return a clear message rather than throwing. // No restart needed: the next query() spawns a fresh subprocess, so once the diff --git a/src/channel/chat-queue.ts b/src/channel/chat-queue.ts new file mode 100644 index 0000000..c236a06 --- /dev/null +++ b/src/channel/chat-queue.ts @@ -0,0 +1,150 @@ +/** + * Per-chat serialisation for agent runs. + * + * Two runs for the same chat must never overlap: with no session yet each would + * start its own Claude session and redo onboarding, and with a session they would + * race to resume the same session id. Different chats stay independent (the + * global concurrency cap lives with the caller). + * + * Messages that pile up behind a running turn are coalesced: when their turn + * comes they are handed over together, in arrival order, so three quick messages + * cost one extra run instead of three. Other work (a reset, a scheduled reminder) + * goes through run(), which never merges and keeps its place in line. + * + * Deliberately import-free so the scheduler and tests can share it cheaply. + */ + +type Pending = T | Promise | null; + +interface OpenBatch { + items: Promise[]; + done: Promise; +} + +const noop = () => {}; + +/** Await a pending input, treating a failed preparation as "nothing to send". */ +async function settle(input: Pending): Promise { + try { + return await input; + } catch { + return null; + } +} + +export class ChatQueue { + // The tail of each chat's chain. Removed as soon as the chat goes idle, so a + // chat that has gone quiet costs nothing. + private readonly tails = new Map>(); + // The message batch still waiting for its turn per chat; new messages join it. + private readonly open = new Map(); + + /** Run a task alone, after everything already queued for this chat. */ + run(key: string, task: () => Promise): Promise { + // Close the waiting batch so a message sent after this task cannot jump ahead of it. + this.open.delete(key); + return this.chain(key, task); + } + + /** + * Queue one inbound message. The input may still be preparing (a download or a + * transcription) and may resolve to null when there turns out to be nothing to + * send. Resolves once the batch holding this message has been handled, and + * rejects if the handler throws; the queue itself keeps going either way. + */ + enqueue( + key: string, + input: Pending, + handler: (key: string, batch: T[]) => Promise, + ): Promise { + // Settle now, not when the turn comes: a preparation that fails while it waits + // behind a long run would otherwise be an unhandled rejection. + const settled = settle(input); + const waiting = this.open.get(key); + if (waiting) { + waiting.items.push(settled); + return waiting.done; + } + + const items: Promise[] = [settled]; + const done = this.chain(key, async () => { + // Let the oldest message finish preparing before cutting the batch, so + // anything sent while it downloaded or transcribed rides along with it. + await items[0]; + if (this.open.get(key)?.items === items) this.open.delete(key); + const ready = (await Promise.all(items)).filter((m) => m !== null) as T[]; + if (ready.length > 0) await handler(key, ready); + }); + this.open.set(key, { items, done }); + return done; + } + + /** Chats with work running or waiting. Zero when everything is idle. */ + get activeChats(): number { + return this.tails.size; + } + + private chain(key: string, task: () => Promise): Promise { + const prev = this.tails.get(key) ?? Promise.resolve(); + const result = prev.then(task); + // The chain must survive a failed task, so the tail swallows the rejection + // while the caller still sees it through result. + const tail = result.then(noop, noop); + this.tails.set(key, tail); + void tail.then(() => { + if (this.tails.get(key) === tail) this.tails.delete(key); + }); + return result; + } +} + +/** Shared by the Telegram handler and the scheduler so they serialise per chat. */ +export const chatQueue = new ChatQueue(); + +export interface QueuedMessage { + text: string; + attachments: A[]; + /** Telegram media_group_id: items of one album share it. */ + group?: string; +} + +/** + * Join coalesced messages into one turn: texts in order, separated by a blank + * line, and every attachment in order. + * + * The model gets all the text first and the attachments after it, so when + * separate messages are merged and any carries an attachment, each text is + * tagged with its attachment numbers ("lunch (attachment 2)"). Otherwise a + * caption could be read as belonging to the wrong photo. An album counts as one + * message, since Telegram sends it as one item per photo with the caption on the + * first only, and tagging the rest "no caption" would be wrong. + */ +export function joinMessages(batch: QueuedMessage[]): { text: string; attachments: A[] } { + const units: { texts: string[]; attachments: A[] }[] = []; + let lastGroup: string | undefined; + for (const m of batch) { + const prev = units[units.length - 1]; + if (prev && m.group && m.group === lastGroup) { + prev.texts.push(m.text.trim()); + prev.attachments.push(...m.attachments); + } else { + units.push({ texts: [m.text.trim()], attachments: [...m.attachments] }); + } + lastGroup = m.group; + } + + const tag = units.length > 1 && units.some((u) => u.attachments.length > 0); + let next = 1; + const texts = units.map((u) => { + const text = u.texts.filter(Boolean).join("\n\n"); + if (!tag || u.attachments.length === 0) return text; + const nums = u.attachments.map(() => next++); + const label = nums.length === 1 ? `attachment ${nums[0]}` : `attachments ${nums.join(", ")}`; + return text ? `${text} (${label})` : `(${label}, no caption)`; + }); + + return { + text: texts.filter(Boolean).join("\n\n"), + attachments: units.flatMap((u) => u.attachments), + }; +} diff --git a/src/channel/progress.ts b/src/channel/progress.ts new file mode 100644 index 0000000..cb7f90f --- /dev/null +++ b/src/channel/progress.ts @@ -0,0 +1,177 @@ +/** + * Progress feedback for long agent runs. + * + * A Notion-heavy reply can take a minute or more, and Telegram's typing + * indicator alone reads as "stuck". For runs that go past a short delay this + * posts one quiet status message, edits it in place as the run moves between + * phases, and removes it when the reply lands. Quick runs show nothing. + * + * Status text only ever comes from the fixed labels below, never from the + * command itself, so paths, ids, and anything secret-like cannot leak into it. + * Set PROGRESS_UPDATES=false to turn the whole thing off. + */ + +export interface ActivityEvent { + tool: string; + command?: string; +} + +/** How the status message reaches the chat. Injected so tests need no Telegram. */ +export interface StatusTransport { + send(text: string): Promise; + edit(messageId: number, text: string): Promise; + remove(messageId: number): Promise; +} + +/** On unless PROGRESS_UPDATES is explicitly set to a falsy word. Read per call. */ +export function progressUpdatesEnabled(): boolean { + const raw = (process.env.PROGRESS_UPDATES ?? "").trim().toLowerCase(); + return !["0", "false", "off", "no"].includes(raw); +} + +const GENERIC = "Working on it..."; + +// Checked in order, first match wins, so a compound command always maps to the +// same label. Writes come before reads: if a command does both, the write is +// the more useful thing to tell the user about. +const COMMAND_LABELS: [RegExp, string][] = [ + // `log` also writes Goals and Body Stats rows, so the label stays neutral. The + // lookahead stops a future `log-something` subcommand from matching (`\b` would). + [/\bnotion\.[mc]?[jt]s\s+log(?=\s|$)/, "Saving it to Notion..."], + [/\bnotion\.[mc]?[jt]s\s+(append|create-page)\b/, "Writing it up in Notion..."], + [/\bnotion\.[mc]?[jt]s\s+(refresh-tile|sync-dashboard)\b/, "Updating your dashboard..."], + [/\bsetup-workspace\.[mc]?[jt]s\b[^\n]*--rebuild-dashboard/, "Updating your dashboard..."], + [/\bsetup-workspace\.[mc]?[jt]s\b/, "Setting up your Notion workspace..."], + [/\bnotion\.[mc]?[jt]s\s+(query-recent|get-page-blocks)\b/, "Checking your training log..."], + [/\bnotion\.[mc]?[jt]s\s+(resolve-workspace|resolve-db)\b/, "Opening your Notion workspace..."], + [/\bnotion\.[mc]?[jt]s\b/, "Working in Notion..."], + [/\bcalendar\.[mc]?[jt]s\s+(create|update|delete)\b/, "Updating your calendar..."], + [/\bcalendar\.[mc]?[jt]s\b/, "Checking your calendar..."], + [/\bexercise-db\.[mc]?[jt]s\b/, "Looking up exercises..."], +]; + +// Skill names may arrive plugin-prefixed ("coach-plugin:weekly-plan"). +const SKILL_LABELS: Record = { + "log-workout": "Logging your session...", + "recommend-workout": "Working out today's session...", + "weekly-plan": "Putting your week together...", + "progress-report": "Going through your progress...", + "nutrition-advice": "Working out the food side...", + "find-exercises": "Looking up exercises...", + "calendar-sync": "Checking your calendar...", + "import-knowledge": "Filing your programs into Notion...", + "setup-notion": "Setting up your Notion workspace...", +}; + +/** + * The status label for one tool call, or null when the call says nothing new + * (reading a file, an unrecognised shell command) and the current label should stay. + */ +export function describeActivity(event: ActivityEvent): string | null { + const command = event.command ?? ""; + if (event.tool === "Bash") { + for (const [pattern, label] of COMMAND_LABELS) { + if (pattern.test(command)) return label; + } + return null; + } + if (event.tool === "Skill") { + const name = command.split(":").pop()?.trim() ?? ""; + return SKILL_LABELS[name] ?? null; + } + if (event.tool === "WebSearch" || event.tool === "WebFetch") return "Looking that up..."; + return null; +} + +const noop = () => {}; + +export class ProgressReporter { + private label: string | null = null; // latest phase seen + private shown: string | null = null; // what the status message currently says + private messageId: Promise | null = null; + // Every Telegram call goes through this chain, so an edit or delete always + // runs after the send that created the message, even if it was still in flight. + private ops: Promise = Promise.resolve(); + private visible = false; + private finished = false; + private lastPostAt = 0; + private readonly delayTimer: ReturnType; + private editTimer: ReturnType | null = null; + private readonly minEditMs: number; + + constructor( + private readonly transport: StatusTransport, + opts: { delayMs?: number; minEditMs?: number } = {}, + ) { + this.minEditMs = opts.minEditMs ?? 4000; + this.delayTimer = setTimeout(() => { + this.visible = true; + this.flush(); + }, opts.delayMs ?? 9000); + } + + /** Feed one tool call from the run. Never throws. */ + onActivity(event: ActivityEvent): void { + try { + if (this.finished) return; + this.label = describeActivity(event) ?? this.label ?? GENERIC; + if (this.visible) this.flush(); + } catch (err) { + console.warn("[progress] activity handling failed:", (err as Error).message); + } + } + + /** + * Stop updating straight away and remove the status message if one was posted. + * The stop is synchronous, so calling this before sending the reply guarantees + * no status lands after it; the returned promise settles once the delete is done. + */ + finish(): Promise { + if (this.finished) return Promise.resolve(); + this.finished = true; + clearTimeout(this.delayTimer); + if (this.editTimer) clearTimeout(this.editTimer); + return this.withMessage((id) => this.transport.remove(id)); + } + + private flush(): void { + if (this.finished || !this.label || this.label === this.shown) return; + const text = this.label; + + if (!this.messageId) { + this.shown = text; + this.lastPostAt = Date.now(); + this.messageId = this.queue(() => this.transport.send(text)).catch(() => undefined); + return; + } + + // Rate-limit edits; a burst of phase changes collapses into one trailing edit. + const wait = this.lastPostAt + this.minEditMs - Date.now(); + if (wait > 0) { + this.editTimer ??= setTimeout(() => { + this.editTimer = null; + this.flush(); + }, wait); + return; + } + this.shown = text; + this.lastPostAt = Date.now(); + void this.withMessage((id) => this.transport.edit(id, text)); + } + + private queue(op: () => Promise): Promise { + const result = this.ops.then(op); + this.ops = result.then(noop, noop); + return result; + } + + /** Queue an operation on the posted status message; a no-op if none was posted. */ + private withMessage(op: (id: number) => Promise): Promise { + const pending = this.messageId; + if (!pending) return Promise.resolve(); + return this.queue(async () => { + const id = await pending; + if (id !== undefined) await op(id); + }).then(noop, (err) => console.warn("[progress] status update failed:", err?.message)); + } +} diff --git a/src/config.ts b/src/config.ts index 83fb72d..b95706d 100644 --- a/src/config.ts +++ b/src/config.ts @@ -65,6 +65,14 @@ export const config = { | "xhigh" | "max", + // After a run that logged rows through the Notion helper, the host re-derives + // the Dashboard data tiles in the background instead of the agent doing it in + // its turn. HOST_DASHBOARD_SYNC=false hands that job back to the agent. Same + // falsy words as PROGRESS_UPDATES so the two switches behave alike. + hostDashboardSync: !["0", "false", "off", "no"].includes( + (process.env.HOST_DASHBOARD_SYNC ?? "").trim().toLowerCase(), + ), + // Voice-note transcription: "local", "api", or "off". See docs/configuration.md. transcribeProvider: (process.env.TRANSCRIBE_PROVIDER ?? "local") as "local" | "api" | "off", transcribeApiUrl: diff --git a/src/index.ts b/src/index.ts index b6e8e03..949dee9 100644 --- a/src/index.ts +++ b/src/index.ts @@ -5,9 +5,15 @@ import { aggregateStats, readRunRecords } from "./agent/runlog.js"; import { classifyQuery, runAgent } from "./agent/runner.js"; import { clearSession, evictExpired, getSession } from "./agent/sessions.js"; import { googleCalendarConfigured } from "./calendar/status.js"; +import { chatQueue, joinMessages } from "./channel/chat-queue.js"; import { toPlainText, toTelegramHtml } from "./channel/format.js"; import { registerBot, sendMessage, splitMessage } from "./channel/notify.js"; import { isAllowed } from "./channel/permissions.js"; +import { + ProgressReporter, + type StatusTransport, + progressUpdatesEnabled, +} from "./channel/progress.js"; import { registerTelegramWebhook, startWebhookServer } from "./channel/webhook-server.js"; import { checkClaudeAuth, config } from "./config.js"; import { type Attachment, isSupportedAttachment } from "./media/attachments.js"; @@ -138,33 +144,57 @@ function buildStatsReply(): string { // ─── Message handling ──────────────────────────────────────────────── -async function handle(opts: { - chatId: string; - userId: number; +/** One inbound message, downloaded and transcribed, ready for the agent. */ +interface ChatMessage { userLabel: string; text: string; attachments: Attachment[]; + /** Album id, so coalescing keeps an album's caption with all of its photos. */ + group?: string; replyTo: (text: string) => Promise; typing: () => Promise; -}) { - const { chatId, userLabel, text, attachments, replyTo, typing } = opts; +} + +/** The status message lives in the chat itself; sent silently so it never buzzes the phone. */ +function statusTransport(chatId: string): StatusTransport { + return { + send: async (text) => + (await bot.api.sendMessage(chatId, text, { disable_notification: true })).message_id, + edit: (id, text) => bot.api.editMessageText(chatId, id, text), + remove: (id) => bot.api.deleteMessage(chatId, id), + }; +} + +/** + * Run one agent turn for a chat. Called through chatQueue, so it never overlaps + * another run for the same chat; batch holds every message that queued up + * behind the previous run, oldest first. + */ +async function handle(chatId: string, batch: ChatMessage[]) { + const { text, attachments } = joinMessages(batch); + // Any message's callbacks reach the same chat; the newest is as good as any. + const { userLabel, replyTo, typing } = batch[batch.length - 1]; + if (batch.length > 1) console.log(`[index] Coalesced ${batch.length} messages into one turn`); await acquireSlot(); await typing().catch(() => {}); // Keep a typing indicator alive while the agent works (it lasts ~5s per call). const typingTimer = setInterval(() => typing().catch(() => {}), 4500); + const progress = progressUpdatesEnabled() ? new ProgressReporter(statusTransport(chatId)) : null; // Route trivial logging messages to the fast model on new chats only, and only // when the fast tier is enabled (off by default for consistent behaviour). // Existing sessions stay on the standard model to avoid switching mid-conversation, // and a message carrying an attachment is never trivial, so it stays on standard. + // Read here, inside the queue, so it sees the session the previous run created. const existingSession = getSession(chatId); const modelTier = config.fastTierEnabled && !existingSession && attachments.length === 0 ? classifyQuery(text) : "standard"; + let reply: string; try { const response = await runAgent({ userMessage: text, @@ -172,16 +202,23 @@ async function handle(opts: { userLabel, modelTier, attachments, - onProgress: undefined, + onActivity: progress ? (event) => progress.onActivity(event) : undefined, }); - clearInterval(typingTimer); - await replyTo(response.text || "(no response)"); + reply = response.text || "(no response)"; } catch (err: any) { - clearInterval(typingTimer); console.error("[index] Agent error:", err?.message, err?.stack); - await replyTo(classifyError(err?.message ?? "unknown error")); + reply = classifyError(err?.message ?? "unknown error"); + } + + clearInterval(typingTimer); + // Stop status edits before the reply goes out; the delete runs alongside it. + const cleared = progress?.finish(); + try { + await replyTo(reply); } finally { releaseSlot(); + // Held per chat until the status is gone, so it never outlives the turn. + await cleared; } } @@ -287,10 +324,16 @@ bot.on("message", async (ctx) => { const cmd = text.slice(1).split(/\s+/)[0].split("@")[0].toLowerCase(); const rest = text.slice(1 + cmd.length).trim(); - // /new clears the conversation so the next message starts fresh. + // /new clears the conversation so the next message starts fresh. It waits its + // turn: clearing under a running turn would be undone when that run saves its + // session, and messages sent before it should still land in the old context. if (cmd === "new" || cmd === "reset") { - clearSession(chatId); - await replyTo("Started a fresh session. Previous context is cleared."); + void chatQueue + .run(chatId, async () => { + clearSession(chatId); + await replyTo("Started a fresh session. Previous context is cleared."); + }) + .catch((err) => console.error("[index] reset failed:", err?.message)); return; } @@ -304,46 +347,66 @@ bot.on("message", async (ctx) => { if (mapped) text = rest ? `${mapped}\n\n${rest}` : mapped; } - const attachments = await collectAttachments(ctx.message); + // Take a place in the chat's queue now, before any download or transcription, + // so a slow voice note cannot be overtaken by a quick text sent after it. The + // handler does not wait for the run: in polling mode grammy handles updates one + // at a time, and blocking here would stall every other chat (and coalescing). + const notice = (out: string) => ctx.reply(out).then(() => undefined); + const prepared = prepareMessage(ctx.message, text, notice).then((ready): ChatMessage | null => + ready + ? { + ...ready, + group: ctx.message.media_group_id, + userLabel, + replyTo, + typing: () => ctx.replyWithChatAction("typing").then(() => undefined), + } + : null, + ); + void chatQueue + .enqueue(chatId, prepared, handle) + .catch((err) => console.error("[index] Turn failed:", err?.message, err?.stack)); +}); + +/** + * Download attachments and transcribe a voice note. Resolves to null when there + * is nothing for the agent (the user has already been told why, where relevant). + */ +async function prepareMessage( + msg: any, + typed: string, + reply: (out: string) => Promise, +): Promise<{ text: string; attachments: Attachment[] } | null> { + let text = typed; + const attachments = await collectAttachments(msg); // Voice notes have no audio path to the model, so transcribe and treat the // transcript as the user's text. A caption (text) takes precedence if both. if (!text.trim()) { - const isVoice = Boolean(ctx.message?.voice || ctx.message?.audio || ctx.message?.video_note); + const isVoice = Boolean(msg?.voice || msg?.audio || msg?.video_note); if (isVoice && !transcriptionAvailable()) { - await ctx.reply( - "I can't transcribe voice notes in this setup. Type it out and I've got you.", - ); - return; + await reply("I can't transcribe voice notes in this setup. Type it out and I've got you."); + return null; } try { - const transcript = await transcribeVoiceNote(ctx.message); + const transcript = await transcribeVoiceNote(msg); if (transcript === "") { if (isVoice) { - await ctx.reply("I couldn't make out that voice note. Try again, or type it out."); + await reply("I couldn't make out that voice note. Try again, or type it out."); } } else if (transcript != null) { text = transcript; } } catch (err) { console.error("[index] transcription failed:", (err as Error).message); - await ctx.reply("I had trouble transcribing that voice note. Type it out and I've got you."); - return; + await reply("I had trouble transcribing that voice note. Type it out and I've got you."); + return null; } } - if (!text.trim() && attachments.length === 0) return; - - await handle({ - chatId, - userId, - userLabel, - text, - attachments, - typing: () => ctx.replyWithChatAction("typing").then(() => undefined), - replyTo, - }); -}); + if (!text.trim() && attachments.length === 0) return null; + return { text, attachments }; +} bot.catch((err) => { console.error("[index] Bot error:", err.message); diff --git a/src/notion/dashboard-sync.ts b/src/notion/dashboard-sync.ts new file mode 100644 index 0000000..348cb1e --- /dev/null +++ b/src/notion/dashboard-sync.ts @@ -0,0 +1,203 @@ +import { spawn as nodeSpawn } from "node:child_process"; +import path from "node:path"; + +/** + * Host-side Dashboard sync. + * + * `scripts/notion.ts sync-dashboard` is deterministic (it re-derives the This + * Week, Goals and Body Stats tiles from the databases), so the host runs it + * after the reply instead of the model running it inside its turn, where it + * cost 9 to 17 seconds plus a model round-trip. + */ + +// Helper subcommands that add or change rows the three data tiles are built from. +const ROW_WRITE_COMMANDS = new Set(["log"]); + +// Matches the helper script argument as .ts (source) or .mjs/.js, with or without a path. +const HELPER_SCRIPT = /(?:^|[\\/])notion\.(?:ts|mjs|js)$/; + +/** + * Splits a shell command into segments (at unquoted ;, &, |, newlines) of + * arguments with quotes removed, roughly as the shell would hand them to argv. + * Quote-aware so a "--dry-run" or ";" inside a --set value stays part of that + * value, exactly as the helper sees it. + */ +function shellSegments(command: string): string[][] { + const segments: string[][] = []; + let tokens: string[] = []; + let token = ""; + let inToken = false; + let quote: '"' | "'" | null = null; + const endToken = () => { + if (inToken) tokens.push(token); + token = ""; + inToken = false; + }; + const endSegment = () => { + endToken(); + if (tokens.length) segments.push(tokens); + tokens = []; + }; + for (let i = 0; i < command.length; i++) { + const c = command[i]; + if (quote) { + if (c === quote) quote = null; + else if (c === "\\" && quote === '"' && i + 1 < command.length) token += command[++i]; + else token += c; + } else if (c === '"' || c === "'") { + quote = c; + inToken = true; + } else if (c === "\\" && i + 1 < command.length) { + // A backslash-newline is a line continuation, not a separator. + const next = command[++i]; + if (next === "\r" && command[i + 1] === "\n") i++; + if (next === "\n" || next === "\r") endToken(); + else { + token += next; + inToken = true; + } + } else if (/\s/.test(c) && c !== "\n") { + endToken(); + } else if (c === ";" || c === "&" || c === "|" || c === "\n") { + endSegment(); + } else { + token += c; + inToken = true; + } + } + endSegment(); + return segments; +} + +/** + * What a Bash command does to the Dashboard's data tiles: "dirty" when its last + * relevant helper call writes rows, "synced" when it is a sync-dashboard call, + * null when it touches neither. Segments are read in order, so "log && sync" + * is synced and "sync && log" is dirty. The flag checks mirror the helper's own + * main(): only a whole "--help" or "--dry-run" argument changes what it does. + */ +export function dashboardSyncEffect(command: string): "dirty" | "synced" | null { + let effect: "dirty" | "synced" | null = null; + for (const tokens of shellSegments(command)) { + const at = tokens.findIndex((t) => HELPER_SCRIPT.test(t)); + if (at === -1) continue; + const sub = tokens[at + 1]; + const rest = tokens.slice(at + 2); + if (!sub || rest.includes("--help")) continue; + if (sub === "sync-dashboard") effect = "synced"; + else if (ROW_WRITE_COMMANDS.has(sub) && !rest.includes("--dry-run")) effect = "dirty"; + } + return effect; +} + +/** Today's calendar date (YYYY-MM-DD) in the given IANA timezone. */ +export function localIsoDate(timeZone: string, at: Date = new Date()): string { + // en-CA formats dates as YYYY-MM-DD. + return new Intl.DateTimeFormat("en-CA", { + timeZone, + year: "numeric", + month: "2-digit", + day: "2-digit", + }).format(at); +} + +/** The subset of a ChildProcess the syncer uses, so tests can pass a fake. */ +export interface SyncChild { + stdout?: { on(event: "data", cb: (chunk: Buffer | string) => void): unknown } | null; + stderr?: { on(event: "data", cb: (chunk: Buffer | string) => void): unknown } | null; + on(event: "error", cb: (err: Error) => void): unknown; + on(event: "close", cb: (code: number | null, signal: string | null) => void): unknown; + kill(signal?: NodeJS.Signals): unknown; +} + +export type SyncSpawner = ( + command: string, + args: string[], + options: { cwd: string; stdio: ["ignore", "pipe", "pipe"]; windowsHide: true }, +) => SyncChild; + +export interface DashboardSyncer { + /** Start a sync for this date, or queue one if a sync is already running. Never throws. */ + request(now: string): void; +} + +export function createDashboardSyncer(opts: { + cwd: string; + spawn?: SyncSpawner; + timeoutMs?: number; + log?: (line: string) => void; +}): DashboardSyncer { + const spawnFn = opts.spawn ?? (nodeSpawn as unknown as SyncSpawner); + const timeoutMs = opts.timeoutMs ?? 60_000; + const log = opts.log ?? ((line: string) => console.log(line)); + let running = false; + // At most one queued run: the latest requested date wins, since a sync always + // re-derives everything from the databases. + let pending: string | null = null; + + const start = (now: string) => { + running = true; + const startedAt = Date.now(); + let settled = false; + let timer: NodeJS.Timeout | undefined; + + // error and close can both fire for one child; only the first one counts, + // or a queued run would start twice. + const finish = (msg: string) => { + if (settled) return; + settled = true; + if (timer) clearTimeout(timer); + log(`[dashboard] ${msg} (${Date.now() - startedAt}ms)`); + running = false; + if (pending !== null) { + const next = pending; + pending = null; + start(next); + } + }; + + try { + const child = spawnFn( + process.execPath, + [path.join("scripts", "notion.ts"), "sync-dashboard", "--now", now], + { cwd: opts.cwd, stdio: ["ignore", "pipe", "pipe"], windowsHide: true }, + ); + const forward = (chunk: Buffer | string) => { + for (const line of String(chunk).split(/\r?\n/)) { + if (line.trim()) log(`[dashboard] ${line.trim()}`); + } + }; + child.stdout?.on("data", forward); + child.stderr?.on("data", forward); + // Without an error listener a spawn failure (e.g. ENOENT) would be an + // uncaught exception and take the bot down. + child.on("error", (err) => finish(`sync failed: ${err.message}`)); + child.on("close", (code, signal) => + finish(code === 0 ? "sync done" : `sync exited with ${code ?? signal}`), + ); + timer = setTimeout(() => { + try { + child.kill(); + } catch { + /* already gone */ + } + // Settle here rather than waiting for close, so a child that ignores + // the kill can never wedge the queue. + finish(`sync timed out after ${timeoutMs}ms, killed`); + }, timeoutMs); + timer.unref?.(); + } catch (err) { + finish(`sync failed to start: ${(err as Error).message}`); + } + }; + + return { + request(now: string) { + if (running) { + pending = now; + return; + } + start(now); + }, + }; +} diff --git a/src/scheduler/scheduler.ts b/src/scheduler/scheduler.ts index 3909671..87d28ac 100644 --- a/src/scheduler/scheduler.ts +++ b/src/scheduler/scheduler.ts @@ -1,6 +1,7 @@ import fs from "node:fs"; import { Cron } from "croner"; import { type ModelTier, runAgent } from "../agent/runner.js"; +import { chatQueue } from "../channel/chat-queue.js"; import { sendMessage } from "../channel/notify.js"; import { config } from "../config.js"; import { writeJsonAtomic } from "../util/atomicfile.js"; @@ -96,12 +97,16 @@ export function getTask(id: string): ScheduledTask | undefined { export async function executeTask(task: ScheduledTask): Promise { console.log(`[scheduler] Running: ${task.name}`); try { - const response = await runAgent({ - userMessage: task.prompt, - chatId: task.chatId, - userLabel: "scheduled task", - modelTier: task.modelTier ?? "standard", - }); + // Same per-chat queue as Telegram messages: a reminder resumes the chat's + // session, so it must not run alongside a message for that chat. + const response = await chatQueue.run(task.chatId, () => + runAgent({ + userMessage: task.prompt, + chatId: task.chatId, + userLabel: "scheduled task", + modelTier: task.modelTier ?? "standard", + }), + ); await sendMessage(task.chatId, response.text || "(no output)"); } catch (err: any) { console.error(`[scheduler] Task ${task.name} failed:`, err.message); diff --git a/tests/chat-queue.test.ts b/tests/chat-queue.test.ts new file mode 100644 index 0000000..dc0c7b4 --- /dev/null +++ b/tests/chat-queue.test.ts @@ -0,0 +1,226 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { ChatQueue, joinMessages } from "../dist/channel/chat-queue.js"; + +const tick = (ms = 5) => new Promise((r) => setTimeout(r, ms)); + +/** A promise plus its resolver, for holding a task open until the test says so. */ +function gate() { + let open!: (value: T) => void; + const promise = new Promise((r) => { + open = r; + }); + return { promise, open }; +} + +test("tasks for one chat run one at a time, in arrival order", async () => { + const q = new ChatQueue(); + const log: string[] = []; + let running = 0; + const task = (name: string, ms: number) => async () => { + running++; + assert.equal(running, 1, "two tasks for the same chat overlapped"); + log.push(`start ${name}`); + await tick(ms); + log.push(`end ${name}`); + running--; + }; + await Promise.all([ + q.run("a", task("1", 15)), + q.run("a", task("2", 1)), + q.run("a", task("3", 5)), + ]); + assert.deepEqual(log, ["start 1", "end 1", "start 2", "end 2", "start 3", "end 3"]); +}); + +test("a rejected task reaches its caller and does not wedge the queue", async () => { + const q = new ChatQueue(); + const failed = q.run("a", async () => { + throw new Error("boom"); + }); + const next = q.run("a", async () => "still going"); + await assert.rejects(failed, /boom/); + assert.equal(await next, "still going"); +}); + +test("a failing message handler does not wedge the queue either", async () => { + const q = new ChatQueue(); + const first = q.enqueue("a", "one", async () => { + throw new Error("handler failed"); + }); + await assert.rejects(first, /handler failed/); + const seen: string[][] = []; + await q.enqueue("a", "two", async (_k, batch: string[]) => { + seen.push(batch); + }); + assert.deepEqual(seen, [["two"]]); +}); + +test("different chats do not wait on each other", async () => { + const q = new ChatQueue(); + const held = gate(); + const slow = q.run("a", () => held.promise); + let otherRan = false; + await q.run("b", async () => { + otherRan = true; + }); + assert.equal(otherRan, true); + held.open(); + await slow; +}); + +test("idle chats leave nothing behind", async () => { + const q = new ChatQueue(); + await Promise.all([ + q.run("a", async () => {}), + q + .run("b", async () => { + throw new Error("x"); + }) + .catch(() => {}), + q.enqueue("c", "m", async () => {}), + q.enqueue("d", null, async () => {}), + ]); + await tick(); + assert.equal(q.activeChats, 0); +}); + +test("messages waiting behind a run are handed over together, in order", async () => { + const q = new ChatQueue(); + const batches: string[][] = []; + const held = gate(); + const handler = async (_k: string, batch: string[]) => { + batches.push(batch); + if (batches.length === 1) await held.promise; + }; + const first = q.enqueue("a", "one", handler); + await tick(); + const rest = [q.enqueue("a", "two", handler), q.enqueue("a", "three", handler)]; + held.open(); + await Promise.all([first, ...rest]); + assert.deepEqual(batches, [["one"], ["two", "three"]]); +}); + +test("arrival order wins even when an earlier message prepares slowly", async () => { + const q = new ChatQueue(); + const batches: string[][] = []; + const voice = gate(); + const done = [ + q.enqueue("a", voice.promise, async (_k, b: string[]) => { + batches.push(b); + }), + q.enqueue("a", "typed after", async (_k, b: string[]) => { + batches.push(b); + }), + ]; + await tick(); + voice.open("voice transcript"); + await Promise.all(done); + assert.deepEqual(batches, [["voice transcript", "typed after"]]); +}); + +test("messages that prepare to nothing are dropped without a run", async () => { + const q = new ChatQueue(); + let calls = 0; + await Promise.all([ + q.enqueue("a", null, async () => { + calls++; + }), + q.enqueue("a", Promise.reject(new Error("download failed")), async () => { + calls++; + }), + ]); + assert.equal(calls, 0); +}); + +test("a preparation that fails while waiting behind a long run is dropped quietly", async () => { + const q = new ChatQueue(); + const held = gate(); + const seen: string[][] = []; + const first = q.enqueue("a", "one", () => held.promise); + await tick(); + const record = async (_k: string, b: string[]) => { + seen.push(b); + }; + const failing = q.enqueue("a", Promise.reject(new Error("reply failed")), record); + const after = q.enqueue("a", "two", record); + // Give an unhandled rejection the chance to surface before the run finishes. + await tick(20); + held.open(); + await Promise.all([first, failing, after]); + assert.deepEqual(seen, [["two"]]); +}); + +test("a run() task is never merged and keeps its place in line", async () => { + const q = new ChatQueue(); + const log: string[] = []; + const held = gate(); + const handler = async (_k: string, batch: string[]) => { + log.push(batch.join("+")); + if (batch[0] === "one") await held.promise; + }; + const all = [ + q.enqueue("a", "one", handler), + q.enqueue("a", "two", handler), + q.run("a", async () => { + log.push("reset"); + }), + q.enqueue("a", "three", handler), + ]; + await tick(); + held.open(); + await Promise.all(all); + // "two" joined "one" (both waiting before the run started); "three" came after the reset. + assert.deepEqual(log, ["one+two", "reset", "three"]); +}); + +test("joinMessages keeps text and attachments in order", () => { + const joined = joinMessages([ + { text: "did squats 5x5 at 80", attachments: [] }, + { text: " ", attachments: ["photo-1"] }, + { text: "and bench 3x8", attachments: ["photo-2", "pdf-1"] }, + ]); + assert.equal( + joined.text, + "did squats 5x5 at 80\n\n(attachment 1, no caption)\n\nand bench 3x8 (attachments 2, 3)", + ); + assert.deepEqual(joined.attachments, ["photo-1", "photo-2", "pdf-1"]); +}); + +test("joinMessages ties each caption to its own photo", () => { + const joined = joinMessages([ + { text: "", attachments: ["meal-a"] }, + { text: "lunch", attachments: ["meal-b"] }, + ]); + assert.equal(joined.text, "(attachment 1, no caption)\n\nlunch (attachment 2)"); + assert.deepEqual(joined.attachments, ["meal-a", "meal-b"]); +}); + +test("joinMessages leaves an album and plain text batches untagged", () => { + // Telegram sends an album as one message per photo, captioned on the first only. + const album = joinMessages([ + { text: "breakfast", attachments: ["p1"], group: "g1" }, + { text: "", attachments: ["p2"], group: "g1" }, + { text: "", attachments: ["p3"], group: "g1" }, + ]); + assert.equal(album.text, "breakfast"); + assert.deepEqual(album.attachments, ["p1", "p2", "p3"]); + + const texts = joinMessages([ + { text: "squats 5x5", attachments: [] }, + { text: "felt heavy", attachments: [] }, + ]); + assert.equal(texts.text, "squats 5x5\n\nfelt heavy"); + + const single = joinMessages([{ text: "lunch", attachments: ["p1"] }]); + assert.equal(single.text, "lunch"); +}); + +test("joinMessages numbers attachments across an album and a later photo", () => { + const joined = joinMessages([ + { text: "breakfast", attachments: ["p1"], group: "g1" }, + { text: "", attachments: ["p2"], group: "g1" }, + { text: "dinner", attachments: ["p3"] }, + ]); + assert.equal(joined.text, "breakfast (attachments 1, 2)\n\ndinner (attachment 3)"); +}); diff --git a/tests/dashboard-sync.test.ts b/tests/dashboard-sync.test.ts new file mode 100644 index 0000000..22c7595 --- /dev/null +++ b/tests/dashboard-sync.test.ts @@ -0,0 +1,240 @@ +import assert from "node:assert/strict"; +import { EventEmitter } from "node:events"; +import { test } from "node:test"; +import { + createDashboardSyncer, + dashboardSyncEffect, + localIsoDate, +} from "../dist/notion/dashboard-sync.js"; + +// ─── detection ──────────────────────────────────────────────────────────────── + +test("a helper log call marks the Dashboard dirty", () => { + assert.equal( + dashboardSyncEffect('node scripts/notion.ts log --db "Workout Log" --set "Session=Push A"'), + "dirty", + ); +}); + +test("the container form with cd and the .mjs script counts", () => { + assert.equal( + dashboardSyncEffect('cd /data && node /app/scripts/notion.mjs log --db "Workout Log"'), + "dirty", + ); +}); + +test("multi-line log with backslash continuations counts", () => { + const cmd = [ + 'node scripts/notion.ts log --db "Workout Log" \\', + ' --set "Session=Push A" --set "Date=2026-06-23" \\', + ' --set "RPE (1-10)=8"', + ].join("\n"); + assert.equal(dashboardSyncEffect(cmd), "dirty"); +}); + +test("log --dry-run does not count, even on a continuation line", () => { + assert.equal(dashboardSyncEffect('node scripts/notion.ts log --db "Goals" --dry-run'), null); + assert.equal( + dashboardSyncEffect('node scripts/notion.ts log --db "Workout Log" \\\n --dry-run'), + null, + ); +}); + +test("--help does not count", () => { + assert.equal(dashboardSyncEffect("node scripts/notion.ts --help"), null); + assert.equal(dashboardSyncEffect("node scripts/notion.ts log --help"), null); + // A help call after a write must not clear the dirty state either. + assert.equal( + dashboardSyncEffect( + 'node scripts/notion.ts log --db "Goals" && node scripts/notion.ts sync-dashboard --help', + ), + "dirty", + ); +}); + +test("flag-like words inside a quoted value, or -h after the subcommand, still count as writes", () => { + // The helper only honours a whole --help or --dry-run argument, and -h only + // as the command itself, so these all write the row. + for (const cmd of [ + 'node scripts/notion.ts log --db "Workout Log" --set "Notes=3x5 -h grip"', + 'node scripts/notion.ts log --db "Workout Log" --set "Notes=skipped the --dry-run idea"', + "node scripts/notion.ts log --db 'Workout Log' --set 'Notes=read --help later'", + 'node scripts/notion.ts log --db "Workout Log" --set "Notes=felt good" -h', + ]) { + assert.equal(dashboardSyncEffect(cmd), "dirty", cmd); + } +}); + +test("an unquoted --dry-run after a quoted value still means no write", () => { + assert.equal( + dashboardSyncEffect( + 'node scripts/notion.ts log --db "Workout Log" --set "Notes=x y" --dry-run', + ), + null, + ); +}); + +test("read-only and non-row subcommands do not count", () => { + assert.equal(dashboardSyncEffect('node scripts/notion.ts query-recent --db "Workout Log"'), null); + assert.equal(dashboardSyncEffect("node scripts/notion.ts append --page abc --md 'x'"), null); + assert.equal(dashboardSyncEffect("node scripts/notion.ts refresh-tile --tile nextSession"), null); + assert.equal(dashboardSyncEffect("ls data && cat PERSONAL.md"), null); +}); + +test("sync-dashboard reports synced", () => { + assert.equal( + dashboardSyncEffect("node scripts/notion.ts sync-dashboard --now 2026-06-30"), + "synced", + ); +}); + +test("order within one command decides: log then sync is synced, sync then log is dirty", () => { + assert.equal( + dashboardSyncEffect( + 'node scripts/notion.ts log --db "Body Stats" --set "Bodyweight=80" && node scripts/notion.ts sync-dashboard --now 2026-06-30', + ), + "synced", + ); + assert.equal( + dashboardSyncEffect( + 'node scripts/notion.ts sync-dashboard --now 2026-06-30; node scripts/notion.ts log --db "Goals" --set "Goal=Squat 100kg"', + ), + "dirty", + ); +}); + +test("a quoted separator inside a --set value does not hide the write", () => { + assert.equal( + dashboardSyncEffect( + 'node scripts/notion.ts log --db "Workout Log" --set "Notes=bench; then OHP" --set "RPE=8"', + ), + "dirty", + ); +}); + +test("a quoted script path with spaces is recognised", () => { + assert.equal( + dashboardSyncEffect('node "/home/me/my repo/scripts/notion.ts" log --db "Workout Log"'), + "dirty", + ); +}); + +// ─── date ───────────────────────────────────────────────────────────────────── + +test("localIsoDate uses the configured timezone, not UTC", () => { + // 23:30 UTC on the 1st is already the 2nd in Rome and still the 1st in New York. + const at = new Date("2026-03-01T23:30:00Z"); + assert.equal(localIsoDate("Europe/Rome", at), "2026-03-02"); + assert.equal(localIsoDate("America/New_York", at), "2026-03-01"); + assert.equal(localIsoDate("UTC", at), "2026-03-01"); +}); + +// ─── spawn and coalesce ─────────────────────────────────────────────────────── + +class FakeChild extends EventEmitter { + stdout = new EventEmitter(); + stderr = new EventEmitter(); + killed = false; + kill() { + this.killed = true; + return true; + } +} + +function harness(timeoutMs = 60_000) { + const spawns: { command: string; args: string[]; cwd: string; child: FakeChild }[] = []; + const lines: string[] = []; + const syncer = createDashboardSyncer({ + cwd: "/app", + timeoutMs, + log: (line) => lines.push(line), + spawn: (command, args, options) => { + const child = new FakeChild(); + spawns.push({ command, args, cwd: options.cwd, child }); + return child; + }, + }); + return { syncer, spawns, lines }; +} + +test("spawns the helper's sync-dashboard with the date from the project root", () => { + const { syncer, spawns } = harness(); + syncer.request("2026-06-30"); + assert.equal(spawns.length, 1); + assert.equal(spawns[0].command, process.execPath); + assert.match(spawns[0].args[0], /scripts[\\/]notion\.ts$/); + assert.deepEqual(spawns[0].args.slice(1), ["sync-dashboard", "--now", "2026-06-30"]); + assert.equal(spawns[0].cwd, "/app"); +}); + +test("logs child output and the exit under the [dashboard] prefix", () => { + const { syncer, spawns, lines } = harness(); + syncer.request("2026-06-30"); + spawns[0].child.stdout.emit("data", Buffer.from("Synced Dashboard tiles\n")); + spawns[0].child.stderr.emit("data", "rate limited, retrying\n"); + spawns[0].child.emit("close", 0, null); + assert.ok(lines.includes("[dashboard] Synced Dashboard tiles")); + assert.ok(lines.includes("[dashboard] rate limited, retrying")); + assert.ok(lines.some((l) => l.startsWith("[dashboard] sync done"))); +}); + +test("overlapping requests collapse into one follow-up run with the latest date", () => { + const { syncer, spawns } = harness(); + syncer.request("2026-06-29"); + syncer.request("2026-06-30"); + syncer.request("2026-07-01"); + assert.equal(spawns.length, 1, "no second process while one is running"); + + spawns[0].child.emit("close", 0, null); + assert.equal(spawns.length, 2, "exactly one queued run starts"); + assert.equal(spawns[1].args.at(-1), "2026-07-01"); + + spawns[1].child.emit("close", 0, null); + assert.equal(spawns.length, 2, "nothing left pending"); +}); + +test("error followed by close settles once, so a queued run starts only once", () => { + const { syncer, spawns, lines } = harness(); + syncer.request("2026-06-30"); + syncer.request("2026-07-01"); + spawns[0].child.emit("error", new Error("spawn ENOENT")); + spawns[0].child.emit("close", -2, null); + assert.equal(spawns.length, 2); + assert.ok(lines.some((l) => l.includes("sync failed: spawn ENOENT"))); +}); + +test("a non-zero exit is logged and the syncer stays usable", () => { + const { syncer, spawns, lines } = harness(); + syncer.request("2026-06-30"); + spawns[0].child.emit("close", 1, null); + assert.ok(lines.some((l) => l.includes("sync exited with 1"))); + syncer.request("2026-06-30"); + assert.equal(spawns.length, 2); +}); + +test("a hung sync is killed after the timeout and does not wedge the queue", async () => { + const { syncer, spawns, lines } = harness(20); + syncer.request("2026-06-30"); + syncer.request("2026-07-01"); + await new Promise((r) => setTimeout(r, 60)); + assert.equal(spawns[0].child.killed, true); + assert.ok(lines.some((l) => l.includes("timed out"))); + assert.equal(spawns.length, 2, "the queued run started after the timeout"); + spawns[1].child.emit("close", 0, null); +}); + +test("a spawner that throws never escapes request()", () => { + const lines: string[] = []; + const syncer = createDashboardSyncer({ + cwd: "/app", + log: (line) => lines.push(line), + spawn: () => { + throw new Error("EAGAIN"); + }, + }); + assert.doesNotThrow(() => syncer.request("2026-06-30")); + assert.ok(lines.some((l) => l.includes("failed to start: EAGAIN"))); + // Not stuck in the running state. + assert.doesNotThrow(() => syncer.request("2026-06-30")); + assert.equal(lines.filter((l) => l.includes("failed to start")).length, 2); +}); diff --git a/tests/progress.test.ts b/tests/progress.test.ts new file mode 100644 index 0000000..26c1480 --- /dev/null +++ b/tests/progress.test.ts @@ -0,0 +1,220 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { + ProgressReporter, + describeActivity, + progressUpdatesEnabled, +} from "../dist/channel/progress.js"; + +const tick = (ms: number) => new Promise((r) => setTimeout(r, ms)); + +/** Records every Telegram call the reporter makes. */ +function fakeTransport(opts: { sendDelayMs?: number } = {}) { + const calls: string[] = []; + let nextId = 100; + return { + calls, + transport: { + send: async (text: string) => { + if (opts.sendDelayMs) await tick(opts.sendDelayMs); + const id = nextId++; + calls.push(`send ${id} ${text}`); + return id; + }, + edit: async (id: number, text: string) => { + calls.push(`edit ${id} ${text}`); + }, + remove: async (id: number) => { + calls.push(`remove ${id}`); + }, + }, + }; +} + +test("maps notion, calendar and exercise commands to plain phases", () => { + const bash = (command: string) => describeActivity({ tool: "Bash", command }); + assert.equal( + bash('node scripts/notion.ts query-recent --db "Workout Log" --limit 5'), + "Checking your training log...", + ); + assert.equal( + bash("node scripts/notion.ts get-page-blocks abc123"), + "Checking your training log...", + ); + assert.equal(bash("node scripts/notion.ts log --json '{}'"), "Saving it to Notion..."); + assert.equal( + bash("node scripts/notion.ts log --db \"Body Stats\" --json '{}'"), + "Saving it to Notion...", + ); + // A hypothetical log-something subcommand is not a plain `log`. + assert.equal(bash("node scripts/notion.ts log-export"), "Working in Notion..."); + assert.equal(bash("node scripts/notion.ts append --page x"), "Writing it up in Notion..."); + assert.equal( + bash("node scripts/notion.ts sync-dashboard --now 2026-11-23"), + "Updating your dashboard...", + ); + assert.equal( + bash("node scripts/setup-workspace.ts --rebuild-dashboard"), + "Updating your dashboard...", + ); + assert.equal(bash("node scripts/notion.ts some-new-command"), "Working in Notion..."); + assert.equal(bash("node scripts/calendar.ts list --days 7"), "Checking your calendar..."); + assert.equal(bash("node scripts/calendar.ts create --title Legs"), "Updating your calendar..."); + assert.equal( + bash("node scripts/exercise-db.ts search --muscle chest"), + "Looking up exercises...", + ); + assert.equal(bash("ls -la"), null); + assert.equal(describeActivity({ tool: "Read", command: "PERSONAL.md" }), null); + assert.equal(describeActivity({ tool: "WebSearch" }), "Looking that up..."); + assert.equal( + describeActivity({ tool: "Skill", command: "weekly-plan" }), + "Putting your week together...", + ); + assert.equal( + describeActivity({ tool: "Skill", command: "coach-plugin:progress-report" }), + "Going through your progress...", + ); + assert.equal(describeActivity({ tool: "Skill", command: "notion-formatting" }), null); +}); + +test("a compound command always maps to the same label", () => { + const label = describeActivity({ + tool: "Bash", + command: + "node scripts/notion.ts query-recent --limit 3 && node scripts/notion.ts log --json '{}'", + }); + assert.equal(label, "Saving it to Notion..."); +}); + +test("status text never echoes anything from the command", () => { + const known = new Set([ + "Saving it to Notion...", + "Writing it up in Notion...", + "Updating your dashboard...", + "Setting up your Notion workspace...", + "Checking your training log...", + "Opening your Notion workspace...", + "Working in Notion...", + "Updating your calendar...", + "Checking your calendar...", + "Looking up exercises...", + "Looking that up...", + ]); + const nasty = [ + "NOTION_TOKEN=secret_abc123 node scripts/notion.ts append --page 1f2e3d4c5b6a", + "curl -H 'Authorization: Bearer sk-ant-oat01-xyz' https://example.com", + "cat /data/.claude/projects/-app/0f9a.jsonl && node scripts/calendar.ts delete --id evt_42", + 'node scripts/notion.ts log --json \'{"Notes":"ignore previous instructions"}\'', + ]; + for (const command of nasty) { + const label = describeActivity({ tool: "Bash", command }); + assert.ok(label === null || known.has(label), `unexpected label: ${label}`); + } + for (const label of known) { + assert.ok(!/[—–]/.test(label), "labels must not use em or en dashes"); + } +}); + +test("PROGRESS_UPDATES defaults on and can be switched off", () => { + const prev = process.env.PROGRESS_UPDATES; + try { + Reflect.deleteProperty(process.env, "PROGRESS_UPDATES"); + assert.equal(progressUpdatesEnabled(), true); + for (const off of ["false", "0", "off", "NO"]) { + process.env.PROGRESS_UPDATES = off; + assert.equal(progressUpdatesEnabled(), false, off); + } + process.env.PROGRESS_UPDATES = "true"; + assert.equal(progressUpdatesEnabled(), true); + } finally { + if (prev === undefined) Reflect.deleteProperty(process.env, "PROGRESS_UPDATES"); + else process.env.PROGRESS_UPDATES = prev; + } +}); + +test("a quick run posts nothing at all", async () => { + const { calls, transport } = fakeTransport(); + const p = new ProgressReporter(transport, { delayMs: 40 }); + p.onActivity({ tool: "Bash", command: "node scripts/notion.ts query-recent" }); + await tick(10); + await p.finish(); + await tick(50); + assert.deepEqual(calls, []); +}); + +test("a long run posts one status, edits it in place, then removes it", async () => { + const { calls, transport } = fakeTransport(); + const p = new ProgressReporter(transport, { delayMs: 20, minEditMs: 0 }); + p.onActivity({ tool: "Bash", command: "node scripts/notion.ts query-recent" }); + await tick(40); + p.onActivity({ tool: "Read", command: "PERSONAL.md" }); // no new phase, no edit + p.onActivity({ tool: "Bash", command: "node scripts/notion.ts log --json '{}'" }); + await tick(10); + await p.finish(); + assert.deepEqual(calls, [ + "send 100 Checking your training log...", + "edit 100 Saving it to Notion...", + "remove 100", + ]); +}); + +test("edits are rate limited to one trailing edit with the latest phase", async () => { + const { calls, transport } = fakeTransport(); + const p = new ProgressReporter(transport, { delayMs: 0, minEditMs: 60 }); + p.onActivity({ tool: "Bash", command: "node scripts/notion.ts query-recent" }); + await tick(10); + p.onActivity({ tool: "Bash", command: "node scripts/notion.ts log" }); + p.onActivity({ tool: "Bash", command: "node scripts/notion.ts append" }); + p.onActivity({ tool: "Bash", command: "node scripts/notion.ts sync-dashboard" }); + await tick(150); + await p.finish(); + assert.deepEqual(calls, [ + "send 100 Checking your training log...", + "edit 100 Updating your dashboard...", + "remove 100", + ]); +}); + +test("finishing while the status is still sending removes it once it lands", async () => { + const { calls, transport } = fakeTransport({ sendDelayMs: 30 }); + const p = new ProgressReporter(transport, { delayMs: 0 }); + p.onActivity({ tool: "WebSearch" }); + await tick(5); + await p.finish(); + assert.deepEqual(calls, ["send 100 Looking that up...", "remove 100"]); + p.onActivity({ tool: "Bash", command: "node scripts/notion.ts log" }); + await tick(10); + assert.equal(calls.length, 2, "nothing is sent after finish"); +}); + +test("an unrecognised tool still shows a generic status on a long run", async () => { + const { calls, transport } = fakeTransport(); + const p = new ProgressReporter(transport, { delayMs: 10 }); + p.onActivity({ tool: "Grep", command: "squat" }); + await tick(30); + await p.finish(); + assert.deepEqual(calls, ["send 100 Working on it...", "remove 100"]); +}); + +test("a failing transport never throws into the run", async () => { + const p = new ProgressReporter( + { + send: async () => { + throw new Error("telegram down"); + }, + edit: async () => { + throw new Error("telegram down"); + }, + remove: async () => { + throw new Error("telegram down"); + }, + }, + { delayMs: 0, minEditMs: 0 }, + ); + p.onActivity({ tool: "WebSearch" }); + await tick(5); + p.onActivity({ tool: "Bash", command: "node scripts/notion.ts log" }); + await tick(5); + await p.finish(); +}); diff --git a/tests/runner-activity.test.ts b/tests/runner-activity.test.ts new file mode 100644 index 0000000..ded3f65 --- /dev/null +++ b/tests/runner-activity.test.ts @@ -0,0 +1,141 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { beforeEach, mock, test } from "node:test"; + +// Same setup as runner-retry.test.ts: config is read at import time, so env is +// set first, and nothing may touch the real data/ directory. NOTION_TOKEN is a +// dummy so the host sync path is reachable; the syncer itself is mocked, so no +// process is spawned and no network is hit. +process.env.TELEGRAM_BOT_TOKEN ??= "0:test"; +process.env.NOTION_TOKEN = "secret_test"; +process.env.HOST_DASHBOARD_SYNC = "true"; +const TMP_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "oak-runner-activity-")); +process.env.SESSION_FILE = path.join(TMP_DIR, "sessions.json"); +process.env.RUN_LOG_FILE = path.join(TMP_DIR, "agent-runs.jsonl"); + +let messages: unknown[] = []; + +mock.module("@anthropic-ai/claude-agent-sdk", { + namedExports: { + query: () => + (async function* () { + for (const message of messages) yield message; + })(), + }, +}); + +// Keep the real pure detection, replace only the syncer. The "?real" query +// loads a separate instance that the mock below does not intercept. +const syncModuleUrl = new URL("../dist/notion/dashboard-sync.js", import.meta.url).href; +const real = await import(`${syncModuleUrl}?real`); +const syncRequests: string[] = []; +mock.module(syncModuleUrl, { + namedExports: { + dashboardSyncEffect: real.dashboardSyncEffect, + localIsoDate: real.localIsoDate, + createDashboardSyncer: () => ({ request: (now: string) => syncRequests.push(now) }), + }, +}); + +const { runAgent } = await import("../dist/agent/runner.js"); + +const init = { type: "system", subtype: "init", session_id: "sess-activity" }; +const ok = { type: "result", subtype: "success", is_error: false, result: "Logged." }; +const toolUse = (name: string, input: Record, parent: string | null = null) => ({ + type: "assistant", + parent_tool_use_id: parent, + message: { content: [{ type: "tool_use", id: `t-${Math.random()}`, name, input }] }, +}); +const bash = (command: string) => toolUse("Bash", { command }); + +const LOG = 'node scripts/notion.ts log --db "Workout Log" --set "Session=Push A"'; +const SYNC = "node scripts/notion.ts sync-dashboard --now 2026-06-30"; + +let chat = 0; +const run = (onActivity?: (e: { tool: string; command?: string }) => void) => + runAgent({ userMessage: "did push day", chatId: `chat-activity-${++chat}`, onActivity }); + +beforeEach(() => { + messages = []; + syncRequests.length = 0; +}); + +test("onActivity fires once per top-level tool_use with the Bash command or Skill name", async () => { + messages = [ + init, + toolUse("Skill", { skill: "log-workout" }), + bash(LOG), + toolUse("Read", { file_path: "PERSONAL.md" }), + toolUse("Bash", { command: "echo from a subagent" }, "parent-1"), + ok, + ]; + const events: { tool: string; command?: string }[] = []; + await run((e) => events.push(e)); + + assert.deepEqual(events, [ + { tool: "Skill", command: "log-workout" }, + { tool: "Bash", command: LOG }, + { tool: "Read" }, + ]); +}); + +test("onActivity commands are truncated to 200 characters", async () => { + messages = [init, bash(`echo ${"x".repeat(500)}`), ok]; + const events: { tool: string; command?: string }[] = []; + await run((e) => events.push(e)); + assert.equal(events[0].command?.length, 200); +}); + +test("a throwing or rejecting onActivity never breaks the run", async () => { + messages = [init, bash("ls"), bash("pwd"), ok]; + const sync = await run(() => { + throw new Error("telegram down"); + }); + assert.equal(sync.text, "Logged."); + + const async = await run((() => Promise.reject(new Error("telegram down"))) as () => void); + assert.equal(async.text, "Logged."); +}); + +test("a helper log write triggers one host sync with today's date", async () => { + messages = [init, bash(LOG), ok]; + await run(); + assert.equal(syncRequests.length, 1); + assert.match(syncRequests[0], /^\d{4}-\d{2}-\d{2}$/); +}); + +test("no host sync when the agent already synced after its write", async () => { + messages = [init, bash(LOG), bash(SYNC), ok]; + await run(); + assert.equal(syncRequests.length, 0); +}); + +test("a sync before the write does not count as synced", async () => { + messages = [init, bash(SYNC), bash(LOG), ok]; + await run(); + assert.equal(syncRequests.length, 1); +}); + +test("no host sync for read-only runs, dry runs, or subagent tool calls", async () => { + messages = [ + init, + bash('node scripts/notion.ts query-recent --db "Workout Log"'), + bash(`${LOG} --dry-run`), + toolUse("Bash", { command: LOG }, "parent-1"), + ok, + ]; + await run(); + assert.equal(syncRequests.length, 0); +}); + +test("a write is still synced when the run then ends in an error result", async () => { + messages = [ + init, + bash(LOG), + { type: "result", subtype: "error_max_turns", is_error: true, result: "" }, + ]; + await run(); + assert.equal(syncRequests.length, 1); +}); diff --git a/tests/runner-sync-off.test.ts b/tests/runner-sync-off.test.ts new file mode 100644 index 0000000..94ab2a5 --- /dev/null +++ b/tests/runner-sync-off.test.ts @@ -0,0 +1,61 @@ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { mock, test } from "node:test"; + +// Its own file because config is read at import time: this one runs with the +// host Dashboard sync switched off, and checks the agent is told to sync itself. +process.env.TELEGRAM_BOT_TOKEN ??= "0:test"; +process.env.NOTION_TOKEN = "secret_test"; +process.env.HOST_DASHBOARD_SYNC = "off"; +const TMP_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "oak-runner-sync-off-")); +process.env.SESSION_FILE = path.join(TMP_DIR, "sessions.json"); +process.env.RUN_LOG_FILE = path.join(TMP_DIR, "agent-runs.jsonl"); + +const prompts: string[] = []; +mock.module("@anthropic-ai/claude-agent-sdk", { + namedExports: { + query: ({ prompt }: { prompt: AsyncIterable<{ message: { content: unknown } }> }) => + (async function* () { + for await (const m of prompt) prompts.push(JSON.stringify(m.message.content)); + yield { type: "system", subtype: "init", session_id: "sess-sync-off" }; + yield { + type: "assistant", + parent_tool_use_id: null, + message: { + content: [ + { + type: "tool_use", + id: "t-1", + name: "Bash", + input: { command: 'node scripts/notion.ts log --db "Workout Log"' }, + }, + ], + }, + }; + yield { type: "result", subtype: "success", is_error: false, result: "Logged." }; + })(), + }, +}); + +const syncModuleUrl = new URL("../dist/notion/dashboard-sync.js", import.meta.url).href; +const real = await import(`${syncModuleUrl}?real`); +const syncRequests: string[] = []; +mock.module(syncModuleUrl, { + namedExports: { + dashboardSyncEffect: real.dashboardSyncEffect, + localIsoDate: real.localIsoDate, + createDashboardSyncer: () => ({ request: (now: string) => syncRequests.push(now) }), + }, +}); + +const { runAgent } = await import("../dist/agent/runner.js"); + +test("with HOST_DASHBOARD_SYNC off the agent is told to sync and the host does not", async () => { + const res = await runAgent({ userMessage: "did push day", chatId: "chat-sync-off" }); + assert.equal(res.text, "Logged."); + assert.equal(prompts.length, 1); + assert.match(prompts[0], /host Dashboard sync is off/); + assert.equal(syncRequests.length, 0); +});