catence 0.2.0-beta.10 → 0.2.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -22,14 +22,14 @@ Catence helps explore recovery, training load, trends, activity detail, swimming
22
22
 
23
23
  ## Quick start
24
24
 
25
- Install Catence and create the first athlete. The default catalog home is `~/.catence`; set `CATENCE_HOME` or pass `--home` to use a different location. For the full local or Docker deployment walkthrough, see [deployment notes](docs/deployment.md).
25
+ Install Catence and create the first athlete. The default catalog home is `~/.catence`; set `CATENCE_HOME` or pass `--home` to use a different location.
26
26
 
27
27
  ```sh
28
- npm install --global catence@0.2.0
28
+ npm install --global catence@beta # or catence@latest for stable
29
29
  catence-data setup --athlete alex --label "Alex"
30
30
  ```
31
31
 
32
- Store each provider value through stdin so it does not enter shell history. Values are written to the selected athlete’s owner-only local secret file.
32
+ Store each provider value through stdin so it does not enter shell history. Values are written to the selected athlete's owner-only local secret file.
33
33
 
34
34
  ```sh
35
35
  printf %s 'alex@example.com' | catence-data --athlete alex secret set --provider garmin --field email --value-stdin
@@ -63,108 +63,42 @@ catence-data --athlete sam sync --provider garmin
63
63
  catence-data athlete list
64
64
  ```
65
65
 
66
- The catalog layout is deliberately simple:
67
-
68
- ```text
69
- ~/.catence/
70
- catalog.json
71
- config.json # shared Console configuration; no secrets
72
- console/chat-history.sqlite3
73
- athletes/
74
- alex/ # isolated DuckDB, raw data, and tokens
75
- secrets/providers.json # mode 0600
76
- sam/
77
- ...
78
- ```
79
-
80
- Garmin, Intervals, and Strava client credentials are isolated per athlete. Strava OAuth tokens remain in that athlete’s own store. The old 0.1 single-store directory cannot be migrated safely: create a fresh home and re-sync each athlete.
66
+ Garmin, Intervals, and Strava client credentials are isolated per athlete. Strava OAuth tokens remain in that athlete's own store. The old 0.1 single-store directory cannot be migrated safely: create a fresh home and re-sync each athlete.
81
67
 
82
68
  ### Common operations
83
69
 
84
70
  ```sh
85
- # Incremental or explicit data work for one athlete
86
71
  catence-data --athlete alex status
87
72
  catence-data --athlete alex sync --provider intervals
88
73
  catence-data --athlete alex sync --provider garmin --from 2025-07-29
89
74
  catence-data --athlete alex backfill --provider garmin --from 2020-01-01 --refresh
90
75
  catence-data --athlete alex retry --run <run-id>
91
- catence-data --athlete alex progress --watch # follow an active sync run live
92
-
93
- # Strava OAuth uses clientId and clientSecret previously stored for this athlete
76
+ catence-data --athlete alex progress --watch
94
77
  catence-data --athlete alex auth strava --callback
95
78
  catence-data --athlete alex disconnect strava
96
-
97
- # Update the runtime and Console together on the tracked release channel
98
79
  catence-data update --check
99
80
  catence-data update
100
-
101
- # Choose a non-default catalog location
102
- catence-data --home /srv/catence setup --athlete alex --label "Alex"
103
- catence --home /srv/catence
104
- ```
105
-
106
- `catence-data update` follows the channel of the installed runtime: a beta
107
- install tracks the npm `beta` tag and the matching PyPI prereleases, a stable
108
- install tracks `latest`. Pass `--channel stable` to move off a beta. The command
109
- replaces the global `catence` package and installs or upgrades
110
- `catence-console` with `uv tool` when `uv` is available; `--check` only reports.
111
-
112
- Register `http://127.0.0.1:8765/strava/callback` with the Strava application for the callback flow. The manual `auth strava --code <authorization-code>` flow remains available for headless environments.
113
-
114
- ## Background sync and live progress
115
-
116
- Long Garmin backfills fetch hundreds of days of data and can take 20-30+ minutes. Sync runs stream worker output to the console in real time, tolerate Ctrl+C and SSH/terminal deaths cleanly, and expose a live progress heartbeat you can follow from the CLI, the MCP server, or a Docker helper.
117
-
118
- ### What happens during a run
119
-
120
- When a sync starts, Catence creates a row in `sync_runs` with status `running` and begins persisting heartbeats to the `sync_run_progress` table (schema migration 14). The Garmin staging worker emits one compact JSON progress record every few seconds on stdout; the runtime parses it, normalizes it, and upserts it. Even if the worker cannot emit — for example while stuck in login — the runtime persists a 30-second fallback heartbeat so a run is always observable and never falsely looks stale.
121
-
122
- Each progress record follows the same contract:
123
-
124
- - `runId`, `provider` — which run the record belongs to
125
- - `stage` — `starting`, `login`, `singletons`, `daily`, `range`, `ftp_history`, `max_metrics`, `hrv_history`, `scores`, `activities`, `collections` while extracting; `completed` on success; `failed`, `interrupted`, or `timed_out` as terminal states written by the runtime
126
- - `currentStep` — the endpoint, date, or activity being fetched right now
127
- - `completedUnits` / `totalUnits` — for example days fetched out of the total days in the window
128
- - `percentComplete` — 0 to 100
129
- - `elapsedSeconds` / `estimatedRemainingSeconds` — the ETA is computed once the run has a known total and has completed at least one unit
130
- - `heartbeatAt` — UTC ISO timestamp of the record
131
-
132
- ### Interruption and stale-run recovery
133
-
134
- - SIGINT, SIGTERM, and SIGHUP (Ctrl+C, terminal close, `kill`) are trapped on both the Node runtime and the Python worker. The child stops between days and the run is marked `interrupted` in `sync_runs` — never a zombie `running` row — and the process exits with 130/143/129.
135
- - Before every sync or retry, runs still stuck in `running` for more than 15 minutes are marked `timed_out` (with `completed_at` set), so a dead SSH session cannot block later syncs.
136
- - Resume a failed or interrupted run without re-reading history with `retry --run <run-id>`.
137
-
138
- ### Watching progress
139
-
140
- ```sh
141
- catence-data --athlete alex progress # one-shot JSON snapshot
142
- catence-data --athlete alex progress --watch # live view; exits when no run is active
143
81
  ```
144
82
 
145
- `--watch` renders a compact progress table on a TTY and exits when the last active run finishes; piped output stays JSON.
146
-
147
- The read-only MCP tool `catence_sync_progress` returns the same snapshot — active runs with their latest heartbeat plus the most recent runs — and takes `athleteId` like every other personal-data tool.
148
-
149
- ### Docker deployments
150
-
151
- `scripts/deploy-console.sh` generates a `sync.sh` helper that gained a `progress` command and a `--detach` flag:
152
-
153
- ```sh
154
- cd catence-deploy
155
- ./sync.sh --athlete alex sync --detach # start the run in the background and return
156
- ./sync.sh --athlete alex progress --watch # follow it live
157
- ./sync.sh --athlete alex progress # one-shot snapshot
158
- ```
83
+ ## Documentation
159
84
 
160
- `--detach` works with `backfill` too. A detached run keeps streaming into the container logs (`docker compose -f catence-deploy/docker-compose.yml logs -f console`) and keeps writing heartbeats, so it survives the shell that started it and is recoverable by the next sync.
85
+ | Document | Covers |
86
+ | --- | --- |
87
+ | [Deployment: local MCP](docs/deployment/local-mcp.md) | Install, catalog, secrets, sync, background progress, stdio/HTTP MCP, demo, common operations |
88
+ | [Deployment: local Console](docs/deployment/local-console.md) | Local web chat setup, model config, doctor, updates, troubleshooting |
89
+ | [Deployment: Docker](docs/deployment/docker.md) | One-container stack: deploy script, `.env`, sync.sh, MCP exposure (SSH/Tailscale), Cloudflare Tunnel |
90
+ | [Configuration](docs/configuration.md) | Complete `config.json` schema: rate limits, Strava budget, Console profiles, environment variables |
91
+ | [LLM providers](docs/llm-providers.md) | Model providers (OpenAI, Anthropic, OpenAI-compatible/Azure, Opencode Go/Zen), reasoning effort |
92
+ | [Architecture](docs/architecture.md) | Design rationale, layers, data flow, serving |
93
+ | [MCP activity retrieval](docs/mcp-activity-retrieval.md) | Implementation contract for answering questions, current tools, planned endpoints |
94
+ | [Distribution](docs/distribution.md) | Release artifacts: npm, PyPI, APM, MCPB |
161
95
 
162
96
  ## Safe demo and Glama
163
97
 
164
98
  Run a clearly marked generated dataset without provider accounts:
165
99
 
166
100
  ```sh
167
- npx --yes catence@0.2.0 demo
101
+ npx --yes catence@beta demo
168
102
  ```
169
103
 
170
104
  It creates or reuses `~/.catence-demo` with one `demo` athlete. The generated data has explicit caveats in every tool response and never contains personal measurements. The Glama registry entry uses this command for **Try in Browser**, so the hosted sandbox has no access to local credentials or personal data.
@@ -196,125 +130,11 @@ Optional local Streamable HTTP MCP and dashboard APIs:
196
130
  catence serve --host 127.0.0.1 --port 8787
197
131
  ```
198
132
 
199
- `GET /api/v1/athletes` returns IDs and labels only. `GET /api/v1/dashboard` requires `athleteId`, for example `http://127.0.0.1:8787/api/v1/dashboard?athleteId=alex&days=28`. Browser origins must be listed with `--allow-origin`; the packaged Console instead proxies the dashboard through its authenticated same-origin route.
200
-
201
- ## Catence Console
202
-
203
- The Console is a local web chat that starts a matching Catence HTTP server on loopback. It uses Chainlit password login and fails closed unless all three authentication variables are supplied.
204
-
205
- ```sh
206
- export CATENCE_HOME="$HOME/.catence"
207
- export CATENCE_CONSOLE_USERNAME='coach'
208
- export CATENCE_CONSOLE_PASSWORD_HASH="$(catence-console auth hash-password)"
209
- export CHAINLIT_AUTH_SECRET="$(openssl rand -hex 32)"
210
- export OPENAI_API_KEY='…'
211
-
212
- uvx catence-console@0.2.0 serve
213
- ```
214
-
215
- On the first authenticated visit, the Console wizard asks for an OpenAI-compatible, OpenAI, or Anthropic model and writes only the non-secret model configuration to `~/.catence/config.json`. The `openai-compatible` option covers Azure and Opencode; see [`docs/llm-providers.md`](docs/llm-providers.md). Model-provider keys remain process environment variables. The Console settings include an athlete selector; the server overwrites model-supplied athlete scope with that selected value on every personal-data call.
216
-
217
- To preflight the Console and a running runtime:
218
-
219
- ```sh
220
- uvx catence-console@0.2.0 doctor --home "$HOME/.catence" --mcp-url http://127.0.0.1:8787/mcp
221
- ```
222
-
223
- Console chats and saved tool context are local at `~/.catence/console/chat-history.sqlite3`.
224
-
225
- ### Docker and Cloudflare Tunnel
226
-
227
- The Console image contains the Node runtime, Catence, and Console. Its MCP server remains loopback-only inside the container; only the Console port is exposed.
228
-
229
- ```sh
230
- docker build -f console/Dockerfile -t catence-console .
231
- docker run --rm -p 127.0.0.1:8000:8000 -v catence-data:/data \
232
- -e CATENCE_CONSOLE_USERNAME='coach' \
233
- -e CATENCE_CONSOLE_PASSWORD_HASH='replace-with-bcrypt-hash' \
234
- -e CHAINLIT_AUTH_SECRET='replace-with-a-long-random-secret' \
235
- -e OPENAI_API_KEY='…' \
236
- catence-console
237
- ```
238
-
239
- Initialize the mounted volume before its first production sync, for example:
240
-
241
- ```sh
242
- docker run --rm -it -v catence-data:/data --entrypoint catence-data catence-console \
243
- setup --athlete alex --label "Alex"
244
- ```
245
-
246
- Use the same `--entrypoint catence-data` pattern for `secret set` and `sync`. Route a Cloudflare Tunnel to `http://127.0.0.1:8000`; do not run a tunnel client in this image. Use HTTPS at the tunnel and retain the Console login—the dashboard is fetched through the authenticated Console origin rather than directly from port 8787.
247
-
248
- [`scripts/deploy-console.sh`](scripts/deploy-console.sh) deploys this stack from
249
- the public registries and seeds a starter `config.json` (the Console model
250
- profiles from [`config.example.json`](config.example.json)) into the data
251
- volume, so the settings panel works before the first chat. Edit
252
- `/data/config.json` in the volume (or the bind-mounted `--home` directory) to
253
- change models and defaults, or discover OpenCode Go profiles from the image:
254
-
255
- ```sh
256
- docker compose -f catence-deploy/docker-compose.yml --env-file catence-deploy/.env run --rm \
257
- --entrypoint node console \
258
- /usr/local/lib/node_modules/catence/scripts/discover-opencode-go.mjs --write /data/config.json
259
- ```
133
+ `GET /api/v1/athletes` returns IDs and labels only. `GET /api/v1/dashboard` requires `athleteId`, for example `http://127.0.0.1:8787/api/v1/dashboard?athleteId=alex&days=28`. Browser origins must be listed with `--allow-origin`; the packaged Console instead proxies the dashboard through its authenticated same-origin route. The MCP server has no authentication of its own — keep it on loopback or restrict it at the network layer (see [Docker MCP exposure](docs/deployment/docker.md#connecting-to-the-docker-based-mcp-from-outside) for the remote-access patterns).
260
134
 
261
135
  ## Configuration
262
136
 
263
- [`config.example.json`](config.example.json) documents rate limits, Strava budgets, and Console model profiles. It intentionally contains environment-variable names rather than credential values. Keep per-athlete provider values in `catence-data secret set`, not in `.env` or `config.json`.
264
-
265
- ### Per-model reasoning effort
266
-
267
- Models that support reasoning effort can set a fixed level per model in `config.json`, or expose a per-chat **Thinking effort** dropdown with custom levels via `variants`.
268
-
269
- **Fixed level** (all requests for the model use it):
270
-
271
- ```json
272
- {
273
- "console": {
274
- "profiles": {
275
- "opencode-zen": {
276
- "label": "OpenCode Zen",
277
- "defaultModel": "deepseek-v4-flash-free",
278
- "models": {
279
- "deepseek-v4-flash-free": {
280
- "label": "DeepSeek V4 Flash Free",
281
- "model": "openai/deepseek-v4-flash-free",
282
- "reasoningEffort": "high"
283
- }
284
- },
285
- "apiKeyEnv": "OPENCODE_API_KEY",
286
- "apiBaseEnv": "OPENCODE_ZEN_API_BASE"
287
- }
288
- }
289
- }
290
- }
291
- ```
292
-
293
- **Custom variants** (per-chat dropdown): `variants` maps each dropdown label to the value sent to the provider. This is how non-OpenAI models (for example DeepSeek V4 Flash, which uses its own Default/High/Max scheme rather than the OpenAI-standard list) expose their native levels:
294
-
295
- ```json
296
- "deepseek-v4-flash-free": {
297
- "label": "DeepSeek V4 Flash Free",
298
- "model": "openai/deepseek-v4-flash-free",
299
- "variants": { "High": "high", "Max": "max" }
300
- }
301
- ```
302
-
303
- With `variants`, the chat **Thinking effort** dropdown shows `Provider default` plus each label; selecting one sends that exact value (e.g. `reasoning_effort: "high"`). Without `variants`, the dropdown falls back to the OpenAI-standard set (`minimal`, `low`, `medium`, `high`, `xhigh`).
304
-
305
- **Disabling reasoning effort**: an explicitly empty `variants` map (`"variants": {}`) disables the feature for that model — no `reasoning_effort` is ever sent and the **Thinking effort** dropdown is greyed out. This is how models that reject the parameter (for example MiMo, which expects its own `thinking` toggle) are configured:
306
-
307
- ```json
308
- "mimo-v2.5": {
309
- "label": "MiMo V2.5",
310
- "model": "openai/mimo-v2.5",
311
- "variants": {}
312
- }
313
- ```
314
-
315
- A model cannot combine `variants: {}` with a fixed `reasoningEffort`.
316
-
317
- A fixed `reasoningEffort` overrides any profile-level `defaultReasoningEffort`; the per-chat dropdown selection (a variant value) overrides both. If nothing is set, the provider default is used. The dropdown options always follow the model currently selected in the **Model** dropdown.
137
+ [`config.example.json`](config.example.json) documents rate limits, Strava budgets, and Console model profiles. It intentionally contains environment-variable names rather than credential values. Keep per-athlete provider values in `catence-data secret set`, not in `.env` or `config.json`. The full `config.json` schema — including per-model reasoning effort — is documented in [`docs/configuration.md`](docs/configuration.md) and [`docs/llm-providers.md`](docs/llm-providers.md).
318
138
 
319
139
  For source development:
320
140
 
@@ -338,22 +158,6 @@ data.
338
158
 
339
159
  ## Data and caveats
340
160
 
341
- Garmin is the primary source for activity and wellness data; Intervals.icu supplements training analysis; Strava is used for targeted segments, efforts, and gear. Missing fields mean a provider did not supply a value. The source credentials and source APIs determine the data available. Catence does not use the official Garmin API; Garmin sync relies on the selected athlete’s email/password credentials.
342
-
343
- See [distribution notes](docs/distribution.md) for release artifacts, including APM and MCPB demo bundles.
161
+ Garmin is the primary source for activity and wellness data; Intervals.icu supplements training analysis; Strava is used for targeted segments, efforts, and gear. Missing fields mean a provider did not supply a value. The source credentials and source APIs determine the data available. Catence does not use the official Garmin API; Garmin sync relies on the selected athlete's email/password credentials.
344
162
 
345
- ##
346
-
347
- ```bash
348
- cd catence-deploy
349
- docker compose -f docker-compose.yml --env-file .env exec console \
350
- catence-data sync --athlete martina --provider all --home /data # incremental sync, all providers
351
- docker compose -f docker-compose.yml --env-file .env exec console \
352
- catence-data backfill --athlete martina --from 2026-01-01 --home /data # full backfill from a date
353
- docker compose -f docker-compose.yml --env-file .env exec console \
354
- catence-data status --athlete martina --home /data # coverage/errors
355
- docker compose -f docker-compose.yml --env-file .env exec console \
356
- catence-data progress --athlete martina --home /data --watch # live sync progress
357
- docker compose -f docker-compose.yml --env-file .env exec console \
358
- catence-data athlete list --home /data # list athlete IDs
359
- ```
163
+ See [distribution notes](docs/distribution.md) for release artifacts, including APM and MCPB demo bundles.
@@ -3,7 +3,7 @@
3
3
  * Keep these values synchronized with release/manifest.json; release checks
4
4
  * deliberately reject drift before a package can be published.
5
5
  */
6
- export declare const CATENCE_RUNTIME_VERSION = "0.2.0-beta.10";
6
+ export declare const CATENCE_RUNTIME_VERSION = "0.2.0-beta.11";
7
7
  export declare const CATENCE_PROTOCOL_VERSION = 1;
8
8
  export type CatenceRuntimeCapabilities = {
9
9
  mcp: true;
@@ -3,7 +3,7 @@
3
3
  * Keep these values synchronized with release/manifest.json; release checks
4
4
  * deliberately reject drift before a package can be published.
5
5
  */
6
- export const CATENCE_RUNTIME_VERSION = '0.2.0-beta.10';
6
+ export const CATENCE_RUNTIME_VERSION = '0.2.0-beta.11';
7
7
  export const CATENCE_PROTOCOL_VERSION = 1;
8
8
  export function catenceRuntimeHealth() {
9
9
  return {
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { SYNC_STAGES } from '../../contracts/progress.js';
4
+ import { mergeProgress, readProgressSidecars } from '../../elt/storage/progress-sidecar.js';
4
5
  import { sqlString } from './sql.js';
5
6
  import { DATASET_CATALOG, getDataset } from './catalog.js';
6
7
  export class ReadOnlyRepository {
@@ -163,7 +164,10 @@ export class ReadOnlyRepository {
163
164
  ORDER BY heartbeat_at DESC
164
165
  LIMIT 10
165
166
  `);
166
- return { running: running.map(toSyncProgressState), recent: recent.map(toSyncProgressState) };
167
+ // Merge with sidecar heartbeat files so an active Garmin run stays visible
168
+ // even while the same process holds the single-writer database lock.
169
+ const sidecars = await readProgressSidecars(this.paths);
170
+ return mergeProgress(running.map(toSyncProgressState), recent.map(toSyncProgressState), sidecars);
167
171
  }
168
172
  async coverage() {
169
173
  const rows = await this.rows(`
@@ -14,7 +14,8 @@ import { importJsonl } from '../ingestion/importer.js';
14
14
  import { IntervalsExtractor } from '../ingestion/providers/intervals.js';
15
15
  import { completeStravaAuthorization, disconnectStrava, getStravaAuthorizationUrl, syncStravaGear } from '../ingestion/providers/strava/service.js';
16
16
  import { setManualActivityLink, unlinkActivitySource } from '../normalization/activities/linking.js';
17
- import { CatenceDatabase } from '../storage/database.js';
17
+ import { CatenceDatabase, openReadOnlyRepository, ReadOnlyDatabaseError } from '../storage/database.js';
18
+ import { mergeProgress, readRunningProgress, removeProgressSidecar, writeProgressSidecar } from '../storage/progress-sidecar.js';
18
19
  import { withDataWriteLock } from '../storage/write-lock.js';
19
20
  function packageRoot() {
20
21
  return path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
@@ -32,7 +33,7 @@ function baseProgress(runId, provider, stage) {
32
33
  * Progress NDJSON lines (kind 'progress') are normalized and persisted as
33
34
  * throttled heartbeats; other output is forwarded to the sync logger.
34
35
  */
35
- function runGarminWorker(runId, arguments_, environment, database, log, onInterruptReady) {
36
+ function runGarminWorker(runId, arguments_, environment, database, paths, log, onInterruptReady) {
36
37
  return new Promise((resolve) => {
37
38
  const child = spawn('uv', arguments_, { ...environment, stdio: ['ignore', 'pipe', 'pipe'] });
38
39
  let killTimer;
@@ -57,6 +58,9 @@ function runGarminWorker(runId, arguments_, environment, database, log, onInterr
57
58
  void database.heartbeatRun(runId, state).catch((error) => {
58
59
  log.debug('Progress heartbeat failed', { runId, error: error instanceof Error ? error.message : String(error) });
59
60
  });
61
+ void writeProgressSidecar(paths, runId, state).catch((error) => {
62
+ log.debug('Progress sidecar write failed', { runId, error: error instanceof Error ? error.message : String(error) });
63
+ });
60
64
  };
61
65
  const fallback = setInterval(() => {
62
66
  heartbeat(lastProgress ?? baseProgress(runId, 'garmin', 'starting'));
@@ -111,6 +115,9 @@ function runGarminWorker(runId, arguments_, environment, database, log, onInterr
111
115
  clearInterval(fallback);
112
116
  if (killTimer)
113
117
  clearTimeout(killTimer);
118
+ if (code === 0 && lastProgress) {
119
+ void writeProgressSidecar(paths, runId, { ...lastProgress, stage: 'importing' }).catch(() => undefined);
120
+ }
114
121
  resolve({ code, signal });
115
122
  });
116
123
  });
@@ -215,7 +222,7 @@ async function syncProvider(database, paths, provider, options, log) {
215
222
  const outcome = await runGarminWorker(runId, arguments_, {
216
223
  cwd: packageRoot(),
217
224
  env: { ...(await athleteProviderEnvironment(paths)), UV_PROJECT_ENVIRONMENT: process.env.UV_PROJECT_ENVIRONMENT ?? path.join(paths.root, 'python-venv') },
218
- }, database, log, (kill) => { interruptChild = kill; });
225
+ }, database, paths, log, (kill) => { interruptChild = kill; });
219
226
  if (!guard.interrupted && outcome.code !== 0) {
220
227
  throw new Error(`Garmin staging worker exited with code ${outcome.code}${outcome.signal ? ` (${outcome.signal})` : ''}.`);
221
228
  }
@@ -243,6 +250,7 @@ async function syncProvider(database, paths, provider, options, log) {
243
250
  else {
244
251
  await database.finishRun(runId);
245
252
  }
253
+ await removeProgressSidecar(paths, runId).catch(() => undefined);
246
254
  const [run] = await database.rows('SELECT status, error_count FROM sync_runs WHERE run_id = $runId', { runId });
247
255
  log.info('Sync run finished', { runId, provider, status: run?.status ?? 'unknown', errorCount: run?.error_count ?? 0 });
248
256
  }
@@ -275,6 +283,9 @@ export async function syncData(paths, provider, explicitFrom, advanceCursor = tr
275
283
  if (timedOutRuns.runIds.length > 0) {
276
284
  log.warn('Marked stale sync runs as timed out', { runIds: timedOutRuns.runIds, timeoutMs: STALE_RUN_TIMEOUT_MS });
277
285
  }
286
+ for (const runId of timedOutRuns.runIds) {
287
+ await removeProgressSidecar(paths, runId).catch(() => undefined);
288
+ }
278
289
  const providers = provider === 'all' ? ['intervals', 'garmin'] : [provider];
279
290
  const toDate = new Date().toISOString().slice(0, 10);
280
291
  const runs = [];
@@ -440,13 +451,27 @@ export async function dataStatus(paths) {
440
451
  }
441
452
  export async function syncProgress(paths) {
442
453
  await ensurePaths(paths);
443
- const database = await CatenceDatabase.open(paths);
454
+ // Live progress must stay readable while a sync run holds the single-writer
455
+ // DuckDB lock, so the running set comes from sidecar heartbeat files first.
456
+ const sidecars = await readRunningProgress(paths);
457
+ let dbRunning = [];
458
+ let dbRecent = [];
444
459
  try {
445
- return await database.syncProgress();
460
+ const repository = await openReadOnlyRepository(paths);
461
+ try {
462
+ const snapshot = await repository.progress();
463
+ dbRunning = snapshot.running;
464
+ dbRecent = snapshot.recent;
465
+ }
466
+ finally {
467
+ await repository.close();
468
+ }
446
469
  }
447
- finally {
448
- await database.close();
470
+ catch (error) {
471
+ if (!(error instanceof ReadOnlyDatabaseError))
472
+ throw error;
449
473
  }
474
+ return mergeProgress(dbRunning, dbRecent, sidecars);
450
475
  }
451
476
  export async function rebuildRetrievalIndex(paths) {
452
477
  if (!existsSync(paths.database))
@@ -0,0 +1,26 @@
1
+ import { type SyncProgressSnapshot, type SyncProgressState } from '../../contracts/progress.js';
2
+ import type { CatencePaths } from '../../contracts/runtime.js';
3
+ export declare const PROGRESS_SIDECAR_SUFFIX = ".progress.json";
4
+ export declare const PROGRESS_SIDECAR_STALE_MS: number;
5
+ export declare function progressSidecarPath(paths: CatencePaths, runId: string): string;
6
+ /**
7
+ * Persist one progress heartbeat as a sidecar file next to the Garmin staging
8
+ * manifest. Reading this file needs no DuckDB lock, so `progress` stays live
9
+ * while a sync run holds the single-writer database lock.
10
+ */
11
+ export declare function writeProgressSidecar(paths: CatencePaths, runId: string, state: SyncProgressState): Promise<void>;
12
+ export declare function removeProgressSidecar(paths: CatencePaths, runId: string): Promise<void>;
13
+ /**
14
+ * Scan every persisted sidecar heartbeat for an athlete store. Corrupt or
15
+ * unreadable files are skipped so a torn write can never break progress reads.
16
+ */
17
+ export declare function readProgressSidecars(paths: CatencePaths): Promise<SyncProgressState[]>;
18
+ /** Active runs from sidecars: non-terminal stage and a fresh heartbeat. */
19
+ export declare function readRunningProgress(paths: CatencePaths, staleAfterMs?: number): Promise<SyncProgressState[]>;
20
+ /**
21
+ * Merge database-backed progress with sidecar heartbeats. Sidecars win for a
22
+ * given run (they are freshest); database rows fill runs that never emitted a
23
+ * sidecar (for example Intervals runs). Recent history is deduplicated across
24
+ * both sources and sorted by heartbeat recency.
25
+ */
26
+ export declare function mergeProgress(dbRunning: SyncProgressState[], dbRecent: SyncProgressState[], sidecars: SyncProgressState[]): SyncProgressSnapshot;
@@ -0,0 +1,87 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { mkdir, readFile, readdir, rename, rm, writeFile } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { normalizeProgress } from '../../contracts/progress.js';
5
+ export const PROGRESS_SIDECAR_SUFFIX = '.progress.json';
6
+ export const PROGRESS_SIDECAR_STALE_MS = 5 * 60 * 1000;
7
+ const TERMINAL_STAGES = new Set(['completed', 'failed', 'interrupted', 'timed_out']);
8
+ export function progressSidecarPath(paths, runId) {
9
+ return path.join(paths.staging, 'garmin', `${runId}${PROGRESS_SIDECAR_SUFFIX}`);
10
+ }
11
+ /**
12
+ * Persist one progress heartbeat as a sidecar file next to the Garmin staging
13
+ * manifest. Reading this file needs no DuckDB lock, so `progress` stays live
14
+ * while a sync run holds the single-writer database lock.
15
+ */
16
+ export async function writeProgressSidecar(paths, runId, state) {
17
+ const target = progressSidecarPath(paths, runId);
18
+ await mkdir(path.dirname(target), { recursive: true });
19
+ const temporary = `${target}.tmp`;
20
+ await writeFile(temporary, JSON.stringify(state));
21
+ await rename(temporary, target);
22
+ }
23
+ export async function removeProgressSidecar(paths, runId) {
24
+ await rm(progressSidecarPath(paths, runId), { force: true });
25
+ }
26
+ /**
27
+ * Scan every persisted sidecar heartbeat for an athlete store. Corrupt or
28
+ * unreadable files are skipped so a torn write can never break progress reads.
29
+ */
30
+ export async function readProgressSidecars(paths) {
31
+ const directory = path.join(paths.staging, 'garmin');
32
+ if (!existsSync(directory))
33
+ return [];
34
+ const files = (await readdir(directory)).filter((file) => file.endsWith(PROGRESS_SIDECAR_SUFFIX));
35
+ const states = [];
36
+ for (const file of files) {
37
+ try {
38
+ const state = normalizeProgress(JSON.parse(await readFile(path.join(directory, file), 'utf8')));
39
+ if (state)
40
+ states.push(state);
41
+ }
42
+ catch {
43
+ // Torn or partial sidecar write; it is not authoritative.
44
+ }
45
+ }
46
+ return states;
47
+ }
48
+ /** Active runs from sidecars: non-terminal stage and a fresh heartbeat. */
49
+ export async function readRunningProgress(paths, staleAfterMs = PROGRESS_SIDECAR_STALE_MS) {
50
+ const now = Date.now();
51
+ const running = [];
52
+ for (const state of await readProgressSidecars(paths)) {
53
+ if (TERMINAL_STAGES.has(state.stage))
54
+ continue;
55
+ const ageMs = now - Date.parse(state.heartbeatAt);
56
+ if (!Number.isFinite(ageMs) || ageMs > staleAfterMs)
57
+ continue;
58
+ running.push(state);
59
+ }
60
+ return running;
61
+ }
62
+ /**
63
+ * Merge database-backed progress with sidecar heartbeats. Sidecars win for a
64
+ * given run (they are freshest); database rows fill runs that never emitted a
65
+ * sidecar (for example Intervals runs). Recent history is deduplicated across
66
+ * both sources and sorted by heartbeat recency.
67
+ */
68
+ export function mergeProgress(dbRunning, dbRecent, sidecars) {
69
+ const running = new Map();
70
+ for (const state of sidecars)
71
+ running.set(state.runId, state);
72
+ for (const state of dbRunning)
73
+ if (!running.has(state.runId))
74
+ running.set(state.runId, state);
75
+ const recent = new Map();
76
+ for (const state of dbRecent)
77
+ recent.set(state.runId, state);
78
+ for (const state of sidecars)
79
+ recent.set(state.runId, state);
80
+ return {
81
+ running: [...running.values()],
82
+ recent: [...recent.values()]
83
+ .sort((a, b) => Date.parse(b.heartbeatAt) - Date.parse(a.heartbeatAt))
84
+ .slice(0, 10),
85
+ };
86
+ }
87
+ //# sourceMappingURL=progress-sidecar.js.map
@@ -87,7 +87,17 @@ The query layer has four shared pieces:
87
87
 
88
88
  ### 4. Serving and retrieval
89
89
 
90
- The server exposes `catence_status`, `describe_data`, `describe_dataset`, `read_series`, `aggregate_data`, `analyze_series`, `fit_series_model`, `query_read_only_data`, `find_activities`, `get_ftp_history`, `get_vo2max_history`, `power_curve_trend`, `power_coverage_report`, `latest_cycling_activities`, `cycling_progress_report`, `review_daily_recovery_load`, `review_weekly_training`, `review_activity_deep_dive`, `search_context`, `hydrate_strava_activity`, `hydrate_recent_strava_activities`, and `hydrate_strava_segment_history`, plus resources for status, catalog, a single activity, and a date-range summary.
90
+ The server exposes these tools, grouped by purpose:
91
+
92
+ - Catalog and status: `list_athletes`, `catence_status`, `catence_sync_progress`.
93
+ - Review workflows: `review_daily_recovery_load`, `review_weekly_training`, `review_activity_deep_dive`, plus the matching `daily_recovery_load_review`, `weekly_training_review`, and `activity_deep_dive` prompts.
94
+ - General data and analytics: `describe_data`, `describe_dataset`, `read_series`, `aggregate_data`, `analyze_series`, `fit_series_model`, `query_read_only_data`, `search_context`.
95
+ - Wellness: `wellness_correlate`, `wellness_baselines`, `wellness_anomalies`, `wellness_coverage`.
96
+ - Fitness and progress: `get_ftp_history`, `get_vo2max_history`, `power_curve_trend`, `power_coverage_report`, `latest_cycling_activities`, `cycling_progress_report`, `get_swim_laps`, `swim_progress_report`.
97
+ - Activity detail and segments: `find_activities`, `get_activity_segments`.
98
+ - Strava hydration (the only writers): `hydrate_strava_activity`, `hydrate_recent_strava_activities`, `hydrate_strava_segment_history`.
99
+
100
+ Resources are mode-dependent. In catalog mode the server registers only `athletes` (`catence://athletes`), the machine-readable roster of configured athlete IDs and labels; in a single-store (non-catalog) deployment it registers resources for status, catalog, a single activity template (`catence://activity/{activityId}`), and a date-range summary template (`catence://summary/{startDate}/{endDate}`).
91
101
 
92
102
  `catence serve` is a loopback-only-by-default Streamable HTTP adapter. It creates a stateless MCP server and transport for each `/mcp` request, so the HTTP and stdio surfaces use the same tool implementation. `GET /health` is a versioned client handshake with runtime version, protocol version, and capabilities; distributed Console builds reject an incompatible protocol before starting a chat. The same listener serves a small read-only `/api/v1/dashboard` snapshot for the local Console: canonical daily-health rows, weekly canonical activity aggregates, recent canonical activities, status, coverage, and explicit missing-data caveats.
93
103