diff --git a/AGENTS.md b/AGENTS.md
index a55fd04..7e2ac88 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -37,6 +37,8 @@ These checks need no Garmin account, key, live archive, client registration, or
| `src/garmin_archive/archive.py` | SQLite schema, stored source data and archive writes |
| `src/garmin_archive/fit.py` | Original activity ZIP handling and FIT decoding |
| `src/garmin_archive/queries.py` | Shared metric definitions, daily summaries and trends |
+| `src/garmin_archive/comparisons.py` | Covered comparisons of two explicit metric periods |
+| `src/garmin_archive/workouts.py` | Activity filtering and covered daily/weekly distance and duration totals |
| `src/garmin_archive/sources.py` | Documented Personal API endpoints and collection scopes |
| `src/garmin_archive/api_data.py` | Native field catalog, bounded response browsing and scalar series |
| `src/garmin_archive/sleep.py` | Bounded sleep fields, source window times and stage completeness |
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 9fae368..bfd6d11 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -25,6 +25,8 @@ The MVP uses only Garmin's official Personal API. [The coverage contract](docs/A
`sources.py` owns collection routes; the packaged response contract owns schema discovery. `api_data.py` provides shared bounded native field access and scalar series. Native access preserves source values, flags and sentinels; interpreted daily metrics in `queries.py` apply documented mappings and validity rules. Every field is accessible without requiring a separate tool or invented daily aggregate. Coordinates are omitted from default MCP responses and require an explicit native-source opt-in.
+`comparisons.py` compares existing metric trends using two explicit periods and available-day denominators. `workouts.py` owns shared activity filtering and daily/weekly volume totals from search summaries. Failed activity refreshes mask measurements; stored multisport parent IDs prevent counting parents alongside their children. These are read-only interpretations over the existing schema, with no collector, scheduler or dependency additions. Provider-specific automation remains with the assistant; native schedule configuration is not proof of unattended execution.
+
[Schema and SQL](docs/USAGE.md#sql-and-source-data) · [Sync behavior](docs/USAGE.md#sync-and-recovery)
## Concurrency and durability
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 2a458dd..a91d134 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -7,26 +7,61 @@ Help with sync reliability, data coverage, FIT decoding, queries, assistant setu
Requires Python 3.12+ and [uv](https://docs.astral.sh/uv/):
```sh
-uv sync --locked
-uv run python -m unittest discover -s tests -v
-uv run garmin-archive --help
-uv run garmin-archive-mcp --help
+git clone https://github.com/0xBreadguy/garmin-data-workbench.git
+cd garmin-data-workbench
+uv sync --locked --extra charts
+uv run --locked --extra charts python -m unittest discover -s tests -v
+uv run --locked --extra charts garmin-archive --help
+uv run --locked --extra charts garmin-archive-mcp --help
```
Tests use synthetic data and fake responses. No Garmin account or key required; dependency installation may need network access.
-Use `uv run` for development. Installed `uv tool` copies don't pick up edits. Change dependencies deliberately: run `uv lock`, then review `pyproject.toml` and `uv.lock` together.
+Fork the repository first if you need your own push destination. If you already have a checkout, start with the `uv` commands. The charts extra enables rendering tests; a base-only environment skips those tests. Keep `--extra charts` on subsequent `uv run` commands when checking chart behavior.
+
+Use `uv run` for development. Installed `uv tool` copies don't pick up edits. Change dependencies deliberately: run `uv lock`, then review `pyproject.toml` and `uv.lock` together. Don't run `install`, `sync`, `setup` or the live connection script as a development smoke test.
+
+## Where a change belongs
+
+The installable Python package lives in `src/garmin_archive/`. CLI and MCP are adapters over the same local query code; neither should define a separate interpretation of a metric.
+
+| Change | Start here | Verification |
+| --- | --- | --- |
+| Collection, retries or resumability | `sources.py`, `sync.py`, `cli.py` sync orchestration | `test_archive.py`, `test_catchup.py`, `test_contract_corpus.py` |
+| Archive/schema or FIT decoding | `archive.py`, `fit.py` | `test_archive.py`, `test_fit_corpus.py`; older synthetic archive compatibility |
+| A named metric or its meaning | `queries.py`, `sleep.py`, `body_battery.py` | Domain tests and matching CLI/MCP results |
+| Period comparisons or workout filtering/totals | `comparisons.py`, `workouts.py` | `test_comparisons_workouts.py`, CLI/MCP parity and installed-wheel smoke |
+| Native API fields or pagination | `api_data.py`, `sources.py`, `personal_api_contract.json` | `test_api_data.py`, `test_contract_corpus.py`; [contract maintenance](docs/API_COVERAGE.md#verification-and-contract-maintenance) |
+| Charts and delivery | `charts.py`, `chart_delivery.py`, `brand.json`, `assets/` | `test_charts.py`, `test_chart_delivery.py`, `test_cli_chart_metadata.py`; inspect a synthetic render |
+| Commands or tool surfaces | `cli.py`, `mcp_server.py` | `test_cli_queries.py`, `test_workbench_mcp.py`; installed-wheel smoke for entry-point changes |
+| Setup, host behavior or scheduling | `install.py`, `onboarding.py`, `platforms.py`, `schedule.py` | Corresponding test files; OS-specific behavior stays at these boundaries |
+| User or assistant guidance | `README.md`, `docs/`, `agent_guide.md`, `skills/` | Check commands and links; keep installed guidance aligned with repository docs |
+
+Python paths in this table are relative to `src/garmin_archive/`; tests live in `tests/`. [`AGENTS.md`](AGENTS.md#repository-map) has the full module map and [`docs/TESTING.md`](docs/TESTING.md#focused-checks) lists focused test commands. You don't need an agent, private tooling or a live Garmin account to contribute.
+
+Start with a small bug, a clearer error, a synthetic edge case or a documentation correction. Use issues to discuss new collectors, storage/durability changes, metric interpretations or new integration claims before building them. The current collection scope is Garmin's official Personal API.
## Make a change
1. Check Git status, use an isolated branch and preserve existing work.
2. Read [AGENTS.md](AGENTS.md) and [ARCHITECTURE.md](ARCHITECTURE.md). Keep collection, storage, shared queries and adapters separate.
-3. Add focused offline tests for changed behavior. Preserve source data, units, dates and the distinction between missing, empty, failed and stale values.
+3. Add focused offline tests for changed behavior. Preserve source data, units, dates and the distinction between missing, empty, failed and stale values. Use invented fixtures; never anonymize a personal archive into a test fixture.
4. Run the [relevant checks](docs/TESTING.md), inspect the diff and run `git diff --check`. Run `uv build` for packaging changes.
5. Open a PR explaining the user-visible change, verification and remaining gaps.
Use the existing Python, unittest and uv conventions. There is no separate lint, formatter or type-check gate. Before pushing or merging to the default branch, the full suite and required release checks must pass for that revision; exact-revision CI counts.
+For a focused check, replace the filename with the affected test:
+
+```sh
+uv run --locked --extra charts python -m unittest discover -s tests -p 'test_queries.py' -v
+git diff --check
+```
+
+Keep a PR focused on one problem and describe the resulting behavior, checks and remaining limits in the [PR template](.github/pull_request_template.md). Include user-facing docs when behavior changes. API/schema changes need preservation and compatibility evidence; rendered changes need synthetic visual inspection. Don't bundle unrelated reformatting or generated archives. Contributions use the repository's [MIT license](LICENSE).
+
+Maintainers: follow [the release checklist](docs/RELEASING.md) for dependency review, required CI and a tagged release. Passing the offline suite doesn't establish live host or assistant support.
+
## Report a problem
Include the source revision, OS/Python version, command or client, expected behavior and sanitized result. For a new host or assistant, use the [setup report](.github/ISSUE_TEMPLATE/setup-report.md). Distinguish installation, discovery, sync, a real query and actual scheduled execution.
diff --git a/README.md b/README.md
index d189e2f..c87cf9b 100644
--- a/README.md
+++ b/README.md
@@ -12,6 +12,7 @@
[](https://www.python.org/)
+[](https://github.com/0xBreadguy/garmin-data-workbench/actions/workflows/tests.yml)
[](https://www.sqlite.org/)
[](LICENSE)
@@ -19,6 +20,17 @@
Sync health data and activities into a SQLite archive on your computer or a persistent remote workstation. Keep the source JSON and original activity files. Ask your agent questions through MCP or the CLI, or work directly with SQL, scripts, notebooks and CSV.
+- Review sleep, Body Battery, heart rate, steps and activities with dates, units and coverage.
+- Compare two metric periods and review workout distance/duration totals by date and sport.
+- Generate charts from the same stored data your agent queries.
+- Explore native fields from all 26 documented Personal API endpoints and retain original activity files for your own analysis.
+
+This is an early **0.1.0** workbench. Start with the synthetic demo or a short sync, and check the [tested hosts and assistant paths](docs/COMPATIBILITY.md) before relying on an integration.
+
+
+
+A captured Muse conversation using generated demo data. The assistant reported using the CLI; this capture demonstrates visible answers and chart delivery. Appearance and connection options depend on your assistant. [Image provenance](assets/README.md).
+
## Get started
**Working with an agent?** Give it this repository and ask:
@@ -35,8 +47,16 @@ uv tool install --from . garmin-data-workbench
Follow the [setup guide](docs/SETUP.md) to create your Garmin Personal API key and run a first sync. Guided setup supports Codex and Claude Code; other agents can use local MCP or shell commands. Built-in scheduling supports macOS; remote workstations can use an OS scheduler or provider routine.
+For charts, replace the install command with `uv tool install --from '.[charts]' garmin-data-workbench`.
+
Keep your key out of chat. On a remote workstation, processes sharing your OS user can read credentials and health data. Query results may reach your agent's AI provider. Choose the host before syncing.
+### Try it without a Garmin key
+
+Follow the [isolated demo setup](docs/SETUP.md#mock-only-setup-stop-before-credentials) to generate synthetic data in a new archive, with its own checkout and environment. It makes no Garmin requests and preserves existing installations. An agent can start with:
+
+> Read AGENTS.md and follow the mock-only route in docs/SETUP.md. Use a new checkout, environment and synthetic archive. Leave my existing installation, credentials, data and schedules unchanged. Show me the sleep overview for April 24–30, 2026.
+
## Use your archive
Ask your agent: “How did my sleep and resting heart rate change over the last week?” Or query it yourself:
@@ -50,6 +70,20 @@ garmin-archive trend sleep_duration --from 2026-01-01 --to 2026-01-07
Queries use stored data. Available history and fields depend on Garmin, your devices and what was recorded.
+
+
+Example output from the [generated demo](docs/VISUALIZATION.md#try-generated-demo-data), not personal health data. Collection timestamps are simulated; wearable scores and stages are estimates.
+
+## What works where
+
+| Path | Current boundary |
+| --- | --- |
+| CLI and local archive | Offline CI covers macOS, Windows and Linux with Python 3.12. Live Windows credential/privacy validation is still incomplete. |
+| Agents | Shell access or local stdio MCP. Codex and Claude Code have guided registration; each assistant connection needs its own query test. |
+| Automatic sync | Built-in macOS scheduling. Other hosts need their own scheduler or provider routine. |
+
+See [assistant connections](docs/ASSISTANTS.md) for remote access and the checks behind each compatibility claim. Garmin's Personal API is for individuals accessing their own data; review [Garmin's FAQ and terms](https://developer.garmin.com/gc-developer-program/personal/personal-faq/) before live setup.
+
## Go deeper
- [Commands, SQL, exports and scheduling](docs/USAGE.md)
@@ -58,4 +92,6 @@ Queries use stored data. Available history and fields depend on Garmin, your dev
- [Contribute](CONTRIBUTING.md) · [Agent instructions](AGENTS.md) · [Testing](docs/TESTING.md)
- [Architecture](ARCHITECTURE.md) · [Security](SECURITY.md)
+Found a problem? Open a [bug report](https://github.com/0xBreadguy/garmin-data-workbench/issues/new?template=bug-report.md) or [setup report](https://github.com/0xBreadguy/garmin-data-workbench/issues/new?template=setup-report.md) with a synthetic reproduction. Keep credentials, personal health data and routes out of public issues. Report vulnerabilities through [the security policy](SECURITY.md).
+
Independent open-source project. Not affiliated with, endorsed by, or supported by Garmin.
diff --git a/SECURITY.md b/SECURITY.md
index eb28f28..6ee7e6e 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -4,7 +4,7 @@ Keep keys, tokens, health records, original activity files and GPS routes out of
## Report a vulnerability
-Use private vulnerability reporting in the repository's GitHub Security tab, if available. Otherwise, open an issue requesting a private channel, without exploit details or sensitive data.
+Use [GitHub private vulnerability reporting](https://github.com/0xBreadguy/garmin-data-workbench/security/advisories/new). If that route is unavailable, open an issue requesting a private channel, without exploit details or sensitive data.
Privately provide the source revision, affected component, impact and a synthetic reproduction. Don't attach an archive or credentials. Fixes target current code unless a maintainer says otherwise; no response time or older-release support is promised.
diff --git a/assets/README.md b/assets/README.md
new file mode 100644
index 0000000..e42e18b
--- /dev/null
+++ b/assets/README.md
@@ -0,0 +1,15 @@
+# Documentation and brand assets
+
+`logo.svg`, `icon.svg` and `icon.png` are the Workbench brand assets. The installed package includes these fixed resources for CLI/MCP charts; documentation screenshots are not runtime resources.
+
+## Muse sleep demonstration
+
+`muse-sleep-demo.png` is a reviewed privacy crop of an actual Muse app screenshot captured November 4, 2026. Its question, answer and chart thumbnail are unchanged. No dialogue, number or UI element was replaced. It uses generated corpus v2, seed 42, with April 24–30, 2026 dates and simulated collection timestamps; no personal health records are shown.
+
+The app interaction and visible attachment were directly observed. The agent reported CLI use on an Ubuntu workstation and source revision `47dcd68`; remote execution details were not independently audited. This screenshot does not establish live Garmin collection, MCP support, persistence or recurring execution. Muse is a separate assistant application, not a UI shipped by this repository.
+
+SHA-256: `53d9f77e788383d47d68e6cbab490c79a6537f252cd063954af9bf61c523928c`.
+
+## Sleep chart preview
+
+`sleep-example.png` is a direct Workbench export from the same default generated corpus and dates, using the `wide` layout. It is not an assistant screenshot. See [reproduction instructions](../docs/VISUALIZATION.md#keep-images-concise). Charts remain illustrative wearable estimates; the generated scores and stages do not establish physiological relationships.
diff --git a/assets/muse-sleep-demo.png b/assets/muse-sleep-demo.png
new file mode 100644
index 0000000..832ec29
Binary files /dev/null and b/assets/muse-sleep-demo.png differ
diff --git a/assets/sleep-example.png b/assets/sleep-example.png
new file mode 100644
index 0000000..3f7e923
Binary files /dev/null and b/assets/sleep-example.png differ
diff --git a/docs/ASSISTANTS.md b/docs/ASSISTANTS.md
index c68b001..e46adeb 100644
--- a/docs/ASSISTANTS.md
+++ b/docs/ASSISTANTS.md
@@ -50,7 +50,9 @@ Replace the executable path. For a custom archive, use `args: ["--data-dir", "/a
### Tool contract
-Sixteen tools read data/status/guidance; `configure_sync` changes the local macOS schedule when requested. Data tools need no Garmin credentials and make no live requests.
+Eighteen tools read data/status/guidance; `configure_sync` changes the local macOS schedule when requested. Data tools need no Garmin credentials and make no live requests.
+
+`compare_periods` calculates changes between two explicit metric periods. `get_workout_summary` returns covered activity distance/duration totals and weekly buckets; `list_activities` also supports date/type filters. See [comparison and workout semantics](USAGE.md#compare-periods-and-summarize-workouts).
They provide daily summaries, up to 90 days of [trend metrics](USAGE.md#summaries-units-and-dates), detailed [sleep summaries](SLEEP.md), [Body Battery summaries](BODY_BATTERY.md), coverage, activities, stored daily responses and paginated FIT records. `agent_guide` returns installed guidance; `setup_receipt` separates setup evidence from outstanding verification. Samples omit coordinates and raw fields. `api_catalog` discovers all documented Personal API sources and native field definitions. `source_data` pages their complete stored responses; `source_series` reads native scalar values across dates. Default output omits coordinates; native coordinate access requires an explicit opt-in. See [Personal API coverage](API_COVERAGE.md). `daily_health` responses over 64 KB are rejected; use `source_data` to page them. Failed refreshes mask retained response data.
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
new file mode 100644
index 0000000..a5cf780
--- /dev/null
+++ b/docs/RELEASING.md
@@ -0,0 +1,36 @@
+# Release a workbench version
+
+Use a reviewed PR and the protected default branch. This checklist covers a source release; there is no automatic PyPI upload, deployment or release-publishing workflow.
+
+## Prepare the candidate
+
+1. Reconcile the intended changes and preserve concurrent work. Check the diff for credentials, real health data, routes, archives and unrelated/generated files.
+2. Update `project.version` in `pyproject.toml` when cutting a new version, run `uv lock` and review both files. Keep README version wording aligned. For the first `v0.1.0` release, confirm the existing version matches the tag.
+3. Review dependency advisories and the resolved lockfile. Upgrade vulnerable direct/transitive dependencies deliberately; don't equate a clean advisory scan with a security audit. See the [dependency audit commands](TESTING.md#dependency-advisories).
+4. Check setup, CLI/MCP guidance, compatibility claims and example output against the candidate. Use only generated data for public screenshots. Keep dates, coverage and synthetic labels visible.
+5. Write release notes describing capabilities, breaking behavior, upgrade instructions and known limits. For 0.1.0, call out macOS-only built-in scheduling, incomplete Windows live privacy validation and separately tested assistant connections.
+
+## Verify before merging
+
+From the candidate checkout:
+
+```sh
+uv sync --locked --extra charts
+uv run --locked --extra charts python -m unittest discover -s tests -v
+uv build
+uv run --locked --extra charts python scripts/smoke_installed.py
+uv run --locked --extra charts python scripts/smoke_installed.py --charts
+git diff --check
+```
+
+The smoke script expects exactly one wheel in `dist/`; preserve or move older artifacts out of that directory before building a different version. Inspect wheel/sdist contents and package provenance. A build from uncommitted changes records a dirty source; build final release artifacts from the clean release revision.
+
+The final PR head must pass all three required GitHub Actions checks: `tests (ubuntu-latest)`, `tests (macos-latest)` and `tests (windows-latest)`, with the branch up to date. Local macOS results do not replace that matrix. Don't bypass the ruleset or treat pending/skipped checks as passed. Require the post-merge package smoke to pass for the merged revision before tagging it.
+
+## Publish and check
+
+Publication requires the maintainer's authorization. Tag the verified commit with the matching `vX.Y.Z`, create a GitHub release with the reviewed notes, and rebuild any attached artifacts from that clean tagged checkout. Check the tag, source revision, installation instructions and attached files after publication. A PyPI release, if introduced later, needs its own packaging and publishing verification.
+
+Enable GitHub secret scanning/push protection, dependency alerts and private vulnerability reporting when available. Confirm [SECURITY.md](../SECURITY.md) leads to a usable private report route. Keep the public bug/setup templates easy to find without requesting private data.
+
+For a rollout, lead with one useful question and a clearly labeled synthetic result, then link to the README's demo and setup routes. Keep an early release's boundaries explicit. A video or agent conversation doesn't establish support for every host, live Garmin setup or recurring execution.
diff --git a/docs/SETUP.md b/docs/SETUP.md
index 5ee5eb8..bc83f37 100644
--- a/docs/SETUP.md
+++ b/docs/SETUP.md
@@ -65,6 +65,8 @@ Find the executable directory with `uv tool dir --bin`; if it isn't on `PATH`, i
uv tool install --force --no-cache --from . garmin-data-workbench
```
+If you installed charts, use `--from '.[charts]'` in the upgrade command too; installing the base package replaces the tool environment without its optional plotting dependencies.
+
## 3. Supply a key and run a first sync
Create your own key on [Garmin Connect's Personal API page](https://connect.garmin.com/app/settings/personalApiToken). Review the terms, choose an expiration and save it securely: Garmin shows it once. Never put the value in chat, command arguments, logs or Git. See [Garmin's key FAQ](https://developer.garmin.com/gc-developer-program/personal/personal-faq/) for expiration and revocation.
diff --git a/docs/TESTING.md b/docs/TESTING.md
index 699de51..08095de 100644
--- a/docs/TESTING.md
+++ b/docs/TESTING.md
@@ -43,6 +43,7 @@ Use `uv run python -m unittest discover -s tests -p '' -v`:
| All 26 Personal API routes, field catalog, native pagination/series, source snapshots and older archives | `test_api_data.py` |
| All 25 JSON sources through SDK collection and complete paged query round trips; empty/error recovery | `test_contract_corpus.py` |
| Metrics and missingness | `test_queries.py` |
+| Period comparisons, workout coverage, field missingness and multisport totals | `test_comparisons_workouts.py` |
| Read-only CLI queries | `test_cli_queries.py` |
| CLI PNG exports, structured captions and save failures | `test_cli_chart_metadata.py` |
| Chart semantics and branding | `test_charts.py` |
@@ -67,6 +68,19 @@ The smoke check expects exactly one wheel in `dist/`. It installs that wheel and
The `--charts` mode also installs the locked chart dependencies and renders a synthetic PNG with the installed command.
+## Dependency advisories
+
+Review the full locked runtime set, including charts, before a release and after dependency changes. These optional checks use package/advisory services over the network, not Garmin credentials or health data. Use a temporary directory outside the checkout for the exported requirements:
+
+```sh
+uv export --locked --extra charts --no-dev --no-emit-project --format requirements-txt --output-file /absolute/temporary/requirements.txt
+uvx pip-audit --requirement /absolute/temporary/requirements.txt --no-deps --disable-pip
+```
+
+The export includes transitive dependencies; `--no-deps` prevents a second resolver from choosing a different set. Review results against upstream advisories, the actual lock APIs used and host permissions. A clean result means no known advisories were returned for that package set at that time. It doesn't prove the code or host is secure. See [releasing](RELEASING.md).
+
+## Additional host and corpus checks
+
On Windows, POSIX mode-bit assertions do not apply; shared behavior still runs. macOS schedule tests use fake `launchctl` and user IDs on every OS. The command-example test executes the native shell (PowerShell on Windows, `sh` elsewhere).
`uv run python scripts/benchmark_archive.py` measures a temporary synthetic database, not sync or assistant latency.
diff --git a/docs/USAGE.md b/docs/USAGE.md
index 9f968a2..24f961c 100644
--- a/docs/USAGE.md
+++ b/docs/USAGE.md
@@ -65,7 +65,7 @@ Use paths on the execution host. `--data-dir` after the command is rejected with
## Output and automation
-`day`, `trend`, `sleep`, `body-battery`, `source-data`, `source-series`, `status`, `activities`, `health` and `records` read an existing archive without creating, migrating or syncing it. They need no Garmin key. `export-original` also opens the archive read-only and writes only the requested destination, with owner-only permissions on POSIX; existing files are never overwritten. `path` prints the configured database location even if it doesn't exist, without opening or creating it.
+`day`, `trend`, `compare`, `workout-summary`, `sleep`, `body-battery`, `source-data`, `source-series`, `status`, `activities`, `health` and `records` read an existing archive without creating, migrating or syncing it. They need no Garmin key. `export-original` also opens the archive read-only and writes only the requested destination, with owner-only permissions on POSIX; existing files are never overwritten. `path` prints the configured database location even if it doesn't exist, without opening or creating it.
`chart` uses the same read-only trend query and writes a new PNG. By default it prints `Chart saved to PATH`. Add `--json` to receive one JSON object on stdout after saving, with `output_path` (the supplied destination) and the shared chart metadata: `caption`, `alt_text`, `coverage`, `units`, `freshness`, `archive_provenance`, `synthetic` and `explanations`. The `delivery` field describes a saved CLI file; attaching and displaying it in the host remains a separate step.
@@ -118,6 +118,22 @@ Argument-parsing errors use JSON on stderr and exit `2` for every command. Runti
## Summaries, units and dates
+### Compare periods and summarize workouts
+
+```sh
+garmin-archive compare steps --from 2026-01-08 --to 2026-01-14 --baseline-from 2026-01-01 --baseline-to 2026-01-07
+garmin-archive activities --from 2026-01-01 --to 2026-01-31 --type running --limit 20
+garmin-archive workout-summary --from 2026-01-01 --to 2026-01-31 --type running
+```
+
+`compare` / MCP `compare_periods` requires two explicit periods of 1–90 inclusive dates each; the baseline must end before the comparison period starts. It returns both existing trend envelopes (dated points, fetch/attempt times, source units and coverage), plus period-minus-baseline differences between their available-day means. Calculations use unrounded observations and round changes to two decimals. Each period uses its own available-value denominator; unequal lengths, incomplete coverage and periods including today/future dates are flagged. Missing or failed data is never substituted with zero. Percentage changes are null with a reason for zero baselines, missing means, scores, Garmin stress, Body Battery scales/points and percentage-valued metrics. Differences use source units even when the underlying distance trends also contain preferred display units. These descriptive comparisons do not establish causes, significance or a personal baseline.
+
+`activities` / MCP `list_activities` accepts optional inclusive `--from`/`--to` (`start`/`end` in MCP) and `--type` (`activity_type`) filters. Type matches Garmin's native `activityType.typeKey` exactly; `running` does not silently include `trail_running`. Omitted bounds leave that side open. Pagination is applied after filtering. CLI retains its existing bare-list fields; MCP reports refresh status and masks numeric measurements after unsuccessful refreshes. The list includes parent and child activities for inspection.
+
+`workout-summary` / MCP `get_workout_summary` covers 1–90 dates (default: seven ending today), returning distance in meters, Garmin's summary duration in seconds, activity counts, per-field available-activity counts, daily coverage/attempt times and Monday-based weekly buckets clipped to the request. It uses stored search summaries and does not decode laps or infer effort. Source activity dates remain unchanged; today's profile zone is not applied to historical timestamps. Available field totals can be partial; counts disclose missing distance/duration. Known empty/filtered-out available days have zero activity volume; unchecked/failed days remain null. An all-missing measurement is null, not zero. A successful empty search does not prove complete Garmin history.
+
+Parents with stored child activities are excluded from volume totals **before** date/type filtering, including children outside the requested window. Missing children can leave multisport volume incomplete. Other overlapping recordings remain separate: summed duration is not deduplicated elapsed time. The archive retains activity rows rather than tracking deletion history; refreshing cannot establish that every retained row still exists at Garmin. These queries are read-only and need no key or network request.
+
`day`, `trend` and `sleep` share MCP's query definitions. `sleep` returns all supported sleep fields and source window times together; `chart sleep` renders a branded overview with separate duration/stages and score panels.
The [Personal API coverage guide](API_COVERAGE.md) lists all 26 collected sources and native field access. `api-catalog` needs no archive. `source-data` pages complete native responses, including large arrays; `source-series` preserves native scalar values across dates without inferring an aggregation. These queries share MCP definitions.
diff --git a/docs/VISUALIZATION.md b/docs/VISUALIZATION.md
index 8fdb606..10f5cfc 100644
--- a/docs/VISUALIZATION.md
+++ b/docs/VISUALIZATION.md
@@ -84,6 +84,8 @@ Demo charts are labeled synthetic automatically, including legacy archives with
## Keep images concise
+The [README sleep preview](../assets/sleep-example.png) uses the default v2 demo (seed 42), April 24–30, 2026, and the `wide` layout. To refresh it, generate a new default demo outside the checkout, then render `garmin-archive --data-dir /absolute/new/demo chart sleep --from 2026-04-24 --to 2026-04-30 --layout wide --output /absolute/new/sleep-example.png`, replacing the demo and output paths. Inspect the image and synthetic label before replacing the documentation asset; keep the archive and metadata outside Git.
+
Lead with the measurements. Keep dates, units, denominators, legends and meaningful missing-data indicators on the image; omit repeated explanations and routine source or fetch-time paragraphs. Explain relevant freshness, estimates, limitations and interpretation in the accompanying response. For custom charts, apply the same approach and preserve the distinction between missing values and zero.
## Agent delivery
diff --git a/docs/acceptance/2026-11-05-comparisons-workouts.md b/docs/acceptance/2026-11-05-comparisons-workouts.md
new file mode 100644
index 0000000..bf5464b
--- /dev/null
+++ b/docs/acceptance/2026-11-05-comparisons-workouts.md
@@ -0,0 +1,26 @@
+# Comparisons and workout summaries — offline acceptance
+
+November 5, 2026. Implementation starts from public main `f2e2312`. This report covers synthetic queries on the development macOS host, with Python 3.12.13. It does not establish a live Garmin or third-party assistant acceptance pass.
+
+## Exercised behavior
+
+The full 171-test offline suite passed with charts installed. Independent synthetic cases verify comparison arithmetic from unrounded observations, distinct zero/missing/scale percentage reasons, unequal/incomplete/current-period warnings, failed-retained masking, date bounds, weekly boundaries, per-field coverage, exact sport filtering and multisport parent exclusion before date/type filtering. Ordinary overlapping recordings remain separate.
+
+Installed-wheel checks passed with and without chart dependencies. Each creates a disposable environment and a separate outside-checkout synthetic archive. Real CLI subprocesses and stdio MCP sessions read that archive from outside the checkout. Both interfaces return identical comparison and workout-summary results; independent smoke expectations are a 1,234-step mean difference / 100% change, and a 5,000-meter / 1,800-second running total. The activity filter selects the expected ID. Archive bytes remain unchanged. Existing checks also exercise PNG/MCP image transport when charts are installed and explicit dependency-unavailable behavior otherwise.
+
+The first extended smoke attempt incorrectly assumed every ordinary MCP response had `structuredContent`. The smoke reader now accepts JSON text as well, matching the existing MCP query convention; both installation modes then passed. This was a verification-script defect, not evidence of failed query transport.
+
+Builds and source diff checks passed. Required platform checks and the final PR revision are recorded by GitHub CI; local macOS checks alone do not validate live Windows/Linux installations.
+
+## Outstanding stages
+
+| Stage | Result / next evidence needed |
+| --- | --- |
+| Actual assistant interpretation of the new tools | Not run; ask a supported client to compare two explicit synthetic periods and summarize a filtered workout week without coaching. |
+| Visible image delivery in a third-party assistant | Not run here; installed MCP PNG transport is separate evidence. Existing client reports retain their original scope. |
+| Controlled provider new-session/restart persistence | Not run; verify the same synthetic installation/archive across the actual lifecycle boundary. Separate local processes are not that boundary. |
+| Private live key entry and Garmin Connect comparison | Not run; requires authorized live setup and representative source-value checks. No credentials or personal archive were accessed here. |
+| Actual unattended sync / report delivery | Not run; no scheduler or provider routine was configured. Verify a real opted-in execution and inspect freshness/failures separately from delivery. |
+| Native Windows storage ACL privacy | Not run; remains a separate prerequisite for claiming private live Windows setup. |
+
+Provider-specific scheduling remains the assistant/provider's responsibility. Existing catch-up, locking, routine templates and status evidence remain the foundation; this change adds no scheduler integration. Diagnostic changes should follow demonstrated operational failures. See [testing](../TESTING.md#assistant-acceptance-reports) for stage-by-stage reporting and [usage](../USAGE.md#compare-periods-and-summarize-workouts) for query limitations.
diff --git a/docs/reviews/2026-11-05-launch-readiness.md b/docs/reviews/2026-11-05-launch-readiness.md
new file mode 100644
index 0000000..d38d9e4
--- /dev/null
+++ b/docs/reviews/2026-11-05-launch-readiness.md
@@ -0,0 +1,59 @@
+# Launch readiness review — November 5, 2026
+
+Reviewed public `main` at `47dcd68`, then prepared the local launch-review changes described below. This is a repository/code/offline review, not a new live Garmin installation or an independent security audit.
+
+This review records that branch's evidence. The combined comparisons, assistant-insights and launch-presentation candidate is tracked in [PR #21](https://github.com/0xBreadguy/garmin-data-workbench/pull/21), whose final revision needs its own release checks.
+
+Security follow-through: [PR #18](https://github.com/0xBreadguy/garmin-data-workbench/pull/18) merged as `f2e2312` after all three required platform checks passed on `b1a31ff`. The filelock update and package metadata are now on public main; the README/contributor presentation work remains separate.
+
+The repository is a sound base for an early public release after the dependency fix is merged and the required platform checks pass. Keep live Windows and assistant-connection limits explicit. There is no reason to reorganize the Python package or add a new service before launch.
+
+## Findings and disposition
+
+| Priority | Finding | Disposition |
+| --- | --- | --- |
+| Before release | Locked `filelock` 3.32.7 returned 13 known advisories. The `<4` constraint excluded patched releases. | Changed the supported range to `>=4.2.1,<5`; lockfile resolves 4.2.9. The complete locked runtime set, including charts, now returns no known advisories. |
+| Enabled after review | GitHub secret scanning, push protection, dependency alerts, automated security updates and private vulnerability reporting were disabled at initial inspection. | Enabled with maintainer authorization on November 5 and verified by API readback. The security policy now links directly to private reporting. |
+| Before release | No GitHub release/tagged release was listed; visitors cannot identify a supported launch snapshot. | Added [release instructions](../RELEASING.md). Cut `v0.1.0` from the verified final revision with capabilities, upgrade instructions and limits. Publication is still pending. |
+| Fixed locally | README described the archive but showed no result and buried the no-key route. Chart dependencies were easy to miss. | Added a synthetic sleep preview, a mock-only prompt, optional charts installation, early-version wording, support boundaries, CI badge and report links. |
+| Fixed locally | Package metadata omitted the README, license expression and project links. The upgrade example could remove a previously installed charts extra. | Added metadata; documented preserving `.[charts]` on upgrades. Added ignore rules for `.sqlite` sidecars and macOS Finder files. |
+| Fixed locally | Contributor guidance lacked a task-to-module/test map and recommended a base environment that skips rendering tests. | Expanded [CONTRIBUTING.md](../../CONTRIBUTING.md) with chart-enabled setup, contribution boundaries, focused verification, PR expectations and release guidance. |
+
+The most directly relevant dependency advisory concerns the Unix backend of the `FileLock` used for sync serialization. Exploitation requires local filesystem conditions such as another account being able to replace/link lock-path entries. Several other reported advisories affect lock types this project does not use. This is not evidence of remote compromise. See [the upstream advisory](https://github.com/tox-dev/filelock/security/advisories/GHSA-69hj-f68j-2879) and [patched release notes](https://github.com/tox-dev/filelock/releases/tag/4.2.1).
+
+## Structure and contribution assessment
+
+The `src/garmin_archive/` package, separate `tests/`, user-facing `docs/`, synthetic helper `scripts/`, reusable `skills/` and small `assets/` directory are appropriate. Collection, archive writes, query definitions, rendering, adapters and host-specific behavior already have named modules. Keep those boundaries and the single shared metric implementation. The wheel contains the runtime package and fixed brand resources; contributor material stays in the source distribution/repository.
+
+Existing bug, feature, setup and PR templates are useful and avoid requesting personal archives. MIT licensing and contributor instructions are present. An active default-branch ruleset requires PRs, an up-to-date base and all three OS test jobs, with no bypass actors. At inspection, there were no open PRs; public main's package smoke and the preceding PR matrix were successful.
+
+As the project grows, split code when a concrete feature needs it. `cli.py` is the largest module and currently owns parser/output/setup orchestration. If CLI and MCP response construction starts diverging, move that behavior into shared query helpers with parity tests. A wholesale package rewrite, new framework or new database would add launch risk without resolving a demonstrated problem.
+
+## Verification evidence
+
+- Baseline and updated-dependency suites: all 161 tests passed with charts enabled on macOS/Python 3.12.13. Tests cover collection with fake responses, archive compatibility, metrics/missingness, FIT, CLI, MCP transport and rendering.
+- Source/wheel builds and installed-wheel CLI/MCP smoke checks with and without charts passed for both the reviewed baseline and the updated candidate. Package metadata and required installed guidance/contract/brand resources were inspected.
+- `pip-audit` checked all 46 locked runtime dependencies including charts: baseline reported 13 advisories in `filelock`; the updated set reported zero. This is a dated known-advisory check, not proof of security.
+- Actual two-process `FileLock` exclusion, reacquisition after the holder exits, and acquisition with a legacy empty lock file passed with 4.2.9. No Garmin authentication or archive sync was involved.
+- `detect-secrets` scanned tracked files and 357 distinct reachable historical text blobs across the baseline's 101 commits. Five unique candidates were reviewed as metadata, fake test literals or checksums. One binary blob was skipped. No actual credential was identified by these scans; unknown patterns and arbitrary sensitive data remain outside that guarantee.
+- Reviewed storage/read-only boundaries, credential import/redaction, retry/stop behavior, subprocess argument handling, schedule preservation, native pagination/location omission, source-unit/date semantics, package contents, templates and public-facing docs. No real key, token cache, health archive or scheduled job was used.
+- Generated and visually inspected the README sleep example from default synthetic corpus v2, seed 42, April 24–30, 2026. Synthetic labels, separate score panel, units and coverage are visible. This does not test image display in a new assistant host.
+- Reviewed launch captures and added the unchanged, privacy-reviewed Muse sleep question/answer/attachment crop to the README. Hash matched the capture manifest. [Asset provenance](../../assets/README.md) distinguishes the native screenshot from the standalone chart and edited ad mockups.
+- Both documented `uv tool install` selectors (`.[charts]` and `.`) passed in isolated disposable tool/bin directories. Replacing the chart-enabled install with the base package removed chart availability, confirming the need for the corrected upgrade guidance. Existing installed tools were untouched.
+- Local documentation targets/heading anchors and `git diff --check` checked. The GitHub-rendered revised README has not been inspected because these changes are local.
+
+The dependency update passed the required Windows/Linux/macOS PR matrix before merging. Live Windows ACL/credential handling, a fresh end-to-end assistant connection on the final revision, restart persistence and actual recurring execution remain separate checks. Existing acceptance reports document their specific paths and limitations; do not broaden those claims.
+
+## Rollout priorities
+
+1. Merge the reviewed security/documentation changes after required CI. Enable the GitHub protections and private reporting route, then publish the verified `v0.1.0` snapshot with concise release notes.
+2. Lead the announcement with one useful question and one visible result. Link directly to the README's synthetic demo and setup paths. For edited/recreated launch conversations, label the presentation accordingly; keep real observations distinct from scripted examples.
+3. Position this as a personal Garmin archive and an agent analysis interface. Garmin describes the Personal API as individual access to one's own data, rather than a commercial multi-user integration; see [Garmin's FAQ](https://developer.garmin.com/gc-developer-program/personal/personal-faq/). Keep the existing non-affiliation statement.
+4. Collect a small first wave of sanitized setup reports with OS, Python, installed revision and the specific CLI/MCP/assistant path. Use those reports to prioritize onboarding work. A successful synthetic chart is not evidence of secure live setup or working automatic sync.
+5. Add repository discovery topics for the actual agent/CLI use cases (for example `mcp` and `python`) and a custom social preview using approved assets. Keep GitHub Issues as the initial support path; a new support channel or community service is not a launch prerequisite.
+
+## Suggested first release description
+
+Garmin Data Workbench keeps your Garmin health and activity data in a local SQLite archive, with source JSON and original activity files retained. Query sleep, Body Battery, heart rate, steps and activities through the CLI or local MCP tools, or use SQL and CSV for your own analysis. Optional charts use the same shared query definitions and show coverage and missing data.
+
+Start with the synthetic demo without a Garmin key. For live use, choose the archive host and follow the setup guide. This early release has built-in scheduling on macOS; other hosts need their own scheduler. Windows live credential/privacy validation and additional assistant paths still need separate verification. Independent project; not affiliated with Garmin.
diff --git a/scripts/smoke_installed.py b/scripts/smoke_installed.py
index 30fbd4c..5e59f74 100644
--- a/scripts/smoke_installed.py
+++ b/scripts/smoke_installed.py
@@ -21,7 +21,7 @@
from garmin_archive.onboarding import installation_info
-async def check_mcp(executable: Path, archive: Path, workdir: Path, env: dict[str, str], charts: bool) -> None:
+async def check_mcp(executable: Path, archive: Path, workdir: Path, env: dict[str, str], charts: bool) -> dict:
params = StdioServerParameters(command=str(executable), args=["--data-dir", str(archive)],
cwd=str(workdir), env=env)
async with stdio_client(params) as (read, write):
@@ -65,6 +65,17 @@ async def check_mcp(executable: Path, archive: Path, workdir: Path, env: dict[st
assert not native.isError, native.content
data = native.structuredContent or json.loads(native.content[0].text)
assert data["value"] == 0, data
+ comparison = await client.call_tool("compare_periods", {"metric": "steps", "start": "2026-01-02", "end": "2026-01-02",
+ "baseline_start": "2026-01-01", "baseline_end": "2026-01-01"})
+ assert not comparison.isError, comparison.content
+ workouts = await client.call_tool("get_workout_summary", {"start": "2026-01-01", "end": "2026-01-02", "activity_type": "running"})
+ assert not workouts.isError, workouts.content
+ activities = await client.call_tool("list_activities", {"start": "2026-01-01", "end": "2026-01-02", "activity_type": "running", "limit": 1})
+ assert not activities.isError, activities.content
+ data = activities.structuredContent or json.loads(activities.content[0].text)
+ assert data["activities"][0]["activity_id"] == 42
+ return {"comparison": comparison.structuredContent or json.loads(comparison.content[0].text),
+ "workouts": workouts.structuredContent or json.loads(workouts.content[0].text)}
def main() -> None:
@@ -143,6 +154,11 @@ def run(arguments: list[str], *, cwd: Path = workdir) -> str:
archive.save_daily('daily_summary', '2026-01-01', {'data': [
{'calendarDate': '2026-01-01', 'movement': {'steps': {'value': 1234}}}
]})
+ archive.save_daily('daily_summary', '2026-01-02', {'data': [
+ {'calendarDate': '2026-01-02', 'movement': {'steps': {'value': 2468}}}]})
+ archive.save_activities('2026-01-01', [{'activityId': 42, 'activityType': {'typeKey': 'running'},
+ 'distance': 5000, 'duration': 1800}])
+ archive.save_activities('2026-01-02', [])
archive.save_daily('sleep', '2026-01-01', {'sleepTimeSeconds': 27000,
'deepSleepSeconds': 5000, 'remSleepSeconds': 6000, 'lightSleepSeconds': 16000,
'unmeasurableSleepSeconds': 0, 'sleepScores': {'overall': {'value': 80}},
@@ -170,7 +186,15 @@ def run(arguments: list[str], *, cwd: Path = workdir) -> str:
assert sleep["nights"][0]["next_sleep_need"]["day"] == "2026-01-02", sleep
battery = json.loads(run([str(cli), "--data-dir", str(archive), "body-battery", "--from", "2026-01-01", "--to", "2026-01-01"]))
assert battery["days"][0]["values"]["body_battery_last"] == 20, battery
- asyncio.run(asyncio.wait_for(check_mcp(mcp, archive, workdir, env, args.charts), timeout=30))
+ comparison = json.loads(run([str(cli), "--data-dir", str(archive), "compare", "steps", "--from", "2026-01-02", "--to", "2026-01-02",
+ "--baseline-from", "2026-01-01", "--baseline-to", "2026-01-01"]))
+ assert comparison["change"]["mean_difference"] == 1234 and comparison["change"]["mean_percent_change"] == 100, comparison
+ workouts = json.loads(run([str(cli), "--data-dir", str(archive), "workout-summary", "--from", "2026-01-01", "--to", "2026-01-02", "--type", "running"]))
+ assert workouts["totals"]["distance_m"] == 5000 and workouts["totals"]["duration_s"] == 1800, workouts
+ activities = json.loads(run([str(cli), "--data-dir", str(archive), "activities", "--from", "2026-01-01", "--to", "2026-01-02", "--type", "running"]))
+ assert [row["activity_id"] for row in activities] == [42], activities
+ mcp_results = asyncio.run(asyncio.wait_for(check_mcp(mcp, archive, workdir, env, args.charts), timeout=30))
+ assert mcp_results == {"comparison": comparison, "workouts": workouts}, "Installed CLI and MCP disagree"
if args.charts:
chart = workdir / "steps.png"
metadata = json.loads(run([str(cli), "--data-dir", str(archive), "chart", "steps", "--from", "2026-01-01",
diff --git a/src/garmin_archive/agent_guide.md b/src/garmin_archive/agent_guide.md
index 0eddee3..d8a7b9d 100644
--- a/src/garmin_archive/agent_guide.md
+++ b/src/garmin_archive/agent_guide.md
@@ -3,6 +3,8 @@
Use the existing local archive for questions. Queries require no Garmin key or live request.
Do not sync, register a client, change a schedule, or create a routine unless the user asks.
+Early in a new analysis or ongoing check-in, ask what the user wants to understand or improve if their goal is not already clear. Keep it conversational: for example, “What are you hoping to learn or improve from your Garmin data?” Use their answer to choose relevant comparisons and practical suggestions. If they have already stated a goal, use it without asking again. For a specific question, answer it first with the available data; ask about a broader goal only when it would make the follow-up more useful. Do not make a goal question a prerequisite for using the workbench, and respect a preference for straightforward numbers.
+
Before setup or handoff, name the command/archive host separately from the chat app's computer. Give same-host absolute executable/archive paths, disclose reused state, and distinguish expected persistence from a controlled new-session test. Follow the [isolated mock setup route](https://github.com/0xBreadguy/garmin-data-workbench/blob/main/docs/SETUP.md#mock-only-setup-stop-before-credentials) for mock-only requests.
For the default synthetic demo, start with “How was sleep April 24–30, 2026?” using `sleep` and `chart sleep` with explicit dates. During explicitly mock-only use, if “this week” has no demo observations, state the requested actual dates and missing coverage, then use the latest available fixture week when the user's demo intent is clear, naming its exact dates before answering. For the default corpus: “There are no demo observations for your current week; I'll demonstrate sleep with the synthetic April 24–30, 2026 week.” Use the selected corpus's actual dates for custom demos; report gaps if none are available. If intent is ambiguous, ask one concise choice: “Use the latest fixture week, or keep the requested period with no observations?” Never override explicit dates, move fixture dates to today, imply the user's real week was measured, or make credentials/live access the required next step. Preserve text-only requests. The [demo guide](https://github.com/0xBreadguy/garmin-data-workbench/blob/main/docs/VISUALIZATION.md#try-generated-demo-data) explains other fixture windows and simulated freshness.
@@ -13,6 +15,9 @@ For the default synthetic demo, start with “How was sleep April 24–30, 2026?
- `metrics`: discover interpreted scalar metric names, titles, datasets and source units as JSON without an archive. Use the query's display units when presenting results.
- `day YYYY-MM-DD` / MCP `get_day`: daily metrics, activities and coverage.
- `trend METRIC --from YYYY-MM-DD --to YYYY-MM-DD` / `get_trend`: one metric over 1–90 inclusive dates.
+- `compare METRIC --from DATE --to DATE --baseline-from DATE --baseline-to DATE` / `compare_periods`: deterministic differences between available-day means over two explicit periods (1–90 days each, baseline before period). Reuse the calculated changes; report both denominators and warnings. Changes use source units; null percentages have an explicit reason. This is not a causal conclusion or a personal baseline.
+- `activities --from DATE --to DATE --type running` / `list_activities`: paginated activity search summaries with optional inclusive bounds and exact native typeKey filters; sport subtypes are not inferred. Lists include parent and child recordings.
+- `workout-summary --from DATE --to DATE --type running` / `get_workout_summary`: covered distance/duration totals, daily values and Monday-based weeks over 1–90 dates. Check field counts and date coverage; failed days and missing measurements are not zero. Parents with stored children are excluded before filtering; missing children can leave incomplete totals. Other overlapping recordings remain separate. Summary duration is not deduplicated elapsed time. Inspect native details for questions beyond these summaries.
- `sleep --from YYYY-MM-DD --to YYYY-MM-DD` / `get_sleep`: sleep duration, score, stages, stress, naps, adjusted/baseline sleep need and source sleep-window times together. Prefer this over extracting raw sleep JSON.
- `body-battery --from YYYY-MM-DD --to YYYY-MM-DD` / `get_body_battery`: reported daily charge/drain and observed min/max/first/last levels, counts and source observation times. No raw readings or events.
- `status` / `archive_status`: stored coverage and sync failures. Successful status reads do not prove successful syncs.
@@ -36,6 +41,10 @@ For multi-day trends, sleep overviews and Body Battery questions, normally reply
- Fewer than three usable observations are available: normally use a small table and state the gap. An explicitly requested chart or useful two-point comparison is still allowed; do not claim a trend or baseline from sparse data.
- Rendering or image delivery is unavailable: explicitly say no chart was delivered and give a small table of available values.
+Answer the user's underlying question, not just a list of measurements. Identify the most relevant pattern or change, explain what it may mean for their stated goal, and, when useful, suggest a practical next step or a focused follow-up question. Use an appropriate comparison with their own history when enough comparable data exists; otherwise say what is missing rather than inventing a baseline. Tailor advice to the user's context and preferences, and do not manufacture an insight or recommendation when the data cannot support one. For a simple factual request, a direct answer may be enough.
+
+For example, if several comparable nights show shorter sleep before early starts, note the observed pattern and suggest tracking whether it repeats or trying a manageable earlier wind-down, if relevant to the user's goal. Do not claim the early starts caused the shorter sleep, promise an outcome, or prescribe an exact bedtime. If the data is sparse, say a pattern cannot yet be judged and suggest what additional observations would help. For symptoms, concerning readings or medical decisions, avoid diagnosis and direct the user to an appropriate clinician; urgency depends on the situation, not a wearable value alone.
+
Use the renderer's caption/alt text when provided. It should state title, inclusive dates, available-day denominator, rendered units, synthetic provenance and wearable estimates where applicable. Keep routine explanation outside the image. Explain the dotted sleep-need line as Garmin's estimate, the independent score panel, and any gap-strip symbols present; do not assume the image explains these by itself.
For MCP, use `chart` with `metric="sleep"` or a named scalar metric. It returns PNG image content and structured caption, coverage, provenance and explanation metadata without creating a file. `brand` returns settings and asset resource URIs retrievable with MCP resources/read. Host display still needs verification.
diff --git a/src/garmin_archive/cli.py b/src/garmin_archive/cli.py
index e7d8d57..97aad2c 100644
--- a/src/garmin_archive/cli.py
+++ b/src/garmin_archive/cli.py
@@ -31,6 +31,8 @@
from .sources import SOURCES
from .sleep import get_sleep
from .body_battery import get_body_battery
+from .comparisons import compare_periods, validate_periods
+from .workouts import activity_filter, get_workout_summary, list_activities
from .sync import DATASETS, SyncStopped, _call, sync
from garmin_personal_api.errors import HttpError
@@ -106,7 +108,7 @@ def parser() -> argparse.ArgumentParser:
garmin-archive version Package/build revision, OS and chart availability
Archive selection: put --data-dir DIRECTORY before the command.
-Read-only queries: day, trend, sleep, body-battery, status, activities, health,
+Read-only queries: day, trend, compare, workout-summary, sleep, body-battery, status, activities, health,
records, source-data, source-series. They never sync or create an archive.
Exports: chart and export-original write new files and never overwrite.
Live/configuration: sync uses credentials/network; install also connects clients
@@ -179,6 +181,16 @@ def parser() -> argparse.ArgumentParser:
trend.add_argument("metric", choices=sorted(METRICS))
trend.add_argument("--from", dest="start", type=_date, help="Start date (default: six days before end)")
trend.add_argument("--to", dest="end", type=_date, help="End date (default: Garmin profile's today)")
+ compare = commands.add_parser("compare", help="Compare available-day means over two explicit periods as JSON")
+ compare.add_argument("metric", choices=sorted(METRICS))
+ compare.add_argument("--from", dest="start", type=_date, required=True)
+ compare.add_argument("--to", dest="end", type=_date, required=True)
+ compare.add_argument("--baseline-from", type=_date, required=True)
+ compare.add_argument("--baseline-to", type=_date, required=True)
+ workouts = commands.add_parser("workout-summary", help="Read covered activity distance/duration totals and Monday-based weeks as JSON")
+ workouts.add_argument("--from", dest="start", type=_date, help="First of 1–90 inclusive dates (default: six days before end)")
+ workouts.add_argument("--to", dest="end", type=_date, help="Last date (default: Garmin profile's today)")
+ workouts.add_argument("--type", dest="activity_type", default="", help="Exact native activity typeKey, e.g. running or cycling")
sleep = commands.add_parser("sleep", help="Read a bounded sleep summary as JSON: stages, score, stress, naps and source times")
sleep.add_argument("--from", dest="start", type=_date, help="First of 1–90 inclusive dates (default: six days before end)")
sleep.add_argument("--to", dest="end", type=_date, help="Last date (default: Garmin profile's today, possibly incomplete)")
@@ -207,6 +219,9 @@ def parser() -> argparse.ArgumentParser:
description="List stored activity summaries as JSON without syncing or modifying the archive.")
activities.add_argument("--limit", type=_positive, default=20, help="Page size, 1–10000 (default: 20); continue with --offset")
activities.add_argument("--offset", type=_nonnegative, default=0)
+ activities.add_argument("--from", dest="start", type=_date, help="Optional inclusive first stored activity date")
+ activities.add_argument("--to", dest="end", type=_date, help="Optional inclusive last stored activity date")
+ activities.add_argument("--type", dest="activity_type", default="", help="Exact native activity typeKey; subtypes are not inferred")
health = commands.add_parser("health", help="Print raw stored daily JSON; use --metadata to mask failed-refresh values")
health.add_argument("dataset", choices=sorted(DATASETS))
@@ -403,13 +418,11 @@ def _status(db: sqlite3.Connection, path: Path) -> int:
def _activities(db: sqlite3.Connection, args: argparse.Namespace) -> int:
- rows = db.execute(
- """SELECT activity_id, day, json_extract(summary_json, '$.activityType.typeKey') AS type,
- json_extract(summary_json, '$.activityName') AS name, fit_status
- FROM activities ORDER BY day DESC, activity_id DESC LIMIT ? OFFSET ?""",
- (args.limit, args.offset),
- )
- _print_json([dict(row) for row in rows])
+ result = list_activities(db, args.start.isoformat() if args.start else "", args.end.isoformat() if args.end else "",
+ args.activity_type, limit=args.limit, offset=args.offset)
+ # Preserve the existing bare-list CLI contract and its fields.
+ _print_json([{key: row[key] for key in ("activity_id", "day", "type", "name", "fit_status")}
+ for row in result["activities"]])
return 0
@@ -461,7 +474,13 @@ def _read(args: argparse.Namespace) -> int:
"""Query an existing archive without creating, migrating or syncing it."""
try:
with open_archive(args.data_dir) as db:
- if args.command == "source-data":
+ if args.command == "compare":
+ _print_json(compare_periods(db, args.metric, args.start.isoformat(), args.end.isoformat(),
+ args.baseline_from.isoformat(), args.baseline_to.isoformat()))
+ elif args.command == "workout-summary":
+ _print_json(get_workout_summary(db, args.start.isoformat() if args.start else "",
+ args.end.isoformat() if args.end else "", args.activity_type))
+ elif args.command == "source-data":
_print_json(source_data(db, args.dataset, args.day.isoformat() if args.day else "", args.activity_id,
args.pointer, limit=args.limit, offset=args.offset, include_location=args.include_location))
elif args.command == "source-series":
@@ -652,12 +671,16 @@ def _validate_args(args: argparse.Namespace) -> None:
if args.command == "save-key" and (not math.isfinite(args.timeout) or not 1 <= args.timeout <= 120):
raise ValueError("--timeout must be between 1 and 120 seconds")
start, end = getattr(args, "start", None), getattr(args, "end", None)
+ if args.command == "compare":
+ validate_periods(start.isoformat(), end.isoformat(), args.baseline_from.isoformat(), args.baseline_to.isoformat())
+ if args.command in {"activities", "workout-summary"}:
+ activity_filter(start.isoformat() if start else "", end.isoformat() if end else "", args.activity_type)
if start is not None and end is not None:
if start > end:
raise ValueError("Date range must be between 1 and 90 days, inclusive" if args.command != "sync" else "--from must not be after --to")
- if args.command != "sync" and (end - start).days >= 90:
+ if args.command not in {"sync", "activities"} and (end - start).days >= 90:
raise ValueError("Date range must be between 1 and 90 days, inclusive")
- if start is None and end is not None and end < date.min + timedelta(days=6):
+ if args.command != "activities" and start is None and end is not None and end < date.min + timedelta(days=6):
raise ValueError("Default seven-day range precedes year 1; supply --from explicitly")
if hasattr(args, "limit"):
maximum = 100 if args.command in {"api-catalog", "source-data"} else 10000
@@ -742,7 +765,7 @@ def main(argv: list[str] | None = None) -> int:
if args.command == "path":
print(args.data_dir.expanduser() / "archive.sqlite3")
return 0
- if args.command in {"day", "trend", "sleep", "body-battery", "chart", "status", "activities", "records", "health", "export-original", "source-data", "source-series"}:
+ if args.command in {"day", "trend", "compare", "workout-summary", "sleep", "body-battery", "chart", "status", "activities", "records", "health", "export-original", "source-data", "source-series"}:
return _read(args)
if args.command == "connect" and not (args.data_dir.expanduser() / "archive.sqlite3").is_file():
print("No local archive found; run `garmin-archive install` first.", file=sys.stderr)
diff --git a/src/garmin_archive/comparisons.py b/src/garmin_archive/comparisons.py
new file mode 100644
index 0000000..07d8c3c
--- /dev/null
+++ b/src/garmin_archive/comparisons.py
@@ -0,0 +1,60 @@
+"""Covered comparisons of two explicit, nonoverlapping metric periods."""
+from __future__ import annotations
+
+import math
+import sqlite3
+
+from .queries import MAX_TREND_DAYS, get_trend, parse_day
+from .preferences import local_today
+
+
+def validate_periods(start: str, end: str, baseline_start: str, baseline_end: str) -> None:
+ first, last, before, after = map(parse_day, (start, end, baseline_start, baseline_end))
+ if any(not 1 <= (b - a).days + 1 <= MAX_TREND_DAYS for a, b in ((first, last), (before, after))):
+ raise ValueError("Each comparison period must be between 1 and 90 days, inclusive")
+ if after >= first:
+ raise ValueError("The baseline must end before the comparison period begins")
+
+
+def compare_periods(db: sqlite3.Connection, metric: str, start: str, end: str,
+ baseline_start: str, baseline_end: str) -> dict:
+ """Compare available-day means; retained failed values use existing trend masking."""
+ validate_periods(start, end, baseline_start, baseline_end)
+ baseline = get_trend(db, metric, baseline_start, baseline_end)
+ period = get_trend(db, metric, start, end)
+ means = []
+ warnings = []
+ today, _ = local_today(period["preferences"])
+ for name, result in (("baseline", baseline), ("period", period)):
+ values = [p["value"] for p in result["points"] if p["value"] is not None]
+ # Divide before summing to avoid overflowing otherwise finite means.
+ means.append(math.fsum(v / len(values) for v in values) if values else None)
+ if len(values) != result["coverage"]["requested_days"]:
+ warnings.append(name + "_incomplete_coverage")
+ if result["to"] >= today.isoformat():
+ warnings.append(name + "_includes_today_or_future")
+ if baseline["coverage"]["requested_days"] != period["coverage"]["requested_days"]:
+ warnings.append("unequal_period_lengths")
+ old, new = means
+ difference = percent = None
+ percent_status = "unavailable"
+ if old is not None and new is not None:
+ difference = round(new - old, 2)
+ # Percentages of scores, bounded scales and percentages imply a ratio
+ # interpretation those units do not support.
+ if period["unit"] in {"score", "Garmin stress", "Body Battery", "points", "%"}:
+ percent_status = "not_applicable_to_scale"
+ elif old == 0:
+ percent_status = "zero_baseline"
+ else:
+ candidate = (new / old - 1) * 100
+ percent_status = "available" if math.isfinite(candidate) else "out_of_range"
+ percent = round(candidate, 2) if math.isfinite(candidate) else None
+ return {"archive_provenance": period["archive_provenance"], "metric": metric, "unit": period["unit"],
+ "source": period["source"], "baseline": baseline, "period": period,
+ "change": {"status": "available" if difference is not None else "unavailable",
+ "mean_difference": difference, "mean_percent_change": percent,
+ "percent_change_status": percent_status}, "warnings": warnings,
+ "basis": "Period minus baseline; each mean uses its own available-day denominator. "
+ "Changes use unrounded source values and are rounded to two decimals. "
+ "Incomplete coverage can bias comparisons; these are descriptive changes, not causes or personal baselines."}
diff --git a/src/garmin_archive/mcp_server.py b/src/garmin_archive/mcp_server.py
index f0c3ca4..9c054b9 100644
--- a/src/garmin_archive/mcp_server.py
+++ b/src/garmin_archive/mcp_server.py
@@ -25,6 +25,8 @@
from .queries import get_day as query_day, get_trend as query_trend, health_response, open_archive
from .sleep import get_sleep as query_sleep
from .body_battery import get_body_battery as query_body_battery
+from .comparisons import compare_periods as query_comparison
+from .workouts import get_workout_summary as query_workouts, list_activities as query_activities
from .guidance import agent_guide as read_agent_guide
from .schedule import configure_schedule, schedule_status
@@ -243,28 +245,42 @@ def archive_status() -> dict:
"coverage": coverage, "activity_files": fit,
"catch_up": dict(catchup) if catchup else None}
+ @server.tool(annotations=READ_ONLY)
+ def compare_periods(metric: str, start: str, end: str, baseline_start: str, baseline_end: str) -> dict:
+ """Compare available-day metric means over two explicit periods of 1–90 inclusive dates each.
+
+ Baseline must end before start. Changes are period minus baseline, in source
+ units. Read warnings and each period's coverage/fetch times before interpreting.
+ Percent changes are unavailable for scores/bounded scales or a zero baseline.
+ """
+ with open_archive(data_dir) as db:
+ return query_comparison(db, metric, start, end, baseline_start, baseline_end)
+
+ @server.tool(annotations=READ_ONLY)
+ def get_workout_summary(start: str = "", end: str = "", activity_type: str = "") -> dict:
+ """Get distance/duration totals and Monday-based weekly buckets over 1–90 inclusive dates.
+
+ Defaults to seven dates ending today. activity_type is an exact native typeKey,
+ not a sport family. Parents with stored children are excluded before filtering.
+ Failed dates are masked; totals use available summaries and report field counts.
+ Duration is the source summary duration; overlapping recordings remain separate.
+ """
+ with open_archive(data_dir) as db:
+ return query_workouts(db, start, end, activity_type)
+
@server.tool(annotations=READ_ONLY)
def list_activities(
limit: Annotated[int, Field(ge=1, le=100)] = 20,
offset: Annotated[int, Field(ge=0)] = 0,
+ start: str = "", end: str = "", activity_type: str = "",
) -> dict:
- """List activity summaries, newest first. Page with offset and limit."""
+ """List activity summaries, newest first. Optional inclusive date bounds and exact typeKey.
+
+ Page with offset and limit. Includes parent/child recordings; use
+ get_workout_summary for totals. Failed refreshes mask numeric measurements.
+ """
with open_archive(data_dir) as db:
- prefs = profile_preferences(db)
- provenance = archive_provenance(db)
- rows = [dict(row) for row in db.execute(
- "SELECT activity_id, day, json_extract(summary_json, '$.activityType.typeKey') AS type, "
- "json_extract(summary_json, '$.activityName') AS name, "
- "json_extract(summary_json, '$.distance') AS distance_m, "
- "json_extract(summary_json, '$.duration') AS duration_s, "
- "json_extract(summary_json, '$.averageHR') AS average_heart_rate_bpm, fit_status, updated_at "
- "FROM activities ORDER BY day DESC, activity_id DESC LIMIT ? OFFSET ?", (limit + 1, offset)
- )]
- for activity in rows:
- activity["display_distance"], activity["display_distance_unit"] = display_distance(activity["distance_m"], prefs)
- return {"archive_provenance": provenance, "source": "local archive", "preferences": prefs, "activities": rows[:limit],
- "units": {"distance_m": "m", "duration_s": "s", "average_heart_rate_bpm": "bpm"},
- "next_offset": offset + limit if len(rows) > limit else None}
+ return query_activities(db, start, end, activity_type, limit=limit, offset=offset)
@server.tool(annotations=READ_ONLY)
def daily_health(dataset: str, day: str) -> dict:
diff --git a/src/garmin_archive/queries.py b/src/garmin_archive/queries.py
index a5f861a..fc4ed87 100644
--- a/src/garmin_archive/queries.py
+++ b/src/garmin_archive/queries.py
@@ -294,7 +294,7 @@ def metric_trend(db: sqlite3.Connection, metric: str, start: str, end: str) -> d
return {"archive_provenance": archive_provenance(db), "metric": metric, "unit": unit, "source": "Garmin Personal API via local archive",
"dataset": dataset, **field_info, "from": start, "to": end,
"coverage": {"requested_days": days, "days_with_value": len(values), "statuses": counts},
- "mean_of_available_days": round(sum(values) / len(values), 2) if values else None,
+ "mean_of_available_days": round(math.fsum(value / len(values) for value in values), 2) if values else None,
"points": points}
diff --git a/src/garmin_archive/workouts.py b/src/garmin_archive/workouts.py
new file mode 100644
index 0000000..0e0f152
--- /dev/null
+++ b/src/garmin_archive/workouts.py
@@ -0,0 +1,127 @@
+"""Bounded activity filtering and covered totals from stored search summaries."""
+from __future__ import annotations
+
+import math
+import sqlite3
+from datetime import timedelta
+
+from .preferences import display_distance, profile_preferences
+from .provenance import archive_provenance
+from .queries import parse_day, query_range
+
+
+def activity_filter(start: str = "", end: str = "", activity_type: str = "") -> tuple[str, list]:
+ if start:
+ parse_day(start)
+ if end:
+ parse_day(end)
+ if start and end and start > end:
+ raise ValueError("--from must not be after --to")
+ if not isinstance(activity_type, str) or len(activity_type) > 100:
+ raise ValueError("Activity type must be a native typeKey of at most 100 characters")
+ clauses, values = [], []
+ for clause, value in (("a.day >= ?", start), ("a.day <= ?", end),
+ ("json_extract(a.summary_json, '$.activityType.typeKey') = ?", activity_type)):
+ if value:
+ clauses.append(clause)
+ values.append(value)
+ return " AND ".join(clauses) or "1", values
+
+
+def list_activities(db: sqlite3.Connection, start: str = "", end: str = "", activity_type: str = "",
+ *, limit: int = 20, offset: int = 0) -> dict:
+ where, args = activity_filter(start, end, activity_type)
+ if isinstance(limit, bool) or not isinstance(limit, int) or not 1 <= limit <= 10000:
+ raise ValueError("Limit must be between 1 and 10000")
+ if isinstance(offset, bool) or not isinstance(offset, int) or not 0 <= offset <= 2**63 - 1:
+ raise ValueError("Offset must be a nonnegative SQLite integer")
+ rows = [dict(row) for row in db.execute(
+ "SELECT a.activity_id, a.day, json_extract(a.summary_json, '$.activityType.typeKey') AS type, "
+ "json_extract(a.summary_json, '$.activityName') AS name, a.fit_status, a.updated_at, "
+ "COALESCE(s.status, 'not_checked') AS status, s.updated_at AS last_attempt, "
+ "CASE WHEN s.status='ok' AND json_type(a.summary_json, '$.distance') IN ('integer','real') THEN json_extract(a.summary_json, '$.distance') END AS distance_m, "
+ "CASE WHEN s.status='ok' AND json_type(a.summary_json, '$.duration') IN ('integer','real') THEN json_extract(a.summary_json, '$.duration') END AS duration_s, "
+ "CASE WHEN s.status='ok' AND json_type(a.summary_json, '$.averageHR') IN ('integer','real') THEN json_extract(a.summary_json, '$.averageHR') END AS average_heart_rate_bpm "
+ "FROM activities a LEFT JOIN sync_state s ON s.dataset='activities' AND s.day=a.day "
+ f"WHERE {where} ORDER BY a.day DESC, a.activity_id DESC LIMIT ? OFFSET ?", [*args, limit + 1, offset])]
+ prefs = profile_preferences(db)
+ for row in rows:
+ for key in ("distance_m", "duration_s", "average_heart_rate_bpm"):
+ value = row[key]
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value < 0:
+ row[key] = None
+ row["display_distance"], row["display_distance_unit"] = display_distance(row["distance_m"], prefs)
+ return {"archive_provenance": archive_provenance(db), "source": "local archive", "preferences": prefs,
+ "activities": rows[:limit], "next_offset": offset + limit if len(rows) > limit else None,
+ "units": {"distance_m": "m", "duration_s": "s", "average_heart_rate_bpm": "bpm"}}
+
+
+def _totals(days: list[dict], prefs: dict) -> dict:
+ available = [day for day in days if day["status"] in {"ok", "empty"}]
+ count = sum(day["activity_count"] for day in available) if available else None
+ result = {"activity_count": count}
+ for metric in ("distance_m", "duration_s"):
+ valid = sum(day[metric + "_activities"] for day in available)
+ result[metric + "_activities"] = valid
+ total = None
+ if valid and not any(day[metric] is None and day[metric + "_activities"] for day in available):
+ try:
+ total = math.fsum(day[metric] for day in available if day[metric] is not None)
+ except OverflowError:
+ pass
+ result[metric] = total if valid else 0 if count == 0 else None
+ result["display_distance"], result["display_distance_unit"] = display_distance(result["distance_m"], prefs)
+ return result
+
+
+def get_workout_summary(db: sqlite3.Connection, start: str = "", end: str = "", activity_type: str = "") -> dict:
+ first, last, prefs, today_source = query_range(db, start, end)
+ where, args = activity_filter(first.isoformat(), last.isoformat(), activity_type)
+ # Parent IDs are tested before sport/date filtering. Otherwise a parent and
+ # its component activities could both contribute to volume totals.
+ rows = {row["day"]: dict(row) for row in db.execute(
+ "WITH selected AS (SELECT a.day, "
+ "CASE WHEN json_type(a.summary_json, '$.distance') IN ('integer','real') "
+ "AND json_extract(a.summary_json, '$.distance') BETWEEN 0 AND 1.7976931348623157e308 THEN json_extract(a.summary_json, '$.distance') END AS distance_m, "
+ "CASE WHEN json_type(a.summary_json, '$.duration') IN ('integer','real') "
+ "AND json_extract(a.summary_json, '$.duration') BETWEEN 0 AND 1.7976931348623157e308 THEN json_extract(a.summary_json, '$.duration') END AS duration_s "
+ "FROM activities a JOIN sync_state s ON s.day=a.day AND s.dataset='activities' AND s.status='ok' "
+ f"WHERE {where} AND a.activity_id NOT IN ("
+ "SELECT json_extract(summary_json, '$.parentId') FROM activities "
+ "WHERE json_type(summary_json, '$.parentId')='integer' AND json_extract(summary_json, '$.parentId') > 0)) "
+ "SELECT day, COUNT(*) AS activity_count, SUM(CAST(distance_m AS REAL)) AS distance_m, SUM(CAST(duration_s AS REAL)) AS duration_s, "
+ "COUNT(distance_m) AS distance_m_activities, COUNT(duration_s) AS duration_s_activities "
+ "FROM selected GROUP BY day", args)}
+ states = {row["day"]: dict(row) for row in db.execute(
+ "SELECT day, status, error, updated_at AS last_attempt FROM sync_state "
+ "WHERE dataset='activities' AND day BETWEEN ? AND ?", (first.isoformat(), last.isoformat()))}
+ days, weeks, statuses = [], {}, {}
+ for index in range((last - first).days + 1):
+ day = first + timedelta(days=index)
+ iso = day.isoformat()
+ state = states.get(iso, {"status": "not_checked", "error": None, "last_attempt": None})
+ point = {"day": iso, **state}
+ point.update(rows.get(iso, {"activity_count": 0, "distance_m": 0, "duration_s": 0,
+ "distance_m_activities": 0, "duration_s_activities": 0}))
+ for metric in ("distance_m", "duration_s"):
+ if point[metric] is not None and not math.isfinite(point[metric]):
+ point[metric] = None
+ if state["status"] not in {"ok", "empty"}:
+ point.update({"activity_count": None, "distance_m": None, "duration_s": None})
+ days.append(point)
+ weeks.setdefault((day - timedelta(days=day.weekday())).isoformat(), []).append(point)
+ statuses[point["status"]] = statuses.get(point["status"], 0) + 1
+ return {"archive_provenance": archive_provenance(db), "source": "stored Garmin activity search summaries",
+ "from": first.isoformat(), "to": last.isoformat(), "activity_type": activity_type or None,
+ "preferences": prefs, "today_source": today_source, "units": {"distance_m": "m", "duration_s": "s"},
+ "coverage": {"requested_days": len(days), "days_available": sum(statuses.get(s, 0) for s in ("ok", "empty")),
+ "statuses": statuses}, "totals": _totals(days, prefs), "days": days,
+ "weeks": [{"week_start": monday, "from": group[0]["day"], "to": group[-1]["day"],
+ "days_available": sum(d["status"] in {"ok", "empty"} for d in group),
+ **_totals(group, prefs)} for monday, group in weeks.items()],
+ "notes": ["Weeks begin Monday and are clipped to the requested dates. Dates are stored activity dates; no historical zone is inferred.",
+ "Totals use available summaries only; missing fields and failed/unchecked dates are not zero. Field counts show missing measurements.",
+ "Nonfinite source values and totals outside the numeric range are unavailable.",
+ "Parents with stored child activities are excluded before filtering. Missing children can leave multisport totals incomplete.",
+ "Other overlapping recordings remain separate. Duration is Garmin's summary duration, not elapsed time or time deduplicated across recordings.",
+ "An empty search is not proof Garmin has returned complete history; retained activity rows do not track deletions."]}
diff --git a/tests/test_cli_queries.py b/tests/test_cli_queries.py
index cf2166b..4e17388 100644
--- a/tests/test_cli_queries.py
+++ b/tests/test_cli_queries.py
@@ -108,6 +108,29 @@ def test_trend_masks_failed_refresh_and_reports_coverage(self):
self.assertEqual(result["coverage"]["days_with_value"], 1)
self.assertEqual(result["mean_of_available_days"], 27000)
+ def test_comparison_and_workout_commands_are_read_only_and_share_query_behavior(self):
+ code, output, errors = self.run_query("compare", "sleep_duration", "--from", "2026-01-02", "--to", "2026-01-02",
+ "--baseline-from", "2026-01-01", "--baseline-to", "2026-01-01")
+ self.assertEqual((code, errors), (0, ""))
+ self.assertIsNone(json.loads(output)["change"]["mean_difference"])
+ code, output, errors = self.run_query("workout-summary", "--from", "2026-01-01", "--to", "2026-01-01", "--type", "cycling")
+ self.assertEqual((code, errors), (0, ""))
+ result = json.loads(output)
+ self.assertEqual(result["totals"]["activity_count"], 4)
+ self.assertIsNone(result["totals"]["distance_m"])
+ code, output, errors = self.run_query("activities", "--from", "2026-01-01", "--to", "2026-01-01", "--type", "running")
+ self.assertEqual((code, errors, json.loads(output)), (0, "", []))
+ target = self.root / "missing"
+ cases = (("compare", "steps", "--from", "2026-01-01", "--to", "2026-01-02",
+ "--baseline-from", "2025-12-01", "--baseline-to", "2026-01-01"),
+ ("workout-summary", "--from", "2026-01-01", "--to", "2026-04-01"),
+ ("activities", "--type", "x" * 101))
+ with patch("garmin_archive.cli.open_archive") as opened:
+ for args in cases:
+ self.assert_error(self.run_query(*args, data_dir=target), 2, "invalid_argument")
+ opened.assert_not_called()
+ self.assertFalse(target.exists())
+
def test_default_dates_use_profile_and_default_trend_is_seven_days(self):
with patch("garmin_archive.queries.local_today", return_value=(date(2026, 1, 7), "Garmin profile")):
code, output, _ = self.run_query("day")
diff --git a/tests/test_comparisons_workouts.py b/tests/test_comparisons_workouts.py
new file mode 100644
index 0000000..7c320d1
--- /dev/null
+++ b/tests/test_comparisons_workouts.py
@@ -0,0 +1,159 @@
+"""Independent synthetic expectations for comparisons and covered activity volume."""
+from __future__ import annotations
+
+import tempfile
+import unittest
+from datetime import date
+from pathlib import Path
+from unittest.mock import patch
+
+from garmin_archive.archive import Archive
+from garmin_archive.comparisons import compare_periods, validate_periods
+from garmin_archive.workouts import get_workout_summary, list_activities
+
+
+class AnalysisTest(unittest.TestCase):
+ def setUp(self):
+ temp = tempfile.TemporaryDirectory()
+ self.addCleanup(temp.cleanup)
+ self.archive = Archive(Path(temp.name))
+ self.addCleanup(self.archive.close)
+ self.db = self.archive.connection
+ self.archive.save_preferences("statute_us", "America/Los_Angeles")
+
+ def steps(self, day, value):
+ self.archive.save_daily("daily_summary", day, {"data": [{"calendarDate": day,
+ "movement": {"steps": {"value": value}}}]})
+
+ def test_comparison_uses_independent_coverage_and_masks_failed_retained_values(self):
+ for day, value in (("2026-01-01", 100), ("2026-01-02", 300), ("2026-01-03", 600), ("2026-01-04", 999)):
+ self.steps(day, value)
+ self.archive.mark_error("daily_summary", "2026-01-04", "HTTP 429")
+ result = compare_periods(self.db, "steps", "2026-01-03", "2026-01-05", "2026-01-01", "2026-01-02")
+ self.assertEqual(result["baseline"]["mean_of_available_days"], 200)
+ self.assertEqual(result["period"]["mean_of_available_days"], 600)
+ self.assertEqual(result["change"]["mean_difference"], 400)
+ self.assertEqual(result["change"]["mean_percent_change"], 200)
+ self.assertEqual(result["period"]["coverage"]["days_with_value"], 1)
+ self.assertEqual(result["period"]["points"][1]["status"], "error")
+ self.assertIsNone(result["period"]["points"][1]["value"])
+ self.assertIsNotNone(result["period"]["points"][0]["fetched_at"])
+ self.assertEqual(result["warnings"], ["period_incomplete_coverage", "unequal_period_lengths"])
+
+ def test_zero_missing_and_score_percentages_have_distinct_reasons(self):
+ self.steps("2026-01-01", 0)
+ self.steps("2026-01-02", 10)
+ zero = compare_periods(self.db, "steps", "2026-01-02", "2026-01-02", "2026-01-01", "2026-01-01")
+ self.assertEqual(zero["change"]["mean_difference"], 10)
+ self.assertIsNone(zero["change"]["mean_percent_change"])
+ self.assertEqual(zero["change"]["percent_change_status"], "zero_baseline")
+ for day, score in (("2026-01-01", 80), ("2026-01-02", 88)):
+ self.archive.save_daily("sleep", day, {"sleepScores": {"overall": {"value": score}}})
+ score = compare_periods(self.db, "sleep_score", "2026-01-02", "2026-01-02", "2026-01-01", "2026-01-01")
+ self.assertEqual(score["change"]["mean_difference"], 8)
+ self.assertEqual(score["change"]["percent_change_status"], "not_applicable_to_scale")
+ missing = compare_periods(self.db, "steps", "2026-01-03", "2026-01-03", "2026-01-01", "2026-01-01")
+ self.assertEqual(missing["change"]["status"], "unavailable")
+ self.assertIsNone(missing["change"]["mean_difference"])
+
+ def test_period_validation_covers_overlap_order_format_and_90_day_boundary(self):
+ for bounds in (("2026-01-02", "2026-01-01", "2025-12-01", "2025-12-02"),
+ ("2026-01-01", "2026-04-01", "2025-12-01", "2025-12-02"),
+ ("2026-01-01", "2026-01-02", "2025-12-31", "2026-01-01"),
+ ("20260101", "2026-01-02", "2025-12-01", "2025-12-02"),
+ ("2026-01-01", "2026-01-02", "2025-01-01", "2025-12-31")):
+ with self.subTest(bounds=bounds), self.assertRaises(ValueError):
+ validate_periods(*bounds)
+ validate_periods("2026-01-01", "2026-03-31", "2025-12-01", "2025-12-31")
+
+ def test_changes_use_unrounded_means_and_today_is_flagged(self):
+ for day, value in enumerate((1, 1, 2, 2, 2, 3), 1):
+ self.steps(f"2026-01-{day:02}", value)
+ with patch("garmin_archive.comparisons.local_today", return_value=(date(2026, 1, 6), "host")):
+ result = compare_periods(self.db, "steps", "2026-01-04", "2026-01-06", "2026-01-01", "2026-01-03")
+ self.assertEqual(result["change"]["mean_difference"], 1)
+ self.assertEqual(result["change"]["mean_percent_change"], 75)
+ self.assertEqual(result["warnings"], ["period_includes_today_or_future"])
+
+ def activity(self, identity, distance=None, duration=None, kind="running", **extra):
+ return {"activityId": identity, "activityName": "Synthetic", "activityType": {"typeKey": kind},
+ "distance": distance, "duration": duration, "position_lat": "PRIVATE", **extra}
+
+ def test_workouts_have_week_boundaries_field_counts_preferences_and_no_locations(self):
+ self.archive.save_activities("2026-01-04", [self.activity(1, 1609.344, 600), self.activity(2, None, 300)])
+ self.archive.save_activities("2026-01-05", [self.activity(3, 3218.688, 900), self.activity(4, 999, 999, "cycling")])
+ self.archive.save_activities("2026-01-06", [])
+ self.archive.save_activities("2026-01-07", [self.activity(5, 99999, 99999)])
+ self.archive.mark_error("activities", "2026-01-07", "HTTP 429")
+ result = get_workout_summary(self.db, "2026-01-04", "2026-01-08", "running")
+ self.assertEqual(result["totals"]["activity_count"], 3)
+ self.assertEqual(result["totals"]["distance_m"], 4828.032)
+ self.assertEqual(result["totals"]["distance_m_activities"], 2)
+ self.assertEqual(result["totals"]["duration_s"], 1800)
+ self.assertEqual(result["totals"]["display_distance"], 3)
+ self.assertEqual(result["totals"]["display_distance_unit"], "mi")
+ self.assertEqual(result["coverage"]["days_available"], 3)
+ self.assertEqual([w["week_start"] for w in result["weeks"]], ["2025-12-29", "2026-01-05"])
+ self.assertEqual([w["duration_s"] for w in result["weeks"]], [900, 900])
+ self.assertEqual(result["days"][2]["activity_count"], 0)
+ self.assertIsNone(result["days"][3]["activity_count"])
+ self.assertIsNone(result["days"][4]["distance_m"])
+ self.assertNotIn("PRIVATE", str(result))
+
+ def test_multisport_parents_are_excluded_before_type_filtering_and_recordings_remain_separate(self):
+ self.archive.save_activities("2026-01-01", [self.activity(1, 9000, 900, "multisport"),
+ self.activity(2, 1000, 100, parentId=1), self.activity(3, 8000, 800, "cycling", parentId=1),
+ self.activity(4, 2000, 200)])
+ result = get_workout_summary(self.db, "2026-01-01", "2026-01-01")
+ self.assertEqual(result["totals"]["activity_count"], 3)
+ self.assertEqual(result["totals"]["distance_m"], 11000)
+ running = get_workout_summary(self.db, "2026-01-01", "2026-01-01", "running")
+ self.assertEqual(running["totals"]["distance_m"], 3000)
+ page = list_activities(self.db, "2026-01-01", "2026-01-01", "running", limit=1)
+ self.assertEqual(page["activities"][0]["activity_id"], 4)
+ self.assertEqual(page["next_offset"], 1)
+ self.assertEqual(list_activities(self.db, activity_type="running", offset=1)["activities"][0]["activity_id"], 2)
+ self.assertNotIn("PRIVATE", str(page))
+
+ def test_missing_fields_zero_empty_and_unchecked_are_not_conflated(self):
+ self.archive.save_activities("2026-01-01", [self.activity(1, True, -1), self.activity(2, "123", None)])
+ self.archive.save_activities("2026-01-02", [])
+ invalid = get_workout_summary(self.db, "2026-01-01", "2026-01-02")
+ self.assertEqual(invalid["totals"]["activity_count"], 2)
+ self.assertIsNone(invalid["totals"]["distance_m"])
+ self.assertEqual(invalid["totals"]["distance_m_activities"], 0)
+ empty = get_workout_summary(self.db, "2026-01-02", "2026-01-02")
+ self.assertEqual(empty["totals"]["distance_m"], 0)
+ missing = get_workout_summary(self.db, "2026-01-03", "2026-01-03")
+ self.assertIsNone(missing["totals"]["activity_count"])
+ self.assertIsNone(missing["totals"]["distance_m"])
+ self.archive.save_activities("2026-01-04", [self.activity(3, 0, 0)])
+ zero = get_workout_summary(self.db, "2026-01-04", "2026-01-04")
+ self.assertEqual(zero["totals"]["distance_m"], 0)
+ self.assertEqual(zero["totals"]["distance_m_activities"], 1)
+
+ def test_list_masks_failed_measurements_and_rejects_unsafe_bounds(self):
+ self.archive.save_activities("2026-01-01", [self.activity(1, 100, 10)])
+ self.archive.mark_error("activities", "2026-01-01", "HTTP 429")
+ row = list_activities(self.db)["activities"][0]
+ self.assertEqual(row["status"], "error")
+ self.assertIsNone(row["distance_m"])
+ self.assertIsNotNone(row["last_attempt"])
+ for kwargs in ({"limit": 0}, {"offset": 2**63}, {"start": "bad"},
+ {"start": "2026-01-02", "end": "2026-01-01"}, {"activity_type": "x" * 101}):
+ with self.subTest(kwargs=kwargs), self.assertRaises(ValueError):
+ list_activities(self.db, **kwargs)
+ with self.assertRaises(ValueError):
+ get_workout_summary(self.db, "2026-01-01", "2026-04-01")
+
+ def test_parent_exclusion_precedes_date_filter_and_large_totals_remain_valid_json(self):
+ self.archive.save_activities("2026-01-01", [self.activity(1, 100, 10)])
+ self.archive.save_activities("2026-01-02", [self.activity(2, 100, 10, parentId=1)])
+ result = get_workout_summary(self.db, "2026-01-01", "2026-01-01")
+ self.assertEqual(result["totals"]["activity_count"], 0)
+ self.archive.save_activities("2026-01-03", [self.activity(3, 10**19, 1e308), self.activity(4, 10**19, 1e308)])
+ result = get_workout_summary(self.db, "2026-01-03", "2026-01-03")
+ self.assertEqual(result["totals"]["distance_m"], 2e19)
+ self.assertIsNone(result["totals"]["duration_s"])
+ import json
+ json.dumps(result, allow_nan=False)
diff --git a/tests/test_workbench_mcp.py b/tests/test_workbench_mcp.py
index 335a265..42e2162 100644
--- a/tests/test_workbench_mcp.py
+++ b/tests/test_workbench_mcp.py
@@ -41,7 +41,7 @@ async def test_stdio_reads_archive_with_bounds_and_no_location(self):
self.assertIn("using Garmin profile preferences", initialized.instructions)
tools = await client.list_tools()
self.assertEqual({t.name for t in tools.tools},
- {"archive_status", "list_activities", "daily_health", "activity_records", "get_day", "get_trend", "setup_status", "configure_sync", "get_sleep", "agent_guide", "setup_receipt", "get_body_battery", "api_catalog", "source_data", "source_series", "chart", "brand"})
+ {"archive_status", "list_activities", "daily_health", "activity_records", "get_day", "get_trend", "setup_status", "configure_sync", "get_sleep", "agent_guide", "setup_receipt", "get_body_battery", "api_catalog", "source_data", "source_series", "chart", "brand", "compare_periods", "get_workout_summary"})
self.assertTrue(all(t.annotations.readOnlyHint for t in tools.tools if t.name != 'configure_sync'))
self.assertFalse(next(t for t in tools.tools if t.name == 'configure_sync').annotations.readOnlyHint)
async def call(name, args):
@@ -49,6 +49,13 @@ async def call(name, args):
self.assertFalse(result.isError, result.content)
return result.structuredContent or json.loads(result.content[0].text)
catalog = await call("api_catalog", {})
+ comparison = await call("compare_periods", {"metric": "steps", "start": "2026-01-02", "end": "2026-01-02",
+ "baseline_start": "2026-01-01", "baseline_end": "2026-01-01"})
+ self.assertEqual(comparison["change"]["status"], "unavailable")
+ workouts = await call("get_workout_summary", {"start": "2026-01-01", "end": "2026-01-01"})
+ self.assertEqual(workouts["totals"]["activity_count"], 1)
+ filtered = await call("list_activities", {"start": "2026-01-01", "end": "2026-01-01", "activity_type": "absent"})
+ self.assertEqual(filtered["activities"], [])
self.assertEqual(len(catalog["sources"]), 26)
fields = await call("api_catalog", {"dataset": "sleep", "pointer": "/dailyNapDTOS/*"})
self.assertIn("/dailyNapDTOS/*/napTimeSec", {field["pointer"] for field in fields["fields"]})