diff --git a/.bestpractices.json b/.bestpractices.json index 3e00497..2e5d4a0 100644 --- a/.bestpractices.json +++ b/.bestpractices.json @@ -38,7 +38,7 @@ "version_unique_status": "Met", "version_unique_justification": "Each source revision has a unique Git commit ID. Release policy requires unique, immutable SemVer tags; the -dev label alone is not used as a release identifier. https://github.com/lennrt/tempestkeep/blob/main/RELEASING.md", "version_semver_status": "Met", - "version_semver_justification": "Version metadata uses 0.2.0 and the release process requires vMAJOR.MINOR.PATCH tags and SemVer artifact versions. https://github.com/lennrt/tempestkeep/blob/main/internal/version/VERSION https://github.com/lennrt/tempestkeep/blob/main/RELEASING.md", + "version_semver_justification": "Version metadata uses 0.4.0 and the release process requires vMAJOR.MINOR.PATCH tags and SemVer artifact versions. https://github.com/lennrt/tempestkeep/blob/main/internal/version/VERSION https://github.com/lennrt/tempestkeep/blob/main/RELEASING.md", "version_tags_status": "Unmet", "version_tags_justification": "There are no published stable releases or release tags yet. Future approved releases require immutable signed SemVer tags. https://github.com/lennrt/tempestkeep/tags https://github.com/lennrt/tempestkeep/blob/main/RELEASING.md", "release_notes_status": "Met", diff --git a/.env.example b/.env.example index 8fb80a3..1005fee 100644 --- a/.env.example +++ b/.env.example @@ -19,9 +19,11 @@ TEMPEST_TOKEN= # Keep the active archive on a local filesystem, outside cloud-sync folders. # TEMPEST_DB=/absolute/path/to/weather/tempest.sqlite -# Optional: device for CLI collection. A positive integer selects the device. +# Optional: device for CLI collection and the MCP server's default station. +# A positive integer selects an accessible Tempest (ST) device. # Unset or 0 discovers the first Tempest device available to the token. -# MCP and live CLI views discover their device and do not use this variable. +# MCP --device-id overrides this value; its explicit value must be positive. +# Live CLI views (now and explore) do not use this variable. # TEMPEST_DEVICE_ID= # Optional: earliest date for CLI backfill on a new archive, YYYY-MM-DD. diff --git a/CHANGELOG.md b/CHANGELOG.md index 17d7372..8e89160 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,79 @@ # Changelog +## 0.4.0 (proposed, unreleased) + +### Added + +- Explicit CLI archive repair with paired inclusive `collect --start` and + `--end` dates, bounded to 366 calendar days and safe to replay. +- Exact `before_epoch` continuation for MCP backfill, including batches that + stop inside a daylight-saving transition day. +- `rain_readings` and `lightning_readings` counts in observation-series buckets, + with missing-value displays and incomplete-coverage notices in MCP Apps. +- Pointer, touch, and keyboard inspection for every returned chart point, + including dense series above 60 readings. +- Optional `export --metadata` fields for device ID, report interval, wind + interval, precipitation type, and source. Defaults remain unchanged. +- Read-only streaming access to stored observation metadata through + `store.ArchiveObs` and `Store.EachArchiveObs`. +- MCP `--device-id` and `TEMPEST_DEVICE_ID` selection for collection and the + default live station, with lazy resolution and explicit station overrides. +- A searchable Devices table in the `list_stations` app, with parent stations, + exact identifiers, bounded traversal, and compatible refresh state. +- Observation and rain-reading counts in rain summaries, with missing/partial + coverage guidance in CLI reports, MCP results, and the rainfall app view. + +### Changed + +- Preserve table search, sorting, dataset selection, and valid page position + across compatible refreshes. New requests and changed table structures reset + controls. Focused search text and selection survive a pending refresh. +- Center both time and temperature by calendar month in the trend fit, so + uneven seasonal coverage does not dilute the within-month slope. +- Report zero slope for repeated constant monthly temperatures and omit the + undefined R². See [ADR 0009](docs/adr/0009-seasonal-trend-estimation.md). +- Bump active development, plugin, and embedded app metadata to 0.4.0. +- Choose the nearest eligible pressure sample on either side of the requested + window start. Sparse history can now use a pair spanning at least half the + window, and an older sample can no longer mask a closer reading after it. +- Reject unsupported CLI report and export dates before configuration or archive + access, with usage status 2 and unchanged local calendar boundaries. +- Return a null rain summary total when no rain readings exist. Preserve measured + zero and sum only reported values in partially observed ranges. +- Lead the docs overview with multi-station workflows and guides to interactive + charts, table refresh, archive repair, metadata exports, and offline analysis. + +### Compatibility + +Archive recovery adds a `before_epoch` input to `backfill_archive` and two +reading-count fields to `get_observations` points. Existing numeric totals +keep their types; a zero count means its total is unknown, and a count below +`obs` means partial coverage. Exported `SeriesPoint` gains the corresponding +fields. See [ADR 0008](docs/adr/0008-archive-recovery-and-coverage.md). + +Default CSV columns and JSON Lines fields remain unchanged. `--metadata` appends +five CSV columns and optional JSON fields. Metadata retains its stored units in +SI and US exports. Older schemas expose unavailable metadata as missing. The +store API additions do not change `model.Obs`. See +[ADR 0010](docs/adr/0010-export-metadata-and-development-version.md). + +MCP now honors `TEMPEST_DEVICE_ID`; empty or zero keeps automatic selection. +An invalid or inaccessible selection does not fall back to another live device. +Sparse pressure results can change because comparison samples now match the +documented nearest-reading rule. See +[ADR 0011](docs/adr/0011-mcp-device-selection-and-pressure-samples.md). + +`RainStats.TotalIn` changes from `float64` to `*float64`; Go callers must check +for nil. CLI rain JSON and MCP `rain_stats` now always encode `total_in` as a +number or `null`, with `observations` and `rain_readings` counts. Consumers must +accept null and the additional fields. Day counts, thresholds, spell rules, +and other rain aggregate types retain their contracts. Counts describe samples, +not continuous coverage. See [ADR 0012](docs/adr/0012-rain-summary-coverage.md). + +Existing archives need no migration. Version 0.4.0 remains a development target; +no tag, release, plugin publication, or merge is part of this change. +Qualification still follows [RELEASING.md](RELEASING.md). + ## 0.3.0 (proposed, unreleased) ### Added diff --git a/README.md b/README.md index 2db3cb1..6c96a71 100644 --- a/README.md +++ b/README.md @@ -36,7 +36,7 @@ credentials described below. | Explore | In the app | |---|---| -| Weather over time | Switch chart metrics, explore the wind rose, and inspect exact readings in the table. | +| Weather over time | Switch metrics, inspect chart points with pointer, touch, or keyboard, and explore the wind rose. | | Archive and SQL results | Search rows, sort columns, and move between table pages. | | Updated results | Refresh the same read-only tool with its original arguments. | | Your working environment | Use responsive views that follow the host's light or dark theme. | @@ -49,6 +49,8 @@ Search and pagination cover the returned rows. Views display up to 2,000 rows and 64 columns, with a notice when a limit applies. If a server limit truncates the result, narrow the tool request before drawing conclusions about the archive. Missing readings remain distinct from zero. The app does not run archive writes. +Observation-series views show when rain or lightning readings are missing or +partial. Available totals do not imply complete sensor coverage. MCP Apps support depends on the host and its version. Clients without the extension retain the existing text and structured tool results. See the @@ -147,7 +149,9 @@ For an existing archive without live access, omit `TEMPEST_TOKEN` and add environment or loaded from `.env`. The server reads `.env` from its working directory, which can differ from your terminal's directory. -If the token can access several devices, read the +If the token can access several devices, use `list_stations` or +`tempestkeep list-devices` to find the intended device. Set `TEMPEST_DEVICE_ID` +or add `--device-id` with that ID to the MCP arguments. See the [device selection rules](docs/mcp.md#capabilities) before collecting. The host launches `tempestkeep mcp` and exchanges JSON-RPC over stdin/stdout. @@ -203,6 +207,17 @@ the interactive setup wizard, then collect history and open the dashboard: ./bin/tempestkeep explore ``` +To fill a gap in an existing archive, collect an explicit range: + +```sh +./bin/tempestkeep collect --start 2025-06-01 --end 2025-06-03 +``` + +Both local dates are included. A range can cover at most 366 calendar days. +Repeating it is safe and leaves ordinary collection progress unchanged. +MCP clients can use `backfill_archive` and pass its exact `next_before` value +as `before_epoch` to continue a bounded request; repeat `start` and `max_days`. + For manual setup on Unix-like systems, copy `.env.example` to `.env` and run `chmod 600 .env` before entering the token. Commands read that file from their current working directory. Use the [CLI guide](cmd/tempestkeep/README.md) for @@ -239,9 +254,9 @@ cycles the month/year metric. The `g` or Home key returns to the latest period. The `q`, Esc, and Ctrl+C keys exit either dashboard. `tempestkeep version` reports the build's injected version, then Go's module -version when available. If neither exists, it falls back to `v0.3.0-dev`. +version when available. If neither exists, it falls back to `v0.4.0-dev`. `make build` injects a version from Git tags or that development fallback. -Version 0.3.0 is the proposed next minor release. See [CHANGELOG.md](CHANGELOG.md) +Version 0.4.0 is the proposed next minor release. See [CHANGELOG.md](CHANGELOG.md) for its scope. This change does not publish a release. ## Archive behavior @@ -382,7 +397,7 @@ Tempest names and marks belong to their respective owners. See [NOTICE.md](NOTIC TempestKeep uses the MIT License. See [LICENSE](LICENSE). -[version-badge]: https://img.shields.io/badge/development-v0.3.0--dev-blue +[version-badge]: https://img.shields.io/badge/development-v0.4.0--dev-blue [ci-b]: https://img.shields.io/github/actions/workflow/status/lennrt/tempestkeep/ci.yml?branch=main [ci]: https://github.com/lennrt/tempestkeep/actions/workflows/ci.yml [license-badge]: https://img.shields.io/github/license/lennrt/tempestkeep diff --git a/RELEASING.md b/RELEASING.md index 6f78a21..00c5378 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -29,7 +29,7 @@ Choose a semantic version. Do not reuse or move a published tag. Use `vMAJOR.MINOR.PATCH` for release tags and the corresponding SemVer version for artifacts. Development snapshots retain the exact source commit as their -unique identifier; `v0.3.0-dev` alone does not identify a source revision. +unique identifier; `v0.4.0-dev` alone does not identify a source revision. Update [CHANGELOG.md](CHANGELOG.md) with a human-readable account of changes, compatibility effects, and upgrade instructions. Include every publicly known diff --git a/cmd/tempestkeep/README.md b/cmd/tempestkeep/README.md index d9a1531..1b49245 100644 --- a/cmd/tempestkeep/README.md +++ b/cmd/tempestkeep/README.md @@ -71,7 +71,9 @@ bin/tempestkeep list-devices This output includes station and device identifiers. Keep it private. If your token can access several devices, select the intended Tempest device for -collection with `--device-id` or `TEMPEST_DEVICE_ID`. +CLI collection or MCP with `--device-id` or `TEMPEST_DEVICE_ID`. For MCP, this +also sets the default live station; explicit tool station arguments can override +individual reads. See the [MCP selection rules](../../docs/mcp.md#capabilities). ## Collection @@ -92,8 +94,28 @@ bin/tempestkeep collect --backfill-start 2025-01-01 ``` The date starts at midnight in the process timezone. The flag does not request -an older gap repair on an archive that already has a watermark. For that case, -use an explicit `backfill_archive` window through [MCP](../../docs/mcp.md#build-an-archive). +an older gap repair on an archive that already has a watermark. + +To repair a gap or collect a selected historical period, provide both dates: + +```sh +bin/tempestkeep collect --start 2025-06-01 --end 2025-06-30 +``` + +This mode requests only the selected local calendar days, including the entire +end date. If the end date is today, it requests observations only through the +current time. Both flags are required. A range may contain at most 366 calendar +days, including 23-hour or 25-hour days across daylight-saving changes. Dates +before the Unix epoch, future end dates, and reversed ranges are rejected +before API requests or archive creation. + +An explicit range can populate a new archive or revisit rows older than the +current watermark. Existing observations are preserved, and repeated runs do +not add duplicates. It leaves saved seed and MCP sync progress unchanged. +It ignores `TEMPEST_BACKFILL_START`; combining the range flags with an explicit +`--backfill-start` flag is an error. Missing upstream observations remain missing. +The [MCP backfill tool](../../docs/mcp.md#build-an-archive) also supports selected +historical windows, with an exclusive end date instead. Each API request covers at most five days. Each successful chunk commits before the next request. The `(device_id, epoch)` key prevents duplicate rows when a @@ -107,7 +129,9 @@ bin/tempestkeep collect --quiet SIGINT and SIGTERM cancel collection. An interrupted run exits with a failure status and preserves committed rows and resume metadata. Rerun the same command -to continue. +to continue. For an explicit range, repeat the same `--start` and `--end` +arguments. Earlier committed chunks are replayed safely before collection +reaches the unfinished part; this mode does not save a separate range cursor. After successful collection, the command checkpoints SQLite's write-ahead log (WAL), which holds recent database changes. It then closes the writer and makes @@ -167,10 +191,23 @@ Both dates are local calendar dates. The end date includes the entire day. Without a start date, the range starts at the beginning of the archive. Without an end date, the range ends at the current time. +Both `stats` and `export` reject unsupported dates before loading configuration +or opening an archive. Resolved UTC timestamps must fall between 1970-01-01 +00:00:00 and 9999-12-31 23:59:59. The inclusive bounds can differ by at most +36,600 days. Invalid ranges return usage status 2. Valid dates still use local +calendar boundaries, including 23-hour and 25-hour daylight-saving days. + The range applies to rain, wind, lightning, solar, pressure, comfort, and weather-spell sections. Coverage, records, and temperature trend always summarize the whole archive. This remains true in JSON output. +The rain section shows unavailable rainfall when no rain readings exist. A +measured zero remains `0.00 in`. Sample counts show how many stored observations +reported rain, and a partial-coverage warning identifies totals based on only +some readings. These counts do not prove continuous weather coverage. +In JSON, `rain.total_in` is a number or explicit `null`; `rain.observations` and +`rain.rain_readings` are always present. Missing rain does not hide other sections. + Reports use US display units for temperature, wind, pressure, and rain. The command reads the archive without contacting WeatherFlow. See the [query guide](../../docs/querying.md) before interpreting gaps or trends. @@ -208,6 +245,36 @@ corresponding key. A missing temperature is not 0°C. See the [query guide](../../docs/querying.md#units-and-aggregation) for interval totals and aggregation rules. +Add `--metadata` to include stored observation context: + +```sh +bin/tempestkeep export --format jsonl --metadata +``` + +The flag appends these CSV columns after the existing sensor columns. JSON Lines +adds the corresponding keys when their stored values are present: + +| Field | Meaning | +|---|---| +| `device_id` | Device identifier stored with the observation. | +| `report_interval_min` | Report interval in minutes. | +| `wind_interval_s` | Wind sampling interval in seconds. | +| `precip_type` | Stored precipitation code: 0 none, 1 rain, 2 hail, 3 rain and hail. | +| `source` | Stored observation source, such as `rest`. | + +These fields retain their stored values and units under `--units us`. Missing +values stay empty in CSV or absent in JSON; a known zero stays zero. If an older +archive lacks a metadata column, its values are missing. Source text is limited +to 1,024 UTF-8 bytes per row. Longer or invalid UTF-8 source values fail the +export rather than being silently changed. Omitting `--metadata` preserves the existing output. + +Use `solar_wm2 * report_interval_min * 60 / 1000000` for each row's solar-energy +estimate in MJ/m². Match the archive report by including only present solar +readings with report intervals greater than zero and no more than 1,440 minutes. +For example, 100 W/m² over one minute gives 0.006 MJ/m². Missing intervals cannot +be reconstructed from an assumed sampling rate. This estimate does not establish +continuous sensor coverage or replace a restorable archive backup. + Exports contain private weather observations. For a saved export on Unix-like systems, use a protected destination and an owner-only creation mask: diff --git a/cmd/tempestkeep/collect.go b/cmd/tempestkeep/collect.go index 4e760cb..3b0b3bb 100644 --- a/cmd/tempestkeep/collect.go +++ b/cmd/tempestkeep/collect.go @@ -38,10 +38,13 @@ func cmdCollect(args []string) error { describe(fs, "Build or refresh the local SQLite archive from the WeatherFlow REST API.\nAn interrupted seed resumes its saved cursor. Later runs sync newer observations.\nCtrl-C cancels the run.", "tempestkeep collect", "tempestkeep collect --backfill-start 2023-01-01", + "tempestkeep collect --start 2025-06-01 --end 2025-06-30 # repair an older gap", "tempestkeep collect --quiet # for cron; progress off, errors still print") db := fs.String("db", "", "archive path (or env TEMPEST_DB; default ./tempest.sqlite)") deviceID := fs.Int("device-id", 0, "Tempest device id (or env TEMPEST_DEVICE_ID; auto-discovered if unset)") backfillStart := fs.String("backfill-start", "", "earliest date to backfill on a fresh archive, YYYY-MM-DD (default: walk back until history ends)") + start := fs.String("start", "", "first local date to repair, YYYY-MM-DD (requires --end; at most 366 calendar days)") + end := fs.String("end", "", "last local date to repair, YYYY-MM-DD inclusive (requires --start; no future dates)") backupKeep := fs.Int("backup-keep", 7, "backup snapshots to keep in the backups directory beside the archive (0 disables, max 365)") noBackup := fs.Bool("no-backup", false, "skip the post-run backup snapshot") throttleMs := fs.Int("throttle-ms", 400, "pause between REST requests, milliseconds") @@ -50,15 +53,30 @@ func cmdCollect(args []string) error { if err := parseFlags(fs, args); err != nil { return err } + setFlags := map[string]bool{} + fs.Visit(func(f *flag.Flag) { setFlags[f.Name] = true }) + explicitRange := setFlags["start"] || setFlags["end"] + var rangeStart, rangeEnd int64 + if explicitRange { + if !setFlags["start"] || !setFlags["end"] { + return usagef("--start and --end must be supplied together") + } + if setFlags["backfill-start"] { + return usagef("--start and --end cannot be combined with --backfill-start") + } + var err error + rangeStart, rangeEnd, err = explicitCollectionRange(*start, *end, time.Now()) + if err != nil { + return err + } + } if err := config.LoadDotenv(ctx, ".env"); err != nil { return err } // Env fallbacks for the archive-shaping knobs, so a cron job can carry its // whole config in .env. An explicit flag wins; only an unset flag defers. - setFlags := map[string]bool{} - fs.Visit(func(f *flag.Flag) { setFlags[f.Name] = true }) - if *backfillStart == "" { + if !explicitRange && *backfillStart == "" { *backfillStart = os.Getenv("TEMPEST_BACKFILL_START") } if !setFlags["backup-keep"] { @@ -172,7 +190,18 @@ func cmdCollect(args []string) error { if err != nil { return errors.Join(err, w.Close()) } - res, collectErr := bf.Collect(ctx, time.Now().Unix(), startEpoch) + var res collect.Summary + var collectErr error + if explicitRange { + result, err := bf.BackfillRange(ctx, rangeStart, rangeEnd, 0) + res = collect.Summary{Mode: "range", Fetched: result.Fetched, RowsAdded: result.RowsAdded} + collectErr = err + if collectErr == nil && !result.Done { + collectErr = collect.ErrOperationLimit + } + } else { + res, collectErr = bf.Collect(ctx, time.Now().Unix(), startEpoch) + } // Restore the default interrupt behavior before cleanup and backup. stop() @@ -193,11 +222,15 @@ func cmdCollect(args []string) error { closeErr := w.Close() var operationErr error + retry := "re-run 'tempestkeep collect' to resume" + if explicitRange { + retry = "re-run with the same --start and --end arguments to finish the range; committed rows are replay-safe" + } switch { case errors.Is(collectErr, context.Canceled): - operationErr = errors.New("interrupted; progress is saved, re-run 'tempestkeep collect' to resume") + operationErr = fmt.Errorf("interrupted; progress is saved, %s", retry) case collectErr != nil: - operationErr = fmt.Errorf("collection stopped early (re-run to resume): %w", collectErr) + operationErr = fmt.Errorf("collection stopped early (%s): %w", retry, collectErr) } cleanupErr := errors.Join( wrapIfError("archive coverage check failed", coverageErr), @@ -218,6 +251,33 @@ func cmdCollect(args []string) error { return nil } +// explicitCollectionRange validates local calendar bounds before configuration, +// discovery, or archive creation. Calendar arithmetic preserves 23/25-hour days. +// Today's end is clipped to now so collection never requests future seconds. +func explicitCollectionRange(start, end string, now time.Time) (int64, int64, error) { + first, err := time.ParseInLocation(time.DateOnly, start, now.Location()) + if err != nil || len(start) != len(time.DateOnly) { + return 0, 0, usagef("--start must be YYYY-MM-DD") + } + last, err := time.ParseInLocation(time.DateOnly, end, now.Location()) + if err != nil || len(end) != len(time.DateOnly) { + return 0, 0, usagef("--end must be YYYY-MM-DD") + } + if first.Unix() < 0 || last.Unix() < 0 { + return 0, 0, usagef("--start and --end must not be before the Unix epoch") + } + if last.Before(first) { + return 0, 0, usagef("--start must not be after --end") + } + if last.After(now) { + return 0, 0, usagef("--end must not be a future date") + } + if !last.Before(first.AddDate(0, 0, 366)) { + return 0, 0, usagef("--start and --end may span at most 366 calendar days") + } + return max(first.Unix(), 1), min(last.AddDate(0, 0, 1).Unix()-1, now.Unix()), nil +} + func wrapIfError(message string, err error) error { if err == nil { return nil diff --git a/cmd/tempestkeep/collect_range_test.go b/cmd/tempestkeep/collect_range_test.go new file mode 100644 index 0000000..b19cd58 --- /dev/null +++ b/cmd/tempestkeep/collect_range_test.go @@ -0,0 +1,308 @@ +package main + +import ( + "bytes" + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "runtime" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/lennrt/tempestkeep/pkg/tempest/model" + "github.com/lennrt/tempestkeep/pkg/tempest/store" +) + +func TestExplicitCollectionRangeCalendarBounds(t *testing.T) { + loc, err := time.LoadLocation("America/Los_Angeles") + if err != nil { + t.Fatal(err) + } + now := time.Date(2025, time.December, 3, 12, 34, 56, 0, loc) + for _, tc := range []struct { + name, start, end string + wantHours int64 + wantError string + }{ + {name: "spring forward", start: "2025-03-09", end: "2025-03-09", wantHours: 23}, + {name: "fall back", start: "2025-11-02", end: "2025-11-02", wantHours: 25}, + {name: "366 days", start: "2024-11-03", end: "2025-11-03", wantHours: 366*24 + 1}, + {name: "367 days", start: "2024-11-03", end: "2025-11-04", wantError: "366 calendar days"}, + {name: "missing start", end: "2025-01-01", wantError: "--start"}, + {name: "missing end", start: "2025-01-01", wantError: "--end"}, + {name: "noncanonical", start: "2025-1-01", end: "2025-01-01", wantError: "--start"}, + {name: "reversed", start: "2025-01-02", end: "2025-01-01", wantError: "after --end"}, + {name: "unsupported", start: "1969-12-31", end: "1970-01-01", wantError: "Unix epoch"}, + {name: "future", start: "2025-12-03", end: "2025-12-04", wantError: "future"}, + } { + t.Run(tc.name, func(t *testing.T) { + start, end, err := explicitCollectionRange(tc.start, tc.end, now) + if tc.wantError != "" { + if !isUsageErr(err) || !strings.Contains(err.Error(), tc.wantError) { + t.Fatalf("error = %v, want usage error containing %q", err, tc.wantError) + } + return + } + if err != nil { + t.Fatal(err) + } + if end-start+1 != tc.wantHours*3600 { + t.Fatalf("range has %d seconds, want %d", end-start+1, tc.wantHours*3600) + } + if got := time.Unix(start, 0).In(loc).Format(time.DateTime); got != tc.start+" 00:00:00" { + t.Fatalf("start = %s", got) + } + if got := time.Unix(end, 0).In(loc).Format(time.DateTime); got != tc.end+" 23:59:59" { + t.Fatalf("end = %s", got) + } + }) + } + start, end, err := explicitCollectionRange("2025-12-03", "2025-12-03", now) + if err != nil || end != now.Unix() || start >= end { + t.Fatalf("today range = [%d,%d], error=%v; want end=%d", start, end, err, now.Unix()) + } +} + +func TestCollectRangeRejectsInvalidInputBeforeIO(t *testing.T) { + t.Chdir(t.TempDir()) + // Even a broken configuration file must not mask a range usage error. + if err := os.WriteFile(".env", []byte("not an assignment\n"), 0o600); err != nil { + t.Fatal(err) + } + var requests atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + requests.Add(1) + http.Error(w, "unexpected request", http.StatusBadRequest) + })) + t.Cleanup(srv.Close) + t.Setenv("TEMPEST_TOKEN", "synthetic-token") + t.Setenv("TEMPEST_API_BASE", srv.URL) + path := filepath.Join(t.TempDir(), "must-not-exist.sqlite") + for _, args := range [][]string{ + {"--start", "2025-01-01"}, + {"--end", "2025-01-01"}, + {"--start=", "--end=2025-01-01"}, + {"--start=2025-01-01", "--end="}, + {"--start=bad", "--end=2025-01-01"}, + {"--start=2025-01-02", "--end=2025-01-01"}, + {"--start=1960-01-01", "--end=1960-01-02"}, + {"--start=2024-01-01", "--end=2025-01-01"}, + {"--start=9999-01-01", "--end=9999-01-01"}, + {"--start=2025-01-01", "--end=2025-01-01", "--backfill-start=2020-01-01"}, + {"--start=2025-01-01", "--end=2025-01-01", "--backfill-start="}, + } { + if err := cmdCollect(append([]string{"--db", path}, args...)); !isUsageErr(err) { + t.Errorf("cmdCollect(%q) = %v, want usage error", args, err) + } + } + if requests.Load() != 0 { + t.Fatalf("invalid ranges made %d requests", requests.Load()) + } + if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("invalid range created archive: %v", err) + } +} + +type collectionWindow struct{ start, end int64 } + +func TestCollectRangeRepairsGapAndReplaysAfterFailure(t *testing.T) { + t.Chdir(t.TempDir()) + start, end, err := explicitCollectionRange("2025-01-01", "2025-01-06", time.Now()) + if err != nil { + t.Fatal(err) + } + path := filepath.Join(t.TempDir(), "archive.sqlite") + metadata := seedCollectionRangeArchive(t, path, start-1, end+1) + windows := make(chan collectionWindow, 10) + var fail atomic.Bool + fail.Store(true) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s, _ := strconv.ParseInt(r.URL.Query().Get("time_start"), 10, 64) + e, _ := strconv.ParseInt(r.URL.Query().Get("time_end"), 10, 64) + windows <- collectionWindow{s, e} + if fail.Load() && s > start { + http.Error(w, "synthetic failure", http.StatusBadRequest) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = fmt.Fprintf(w, `{"obs":[[%d],[%d]]}`, s, e) + })) + t.Cleanup(srv.Close) + configureCollectionRangeTest(t, srv.URL) + // An invalid seed floor must not affect explicit range collection. + t.Setenv("TEMPEST_BACKFILL_START", "invalid-and-irrelevant") + args := []string{"--db", path, "--device-id=456", "--start=2025-01-01", "--end=2025-01-06", "--quiet"} + if err := cmdCollect(args); err == nil || !strings.Contains(err.Error(), "same --start and --end") { + t.Fatalf("partial failure = %v, want range replay guidance", err) + } + assertCollectionRangeArchive(t, path, 4, metadata) + // Failed collection must not create a backup even if the caller normally enables it. + if _, err := os.Stat(filepath.Join(filepath.Dir(path), "backups")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("failed collection produced backup: %v", err) + } + fail.Store(false) + for range 2 { + if err := cmdCollect(append(args, "--no-backup")); err != nil { + t.Fatal(err) + } + assertCollectionRangeArchive(t, path, 6, metadata) + } + if err := cmdCollect(args); err != nil { + t.Fatal(err) + } + backups, err := filepath.Glob(filepath.Join(filepath.Dir(path), "backups", "*.sqlite")) + if err != nil || len(backups) != 1 { + t.Fatalf("completed range backups = %v, error=%v", backups, err) + } + assertCollectionRangeArchive(t, backups[0], 6, metadata) + wantWindows := []collectionWindow{{start, start + 5*86400 - 1}, {start + 5*86400, end}} + for i := range 8 { + select { + case got := <-windows: + if got != wantWindows[i%2] { + t.Fatalf("request %d = %+v, want %+v", i, got, wantWindows[i%2]) + } + default: + t.Fatalf("missing request %d", i) + } + } + if len(windows) != 0 { + t.Fatalf("unexpected requests beyond explicit range: %d", len(windows)) + } +} + +func configureCollectionRangeTest(t *testing.T, baseURL string) { + t.Helper() + t.Setenv("TEMPEST_TOKEN", "synthetic-token") + t.Setenv("TEMPEST_API_BASE", baseURL) + t.Setenv("TEMPEST_THROTTLE_MS", "0") + t.Setenv("TEMPEST_BACKUP_KEEP", "7") + t.Setenv("TEMPEST_CACHE_TTL", "0") +} + +func seedCollectionRangeArchive(t *testing.T, path string, before, after int64) map[string]string { + t.Helper() + w, err := store.OpenWriter(t.Context(), path) + if err != nil { + t.Fatal(err) + } + closeOnCleanup(t, w) + if _, err := w.InsertObs(t.Context(), 456, []model.DeviceObs{{Epoch: before}, {Epoch: after}}); err != nil { + t.Fatal(err) + } + metadata := map[string]string{ + "backfill_cursor": "12345", "backfill_complete": "0", + "mcp_sync_cursor": `{"watermark":12345,"next":23456}`, + "mcp_backfill_empty_span": `{"before":12345,"empty_seconds":86400}`, + } + for key, value := range metadata { + if err := w.SetMeta(t.Context(), key, value); err != nil { + t.Fatal(err) + } + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + return metadata +} + +func assertCollectionRangeArchive(t *testing.T, path string, wantRows int64, metadata map[string]string) { + t.Helper() + st, err := store.Open(t.Context(), path) + if err != nil { + t.Fatal(err) + } + defer func() { + if err := st.Close(); err != nil { + t.Error(err) + } + }() + cov, err := st.Coverage(t.Context()) + if err != nil || cov.Count != wantRows { + t.Fatalf("coverage = %+v, error=%v; want %d rows", cov, err, wantRows) + } + for key, want := range metadata { + got, ok, err := st.Meta(t.Context(), key) + if err != nil || !ok || got != want { + t.Errorf("metadata %s = %q, exists=%v, error=%v; want %q", key, got, ok, err, want) + } + } +} + +const collectRangeHelperEnv = "TEMPESTKEEP_TEST_COLLECT_RANGE_HELPER" + +func TestCollectRangeSubprocessHelper(t *testing.T) { + if os.Getenv(collectRangeHelperEnv) != "1" { + return + } + os.Args = []string{"tempestkeep", "collect", "--start=2025-01-01", "--end=2025-01-06", "--device-id=456", "--no-backup", "--quiet"} + main() + os.Exit(0) +} + +func TestCollectRangeCancellationKeepsCommittedRows(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("os.Interrupt cannot signal a subprocess on Windows") + } + ctx, cancel := context.WithTimeout(t.Context(), 20*time.Second) + defer cancel() + dir := t.TempDir() + path := filepath.Join(dir, "archive.sqlite") + start, end, err := explicitCollectionRange("2025-01-01", "2025-01-06", time.Now()) + if err != nil { + t.Fatal(err) + } + metadata := seedCollectionRangeArchive(t, path, start-1, end+1) + secondRequest := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + s, _ := strconv.ParseInt(r.URL.Query().Get("time_start"), 10, 64) + if s != start { + close(secondRequest) + <-r.Context().Done() + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = fmt.Fprintf(w, `{"obs":[[%d]]}`, s) + })) + t.Cleanup(srv.Close) + configureCollectionRangeTest(t, srv.URL) + t.Setenv("TEMPEST_DB", path) + t.Setenv("TEMPEST_BACKFILL_START", "") + t.Setenv(collectRangeHelperEnv, "1") + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestCollectRangeSubprocessHelper$") + cmd.Dir = dir + var stderr bytes.Buffer + cmd.Stderr = &stderr + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if cmd.ProcessState == nil { + _ = cmd.Process.Kill() + _ = cmd.Wait() + } + }) + select { + case <-secondRequest: + case <-ctx.Done(): + t.Fatal("collector did not reach its second request") + } + if err := cmd.Process.Signal(os.Interrupt); err != nil { + t.Fatal(err) + } + if err := cmd.Wait(); err == nil { + t.Fatal("interrupted collector reported success") + } + if got := stderr.String(); !strings.Contains(got, "interrupted") || !strings.Contains(got, "same --start and --end") { + t.Fatalf("cancellation diagnostic = %q", got) + } + assertCollectionRangeArchive(t, path, 3, metadata) +} diff --git a/cmd/tempestkeep/export.go b/cmd/tempestkeep/export.go index c4b7337..973cb6f 100644 --- a/cmd/tempestkeep/export.go +++ b/cmd/tempestkeep/export.go @@ -8,6 +8,7 @@ import ( "bufio" "context" "encoding/csv" + "encoding/json" "errors" "flag" "fmt" @@ -90,11 +91,13 @@ func cmdExport(args []string) (err error) { fs := flag.NewFlagSet("export", flag.ContinueOnError) describe(fs, "tempestkeep export: stream a date range of observations to stdout as CSV or\nJSON Lines, in SI or US units.", "tempestkeep export > archive.csv", + "tempestkeep export --metadata --format jsonl > archive-with-intervals.jsonl", "tempestkeep export --start 2024-06-01 --end 2024-06-30 --units us > june.csv", "tempestkeep export --format jsonl | jq .air_temp_c") db := fs.String("db", "", "path to the tempest.sqlite archive (or env TEMPEST_DB)") format := fs.String("format", "csv", "output format: csv or jsonl") units := fs.String("units", "si", "unit system: si (stored values) or us (display units)") + metadata := fs.Bool("metadata", false, "append stored device, report/wind intervals, precipitation type, and source metadata") start := fs.String("start", "", "start date YYYY-MM-DD in local time (default: whole archive)") end := fs.String("end", "", "end date YYYY-MM-DD in local time, inclusive (default: now)") if err := parseFlags(fs, args); err != nil { @@ -136,9 +139,9 @@ func cmdExport(args []string) (err error) { defer func() { err = errors.Join(err, out.Flush()) }() if *format == "csv" { - return exportCSV(ctx, st, out, startEpoch, endEpoch, us) + return exportCSV(ctx, st, out, startEpoch, endEpoch, us, *metadata) } - return exportJSONL(ctx, st, out, startEpoch, endEpoch, us) + return exportJSONL(ctx, st, out, startEpoch, endEpoch, us, *metadata) } // exportRange resolves optional local start/end dates to an inclusive epoch @@ -163,20 +166,31 @@ func exportRange(start, end string) (int64, int64, error) { if startEpoch > endEpoch { return 0, 0, fmt.Errorf("--start must not be after --end") } + if startEpoch < 0 || endEpoch < 0 || startEpoch > model.MaxEpochSeconds || endEpoch > model.MaxEpochSeconds { + return 0, 0, fmt.Errorf("--start and --end must resolve within supported observation timestamps") + } + if endEpoch-startEpoch > store.MaxRangeSeconds { + return 0, 0, fmt.Errorf("--start and --end must not span more than %d days", store.MaxRangeSeconds/(24*60*60)) + } return startEpoch, endEpoch, nil } -func exportCSV(ctx context.Context, st *store.Store, out *bufio.Writer, start, end int64, us bool) error { +func exportCSV(ctx context.Context, st *store.Store, out *bufio.Writer, start, end int64, us, metadata bool) error { w := csv.NewWriter(out) // Header: epoch + local time, then the sensor columns in field order. header := []string{"epoch", "time"} for _, f := range obsFields(model.Obs{}, us) { header = append(header, f.Name) } + if metadata { + for _, f := range archiveFields(store.ArchiveObs{}) { + header = append(header, f.name) + } + } if err := w.Write(header); err != nil { return err } - err := st.EachObs(ctx, start, end, func(o model.Obs) error { + err := eachExportObs(ctx, st, start, end, metadata, func(o model.Obs, archive *store.ArchiveObs) error { rec := make([]string, 0, len(header)) rec = append(rec, strconv.FormatInt(o.Epoch, 10), time.Unix(o.Epoch, 0).Local().Format(time.RFC3339)) @@ -187,6 +201,11 @@ func exportCSV(ctx context.Context, st *store.Store, out *bufio.Writer, start, e rec = append(rec, fmtNum(*f.Val, us)) } } + if archive != nil { + for _, f := range archiveFields(*archive) { + rec = append(rec, f.value) + } + } return w.Write(rec) }) if err != nil { @@ -196,8 +215,8 @@ func exportCSV(ctx context.Context, st *store.Store, out *bufio.Writer, start, e return w.Error() } -func exportJSONL(ctx context.Context, st *store.Store, out *bufio.Writer, start, end int64, us bool) error { - return st.EachObs(ctx, start, end, func(o model.Obs) error { +func exportJSONL(ctx context.Context, st *store.Store, out *bufio.Writer, start, end int64, us, metadata bool) error { + return eachExportObs(ctx, st, start, end, metadata, func(o model.Obs, archive *store.ArchiveObs) error { var b strings.Builder b.WriteByte('{') fmt.Fprintf(&b, `"epoch":%d,"time":%q`, o.Epoch, @@ -210,8 +229,60 @@ func exportJSONL(ctx context.Context, st *store.Store, out *bufio.Writer, start, b.WriteString(fmtNum(*f.Val, us)) } } + if archive != nil { + for _, f := range archiveFields(*archive) { + if !f.present { + continue + } + fmt.Fprintf(&b, ",%q:", f.name) + if f.name == "source" { + encoded, err := json.Marshal(f.value) + if err != nil { + return err + } + b.Write(encoded) + } else { + b.WriteString(f.value) + } + } + } b.WriteString("}\n") _, err := out.WriteString(b.String()) return err }) } + +// The default path retains its original reader and shape, including support for +// older archives. Only an explicit metadata request uses the richer iterator. +func eachExportObs(ctx context.Context, st *store.Store, start, end int64, metadata bool, fn func(model.Obs, *store.ArchiveObs) error) error { + if metadata { + return st.EachArchiveObs(ctx, start, end, func(o store.ArchiveObs) error { + return fn(o.Obs, &o) + }) + } + return st.EachObs(ctx, start, end, func(o model.Obs) error { return fn(o, nil) }) +} + +type archiveField struct { + name, value string + present bool +} + +func archiveFields(o store.ArchiveObs) []archiveField { + fields := []archiveField{ + {name: "device_id"}, {name: "report_interval_min"}, {name: "wind_interval_s"}, + {name: "precip_type"}, {name: "source"}, + } + if o.DeviceID != nil { + fields[0].value, fields[0].present = strconv.FormatInt(*o.DeviceID, 10), true + } + for i, value := range []*float64{o.ReportIntervalMin, o.WindIntervalSeconds, o.PrecipType} { + if value != nil { + fields[i+1].value, fields[i+1].present = fmtNum(*value, false), true + } + } + if o.Source != nil { + fields[4].value, fields[4].present = *o.Source, true + } + return fields +} diff --git a/cmd/tempestkeep/export_metadata_test.go b/cmd/tempestkeep/export_metadata_test.go new file mode 100644 index 0000000..796a02c --- /dev/null +++ b/cmd/tempestkeep/export_metadata_test.go @@ -0,0 +1,255 @@ +package main + +import ( + "bufio" + "context" + "database/sql" + "encoding/csv" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "os" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "github.com/lennrt/tempestkeep/pkg/tempest/model" + "github.com/lennrt/tempestkeep/pkg/tempest/store" +) + +func runExport(t *testing.T, args ...string) (string, error) { + t.Helper() + file, err := os.Create(filepath.Join(t.TempDir(), "export.txt")) + if err != nil { + t.Fatal(err) + } + defer func() { + if err := file.Close(); err != nil { + t.Error(err) + } + }() + previous := os.Stdout + os.Stdout = file + defer func() { os.Stdout = previous }() + exportErr := cmdExport(args) + if _, err := file.Seek(0, io.SeekStart); err != nil { + t.Fatal(err) + } + data, err := io.ReadAll(file) + if err != nil { + t.Fatal(err) + } + return string(data), exportErr +} + +func exportMetadataArchive(t *testing.T) (string, int64, string) { + t.Helper() + path := filepath.Join(t.TempDir(), "archive.sqlite") + base := time.Date(2025, time.June, 1, 12, 0, 0, 0, time.Local).Unix() + w, err := store.OpenWriter(t.Context(), path) + if err != nil { + t.Fatal(err) + } + if _, err := w.InsertObs(t.Context(), 456, []model.DeviceObs{ + {Epoch: base, SolarWm2: new(100.0), ReportIntervalMin: new(1.0), WindInterval: new(3.0), PrecipType: new(2.0)}, + {Epoch: base + 60, SolarWm2: new(200.0), ReportIntervalMin: new(0.0), WindInterval: new(0.0), PrecipType: new(0.0)}, + {Epoch: base + 120, SolarWm2: new(300.0)}, + {Epoch: base + 180, ReportIntervalMin: new(1.23456789), WindInterval: new(2.3456789)}, + }); err != nil { + t.Fatal(errors.Join(err, w.Close())) + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + db, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + source := "synthetic \"source\", with\nnewline\tand control \x00\x01 and snow 雪" + if _, err := db.ExecContext(t.Context(), "UPDATE obs_st SET source=? WHERE epoch=?", source, base+60); err != nil { + t.Fatal(errors.Join(err, db.Close())) + } + if _, err := db.ExecContext(t.Context(), "UPDATE obs_st SET source=NULL WHERE epoch=?", base+120); err != nil { + t.Fatal(errors.Join(err, db.Close())) + } + if err := db.Close(); err != nil { + t.Fatal(err) + } + return path, base, source +} + +func TestExportMetadataReproducesSolarEstimate(t *testing.T) { + t.Chdir(t.TempDir()) + path, base, source := exportMetadataArchive(t) + metadataKeys := []string{"device_id", "report_interval_min", "wind_interval_s", "precip_type", "source"} + for _, format := range []string{"csv", "jsonl"} { + for _, units := range []string{"si", "us"} { + t.Run(format+"/"+units, func(t *testing.T) { + args := []string{"--db", path, "--format", format, "--units", units, "--start", "2025-06-01", "--end", "2025-06-01"} + legacy, err := runExport(t, args...) + if err != nil { + t.Fatal(err) + } + output, err := runExport(t, append(args, "--metadata")...) + if err != nil { + t.Fatal(err) + } + var rows []map[string]string + if format == "csv" { + records, err := csv.NewReader(strings.NewReader(output)).ReadAll() + if err != nil { + t.Fatal(err) + } + original, err := csv.NewReader(strings.NewReader(legacy)).ReadAll() + if err != nil { + t.Fatal(err) + } + if len(records) != 5 || len(original) != len(records) || strings.Join(records[0][len(original[0]):], ",") != strings.Join(metadataKeys, ",") { + t.Fatalf("unexpected metadata CSV header or rows: %q", records) + } + for i, record := range records { + if strings.Join(record[:len(original[i])], "\x00") != strings.Join(original[i], "\x00") { + t.Fatalf("metadata changed original CSV fields in row %d", i) + } + if i == 0 { + continue + } + row := map[string]string{} + for col, key := range records[0] { + row[key] = record[col] + } + rows = append(rows, row) + } + } else { + original := strings.Split(strings.TrimSpace(legacy), "\n") + scanner := bufio.NewScanner(strings.NewReader(output)) + for scanner.Scan() { + var values map[string]json.RawMessage + if err := json.Unmarshal(scanner.Bytes(), &values); err != nil { + t.Fatal(err) + } + row := map[string]string{} + for key, raw := range values { + if key == "time" || key == "source" { + var value string + if err := json.Unmarshal(raw, &value); err != nil { + t.Fatal(err) + } + row[key] = value + } else { + row[key] = string(raw) + } + } + var originalFields map[string]json.RawMessage + if err := json.Unmarshal([]byte(original[len(rows)]), &originalFields); err != nil { + t.Fatal(err) + } + for key, want := range originalFields { + if string(values[key]) != string(want) { + t.Fatalf("metadata changed original JSON field %s", key) + } + } + rows = append(rows, row) + } + if err := scanner.Err(); err != nil { + t.Fatal(err) + } + } + if len(rows) != 4 { + t.Fatalf("got %d rows, want 4", len(rows)) + } + var energy float64 + for i, row := range rows { + if row["epoch"] != strconv.FormatInt(base+int64(i)*60, 10) || row["device_id"] != "456" { + t.Fatalf("row identity/order lost: %v", row) + } + interval, _ := strconv.ParseFloat(row["report_interval_min"], 64) + solar, _ := strconv.ParseFloat(row["solar_wm2"], 64) + if interval > 0 { + energy += solar * interval * 60 / 1e6 + } + } + if math.Abs(energy-.006) > 1e-12 { + t.Fatalf("export-derived solar energy = %g, want 0.006 MJ/m²", energy) + } + if rows[0]["report_interval_min"] != "1" || rows[0]["wind_interval_s"] != "3" || rows[0]["precip_type"] != "2" || rows[0]["source"] != "rest" { + t.Fatalf("stored metadata was lost: %v", rows[0]) + } + if rows[1]["report_interval_min"] != "0" || rows[1]["wind_interval_s"] != "0" || rows[1]["precip_type"] != "0" || rows[1]["source"] != source { + t.Fatalf("zero metadata or source escaping lost: %v", rows[1]) + } + for _, key := range metadataKeys[1:] { + value, present := rows[2][key] + if value != "" || format == "jsonl" && present { + t.Errorf("missing %s became %q (present=%v)", key, value, present) + } + } + if rows[3]["report_interval_min"] != "1.23456789" || rows[3]["wind_interval_s"] != "2.3456789" { + t.Fatalf("metadata precision changed under %s: %v", units, rows[3]) + } + }) + } + } +} + +func TestDefaultExportShapeRemainsStable(t *testing.T) { + t.Chdir(t.TempDir()) + path, base, _ := exportMetadataArchive(t) + for _, format := range []string{"csv", "jsonl"} { + output, err := runExport(t, "--db", path, "--format", format) + if err != nil { + t.Fatal(err) + } + if format == "csv" { + want := "epoch,time,wind_lull_mps,wind_avg_mps,wind_gust_mps,wind_dir_deg,pressure_mb,air_temp_c,humidity_pct,illuminance_lux,uv,solar_wm2,rain_mm,strike_dist_km,strike_count,battery_v\n" + if !strings.HasPrefix(output, want) { + t.Fatalf("default CSV header changed: %s", output) + } + } else { + want := fmt.Sprintf("{\"epoch\":%d,\"time\":%q,\"solar_wm2\":100}\n", base, time.Unix(base, 0).Local().Format(time.RFC3339)) + if !strings.HasPrefix(output, want) { + t.Fatalf("default JSON output changed: %s", output) + } + } + for _, key := range []string{"device_id", "report_interval_min", "wind_interval_s", "precip_type", "source"} { + if strings.Contains(output, key) { + t.Errorf("default %s unexpectedly contains %s", format, key) + } + } + } +} + +func TestExportMetadataOutputFailureAndCancellation(t *testing.T) { + path, base, _ := exportMetadataArchive(t) + s, err := store.Open(t.Context(), path) + if err != nil { + t.Fatal(err) + } + closeOnCleanup(t, s) + for _, write := range []struct { + name string + fn func(context.Context, *store.Store, *bufio.Writer, int64, int64, bool, bool) error + }{{"csv", exportCSV}, {"jsonl", exportJSONL}} { + t.Run(write.name, func(t *testing.T) { + out := bufio.NewWriterSize(failedOutput{}, 1) + if err := write.fn(t.Context(), s, out, base, base+180, false, true); !errors.Is(err, io.ErrClosedPipe) { + t.Fatalf("output failure = %v, want closed pipe", err) + } + ctx, cancel := context.WithCancel(t.Context()) + cancel() + out = bufio.NewWriter(io.Discard) + if err := write.fn(ctx, s, out, base, base+180, false, true); !errors.Is(err, context.Canceled) { + t.Fatalf("canceled export = %v", err) + } + checkCtx, stop := context.WithTimeout(t.Context(), time.Second) + defer stop() + if _, err := s.Coverage(checkCtx); err != nil { + t.Fatalf("output failure/cancellation leaked rows: %v", err) + } + }) + } +} diff --git a/cmd/tempestkeep/mcp.go b/cmd/tempestkeep/mcp.go index 4576a0c..5a65df1 100644 --- a/cmd/tempestkeep/mcp.go +++ b/cmd/tempestkeep/mcp.go @@ -4,6 +4,7 @@ import ( "flag" "fmt" "os" + "strconv" "github.com/lennrt/tempestkeep/internal/mcpapp" "github.com/lennrt/tempestkeep/internal/version" @@ -21,11 +22,17 @@ func cmdMCP(args []string) error { "tempestkeep mcp --db ./tempest.sqlite", "tempestkeep mcp --read-only") dbFlag := fs.String("db", "", "path to the tempest.sqlite archive (or env TEMPEST_DB)") + deviceFlag := fs.Int("device-id", 0, "default Tempest device id (or env TEMPEST_DEVICE_ID; auto-discovered if unset)") readOnlyFlag := fs.Bool("read-only", false, "remove archive write tools (or env TEMPEST_READ_ONLY)") versionFlag := fs.Bool("version", false, "print the version and exit") if err := parseFlags(fs, args); err != nil { return err } + deviceSet := false + fs.Visit(func(f *flag.Flag) { deviceSet = deviceSet || f.Name == "device-id" }) + if deviceSet && *deviceFlag <= 0 { + return usagef("--device-id must be positive") + } if *versionFlag { _, err := fmt.Printf("tempestkeep mcp %s\n", version.String()) return err @@ -36,6 +43,10 @@ func cmdMCP(args []string) error { if err := config.LoadDotenv(ctx, ".env"); err != nil { return err } + deviceID, err := resolveMCPDeviceID(*deviceFlag) + if err != nil { + return err + } dbPath, err := config.ResolveDB(ctx, *dbFlag) if err != nil { return err @@ -53,10 +64,28 @@ func cmdMCP(args []string) error { return mcpapp.Run(ctx, mcpapp.Options{ Client: client, DBPath: dbPath, + DeviceID: deviceID, ReadOnly: *readOnlyFlag || envReadOnly, }) } +// resolveMCPDeviceID receives either a validated positive flag or zero when the +// flag was absent. An explicit flag must not parse an overridden environment. +func resolveMCPDeviceID(flagValue int) (int, error) { + if flagValue > 0 { + return flagValue, nil + } + value := os.Getenv("TEMPEST_DEVICE_ID") + if value == "" { + return 0, nil + } + id, err := strconv.Atoi(value) + if err != nil || id < 0 { + return 0, fmt.Errorf("TEMPEST_DEVICE_ID must be zero for discovery or a positive integer") + } + return id, nil +} + // readOnlyEnv parses TEMPEST_READ_ONLY. Unknown values are an error so a // misspelling cannot enable writes. func readOnlyEnv() (bool, error) { diff --git a/cmd/tempestkeep/mcp_device_test.go b/cmd/tempestkeep/mcp_device_test.go new file mode 100644 index 0000000..5039816 --- /dev/null +++ b/cmd/tempestkeep/mcp_device_test.go @@ -0,0 +1,155 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/lennrt/tempestkeep/internal/mcpapp" + "github.com/lennrt/tempestkeep/pkg/tempest/api" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +func TestMCPInvalidDeviceFlagsFailBeforeConfiguration(t *testing.T) { + t.Chdir(t.TempDir()) + // A directory cannot be loaded as dotenv. Invalid flags must still report + // usage errors rather than this configuration failure. + if err := os.Mkdir(".env", 0o700); err != nil { + t.Fatal(err) + } + t.Setenv("TEMPEST_DEVICE_ID", "777") + path := filepath.Join(t.TempDir(), "must-not-exist.sqlite") + for _, value := range []string{"0", "-1", "", "invalid", "9999999999999999999999999"} { + t.Run(value, func(t *testing.T) { + var stdout, stderr bytes.Buffer + if status := run([]string{"mcp", "--db", path, "--device-id=" + value}, &stdout, &stderr); status != exitUsage { + t.Fatalf("invalid flag status=%d stderr=%s", status, stderr.String()) + } + if strings.Contains(stderr.String(), "dotenv") || stdout.Len() != 0 { + t.Fatalf("invalid flag read configuration: stdout=%q stderr=%q", stdout.String(), stderr.String()) + } + }) + } + if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("invalid flag initialized archive: %v", err) + } +} + +func TestMCPInvalidDeviceEnvironmentFailsBeforeArchiveAndAPIConfiguration(t *testing.T) { + t.Chdir(t.TempDir()) + t.Setenv("TEMPEST_TOKEN", "synthetic-token") + t.Setenv("TEMPEST_API_BASE", "invalid-api-endpoint") + path := filepath.Join(t.TempDir(), "must-not-exist.sqlite") + for _, value := range []string{"-1", "invalid", "9999999999999999999999999"} { + t.Setenv("TEMPEST_DEVICE_ID", value) + err := cmdMCP([]string{"--db", path}) + if err == nil || !strings.Contains(err.Error(), "TEMPEST_DEVICE_ID") { + t.Fatalf("invalid device environment = %v", err) + } + } + if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("invalid environment initialized archive: %v", err) + } +} + +const deviceCommandHelper = "TEMPESTKEEP_DEVICE_COMMAND_HELPER" +const deviceCommandFlag = "TEMPESTKEEP_DEVICE_COMMAND_FLAG" + +func TestMCPDeviceCommandHelper(t *testing.T) { + if os.Getenv(deviceCommandHelper) != "1" { + return + } + os.Args = []string{"tempestkeep", "mcp"} + if value := os.Getenv(deviceCommandFlag); value != "" { + os.Args = append(os.Args, "--device-id="+value) + } + main() +} + +func TestE2EMCPDeviceConfigurationPrecedence(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Path != "/stations" { + http.NotFound(w, r) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"stations": []api.Station{ + {StationID: 123, Name: "First station", Devices: []api.Device{{DeviceID: 456, DeviceType: "ST"}}}, + {StationID: 789, Name: "Selected station", Devices: []api.Device{{DeviceID: 777, DeviceType: "ST"}}}, + }}) + })) + t.Cleanup(server.Close) + for _, tc := range []struct { + name, flag, env, dotenv string + want int + }{ + {name: "discovery", want: 123}, + {name: "zero environment", env: "0", want: 123}, + {name: "environment selection", env: "777", want: 789}, + {name: "flag overrides environment", flag: "456", env: "777", want: 123}, + {name: "flag overrides malformed environment", flag: "777", env: "invalid", want: 789}, + {name: "dotenv selection", dotenv: "777", want: 789}, + {name: "environment overrides dotenv", env: "456", dotenv: "777", want: 123}, + {name: "zero environment overrides dotenv", env: "0", dotenv: "777", want: 123}, + {name: "flag overrides dotenv", flag: "777", dotenv: "invalid", want: 789}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestMCPDeviceCommandHelper$") + cmd.Dir = t.TempDir() + if tc.dotenv != "" { + if err := os.WriteFile(filepath.Join(cmd.Dir, ".env"), []byte("TEMPEST_DEVICE_ID="+tc.dotenv+"\n"), 0o600); err != nil { + t.Fatal(err) + } + } + for _, entry := range os.Environ() { + key, _, _ := strings.Cut(entry, "=") + if strings.HasPrefix(key, "TEMPEST_") || key == deviceCommandHelper || key == deviceCommandFlag { + continue + } + cmd.Env = append(cmd.Env, entry) + } + cmd.Env = append(cmd.Env, deviceCommandHelper+"=1", deviceCommandFlag+"="+tc.flag, + "TEMPEST_TOKEN=synthetic-command-token", "TEMPEST_API_BASE="+server.URL, "TEMPEST_CACHE_TTL=0") + if tc.env != "" { + cmd.Env = append(cmd.Env, "TEMPEST_DEVICE_ID="+tc.env) + } + var stderr bytes.Buffer + cmd.Stderr = &stderr + cs, err := mcp.NewClient(&mcp.Implementation{Name: "selection-command", Version: "test"}, nil).Connect(ctx, &mcp.CommandTransport{Command: cmd, TerminateDuration: 2 * time.Second}, nil) + if err != nil { + t.Fatalf("connect selection command: %v; stderr=%s", err, &stderr) + } + defer func() { + if err := cs.Close(); err != nil { + t.Errorf("close selection command: %v", err) + } + }() + result, err := cs.CallTool(ctx, &mcp.CallToolParams{Name: "station_details"}) + if err != nil || result.IsError { + t.Fatalf("selected station call: error=%v result=%+v", err, result) + } + data, err := json.Marshal(result.StructuredContent) + if err != nil { + t.Fatal(err) + } + var details mcpapp.StationDetailsOut + if err := json.Unmarshal(data, &details); err != nil { + t.Fatal(err) + } + if details.StationID != tc.want { + t.Fatalf("configuration selected station %d, want %d", details.StationID, tc.want) + } + }) + } +} diff --git a/cmd/tempestkeep/rain_coverage_test.go b/cmd/tempestkeep/rain_coverage_test.go new file mode 100644 index 0000000..5692d50 --- /dev/null +++ b/cmd/tempestkeep/rain_coverage_test.go @@ -0,0 +1,127 @@ +package main + +import ( + "encoding/json" + "errors" + "io" + "math" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/lennrt/tempestkeep/pkg/tempest/model" + "github.com/lennrt/tempestkeep/pkg/tempest/store" +) + +func runStats(t *testing.T, args ...string) (string, error) { + t.Helper() + file, err := os.Create(filepath.Join(t.TempDir(), "report.txt")) + if err != nil { + t.Fatal(err) + } + defer func() { + if err := file.Close(); err != nil { + t.Error(err) + } + }() + previous := os.Stdout + os.Stdout = file + defer func() { os.Stdout = previous }() + commandErr := cmdStats(args) + if _, err := file.Seek(0, io.SeekStart); err != nil { + t.Fatal(err) + } + data, err := io.ReadAll(file) + if err != nil { + t.Fatal(err) + } + return string(data), commandErr +} + +func TestE2EStatsRainCoverage(t *testing.T) { + t.Chdir(t.TempDir()) + for _, tc := range []struct { + name string + rain []*float64 + readings int + total *float64 + }{ + {"empty range", nil, 0, nil}, + {"missing", []*float64{nil, nil}, 0, nil}, + {"measured zero", []*float64{new(0.0), new(0.0)}, 2, new(0.0)}, + {"partial zero", []*float64{new(0.0), nil}, 1, new(0.0)}, + {"partial positive", []*float64{new(25.4), nil}, 1, new(1.0)}, + {"reported positive", []*float64{new(25.4), new(12.7)}, 2, new(1.5)}, + } { + t.Run(tc.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "archive.sqlite") + base := time.Date(2025, time.June, 1, 12, 0, 0, 0, time.Local) + rows := []model.DeviceObs{ + {Epoch: base.AddDate(0, 0, -1).Unix(), RainMm: new(100.0)}, + {Epoch: base.AddDate(0, 0, 1).Unix(), RainMm: new(100.0)}, + } + for i, rain := range tc.rain { + rows = append(rows, model.DeviceObs{Epoch: base.Unix() + int64(i*60), RainMm: rain, WindAvg: new(2.0)}) + } + writer, err := store.OpenWriter(t.Context(), path) + if err != nil { + t.Fatal(err) + } + _, insertErr := writer.InsertObs(t.Context(), 456, rows) + if err := errors.Join(insertErr, writer.Close()); err != nil { + t.Fatal(err) + } + args := []string{"--db", path, "--start", "2025-06-01", "--end", "2025-06-01"} + output, err := runStats(t, append(args, "--format", "json")...) + if err != nil { + t.Fatal(err) + } + var result struct { + Rain map[string]any `json:"rain"` + } + if err := json.Unmarshal([]byte(output), &result); err != nil { + t.Fatal(err) + } + value, exists := result.Rain["total_in"] + if !exists || (tc.total == nil && value != nil) { + t.Fatalf("missing rain must encode explicit null: %s", output) + } + if tc.total != nil { + got, numeric := value.(float64) + if !numeric || math.Abs(got-*tc.total) > 1e-9 { + t.Fatalf("measured total=%v, want%v", value, *tc.total) + } + } + if result.Rain["observations"] != float64(len(tc.rain)) || result.Rain["rain_readings"] != float64(tc.readings) { + t.Fatalf("rain coverage counts lost or included outside rows: %+v", result.Rain) + } + output, err = runStats(t, args...) + if err != nil { + t.Fatal(err) + } + switch { + case len(tc.rain) == 0: + if !strings.Contains(output, "No observations in the selected date range") { + t.Fatalf("empty range: %s", output) + } + case tc.readings == 0: + if !strings.Contains(output, "No rain readings") || strings.Contains(output, "Total: 0.00") || !strings.Contains(output, "\nWind\n") { + t.Fatalf("missing rain shown as zero or hid other weather: %s", output) + } + default: + if tc.total != nil && *tc.total == 0 && !strings.Contains(output, "Total: 0.00 in") { + t.Fatalf("measured zero lost: %s", output) + } + partial := tc.readings < len(tc.rain) + if strings.Contains(output, "Partial rain coverage") != partial { + t.Fatalf("partial warning mismatch: %s", output) + } + if !strings.Contains(output, "Rain readings:") { + t.Fatalf("missing sample coverage: %s", output) + } + } + }) + } +} diff --git a/cmd/tempestkeep/report_range_test.go b/cmd/tempestkeep/report_range_test.go new file mode 100644 index 0000000..d19a6cc --- /dev/null +++ b/cmd/tempestkeep/report_range_test.go @@ -0,0 +1,95 @@ +package main + +import ( + "bytes" + "errors" + "io" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/lennrt/tempestkeep/pkg/tempest/model" + "github.com/lennrt/tempestkeep/pkg/tempest/store" +) + +func TestReportRangesRejectUnsupportedBoundsBeforeIO(t *testing.T) { + previous := time.Local + time.Local = time.UTC + t.Cleanup(func() { time.Local = previous }) + t.Chdir(t.TempDir()) + // If a command reads configuration first, this malformed file masks the + // range error. Neither report needs to inspect configuration for bad dates. + if err := os.WriteFile(".env", []byte("not a dotenv assignment\n"), 0o600); err != nil { + t.Fatal(err) + } + path := filepath.Join(t.TempDir(), "missing", "archive.sqlite") + for _, command := range []string{"stats", "export"} { + for _, dates := range [][2]string{{"1900-01-01", "1900-01-02"}, {"0001-01-01", "9999-12-31"}, {"1970-01-01", "2100-01-01"}} { + t.Run(command+"/"+dates[0]+"/"+dates[1], func(t *testing.T) { + var stderr bytes.Buffer + code := run([]string{command, "--db", path, "--start", dates[0], "--end", dates[1]}, io.Discard, &stderr) + if code != exitUsage || !strings.Contains(stderr.String(), "--start") || strings.Contains(stderr.String(), "dotenv") { + t.Fatalf("invalid range: status=%d, diagnostic=%q", code, stderr.String()) + } + if _, err := os.Stat(filepath.Dir(path)); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("range validation touched archive parent: %v", err) + } + }) + } + } +} + +func TestReportRangeSupportedBoundaries(t *testing.T) { + previous := time.Local + time.Local = time.UTC + t.Cleanup(func() { time.Local = previous }) + start, end, err := exportRange("1970-01-01", "1970-01-01") + if err != nil || start != 0 || end != 86399 { + t.Fatalf("first supported day = %d..%d, %v", start, end, err) + } + start, end, err = exportRange("9999-12-31", "9999-12-31") + if err != nil || end != model.MaxEpochSeconds || end-start != 86399 { + t.Fatalf("last supported day = %d..%d, %v", start, end, err) + } + // The limit is elapsed seconds, not a count of calendar years. Test the + // largest inclusive whole-day range and one additional day. + lastDay := time.Unix(store.MaxRangeSeconds-1, 0).UTC().Format("2006-01-02") + _, end, err = exportRange("1970-01-01", lastDay) + if err != nil || end != store.MaxRangeSeconds-1 { + t.Fatalf("last full day in span limit = %d, %v", end, err) + } + tooLate := time.Unix(store.MaxRangeSeconds, 0).UTC().Format("2006-01-02") + if _, _, err := exportRange("1970-01-01", tooLate); err == nil { + t.Fatal("inclusive end day beyond span limit accepted") + } + // Local calendar dates can fall outside supported UTC epochs. + time.Local = time.FixedZone("synthetic-east", 3600) + if _, _, err := exportRange("1970-01-01", "1970-01-01"); err == nil { + t.Fatal("local start before epoch accepted") + } + time.Local = time.FixedZone("synthetic-west", -3600) + if _, _, err := exportRange("9999-12-31", "9999-12-31"); err == nil { + t.Fatal("local end beyond supported epoch accepted") + } +} + +func TestReportRangePreservesDSTCalendarDays(t *testing.T) { + zone, err := time.LoadLocation("America/Los_Angeles") + if err != nil { + t.Fatal(err) + } + previous := time.Local + time.Local = zone + t.Cleanup(func() { time.Local = previous }) + for _, tc := range []struct { + date string + hours int64 + }{{"2024-03-10", 23}, {"2024-11-03", 25}} { + start, end, err := exportRange(tc.date, tc.date) + if err != nil || end-start+1 != tc.hours*3600 { + t.Errorf("%s range = %d..%d, %v; want %d hours", tc.date, start, end, err, tc.hours) + } + } +} diff --git a/cmd/tempestkeep/stats.go b/cmd/tempestkeep/stats.go index 4cfe76f..8abfce1 100644 --- a/cmd/tempestkeep/stats.go +++ b/cmd/tempestkeep/stats.go @@ -210,6 +210,8 @@ func writeStats(w io.Writer, r statsReport) error { dir := "warming" if *r.trend.SlopePerDecadeF < 0 { dir = "cooling" + } else if *r.trend.SlopePerDecadeF == 0 { + dir = "flat" } r2 := "" if r.trend.RSquared != nil { @@ -228,9 +230,17 @@ func writeStats(w io.Writer, r statsReport) error { } out.println("\nRain") - out.printf(" Total: %.2f in over %d days, %d rainy\n", r.rain.TotalIn, r.rain.DaysObserved, r.rain.RainyDays) - if r.rain.LongestDrySpellDays > 0 { - out.printf(" Longest dry spell: %d days (%s to %s)\n", r.rain.LongestDrySpellDays, r.rain.DrySpellStart, r.rain.DrySpellEnd) + if r.rain.TotalIn == nil { + out.println(" No rain readings in the selected date range; rainfall is unavailable.") + } else { + out.printf(" Total: %.2f in over %d observed days, %d observed rainy\n", *r.rain.TotalIn, r.rain.DaysObserved, r.rain.RainyDays) + if r.rain.LongestDrySpellDays > 0 { + out.printf(" Longest observed dry spell: %d days (%s to %s)\n", r.rain.LongestDrySpellDays, r.rain.DrySpellStart, r.rain.DrySpellEnd) + } + } + out.printf(" Rain readings: %d of %d stored observations; counts describe samples, not continuous coverage.\n", r.rain.RainReadings, r.rain.Observations) + if r.rain.RainReadings > 0 && r.rain.RainReadings < r.rain.Observations { + out.println(" Partial rain coverage: total and spells use reported readings only; missing rain is not treated as zero.") } out.println("\nWind") diff --git a/cmd/tempestkeep/stats_test.go b/cmd/tempestkeep/stats_test.go index 39949f4..2219ed6 100644 --- a/cmd/tempestkeep/stats_test.go +++ b/cmd/tempestkeep/stats_test.go @@ -25,7 +25,7 @@ func TestWriteStatsRendersSections(t *testing.T) { cov: store.Coverage{Count: 1000, MinEpoch: sql.NullInt64{Int64: 1700000000, Valid: true}, MaxEpoch: sql.NullInt64{Int64: 1700600000, Valid: true}}, rec: store.Records{HottestF: f(99.5), ColdestF: f(20.1), PeakGustMph: f(41.2)}, trend: store.TempTrend{Years: 3, SlopePerDecadeF: f(2.5), RSquared: f(0.8)}, - rain: store.RainStats{TotalIn: 12.3, DaysObserved: 90, RainyDays: 14, LongestDrySpellDays: 8, DrySpellStart: "2024-07-01", DrySpellEnd: "2024-07-08"}, + rain: store.RainStats{TotalIn: f(12.3), Observations: 1000, RainReadings: 1000, DaysObserved: 90, RainyDays: 14, LongestDrySpellDays: 8, DrySpellStart: "2024-07-01", DrySpellEnd: "2024-07-08"}, wind: store.WindStats{Obs: 1000, AvgWindMph: f(4.1), PeakGustMph: f(41.2), PeakGustDay: "2024-05-27", CalmPct: 33}, light: store.LightningStats{TotalStrikes: 42, StormDays: 3, ClosestStrikeMi: f(1.9), ClosestStrikeDay: "2024-08-04"}, solar: store.SolarStats{PeakSolarWm2: f(1100), PeakUV: f(9), SunniestDayMJ: f(28.5), SunniestDay: "2024-06-21"}, @@ -44,8 +44,8 @@ func TestWriteStatsRendersSections(t *testing.T) { "99.5°F", // hottest "+2.5 °F/decade (warming", "R²=0.80", - "12.30 in over 90 days", - "Longest dry spell: 8 days", + "12.30 in over 90 observed days", + "Longest observed dry spell: 8 days", "calm 33%", "42 strikes over 3 storm days", "closest 1.9 mi", @@ -113,3 +113,18 @@ func TestWriteStatsCoolingTrend(t *testing.T) { t.Errorf("expected the no-lightning line; got:\n%s", out) } } + +func TestWriteStatsFlatTrend(t *testing.T) { + rep := statsReport{ + cov: store.Coverage{Count: 2, MinEpoch: sql.NullInt64{Int64: 1700000000, Valid: true}, + MaxEpoch: sql.NullInt64{Int64: 1731622400, Valid: true}}, + trend: store.TempTrend{Years: 2, SlopePerDecadeF: new(0.0)}, + } + var out strings.Builder + if err := writeStats(&out, rep); err != nil { + t.Fatal(err) + } + if !strings.Contains(out.String(), "+0.0 °F/decade (flat)") || strings.Contains(out.String(), "warming") || strings.Contains(out.String(), "R²=") { + t.Fatalf("flat trend was mislabeled: %s", out.String()) + } +} diff --git a/docs/README.md b/docs/README.md index 67f7a9c..5d0c902 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,9 +1,82 @@ # Documentation -Start with the [repository README](../README.md). It covers requirements, -building, setup, collection, MCP operation, privacy, and verification. +TempestKeep brings live weather, forecasts, and your local observation history +into an MCP client or terminal. Start with the +[setup and connection guide](../README.md#connect-your-agent), +then choose a workflow below. One Go executable includes the MCP server, +interactive app, terminal dashboards, reports, and exports. -## Use TempestKeep +## Work with several stations + +If your token can access multiple stations, choose which Tempest device supplies +your archive and default live station: + +1. Run `tempestkeep list-devices` or ask your agent to call `list_stations`. + In a supporting MCP Apps host, open the **Devices** table and search by ID, + serial number, or station name. Each device keeps its parent station beside it. +2. Set `TEMPEST_DEVICE_ID` or start MCP with `--device-id` to select that device. + The flag overrides the environment. Without a selection, TempestKeep chooses + the first accessible Tempest device. +3. Keep **one device per archive**. Give each device its own archive path when + collecting from several stations; TempestKeep rejects writes for another device. + +The selected device controls collection and the default station for live reads. +Conditions and forecasts remain station-level results. Pass `station_id` to +`forecast` or `station_details` to read another station without changing that +default or the archive. See [device selection and capabilities](mcp.md#capabilities), +[MCP configuration](mcp.md#build-and-connect), and the +[searchable device view](mcp-apps.md#read-charts-and-tables). + +## Explore weather in your conversation + +In a host that supports MCP Apps, ask for a forecast, daily summary, wind rose, +or archive query, then open its interactive view. + +| Try this | What you can do | +|---|---| +| Inspect a dense weather chart | Point, tap, or use the keyboard slider to inspect every displayed reading, up to 2,000 points, with its time and units. | +| Find a particular day or device | Search returned rows, sort columns, and move through table pages. | +| Refresh while exploring | Keep the selected table, search, sort, and valid page when the refreshed columns remain compatible. | +| Check incomplete observations | Inspect rain or lightning coverage in observation series, and distinguish missing rain, measured zero, and partial totals in rainfall summaries. | + +Refresh repeats a read-only tool; it does not collect new archive history. +Search covers received rows, and display limits are shown. Clients without app +support still receive ordinary MCP results. The [MCP Apps guide](mcp-apps.md) +explains controls, limits, and host support. + +## Repair and reuse an archive + +- **Fill a historical gap.** Use `collect --start YYYY-MM-DD --end YYYY-MM-DD` + for an inclusive range of up to 366 local calendar days. Repeat an interrupted + command safely: committed observations remain and duplicates are ignored. + See [collection and backups](../cmd/tempestkeep/README.md#collection). +- **Continue a bounded MCP backfill.** Inspect `archive_status`, then use + `backfill_archive`. When more history remains, explicit windows return + `next_before` for exact continuation without changing the shared collection cursor. Follow the + [archive-building workflow](mcp.md#build-an-archive). +- **Export enough context for your own analysis.** Add `export --metadata` to CSV + or JSON Lines exports for stored device identity, report and wind intervals, + precipitation type, and source. Report intervals let you reproduce the solar + energy estimate. See the + [export guide](../cmd/tempestkeep/README.md#export-observations). + +## Ask questions about your weather history + +Compare months, find recorded extremes, revisit a date across years, inspect +wind direction, or examine pressure changes. Start with the +[tool-to-question guide](querying.md#choose-a-query) and +[worked queries](querying.md#worked-tool-calls). For a terminal report, use +[`tempestkeep stats`](../cmd/tempestkeep/README.md#archive-reports); for a custom +archive question, use read-only `query_sql`. Coverage and missing sensor readings +remain part of interpreting any result. + +An existing archive supports reports, exports, and history queries without a +token or live API connection. MCP `--read-only` removes collection tools while +keeping available reads; a configured token can still enable live weather. +See [offline startup and capabilities](mcp.md#start-and-stop) and +[dates, units, and aggregation](querying.md). + +## User guides - [`tempestkeep` command guide](../cmd/tempestkeep/README.md): setup, collection, displays, exports, and configuration precedence. @@ -40,6 +113,19 @@ building, setup, collection, MCP operation, privacy, and verification. - [Go patch toolchain ADR](adr/0007-go-patch-toolchain.md): the Go 1.27.2 pin and qualification of the updated toolchain. +- [Archive recovery and coverage ADR](adr/0008-archive-recovery-and-coverage.md): + explicit collection ranges, exact MCP continuation, and event sensor counts. + +- [Seasonal trend ADR](adr/0009-seasonal-trend-estimation.md): a common trend + with separate calendar-month baselines and explicit limits on interpretation. + +- [Export metadata and version ADR](adr/0010-export-metadata-and-development-version.md): + opt-in observation metadata, streaming access, and the 0.4.0 development target. +- [Device selection and pressure ADR](adr/0011-mcp-device-selection-and-pressure-samples.md): + MCP device choice, station-device tables, pressure samples, and report bounds. +- [Rain summary coverage ADR](adr/0012-rain-summary-coverage.md): nullable totals, + sample counts, and missing/partial rain in reports and interactive views. + ## Review correctness and security - [Correctness properties](testing/properties.md): guarantees converted into diff --git a/docs/adr/0008-archive-recovery-and-coverage.md b/docs/adr/0008-archive-recovery-and-coverage.md new file mode 100644 index 0000000..831b323 --- /dev/null +++ b/docs/adr/0008-archive-recovery-and-coverage.md @@ -0,0 +1,41 @@ +# ADR 0008: Explicit archive recovery and event sensor coverage + +- Status: proposed +- Date: 2026-10-18 + +## Context + +CLI collection follows the newest observation and saved seed progress. It +cannot revisit a selected old gap. MCP explicit backfill has calendar-date +inputs but returns an epoch cursor, which can fall inside a daylight-saving +day. Observation series also coalesce missing event readings into zero totals. + +## Decision + +Add paired inclusive CLI range flags and an exclusive MCP `before_epoch` input. +Reuse existing collection and replay behavior. Explicit requests leave shared +seed and sync metadata alone. Bound CLI requests to 366 local calendar days, +and retain existing MCP work budgets. Validate bounds before external work. + +Add exported `SeriesPoint.RainReadings` and `SeriesPoint.LightningReadings` +integer fields with JSON keys `rain_readings` and `lightning_readings`. +Keep existing numeric totals and field types. Counts distinguish unknown, +measured zero, and partial coverage. The MCP description and app explain this +contract; the app displays unknown event totals as missing values. + +## Compatibility and consequences + +No observation schema or configuration migration is required. Existing calls +retain their behavior, and existing keyed Go struct literals remain compatible. +Unkeyed external struct literals must include the added fields. Strict JSON +consumers must accept the added count fields. Numeric totals alone still do +not establish sensor coverage; consumers should use the counts. + +An explicit CLI range ignores an environment seed floor and rejects an explicit +seed-floor flag. After failure, repeat the same range; already committed rows +are replay-safe. MCP callers repeat start and max_days and pass next_before as +before_epoch. The shared no-argument cursor remains separate. + +Recovery adds no automatic scheduler, external write, or archive replacement. +Missing upstream data stays missing. Counts measure available samples, not +continuous sensor uptime. The existing privacy and backup constraints remain. diff --git a/docs/adr/0009-seasonal-trend-estimation.md b/docs/adr/0009-seasonal-trend-estimation.md new file mode 100644 index 0000000..c07a674 --- /dev/null +++ b/docs/adr/0009-seasonal-trend-estimation.md @@ -0,0 +1,34 @@ +# ADR 0009: Seasonal trend estimation + +- Status: proposed +- Date: 2026-10-18 + +## Context + +Subtracting calendar-month temperature means alone does not remove the effect +of uneven seasonal time coverage from a regression. The previous fit divides +by time variation between unrelated months and understates the within-month +trend. Its broad numerical test tolerated this error. + +## Decision + +Fit one slope with a separate intercept for each calendar month. Give each +usable monthly mean equal weight. Center both time and temperature within its +calendar-month group, then calculate the slope from centered cross-products. +Report R² for the within-month fit, not the seasonal level differences. + +A calendar month observed once supplies no trend information. If no month +repeats, omit the slope and R². Repeated constant temperatures identify a zero +slope but no R² because temperature variance is zero. Keep existing anomaly +extrema and coverage metadata. + +## Consequences + +Corrected slopes and R² values can differ from previous reports. Constant +repeated readings now return zero slope instead of no slope. Field names, +JSON types, public Go signatures, and stored data remain unchanged. + +This is a descriptive fit to the available archive. It does not establish +climate attribution, station stability, complete coverage, or statistical +significance. Sparse months receive the same weight as more complete months; +users must inspect coverage before interpreting the result. diff --git a/docs/adr/0010-export-metadata-and-development-version.md b/docs/adr/0010-export-metadata-and-development-version.md new file mode 100644 index 0000000..8089f90 --- /dev/null +++ b/docs/adr/0010-export-metadata-and-development-version.md @@ -0,0 +1,34 @@ +# ADR 0010: Export metadata and development version + +Status: proposed + +## Context + +The archive stores observation intervals and provenance that existing exports +omit. In particular, solar-energy estimates cannot be reproduced without the +report interval. Existing scripts may depend on the current export columns. +The improvement batch also adds user-facing features beyond the proposed 0.3.0 +MCP Apps baseline. + +## Decision + +Add `export --metadata`. Append device ID, report interval in minutes, wind +interval in seconds, precipitation type, and stored source. Preserve defaults, +missing values, and numeric zeroes. Metadata retains its units in US exports. +Use a separate additive store row type and streaming iterator, without changing +`model.Obs` or unrelated MCP JSON. Older missing columns yield missing values. +Bound source text before allocation and use format-correct escaping. No archive +migration is needed. + +Version this feature batch as 0.4.0 in active development and plugin metadata. +Preserve build overrides and historical version records. Keep release and +plugin publication as separate maintainer actions. + +## Consequences + +Default exports stay compatible. Opt-in CSV consumers must accept five added +columns, and JSON consumers must accept optional fields. Exports remain analysis +files rather than restorable archive backups. Energy calculations must exclude +missing or invalid intervals; they must not assume continuous sensor coverage. +The API snapshot and regression tests record the additive store contract. +The version bump does not publish or merge the PR. diff --git a/docs/adr/0011-mcp-device-selection-and-pressure-samples.md b/docs/adr/0011-mcp-device-selection-and-pressure-samples.md new file mode 100644 index 0000000..8dda2e8 --- /dev/null +++ b/docs/adr/0011-mcp-device-selection-and-pressure-samples.md @@ -0,0 +1,35 @@ +# ADR 0011: MCP device selection and pressure samples + +Status: proposed + +## Context + +CLI collection can select a device but MCP always selects the first Tempest on +the account. This prevents consistent use of another station's archive. Pressure +tendency promises the nearest window sample but considers only earlier candidates, +which can reverse the reported pressure direction in sparse history. + +## Decision + +Add MCP `--device-id` and honor `TEMPEST_DEVICE_ID`. A positive explicit flag +wins. Empty or zero environment values preserve discovery. Validate configuration +before archive/API work, then resolve authorized ST membership lazily. Do not +cache failed resolution or fall back to a different live device. Preserve offline +archive access, explicit station read overrides, and existing archive identity +checks. Live requests remain station-level even when a device is selected. + +Compare indexed pressure candidates on both sides of the requested start. Require +at least half the window between distinct samples, prefer the older sample on a +tie, and retain actual-span normalization. No schema or output-field changes are +needed. Invalid report ranges fail as usage errors before configuration or I/O. + +## Consequences + +Existing MCP configurations that set `TEMPEST_DEVICE_ID` now select that device. +Previously ignored malformed values become errors. Discovery remains the default +when the key is empty or zero. Startup can initialize an empty archive before +lazy device resolution, but failed resolution cannot bind or collect into it. +Pressure values can change when a closer eligible sample exists, and sufficiently +long short histories can now yield a trend. The station app adds a local derived +device table without changing MCP payloads or adding calls. Version 0.4.0 remains +the current development target; no publication or merge is included. diff --git a/docs/adr/0012-rain-summary-coverage.md b/docs/adr/0012-rain-summary-coverage.md new file mode 100644 index 0000000..590fa44 --- /dev/null +++ b/docs/adr/0012-rain-summary-coverage.md @@ -0,0 +1,34 @@ +# ADR 0012: Missing rain summaries and sample coverage + +Status: proposed + +## Context + +RainStats converts missing rain to zero through daily sum aggregation. Missing, +measured-zero, and partial samples can therefore produce identical summaries. +The user requests that missing readings stop appearing as zero. + +## Decision + +Use one canonical nullable total. RainStats.TotalIn becomes *float64, encoded as +number-or-null under the existing total_in key without omitempty. A total is nil +exactly when no rain readings exist. Add observations and rain_readings counts +from the existing daily aggregate pass. Positive counts preserve measured zero; +partial totals sum reported values without extrapolation. + +Keep day counts, thresholds, wettest-day selection, and spell semantics unchanged. +Distinguish empty, missing, and partial results in CLI/MCP and the scalar app. +Keep the app's rainfall headline stable when missing and preserve original data. + +## Consequences + +Go callers must handle a pointer and check nil. JSON/MCP consumers must accept +null and two new count fields. This intentional contract change supersedes the +previous RainStats shape-stability decision; other rain result types do not +change. Count-only output was rejected because canonical zero remains misleading. +A second total field would duplicate meaning and burden consumers. + +No schema migration, additional query pass, or dependency is needed. Coverage +counts describe stored samples, never continuous observation time. Daily, period, +and normal rainfall aggregates need their own coverage design. Version 0.4.0 +remains the unreleased development target, and PR #9 remains open for review. diff --git a/docs/architecture.md b/docs/architecture.md index dd7d0b4..7f1e6f0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -44,6 +44,12 @@ rejects an explicit different observation type, mismatched device ID, failed API status, or observation outside the requested range. Missing optional identity fields remain compatible with older responses. +MCP resolves its configured Tempest device lazily from accessible stations. The +positive `--device-id` flag overrides `TEMPEST_DEVICE_ID`; empty or zero +environment values retain automatic selection. Only successful resolution is +cached. The exact device controls collection, while its parent station controls +default live reads. Explicit station arguments do not replace that default. + The model validates array width, epoch, numeric fields, and physical bounds. It copies retained pointer values. One malformed row rejects the complete response. The client does not cache rejected JSON or observation responses. @@ -60,11 +66,29 @@ sync starts after the stored watermark. During bounded MCP catch-up, private metadata also preserves successful empty windows across calls and restarts. After catch-up completes, the next sync rechecks the tail after the watermark. +Explicit CLI range collection replays inclusive local dates through the same +collector. It leaves seed and MCP sync metadata unchanged. MCP explicit +backfill accepts an exclusive `before_epoch`, so clients can continue directly +from `next_before` even when a work budget stops inside a local date. Explicit +MCP bounds also leave shared continuation metadata unchanged. + MCP work budgets limit each backward call's requested history. Empty-history progress survives bounded calls and restarts. One MCP server serializes its archive write workflows. Separate server processes do not share that coordination, so avoid overlapping collectors for one archive. +Exports use read-only streaming iterators. `EachObs` keeps the presentation +subset; `EachArchiveObs` adds nullable stored intervals, device identity, +precipitation type, and source. The CLI includes those fields only with +`--metadata`. It discovers optional columns through a fixed allowlist, treats +absent legacy columns as missing, and bounds source text before loading it. +No file-wide result buffer or archive migration is needed. + +Pressure tendency probes the indexed predecessor and successor around the +requested window start. It chooses the nearest eligible reading, with an older +tie winner and at least half a window between samples. The rate uses the actual +sample span. It does not sort the full archive by distance from the target. + ## SQLite ownership `store.Writer` creates the parent directory, file, and schema. It owns one @@ -115,6 +139,11 @@ before startup when the station and host use different timezones. Native Windows uses the host timezone. Queries do not infer timezone from the archive. See the [query guide](querying.md) for date bounds and missing readings. +Observation-series rain and lightning totals retain numeric zero for no +samples. Separate `rain_readings` and `lightning_readings` counts distinguish +unknown totals, measured zeros, and partial sensor coverage. The app uses these +counts in derived display rows; the original tool result remains unchanged. + ## MCP capabilities The server registers only supported capabilities: diff --git a/docs/mcp-apps.md b/docs/mcp-apps.md index cee6833..54c1e49 100644 --- a/docs/mcp-apps.md +++ b/docs/mcp-apps.md @@ -29,6 +29,7 @@ This repository does not certify a particular host or version. | "Show daily weather for the past month." | Trends and a table of daily summaries. | | "Show the windiest days in my archive." | Ranked rows from a summary or read-only SQL result. | | "Show the archive status." | Coverage and the available structured details. | +| "List my stations and devices." | Stations and a Devices table with parent station names and exact IDs. | All 27 read-only tools have views when live and archive sources are available. Only tools supported by the current configuration appear. `backfill_archive` @@ -36,14 +37,32 @@ and `sync_archive` retain their ordinary MCP results and have no app controls. ## Read charts and tables -Charts show supported weather series with a metric selector. Hover over bars -or line series with up to 60 readings to see values. For larger line series, -use the table for exact readings. Wind results include a 16-sector rose. +Charts show supported weather series with a metric selector. Point or tap on a +chart to inspect the nearest returned reading, including its full source time, +timezone when supplied, metric, and units. The slider selects every displayed +point, including dense series of up to 2,000 readings. Focus the slider and use +arrow keys for adjacent readings, or Home and End for the first and last. +Missing readings are labeled explicitly. Selection follows the plotted spacing +and does not interpolate across gaps or fetch data. Changing the metric or +replacing the result resets selection to the first reading. +Wind results include a 16-sector rose with exact frequencies in the table. Dataset tabs separate collections such as hourly and daily forecasts. Tables provide text search, numeric-aware column sorting, and eight-row pages. These controls operate on the received result. They do not run a new archive query or retrieve rows beyond a server limit. +The `list_stations` view includes a Devices table with station ID, station name, +device ID, device type, and serial number. Search an exact ID or serial number to +find its parent station. Numeric station and device IDs use ungrouped digits so +they can be copied into configuration. Duplicate entries and missing fields stay +visible. The view uses only the received station result and leaves it unchanged. +If a numeric ID exceeds the browser's exact integer range, the cell reports +`ID exceeds browser precision` instead of presenting a rounded ID for copying. +Use `tempestkeep list-devices` to read that ID; text IDs remain unchanged. +It examines at most 2,000 stations and 2,000 device entries, +with a notice when either limit omits data. Its fixed columns also let table +controls survive a refresh that temporarily returns no devices. + The view displays at most 2,000 rows and 64 columns per table. It reports when these display limits omit data. The original structured tool result remains available to the host. Long cell text is also bounded in the display. @@ -56,12 +75,37 @@ Missing readings remain distinct from measured zero. Labels and field units come from the tool result. Raw SQL retains SI units unless the query explicitly converts them. SQL column names and values remain in their original order, even when names repeat. The app does not infer units from arbitrary SQL column names. +For observation series, `rain_readings` and `lightning_readings` count the samples +that supplied each event measurement. A zero count displays the corresponding +total as missing in charts, tables, and summaries. A positive count preserves a +measured zero. If a count is below `obs`, the total covers only some samples. +The view reports missing and partial buckets, and keeps their counts in the table. +These counts describe samples, not continuous sensor uptime. Original tool +results remain intact. Older results without counts retain their existing display. + +The Rainfall patterns view for `rain_stats` keeps rainfall as its headline even +when no measurement is available. It shows missing rainfall and unavailable +rain statistics as `—`, while measured zero stays zero. The sample-count notice +distinguishes an empty range, absent rain readings, and a partial reported total. +Counts describe stored samples, not continuous coverage. Refresh updates the +total and notice together; original tool results and other views stay unchanged. See the [query guide](querying.md) for date boundaries, aggregation, and incomplete sensor coverage. Refresh repeats the current read-only tool with the same arguments through the host. Live tools retain the configured API cache behavior. Archive views read the archive's current contents. Refresh does not sync or backfill history. +A compatible refresh keeps the selected dataset, search text, sort column and +direction, and page. If fewer filtered rows remain, the page moves to the last +available page. Edits made while the call is pending are retained, including +search focus and text selection. A failed refresh leaves the prior result and +controls available. + +A new tool input resets table controls. A missing selected dataset or a changed +ordered column structure also resets them, so stale sorting cannot select a +different column. Empty results without explicit column metadata also reset +controls because their structure is unknown. This state lasts only in the current +app instance. Chart reading selection still resets when a result is replaced. For a different range or query, ask the agent to call the tool with new arguments. The view follows the host's theme and fits narrow containers. Loading, empty diff --git a/docs/mcp.md b/docs/mcp.md index ce0250e..306a90f 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -22,6 +22,7 @@ Provide configuration in the client's private environment: |---|---|---| | `TEMPEST_TOKEN` | Empty | Enables live API operations. With a writable archive, it also enables collection. | | `TEMPEST_DB` | `./tempest.sqlite` if that file exists | Selects one local SQLite archive. Set an explicit path to create a new archive with live access. | +| `TEMPEST_DEVICE_ID` | First accessible Tempest device | Positive ID of a Tempest (`ST`) device for collection and the default live station. Empty or zero selects automatically. | | `TEMPEST_READ_ONLY` | False | `1`, `true`, `yes`, or `on` removes archive write tools. Values are case-insensitive. | | `TEMPEST_CACHE_TTL` | 300 | Seconds to cache live API responses, from 0 through 86400. Zero disables caching. | | `TEMPEST_THROTTLE_MS` | 400 | Delay between collection requests, from 0 through 60000 milliseconds. Zero disables the delay. | @@ -38,7 +39,8 @@ Do not pass a token as a command argument. Use the client's secret store or private environment. An alternate API endpoint receives the token. Use only synthetic tokens with plaintext HTTP test endpoints. -`--db` selects an archive. `--read-only` disables archive writes. Either +`--db` selects an archive. `--device-id` selects a positive device ID and overrides +`TEMPEST_DEVICE_ID`. `--read-only` disables archive writes. Either `--read-only` or a true `TEMPEST_READ_ONLY` disables writes, so `--read-only=false` cannot override a true environment value. Read-only mode still permits live API calls when a token exists. @@ -64,10 +66,28 @@ With all capabilities enabled, the server exposes 29 tools. Use the client's tool discovery to determine availability. Do not assume that every deployment has live access or write access. -The server selects the first Tempest device found for the token. MCP does not -use `TEMPEST_DEVICE_ID`, which applies to CLI collection. If a token can access -multiple devices, make sure that the selected device matches the archive. -The archive rejects writes for a different device. +If the token can access several devices, call `list_stations` or run +`tempestkeep list-devices` to find the intended Tempest device. Set its ID through +`TEMPEST_DEVICE_ID` or `mcp --device-id` before collecting. The server resolves +the selection on its first live request. An unknown device or a non-Tempest +device fails that request without selecting another live station. Failed +resolution can be retried, subject to the configured API cache lifetime. +Without a selection, the server uses the first +accessible Tempest device. The archive rejects writes for a different device. + +The selected device sets the default station for live conditions and forecasts, +which remain station-level API results. It also selects the exact device for +archive collection. An explicit tool `station_id` overrides the station for that +read only. `list_stations` still lists every accessible station. With no token, +a valid device setting does not change archive-only reads. Current conditions +can still fall back to the archive and report `source: "archive"` if live access +fails. Failed station resolution never labels an archive with another station. + +Malformed or negative environment IDs fail before archive or API access. Explicit +flag IDs must be positive; a valid flag overrides an invalid environment value. +An inaccessible positive ID is discovered lazily, so writable startup can create +an empty archive before that first live failure. It does not bind or collect +observations for the failed selection. `station_info` adds live station metadata only when the archive's device belongs to that station. Missing or mismatched identity leaves those fields @@ -140,11 +160,12 @@ If the archive needs older history, call `backfill_archive`: ``` After each successful call, inspect `rows_added`, `coverage`, `has_more`, and -`next_before`. If `has_more` is true, another call without dates resumes the -saved cursor. Stop on an error or when the client's time budget ends. A later -session can continue from the committed progress. +`next_before`. If `has_more` is true, another call without `end` or +`before_epoch` resumes the saved cursor. Stop on an error or when the client's +time budget ends. A later session can continue from the committed progress. -To stop at a chosen oldest date, pass `start` and leave `end` unset: +To stop at a chosen oldest date, pass `start` and leave `end` and `before_epoch` +unset: ```json {"start": "2025-01-01", "max_days": 30} @@ -172,17 +193,37 @@ lets the walk continue through empty ranges to that date. Completion does not prove that every date has complete observations. A data gap can remain even after the API's available history is exhausted. -For a specific gap, use an explicit window shorter than the call budget: +For a specific gap, use an explicit window: ```json -{"start": "2025-06-01", "end": "2025-06-04", "max_days": 5} +{"start": "2025-06-01", "end": "2025-06-04", "max_days": 1} ``` -This example includes June 1 through June 3 in the process timezone. +The requested window includes June 1 through June 3 in the process timezone. +Each call fetches at most one 24-hour day because `max_days` is one. For `backfill_archive`, `end` is exclusive local midnight. An explicit `end` -does not update the shared resume cursor. Repeating the same window rereads -that window and ignores duplicate rows. Split larger repairs into bounded -windows instead of repeating an unchanged `end`. +or `before_epoch` leaves the shared resume cursor, completion marker, and +empty-history progress unchanged. Repeating the same window rereads that +window and ignores duplicate rows. + +If `has_more` is true, pass the returned `next_before` integer as `before_epoch` +on the next call. Omit `end` and repeat the same `start` and `max_days`. +The epoch boundary is exclusive, so the next batch continues exactly where +the previous one stopped. For example, when the process timezone is UTC and +`next_before` is `1748908800`, continue with: + +```json +{"start": "2025-06-01", "before_epoch": 1748908800, "max_days": 1} +``` + +That boundary is June 3, 2025 at 00:00 UTC. Use the integer from your own result. +Do not convert it to a date: a budget counts 24-hour days, and its boundary +can fall within a local calendar day during a daylight-saving transition. +Repeat until `has_more` is false. `before_epoch` must be a positive epoch second +within the supported observation range, and cannot be combined with `end`. +Omitting `start` on a continuation removes the requested lower bound. +After an error, repeat the failed explicit request; committed rows remain +replay-safe, and explicit requests do not save a separate resume cursor. The CLI and MCP use the same archive and collection metadata. MCP collection does not create the CLI's post-collection backups. See the @@ -208,6 +249,13 @@ and pressure, maxima for gusts and UV, and sums for rain and lightning. Empty time buckets are absent. See the [query guide](querying.md) for units, missing readings, comparison rules, and SQL examples. +For a rainfall summary, call `rain_stats` with the same inclusive date arguments. +Its `total_in` is `null` without rain readings and numeric zero for measured zero. +`rain_readings` and `observations` describe stored sample coverage; a note marks +missing or partial readings. Partial totals include reported measurements only. +Counts do not establish continuous coverage of the range. The app keeps a +rainfall headline even when the total is missing. + ## Limits and failure behavior | Operation | Limit or default | diff --git a/docs/public-api.txt b/docs/public-api.txt index 9931b8e..ea2f71a 100644 --- a/docs/public-api.txt +++ b/docs/public-api.txt @@ -301,6 +301,7 @@ const ( MaxRangeSeconds = int64(100 * 366 * 24 * time.Hour / time.Second) MaxSeriesPoints = 2000 ) +const MaxArchiveSourceBytes = 1024 VARIABLES var ( ErrInvalidArgument = errors.New("invalid argument") @@ -312,6 +313,14 @@ var ( ErrArchiveIO = errors.New("archive I/O failure") ) TYPES +type ArchiveObs struct { + model.Obs + DeviceID *int64 `json:"device_id,omitempty"` + ReportIntervalMin *float64 `json:"report_interval_min,omitempty"` + WindIntervalSeconds *float64 `json:"wind_interval_s,omitempty"` + PrecipType *float64 `json:"precip_type,omitempty"` + Source *string `json:"source,omitempty"` +} type ClimateIndexParams struct { FrostMaxF float64 // frost day: daily low below this (default 32°F / 0°C) IceMaxF float64 // ice day: daily high stays below this (default 32°F) @@ -452,7 +461,9 @@ type QueryResult struct { Truncated bool `json:"truncated,omitempty"` // hit maxRows; more rows exist } type RainStats struct { - TotalIn float64 `json:"total_in"` + Observations int64 `json:"observations"` // stored rows, regardless of rain availability + RainReadings int64 `json:"rain_readings"` // non-NULL rain samples, including measured zero + TotalIn *float64 `json:"total_in"` DaysObserved int64 `json:"days_observed"` RainyDays int64 `json:"rainy_days"` WettestDay string `json:"wettest_day,omitempty"` @@ -496,20 +507,22 @@ type SensorStatus struct { Stale bool `json:"stale,omitempty"` } type SeriesPoint struct { - Epoch int64 `json:"epoch"` // bucket start, unix seconds - Time string `json:"time"` // bucket start, local RFC3339 - TempAvgF *float64 `json:"temp_avg_f,omitempty"` - TempMinF *float64 `json:"temp_min_f,omitempty"` - TempMaxF *float64 `json:"temp_max_f,omitempty"` - HumidityPct *float64 `json:"humidity_pct,omitempty"` - PressureInHg *float64 `json:"pressure_inhg,omitempty"` - WindMph *float64 `json:"wind_mph,omitempty"` - GustMph *float64 `json:"gust_mph,omitempty"` - RainIn float64 `json:"rain_in"` - UVMax *float64 `json:"uv_max,omitempty"` - SolarAvgWm2 *float64 `json:"solar_avg_wm2,omitempty"` - Strikes int64 `json:"lightning_strikes"` - Obs int64 `json:"obs"` + Epoch int64 `json:"epoch"` // bucket start, unix seconds + Time string `json:"time"` // bucket start, local RFC3339 + TempAvgF *float64 `json:"temp_avg_f,omitempty"` + TempMinF *float64 `json:"temp_min_f,omitempty"` + TempMaxF *float64 `json:"temp_max_f,omitempty"` + HumidityPct *float64 `json:"humidity_pct,omitempty"` + PressureInHg *float64 `json:"pressure_inhg,omitempty"` + WindMph *float64 `json:"wind_mph,omitempty"` + GustMph *float64 `json:"gust_mph,omitempty"` + RainIn float64 `json:"rain_in"` + RainReadings int64 `json:"rain_readings"` + UVMax *float64 `json:"uv_max,omitempty"` + SolarAvgWm2 *float64 `json:"solar_avg_wm2,omitempty"` + Strikes int64 `json:"lightning_strikes"` + LightningReadings int64 `json:"lightning_readings"` + Obs int64 `json:"obs"` } type SolarStats struct { DaysObserved int64 `json:"days_observed"` @@ -536,6 +549,7 @@ func (s *Store) ComfortStatistics(ctx context.Context, startEpoch, endEpoch int6 func (s *Store) Coverage(ctx context.Context) (Coverage, error) func (s *Store) DailySummary(ctx context.Context, startEpoch, endEpoch int64) ([]DayStat, error) func (s *Store) DegreeDays(ctx context.Context, p DegreeDayParams, startEpoch, endEpoch int64) (DegreeDayStat, []DegreeDayStat, error) +func (s *Store) EachArchiveObs(ctx context.Context, startEpoch, endEpoch int64, fn func(ArchiveObs) error) (err error) func (s *Store) EachObs(ctx context.Context, startEpoch, endEpoch int64, fn func(model.Obs) error) (err error) func (s *Store) Gaps(ctx context.Context, minSeconds int64, limit int) (_ []Gap, err error) func (s *Store) HourlyClimatology(ctx context.Context, startEpoch, endEpoch int64) (_ []HourStat, err error) @@ -579,11 +593,10 @@ type TempTrend struct { FirstMonth string `json:"first_month,omitempty"` // YYYY-MM LastMonth string `json:"last_month,omitempty"` // SlopePerDecadeF is the fitted warming rate in °F per decade; positive is - // warming. Nil until the anomalies actually vary over time, which needs the - // same calendar month observed in more than one year (a single year, or years - // that never share a month, leave every anomaly at zero and carry no trend). + // warming. Nil until a calendar month has usable means in more than one year. + // Repeated constant temperatures identify a zero slope. SlopePerDecadeF *float64 `json:"slope_per_decade_f,omitempty"` - RSquared *float64 `json:"r_squared,omitempty"` // fit quality, 0..1 + RSquared *float64 `json:"r_squared,omitempty"` // within-month fit, 0..1; nil for zero temperature variance WarmestAnomalyF *float64 `json:"warmest_anomaly_f,omitempty"` WarmestMonth string `json:"warmest_month,omitempty"` ColdestAnomalyF *float64 `json:"coldest_anomaly_f,omitempty"` diff --git a/docs/querying.md b/docs/querying.md index c24c3c1..bc6d9e7 100644 --- a/docs/querying.md +++ b/docs/querying.md @@ -51,6 +51,10 @@ A daylight-saving transition can make a local day 23 or 25 hours long. Do not assume that every local day contains 1440 one-minute observations. Prefer the calendar tools to SQL that applies a fixed UTC offset across changing dates. +CLI `stats` and `export` validate resolved dates before configuration and archive +access. UTC bounds must stay within 1970-01-01 through 9999-12-31 and differ by +at most 36,600 days. An invalid range returns usage status 2. + `get_observations` uses fixed-duration buckets aligned to the Unix epoch. Its timestamps identify bucket starts. A large bucket does not necessarily start at local midnight, and the first or last bucket can contain only part @@ -86,6 +90,28 @@ Rain and lightning increments cover each row's report interval, which can differ from one minute. Sum the increments without multiplying by interval length. +`rain_stats` and the rain section of CLI `stats --format json` include +`observations`, `rain_readings`, and `total_in`. The counts cover stored samples +within the inclusive query bounds: + +| Sample coverage | Meaning of `total_in` | +|---|---| +| No observations | `null`: the range contains no stored samples. | +| Observations exist, no rain readings | `null`: rainfall is unknown. | +| Some observations lack rain | A partial sum of reported readings, including measured zero. | +| Every stored observation has rain | The sum of those readings, including measured zero. | + +Equal counts do not prove continuous coverage of the time range. No missing +samples are filled or extrapolated. `days_observed` still counts days with any +observation. Rainy days and wet/dry spells describe reported readings; a day +without rain readings or a calendar gap ends a spell. A numeric zero count of +recorded rainy days does not establish dry weather when rain readings are absent. +Daily, period, and climate-normal rainfall fields retain their existing contracts. + +Go callers now check `RainStats.TotalIn` for nil before dereferencing it. JSON +and MCP consumers must accept a number or explicit `null`; the key is always +present. See [ADR 0012](adr/0012-rain-summary-coverage.md). + `solar_stats` estimates solar energy by summing each `solar_wm2` reading times its positive `report_interval_min`, times 60, divided by 1,000,000. The result is MJ/m². For example, 100 W/m² over one reported minute contributes 0.006 MJ/m². @@ -99,6 +125,12 @@ subtract overlaps between intervals. Gaps receive no estimated energy. interval. `days_observed` counts all days with stored observations, including days without solar readings. +To reproduce this estimate outside TempestKeep, use `export --metadata` in CSV +or JSON Lines format. It includes each available `report_interval_min` beside +`solar_wm2`; both stay in the same units under `--units us`. The default export +omits report intervals. See the [export guide](../cmd/tempestkeep/README.md#export-observations) +for missing-value rules and the optional fields. + Treat insolation as an estimate from reported intervals. A station's sunlight measurements do not measure a solar panel's electrical output. @@ -118,10 +150,25 @@ sample span. It is not necessarily a measured change over exactly three hours. The separate `pressure_trend` tool retains the historical samples' time, span, and actual change, along with the normalized rate. +Pressure tendency uses the latest nonmissing pressure reading and the earlier +reading closest to the requested window start. It considers samples before and +after that target, with the older sample winning an equal-distance tie. The pair +must span at least half the requested window, rounded up to whole seconds. A +three-hour request can therefore use a two-hour pair, while a recent cluster +under 90 minutes cannot establish that trend. Missing pressure readings do not +count as samples. Inspect the returned span when the archive is sparse. + `get_observations` preserves temperature means, minima, and maxima. It uses mean wind speed, maximum gust and UV, and total rain and lightning per bucket. An hourly `gust_mph` is the largest stored gust in that bucket. +Each series bucket also includes `rain_readings` and `lightning_readings`. +These count non-missing samples for each event sensor. If a count is zero, +its numeric total is unknown even though the compatible total field is zero. +A positive count with a zero total is a measured zero. A count below `obs` +means the total covers only some observations. MCP Apps shows unknown totals +as missing values and warns about incomplete coverage. + ## Coverage and missing readings Start an analysis with `archive_status`, then inspect the requested range. @@ -133,7 +180,7 @@ while `COUNT(air_temp_c)` counts rows with a temperature reading. `AVG`, `MIN`, `MAX`, and `SUM` skip missing values. `SUM` returns `NULL` when there are no non-null input values. -Some history totals use zero when no valid increments exist. Compare those +Other history totals can use zero when no valid increments exist. Compare those totals with SQL reading counts for `rain_mm` or `strike_count`. `sensor_health` covers continuous sensors, not these interval counts. A returned zero alone does not prove that a working sensor recorded no rain or lightning. @@ -155,9 +202,16 @@ can still contribute to a daily summary. Compare sample counts and covered dates before ranking days, months, or years. `climate_normals` describes the available archive. It does not establish a -standard long-term climate baseline. `temperature_trend` fits the recorded -series. Gaps, partial years, and changes to station placement can affect that -fit. Report the available span and evidence before interpreting a trend. +standard long-term climate baseline. `temperature_trend` fits one slope with a +separate baseline for each calendar month. Each usable monthly mean has equal +weight. The fit centers both time and temperature within that calendar month, +so a month observed only once does not change the slope. + +The trend needs at least one calendar month repeated across years. Repeated +constant temperatures produce a zero slope and no R². Otherwise R² describes +the fit after seasonal baselines are removed. It does not measure statistical +significance. Sparse months, gaps, and changes to station placement still limit +interpretation. Report the available span and evidence before interpreting a trend. ## Worked tool calls diff --git a/docs/screenshots/mcp-app-weather.png b/docs/screenshots/mcp-app-weather.png index 300f7ac..83a70ee 100644 Binary files a/docs/screenshots/mcp-app-weather.png and b/docs/screenshots/mcp-app-weather.png differ diff --git a/docs/testing/properties.md b/docs/testing/properties.md index a856471..57234f9 100644 --- a/docs/testing/properties.md +++ b/docs/testing/properties.md @@ -43,6 +43,21 @@ store any failing input in the Go fuzz corpus so the failure can be replayed. | P-33 | Bounded MCP sync crosses empty windows while preserving retries and late arrivals. | Restarts, API errors, checkpoint failures, cancellation, changed watermarks, and delayed observations after a completed scan. | `TestSyncCrossesEmptyBudgetAcrossCalls`, `TestSyncCursorSurvivesRestartAndAPIError`, `TestSyncDiscardsCursorAfterWatermarkChanges`, `TestSyncReplaysWindowWhenCheckpointFails`, `TestSyncCancellationReplaysUncommittedWindow`, `TestSyncCompletedScanRetriesLateArrivingObservations` | | P-34 | Terminal displays retain valid sensors and calendar boundaries, and setup preserves usable configuration on failure. | Quarter-hour timezones, daylight-saving changes, missing temperatures, empty ranges, terminal controls, literal PowerShell paths, and oversized dotenv output. | `TestDayChartRetainsQuarterHourTimezoneBuckets`, `TestDaysInCountsCalendarDaysAcrossSpringForward`, `TestWeekViewKeepsRainWhenTemperatureIsMissing`, `TestStatsEmptyAnalysisRangeDoesNotClaimNoLightning`, `TestListDevicesTextSanitizesAPILabels`, `TestPowerShellCommandArgPreservesLiteralPath`, `TestWriteEnvFileRejectsOversizedOutputBeforeReplacement` | | P-35 | Live identity labels an archive only when its device belongs to that station; current pressure trends require recent readings and use a normalized three-hour rate. | Matched, mismatched, and unknown identities; future pressure; the one-hour freshness boundary; fresh rows without pressure; and sparse six-hour samples. | `TestNowFallbackRequiresMatchingArchiveIdentity`, `TestCrossSourceEnrichmentRequiresMatchingDevice`, `TestCurrentConditionsArchivePressureFreshnessAndRate` | +| P-36 | Explicit CLI repair is bounded, replay-safe, and preserves ordinary progress. | DST, 366-day bounds, invalid input before I/O, partial failure, duplicate replay, backups, and subprocess interruption. | `TestExplicitCollectionRangeCalendarBounds`, `TestCollectRangeRejectsInvalidInputBeforeIO`, `TestCollectRangeRepairsGapAndReplaysAfterFailure`, `TestCollectRangeCancellationKeepsCommittedRows` | +| P-37 | Explicit MCP continuation consumes an exact exclusive cursor without changing shared state. | Non-midnight DST boundary, invalid input before discovery, stored and absent metadata, and partial-failure replay. | `TestBackfillExactContinuationAcrossDST`, `TestBackfillExactContinuationPreservesSharedState`, `TestBackfillExactContinuationRejectsInvalidBeforeIO`, `TestBackfillExactContinuationReplaysAfterPartialFailure` | +| P-38 | Observation event totals carry independent sensor coverage. | Missing, measured-zero, partial and nonzero samples, clipped ranges, combined coverage/resolution notes, and legacy/SQL app compatibility. | `TestSeriesEventSensorCoverage`, `TestObservationSeriesReportsEventCoverage`, `npm run app:test` | +| P-39 | Seasonal trends depend on within-month change rather than unrelated seasonal coverage. | Exact warming/cooling, unmatched months, uneven groups, equal monthly weights, flat readings, absent repeated months, and large years. | `TestTemperatureTrendUnmatchedMonthCannotDiluteSlope`, `TestTemperatureTrendCentersUnevenMonthGroups`, `TestTemperatureTrendWeightsMonthlyMeansEqually`, `TestTemperatureTrendFlatRepeatedMonths`, `TestTemperatureTrendStableNearSupportedYearLimit`, `TestWriteStatsFlatTrend` | +| P-40 | Chart inspection selects returned readings without interpolation or extra tool calls. | Dense 2,000-point data, irregular time spacing, keyboard, touch, missing and zero readings, changed results, and resize selection/focus. | `npm run app:test`, `npm run app:screenshots` | +| P-41 | Optional export metadata preserves source values without changing default output. | CSV/JSONL, SI/US, exact solar arithmetic, missing/zero/fractional metadata, source controls, and failed writes. | `TestExportMetadataReproducesSolarEstimate`, `TestDefaultExportShapeRemainsStable`, `TestExportMetadataOutputFailureAndCancellation` | +| P-42 | Archive metadata streams through read-only bounded queries. | Legacy and uppercase columns, inclusive ordering, source byte/UTF-8 bounds, nonfinite metadata, cancellation, callback failure, and released connections. | `TestEachArchiveObsMetadataAndBounds`, `TestEachArchiveObsLegacySchema`, `TestEachArchiveObsSourceBounds`, `TestEachArchiveObsStopsAndClosesRows`, `TestEachArchiveObsRejectsInvalidOperations`, `TestEachArchiveObsRejectsNonFiniteMetadata` | +| P-43 | Compatible refreshes retain table exploration while displaying fresh rows. | Search/sort/page, changed data, page clamping, pending edits and focus, dataset reorder/removal, SQL duplicate columns, new contexts, and failed refreshes. | `tests/mcp-app/refresh.spec.mjs`, `npm run app:test` | +| P-44 | MCP collection and default live reads use the selected accessible Tempest device. | Flag/environment precedence, lazy startup, second stations, multiple devices per station, overrides, unknown and non-Tempest IDs, failed retries without writes, archive identity, offline reads, cancellation, and concurrency. | `TestE2EMCPDeviceConfigurationPrecedence`, `TestMCPSelectedDeviceControlsDefaultStationAndCollection`, `TestMCPDeviceSelectionFailuresDoNotWriteAndCanRetry`, `TestMCPSelectedDevicePreservesArchiveIdentityAndOfflineReads`, `TestSelectedDeviceResolutionCancellationAndConcurrency` | +| P-45 | Device inspection preserves parent stations and identifies bounded or imprecise values. | Exact ID/serial search, duplicates, missing and hostile labels, unsafe numeric IDs, stable empty refresh, traversal bounds, and unchanged raw and SQL results. | `tests/mcp-app/devices.spec.mjs`, `npm run app:test` | +| P-46 | Pressure tendency selects the nearest eligible sample without a full-history distance sort. | Reversed-direction regression, predecessor/successor/tie, exact and half windows, short histories, one-second and odd windows, early epochs, missing pressure, cancellation, and classified errors. | `TestPressureTendencyNearestEligibleSample`, `TestPressureTendencyNearEpochStart`, `TestPressureTendencyMissingAndErrors`, `TestPressureSampleQueriesUseEpochIndex`, `TestArchivePressureUsesNearestEligibleReading` | +| P-47 | Reports reject unsupported ranges before configuration or archive access. | Malformed dotenv, absent archive paths, epoch and elapsed-span bounds, timezone offsets, and 23/25-hour days. | `TestReportRangesRejectUnsupportedBoundsBeforeIO`, `TestReportRangeSupportedBoundaries`, `TestReportRangePreservesDSTCalendarDays` | +| P-48 | Rain totals distinguish missing readings, zero, and partial samples. | Empty and all-missing ranges, mixed zero/positive values, inclusive clipping, DST days, missing-day spells, cancellation, and closed stores. | `TestRainStatsJSONCoverage`, `TestRainStatsCoverageUsesInclusiveSelectedRange`, `TestRainStatsCoverageAcrossDST`, `TestRainStatsCoveragePreservesErrors` | +| P-49 | CLI and MCP preserve nullable totals and sample counts. | Actual command JSON/text, unrelated weather sections, nullable required MCP schema, plain/structured results, and bounded date selection. | `TestE2EStatsRainCoverage`, `TestRainStatsSchemaAndCoverage` | +| P-50 | The rainfall app keeps missing totals visible without implying dry weather. | Empty/missing/partial/zero, coverage notices, legacy payloads, raw-data preservation, unrelated SQL, and refresh. | `tests/mcp-app/rain-summary.spec.mjs`, `npm run app:test` | ## Test commands diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index ede64c4..6094072 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -88,6 +88,11 @@ make sure that your collection method selects the device that owns the archive. Repeated `sync_archive` calls retrieve new data, not historical gaps. For a gap, use the bounded `backfill_archive` example in the [MCP guide](mcp.md#build-an-archive). +Continue an explicit MCP request with its exact `next_before` as `before_epoch`. +Repeat `start` and `max_days`, and omit `end`. For CLI repair, use +`tempestkeep collect --start YYYY-MM-DD --end YYYY-MM-DD` with both local dates +included. Repeat the same CLI range after interruption. Explicit repair leaves +ordinary collection progress unchanged. WeatherFlow can return no data for a gap that the API cannot recover. If collection reports invalid checkpoint metadata, preserve the archive and @@ -114,8 +119,10 @@ the database manually. Transfer a completed backup or export between machines. ## Recover an archive from a backup Use a completed SQLite backup for recovery. CSV and JSON Lines exports omit -collector metadata and some stored columns. TempestKeep does not provide an -export-import command that reconstructs the archive. +collector progress metadata. Default exports also omit observation metadata; +`export --metadata` includes available stored intervals and provenance. +TempestKeep does not provide an export-import command that reconstructs the +archive. 1. Stop TempestKeep processes that write to the affected archive. 2. Copy a known-good backup to a new, unused local archive path. diff --git a/internal/mcpapp/archive.go b/internal/mcpapp/archive.go index 2615f18..b2530f5 100644 --- a/internal/mcpapp/archive.go +++ b/internal/mcpapp/archive.go @@ -83,16 +83,18 @@ type SyncOut struct { } // BackfillArgs is the backfill_archive input. With no arguments it walks history -// backward from where it left off, one bounded batch per call; start/end aim it -// at a specific older window. +// backward from where it left off, one bounded batch per call. An explicit end +// or BeforeEpoch targets a separate window without changing the shared cursor. type BackfillArgs struct { - Start string `json:"start,omitempty" jsonschema:"oldest date to fetch back to, YYYY-MM-DD local; the walk stops here"` - End string `json:"end,omitempty" jsonschema:"exclusive end date YYYY-MM-DD local (its midnight is not fetched); omit to resume the saved cursor"` - MaxDays int `json:"max_days,omitempty" jsonschema:"cap on 24-hour days of history fetched per call (default 30, max 365); batches may use fewer days to fit whole request windows"` + Start string `json:"start,omitempty" jsonschema:"oldest date to fetch back to, YYYY-MM-DD local; repeat this floor on each continuation"` + End string `json:"end,omitempty" jsonschema:"exclusive end date YYYY-MM-DD local (its midnight is not fetched); cannot combine with before_epoch; omit both to resume the saved cursor"` + BeforeEpoch *int64 `json:"before_epoch,omitempty" jsonschema:"positive exclusive epoch-second boundary; pass next_before here to continue an explicit window exactly; cannot combine with end"` + MaxDays int `json:"max_days,omitempty" jsonschema:"cap on 24-hour days of history fetched per call (default 30, max 365); batches may use fewer days to fit whole request windows"` } -// BackfillOut is the backfill_archive output. Call again while has_more is true -// (no arguments needed; it resumes) until the whole history is stored. +// BackfillOut is the backfill_archive output. While HasMore is true, undated +// calls resume shared progress; explicit windows continue with NextBefore as +// BeforeEpoch. Repeat the same Start and MaxDays on each continuation. type BackfillOut struct { RowsAdded int `json:"rows_added"` Fetched int `json:"fetched"` @@ -202,12 +204,21 @@ func registerArchiveTools(srv *mcp.Server, live *liveSource, writer *store.Write mcp.AddTool(srv, &mcp.Tool{ Name: "backfill_archive", Title: "Backfill archive (download history)", - Description: "Append older observations in one bounded batch. A call without dates resumes the saved cursor. max_days defaults to 30 and cannot exceed 365. Call again while has_more is true.", + Description: "Append older observations in one bounded batch. Omit end and before_epoch to resume the saved cursor. For explicit windows, pass next_before as before_epoch and repeat start and max_days while has_more is true. max_days defaults to 30 and cannot exceed 365.", Annotations: appendOnlyWrite(), }, func(ctx context.Context, _ *mcp.CallToolRequest, args BackfillArgs) (*mcp.CallToolResult, BackfillOut, error) { if args.MaxDays < 0 || args.MaxDays > maxBackfillMaxDays { return nil, BackfillOut{}, fmt.Errorf("max_days must be in 0..%d", maxBackfillMaxDays) } + if args.BeforeEpoch != nil { + if args.End != "" { + return nil, BackfillOut{}, fmt.Errorf("end and before_epoch cannot be combined") + } + if *args.BeforeEpoch <= 0 || *args.BeforeEpoch > model.MaxEpochSeconds { + return nil, BackfillOut{}, fmt.Errorf("before_epoch must be in 1..%d", model.MaxEpochSeconds) + } + } + useCursor := args.End == "" && args.BeforeEpoch == nil var floor int64 if args.Start != "" { t, err := parseLocalDate(args.Start) @@ -221,8 +232,8 @@ func registerArchiveTools(srv *mcp.Server, live *liveSource, writer *store.Write // Observations require a positive epoch. Reserve zero for the // open-ended heuristic even when the requested local date is epoch zero. floor = max(floor, 1) - if args.End == "" && floor > time.Now().Unix() { - return nil, BackfillOut{}, fmt.Errorf("start date must not be in the future when end is omitted") + if useCursor && floor > time.Now().Unix() { + return nil, BackfillOut{}, fmt.Errorf("start date must not be in the future when end and before_epoch are omitted") } } if args.End != "" { @@ -237,6 +248,9 @@ func registerArchiveTools(srv *mcp.Server, live *liveSource, writer *store.Write return nil, BackfillOut{}, fmt.Errorf("start date must be before the exclusive end date") } } + if args.BeforeEpoch != nil && floor >= *args.BeforeEpoch { + return nil, BackfillOut{}, fmt.Errorf("start date must be before the exclusive before_epoch boundary") + } if err := acquire(ctx); err != nil { return nil, BackfillOut{}, err } @@ -250,10 +264,14 @@ func registerArchiveTools(srv *mcp.Server, live *liveSource, writer *store.Write } // Where to start walking back from, and whether to track the shared cursor. - useCursor := args.End == "" - before, err := backfillStartPoint(ctx, writer, deviceID, args.End, useCursor) - if err != nil { - return nil, BackfillOut{}, err + var before int64 + if args.BeforeEpoch != nil { + before = *args.BeforeEpoch + } else { + before, err = backfillStartPoint(ctx, writer, deviceID, args.End, useCursor) + if err != nil { + return nil, BackfillOut{}, err + } } // A completed whole-history walk short-circuits, so re-calling is a no-op. if useCursor && floor == 0 { @@ -291,7 +309,7 @@ func registerArchiveTools(srv *mcp.Server, live *liveSource, writer *store.Write } err = errors.Join(err, fillCoverage(ctx, writer, deviceID, &out)) if err != nil { - return nil, out, err // partial progress is durable; the cursor lets a retry resume + return nil, out, err // Committed rows survive; replaying an explicit window is safe. } if !out.HasMore { if floor > 0 { @@ -300,7 +318,7 @@ func registerArchiveTools(srv *mcp.Server, live *liveSource, writer *store.Write out.Note = "backfill stopped after 15 consecutive days without observations, or at the earliest supported timestamp; older data may exist beyond a long outage" } } else if !useCursor { - out.Note = "this explicit end date does not advance the shared cursor; continue with an earlier end date to fetch an older window" + out.Note = "this explicit end or before_epoch does not advance the shared cursor; pass next_before as before_epoch and repeat the same start and max_days to continue exactly" } return nil, out, nil }) diff --git a/internal/mcpapp/backfill_continuation_test.go b/internal/mcpapp/backfill_continuation_test.go new file mode 100644 index 0000000..ac75165 --- /dev/null +++ b/internal/mcpapp/backfill_continuation_test.go @@ -0,0 +1,192 @@ +package mcpapp + +import ( + "context" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/lennrt/tempestkeep/pkg/tempest/model" + "github.com/lennrt/tempestkeep/pkg/tempest/store" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +func TestBackfillExactContinuationAcrossDST(t *testing.T) { + loc, err := time.LoadLocation("America/Los_Angeles") + if err != nil { + t.Fatal(err) + } + previous := time.Local + time.Local = loc + t.Cleanup(func() { time.Local = previous }) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + start := time.Date(2025, time.November, 2, 0, 0, 0, 0, loc).Unix() + end := time.Date(2025, time.November, 3, 0, 0, 0, 0, loc).Unix() + boundary := end - 86400 // 01:00 on the 25-hour local day. + history := &requestedHistory{epochs: []int64{start, boundary - 1, boundary, end - 1}} + _ = batchTestSource(t, history) + cs := connectWritableServer(t, ctx, "synthetic-token", filepath.Join(t.TempDir(), "archive.sqlite")) + var first BackfillOut + callTool(t, ctx, cs, "backfill_archive", map[string]any{ + "start": "2025-11-02", "end": "2025-11-03", "max_days": 1, + }, &first) + if !first.HasMore || first.NextBefore != boundary || first.RowsAdded != 2 { + t.Fatalf("first batch = %+v, want two observations and cursor %d", first, boundary) + } + var second BackfillOut + callTool(t, ctx, cs, "backfill_archive", map[string]any{ + "start": "2025-11-02", "before_epoch": first.NextBefore, "max_days": 1, + }, &second) + if !strings.Contains(first.Note, "before_epoch") || !strings.Contains(first.Note, "start") || !strings.Contains(first.Note, "max_days") { + t.Fatalf("continuation instructions omit required arguments: %q", first.Note) + } + if second.HasMore || second.NextBefore != 0 || second.RowsAdded != 2 || second.Observations != 4 { + t.Fatalf("final batch = %+v, want all four observations and exact floor completion", second) + } + windows := history.requests() + if len(windows) != 2 || windows[0] != [2]int64{boundary, end - 1} || windows[1] != [2]int64{start, boundary - 1} { + t.Fatalf("non-adjacent or incorrectly bounded requests: %v", windows) + } + var replay BackfillOut + callTool(t, ctx, cs, "backfill_archive", map[string]any{ + "start": "2025-11-02", "before_epoch": first.NextBefore, "max_days": 1, + }, &replay) + if replay.RowsAdded != 0 || replay.Observations != 4 || replay.HasMore { + t.Fatalf("replayed continuation was not idempotent: %+v", replay) + } +} + +func TestBackfillExactContinuationPreservesSharedState(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + const before = int64(1700000123) // Deliberately not a date or minute boundary. + history := &requestedHistory{epochs: []int64{before - 1, before}} + _ = batchTestSource(t, history) + path := filepath.Join(t.TempDir(), "archive.sqlite") + writer, err := store.OpenWriter(ctx, path) + if err != nil { + t.Fatal(err) + } + closeOnCleanup(t, writer) + state := map[string]string{ + metaBackfillCursor: "1690000000", metaBackfillComplete: "1", + metaBackfillEmptySpan: `{"before":1690000000,"empty_seconds":43200}`, + metaSyncCursor: `{"watermark":1690000000,"next":1690000100}`, + } + for key, value := range state { + if err := writer.SetMeta(ctx, key, value); err != nil { + t.Fatal(err) + } + } + cs := connectWritableServer(t, ctx, "synthetic-token", path) + var result BackfillOut + callTool(t, ctx, cs, "backfill_archive", map[string]any{"before_epoch": before, "max_days": 1}, &result) + if !result.HasMore || result.NextBefore != before-86400 || result.RowsAdded != 1 { + t.Fatalf("exact exclusive cursor result = %+v", result) + } + windows := history.requests() + if len(windows) != 1 || windows[0] != [2]int64{before - 86400, before - 1} { + t.Fatalf("requested windows = %v", windows) + } + // Date-based explicit calls must preserve the same state as epoch calls. + callTool(t, ctx, cs, "backfill_archive", map[string]any{"end": "2023-01-03", "max_days": 1}, &result) + for key, want := range state { + got, ok, err := writer.Meta(ctx, key) + if err != nil || !ok || got != want { + t.Errorf("explicit request changed %s: got %q, present=%v, err=%v, want %q", key, got, ok, err, want) + } + } +} + +func TestBackfillExactContinuationRejectsInvalidBeforeIO(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + history := &requestedHistory{} + _ = batchTestSource(t, history) + path := filepath.Join(t.TempDir(), "archive.sqlite") + cs := connectWritableServer(t, ctx, "synthetic-token", path) + start, err := parseLocalDate("2024-01-01") + if err != nil { + t.Fatal(err) + } + for _, args := range []map[string]any{ + {"before_epoch": 0}, {"before_epoch": -1}, {"before_epoch": model.MaxEpochSeconds + 1}, + {"before_epoch": 1.5}, {"before_epoch": "1700000000"}, + {"before_epoch": start.Unix(), "end": "2024-01-02"}, + {"before_epoch": start.Unix(), "start": "2024-01-01"}, + {"before_epoch": start.Unix() - 1, "start": "2024-01-01"}, + {"before_epoch": start.Unix(), "start": "invalid"}, + } { + result, err := cs.CallTool(ctx, &mcp.CallToolParams{Name: "backfill_archive", Arguments: args}) + if err != nil || !result.IsError { + t.Fatalf("args=%v, result=%+v, err=%v", args, result, err) + } + } + if windows := history.requests(); len(windows) != 0 { + t.Fatalf("invalid arguments fetched observations: %v", windows) + } + history.mu.Lock() + stationRequests := history.stationRequests + history.mu.Unlock() + if stationRequests != 0 { + t.Fatalf("invalid arguments made %d discovery requests", stationRequests) + } + st, err := store.Open(ctx, path) + if err != nil { + t.Fatal(err) + } + closeOnCleanup(t, st) + if _, exists, err := st.Meta(ctx, "archive_device_id"); err != nil || exists { + t.Fatalf("invalid arguments bound the archive: exists=%v, err=%v", exists, err) + } +} + +func TestBackfillExactContinuationReplaysAfterPartialFailure(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + start, err := parseLocalDate("2023-01-01") + if err != nil { + t.Fatal(err) + } + before := start.Unix() + 10*86400 + history := &requestedHistory{ + epochs: []int64{start.Unix(), before - 1}, + failAt: start.Unix(), // The second five-day chunk fails. + } + _ = batchTestSource(t, history) + path := filepath.Join(t.TempDir(), "archive.sqlite") + cs := connectWritableServer(t, ctx, "synthetic-token", path) + args := map[string]any{"start": "2023-01-01", "before_epoch": before, "max_days": 10} + failed, err := cs.CallTool(ctx, &mcp.CallToolParams{Name: "backfill_archive", Arguments: args}) + if err != nil || !failed.IsError { + t.Fatalf("partial request should fail: result=%+v, err=%v", failed, err) + } + st, err := store.Open(ctx, path) + if err != nil { + t.Fatal(err) + } + closeOnCleanup(t, st) + cov, err := st.Coverage(ctx) + if err != nil || cov.Count != 1 { + t.Fatalf("first chunk was not durable: coverage=%+v, err=%v", cov, err) + } + history.mu.Lock() + history.failAt = 0 + history.mu.Unlock() + var retried BackfillOut + callTool(t, ctx, cs, "backfill_archive", args, &retried) + if retried.HasMore || retried.RowsAdded != 1 || retried.Observations != 2 { + t.Fatalf("retry did not complete the range safely: %+v", retried) + } + windows := history.requests() + if len(windows) != 4 || windows[0] != windows[2] || windows[1] != windows[3] { + t.Fatalf("retry did not replay the failed explicit window: %v", windows) + } + for _, key := range []string{metaBackfillCursor, metaBackfillComplete, metaBackfillEmptySpan, metaSyncCursor} { + if _, exists, err := st.Meta(ctx, key); err != nil || exists { + t.Errorf("explicit request created %s: exists=%v, err=%v", key, exists, err) + } + } +} diff --git a/internal/mcpapp/device_selection_test.go b/internal/mcpapp/device_selection_test.go new file mode 100644 index 0000000..52f29d7 --- /dev/null +++ b/internal/mcpapp/device_selection_test.go @@ -0,0 +1,373 @@ +package mcpapp + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/lennrt/tempestkeep/pkg/tempest/api" + "github.com/lennrt/tempestkeep/pkg/tempest/model" + "github.com/lennrt/tempestkeep/pkg/tempest/store" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +func selectionStations() []api.Station { + return []api.Station{ + {StationID: 123, Name: "First station", Devices: []api.Device{{DeviceID: 456, DeviceType: "ST"}, {DeviceID: 457, DeviceType: "ST"}, {DeviceID: 458, DeviceType: "HB"}}}, + {StationID: 789, Name: "Second station", Devices: []api.Device{{DeviceID: 777, DeviceType: "ST"}}}, + } +} + +func selectionClient(t *testing.T, handler http.HandlerFunc) *api.Client { + t.Helper() + server := httptest.NewServer(handler) + t.Cleanup(server.Close) + client, err := api.New("synthetic-selection-token", api.WithBaseURL(server.URL), api.WithCacheTTL(0)) + if err != nil { + t.Fatal(err) + } + return client +} + +// Use Run rather than manually constructing liveSource, so the tests cover +// resolved Options, lazy startup, capability registration and archive ownership. +func connectSelectedServer(t *testing.T, options Options) *mcp.ClientSession { + t.Helper() + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + serverTransport, clientTransport := mcp.NewInMemoryTransports() + options.Transport = serverTransport + done := make(chan error, 1) + go func() { done <- Run(ctx, options) }() + t.Cleanup(func() { + cancel() + select { + case err := <-done: + if err != nil && !errors.Is(err, context.Canceled) { + t.Errorf("stop selected server: %v", err) + } + case <-time.After(3 * time.Second): + t.Error("selected server did not stop") + } + }) + client, err := mcp.NewClient(&mcp.Implementation{Name: "device-selection", Version: "test"}, nil).Connect(ctx, clientTransport, nil) + if err != nil { + t.Fatal(err) + } + closeOnCleanup(t, client) + return client +} + +func TestMCPSelectedDeviceControlsDefaultStationAndCollection(t *testing.T) { + t.Setenv("TEMPEST_THROTTLE_MS", "0") + for _, tc := range []struct { + name string + selected, device, sid int + }{ + {"automatic", 0, 456, 123}, + {"second station", 777, 777, 789}, + {"second Tempest in same station", 457, 457, 123}, + } { + t.Run(tc.name, func(t *testing.T) { + var requests, discovery, deviceCalls atomic.Int32 + client := selectionClient(t, func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + w.Header().Set("Content-Type", "application/json") + switch { + case r.URL.Path == "/stations": + discovery.Add(1) + _ = json.NewEncoder(w).Encode(map[string]any{"stations": selectionStations()}) + case strings.HasPrefix(r.URL.Path, "/observations/station/"): + if r.URL.Path != "/observations/station/"+strconv.Itoa(tc.sid) { + t.Errorf("wrong default live station: %s", r.URL.Path) + } + _ = json.NewEncoder(w).Encode(map[string]any{"obs": []api.StationObs{{Timestamp: 1700000000, AirTemperature: new(20.0)}}}) + case r.URL.Path == "/better_forecast": + if id := r.URL.Query().Get("station_id"); id != "123" && id != strconv.Itoa(tc.sid) { + t.Errorf("wrong forecast station: %s", id) + } + _ = json.NewEncoder(w).Encode(api.Forecast{CurrentConditions: api.ForecastCurrent{Time: 1700000000}}) + case strings.HasPrefix(r.URL.Path, "/observations/device/"): + deviceCalls.Add(1) + if r.URL.Path != "/observations/device/"+strconv.Itoa(tc.device) { + t.Errorf("collected from wrong device: %s", r.URL.Path) + } + epoch, _ := strconv.ParseInt(r.URL.Query().Get("time_start"), 10, 64) + writeObs(w, []int64{epoch}) + default: + http.NotFound(w, r) + } + }) + path := filepath.Join(t.TempDir(), "selected.sqlite") + cs := connectSelectedServer(t, Options{Client: client, DBPath: path, DeviceID: tc.selected}) + if _, err := cs.ListTools(t.Context(), nil); err != nil { + t.Fatal(err) + } + if requests.Load() != 0 { + t.Fatal("startup or discovery contacted the API") + } + var conditions ConditionsOut + callTool(t, t.Context(), cs, "current_conditions", nil, &conditions) + wantName := "First station" + if tc.sid == 789 { + wantName = "Second station" + } + if conditions.Source != "live" || conditions.Station != wantName { + t.Fatalf("default conditions = %+v", conditions) + } + var overridden ForecastOut + callTool(t, t.Context(), cs, "forecast", map[string]any{"station_id": 123}, &overridden) + if overridden.Station != "First station" { + t.Fatalf("explicit station was ignored: %+v", overridden) + } + var explicit StationDetailsOut + callTool(t, t.Context(), cs, "station_details", map[string]any{"station_id": 123}, &explicit) + if explicit.StationID != 123 { + t.Fatalf("explicit station details = %+v", explicit) + } + beforeDefault := discovery.Load() + var details StationDetailsOut + callTool(t, t.Context(), cs, "station_details", nil, &details) + var forecast ForecastOut + callTool(t, t.Context(), cs, "forecast", nil, &forecast) + if details.StationID != tc.sid || forecast.Station != wantName || discovery.Load() != beforeDefault { + t.Fatalf("override changed cached default: details=%+v forecast=%+v", details, forecast) + } + var backfill BackfillOut + callTool(t, t.Context(), cs, "backfill_archive", map[string]any{"start": "2025-01-01", "end": "2025-01-02", "max_days": 1}, &backfill) + if backfill.RowsAdded != 1 || deviceCalls.Load() != 1 { + t.Fatalf("selected backfill = %+v, calls=%d", backfill, deviceCalls.Load()) + } + st, err := store.Open(t.Context(), path) + if err != nil { + t.Fatal(err) + } + closeOnCleanup(t, st) + if err := st.EachArchiveObs(t.Context(), 0, 1800000000, func(o store.ArchiveObs) error { + if o.DeviceID == nil || *o.DeviceID != int64(tc.device) { + t.Fatalf("archive contains wrong device: %+v", o.DeviceID) + } + return nil + }); err != nil { + t.Fatal(err) + } + var info StationInfoOut + callTool(t, t.Context(), cs, "station_info", nil, &info) + if info.StationID != tc.sid || info.Name != wantName { + t.Fatalf("selected archive label = %+v", info) + } + }) + } +} + +func TestMCPDeviceSelectionFailuresDoNotWriteAndCanRetry(t *testing.T) { + t.Setenv("TEMPEST_THROTTLE_MS", "0") + for _, failure := range []string{"unknown", "hub", "empty stations", "unavailable"} { + t.Run(failure, func(t *testing.T) { + var ready atomic.Bool + var deviceCalls atomic.Int32 + const selected = 999 + client := selectionClient(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if r.URL.Path == "/stations" { + stations := selectionStations() + if ready.Load() { + stations[1].Devices = []api.Device{{DeviceID: selected, DeviceType: "ST"}} + } else { + switch failure { + case "hub": + stations[1].Devices = []api.Device{{DeviceID: selected, DeviceType: "HB"}} + case "empty stations": + stations = []api.Station{} + case "unavailable": + w.WriteHeader(http.StatusUnauthorized) + return + } + } + _ = json.NewEncoder(w).Encode(map[string]any{"stations": stations}) + return + } + if strings.HasPrefix(r.URL.Path, "/observations/device/") { + deviceCalls.Add(1) + if r.URL.Path != "/observations/device/999" { + t.Errorf("retried wrong device: %s", r.URL.Path) + } + epoch, _ := strconv.ParseInt(r.URL.Query().Get("time_start"), 10, 64) + writeObs(w, []int64{epoch}) + return + } + http.NotFound(w, r) + }) + path := filepath.Join(t.TempDir(), "unbound.sqlite") + cs := connectSelectedServer(t, Options{Client: client, DBPath: path, DeviceID: selected}) + st, err := store.Open(t.Context(), path) + if err != nil { + t.Fatal(err) + } + closeOnCleanup(t, st) + before := selectionArchiveState(t, st) + for _, tool := range []string{"backfill_archive", "sync_archive"} { + result, err := cs.CallTool(t.Context(), &mcp.CallToolParams{Name: tool}) + if err != nil || !result.IsError { + t.Fatalf("%s with failed selection: result=%+v error=%v", tool, result, err) + } + } + if after := selectionArchiveState(t, st); !reflect.DeepEqual(after, before) || deviceCalls.Load() != 0 { + t.Fatalf("failed selection changed archive or fetched observations: before=%v after=%v calls=%d", before, after, deviceCalls.Load()) + } + if failure != "unavailable" { + var stations StationsOut + callTool(t, t.Context(), cs, "list_stations", nil, &stations) + } + ready.Store(true) + var backfill BackfillOut + callTool(t, t.Context(), cs, "backfill_archive", map[string]any{"start": "2025-01-01", "end": "2025-01-02", "max_days": 1}, &backfill) + if backfill.RowsAdded != 1 || deviceCalls.Load() != 1 { + t.Fatalf("selection failure was cached: %+v calls=%d", backfill, deviceCalls.Load()) + } + }) + } +} + +func selectionArchiveState(t *testing.T, st *store.Store) []store.QueryResult { + t.Helper() + var state []store.QueryResult + for _, sql := range []string{"SELECT device_id, epoch FROM obs_st ORDER BY epoch", "SELECT key,value FROM meta ORDER BY key"} { + result, err := st.Query(t.Context(), sql, 100) + if err != nil { + t.Fatal(err) + } + state = append(state, result) + } + return state +} + +func TestMCPSelectedDevicePreservesArchiveIdentityAndOfflineReads(t *testing.T) { + for _, tc := range []struct { + name string + selected int + live bool + }{ + {"different station", 777, true}, + {"unknown selected device", 999, true}, + {"archive only", 777, false}, + } { + t.Run(tc.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "existing.sqlite") + writer, err := store.OpenWriter(t.Context(), path) + if err != nil { + t.Fatal(err) + } + _, insertErr := writer.InsertObs(t.Context(), 456, []model.DeviceObs{ + {Epoch: 1700000000 - 3*3600, PressureMb: new(1018.0)}, + {Epoch: 1700000000, PressureMb: new(1012.0), AirTempC: new(10.0)}, + }) + if err := errors.Join(insertErr, writer.Close()); err != nil { + t.Fatal(err) + } + var deviceCalls atomic.Int32 + options := Options{DeviceID: tc.selected, DBPath: path} + if tc.live { + options.Client = selectionClient(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case r.URL.Path == "/stations": + _ = json.NewEncoder(w).Encode(map[string]any{"stations": selectionStations()}) + case r.URL.Path == "/observations/station/789": + _ = json.NewEncoder(w).Encode(map[string]any{"obs": []api.StationObs{{Timestamp: 1700000000, AirTemperature: new(20.0)}}}) + case strings.HasPrefix(r.URL.Path, "/observations/device/"): + deviceCalls.Add(1) + writeObs(w, nil) + default: + http.NotFound(w, r) + } + }) + } + cs := connectSelectedServer(t, options) + st, err := store.Open(t.Context(), path) + if err != nil { + t.Fatal(err) + } + closeOnCleanup(t, st) + before := selectionArchiveState(t, st) + var info StationInfoOut + callTool(t, t.Context(), cs, "station_info", nil, &info) + if info.Name != "" || info.StationID != 0 || info.Observations != 2 { + t.Fatalf("mislabeled archive: %+v", info) + } + var conditions ConditionsOut + callTool(t, t.Context(), cs, "current_conditions", nil, &conditions) + if tc.live && tc.selected == 777 { + if conditions.Source != "live" || conditions.Station != "Second station" || conditions.PressureTrend3hInHg != nil { + t.Fatalf("mismatched source enrichment: %+v", conditions) + } + } else if conditions.Source != "archive" || conditions.Station != "" || conditions.TempC == nil || *conditions.TempC != 10 { + t.Fatalf("archive fallback unavailable or mislabeled: %+v", conditions) + } + if tc.live { + for _, tool := range []string{"backfill_archive", "sync_archive"} { + result, err := cs.CallTool(t.Context(), &mcp.CallToolParams{Name: tool}) + if err != nil || !result.IsError { + t.Fatalf("%s accepted wrong archive device: result=%+v error=%v", tool, result, err) + } + } + } + if after := selectionArchiveState(t, st); !reflect.DeepEqual(after, before) || deviceCalls.Load() != 0 { + t.Fatalf("failed selection/mismatch changed archive: before=%v after=%v calls=%d", before, after, deviceCalls.Load()) + } + }) + } +} + +func TestSelectedDeviceResolutionCancellationAndConcurrency(t *testing.T) { + var requests atomic.Int32 + client := selectionClient(t, func(w http.ResponseWriter, _ *http.Request) { + requests.Add(1) + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"stations": selectionStations()}) + }) + live := &liveSource{client: client, selectedDeviceID: 777} + canceled, cancel := context.WithCancel(t.Context()) + cancel() + if _, err := live.resolveStation(canceled); !errors.Is(err, context.Canceled) || requests.Load() != 0 { + t.Fatalf("canceled resolution: error=%v requests=%d", err, requests.Load()) + } + var wg sync.WaitGroup + for range 8 { + wg.Go(func() { + device, err := live.resolveDevice(t.Context()) + if err != nil || device != 777 { + t.Errorf("concurrent resolution: device=%d error=%v", device, err) + } + }) + } + wg.Wait() + before := requests.Load() + if _, err := live.resolveStation(canceled); !errors.Is(err, context.Canceled) { + t.Fatalf("cached resolution ignored cancellation: %v", err) + } + station, err := live.resolveStation(t.Context()) + if err != nil || station.StationID != 789 || requests.Load() != before { + t.Fatalf("successful resolution was not cached: station=%+v error=%v", station, err) + } +} + +func TestRunRejectsNegativeDeviceBeforeArchiveInitialization(t *testing.T) { + path := filepath.Join(t.TempDir(), "must-not-exist.sqlite") + if err := Run(t.Context(), Options{DeviceID: -1, DBPath: path}); err == nil || !strings.Contains(err.Error(), "device id") { + t.Fatalf("negative option: %v", err) + } + if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("negative option initialized archive: %v", err) + } +} diff --git a/internal/mcpapp/history.go b/internal/mcpapp/history.go index f43c061..bea9f82 100644 --- a/internal/mcpapp/history.go +++ b/internal/mcpapp/history.go @@ -399,7 +399,7 @@ func registerCalendarTools(srv *mcp.Server, st *store.Store) { addAppTool(srv, &mcp.Tool{ Name: "get_observations", Title: "Observation series (downsampled)", - Description: "Return a bounded, downsampled observation series. Values use °F, inHg, mph, and inches. The default range is 24 hours. max_points defaults to 288 and cannot exceed 2000.", + Description: "Return a bounded, downsampled observation series. Values use °F, inHg, mph, and inches. rain_readings and lightning_readings count available event samples: zero means unknown, and a count below obs means partial coverage. The default range is 24 hours. max_points defaults to 288 and cannot exceed 2000.", Annotations: &mcp.ToolAnnotations{ReadOnlyHint: true, OpenWorldHint: new(false)}, }, func(ctx context.Context, _ *mcp.CallToolRequest, args GetObservationsArgs) (*mcp.CallToolResult, GetObservationsOut, error) { maxPoints, err := optionalBoundedInt(args.MaxPoints, 288, 2000, "max_points") @@ -443,6 +443,15 @@ func registerCalendarTools(srv *mcp.Server, st *store.Store) { // resolution isn't silently coarser than what it asked for. out.Note = fmt.Sprintf("requested bucket_minutes was too fine for this range; widened to %d to stay under the point cap", bucket/60) } + for _, point := range points { + if point.RainReadings < point.Obs || point.LightningReadings < point.Obs { + if out.Note != "" { + out.Note += "; " + } + out.Note += "incomplete rain or lightning coverage: check rain_readings and lightning_readings against obs; a zero reading count means the total is unknown" + break + } + } return nil, out, nil }) @@ -466,7 +475,7 @@ func registerCalendarTools(srv *mcp.Server, st *store.Store) { addAppTool(srv, &mcp.Tool{ Name: "rain_stats", Title: "Rainfall statistics", - Description: "Return rain totals, rainy days, the wettest day, and the longest dry and wet spells. Coverage gaps end a spell. The default range is the full archive.", + Description: "Return recorded rain totals, rainy days, the wettest day, and observed dry and wet spells. total_in is null without rain readings. rain_readings and observations describe sample coverage; partial totals include only reported readings. Gaps and days without rain readings end spells. The default range is the full archive.", Annotations: &mcp.ToolAnnotations{ReadOnlyHint: true, OpenWorldHint: new(false)}, }, func(ctx context.Context, _ *mcp.CallToolRequest, args RainStatsArgs) (*mcp.CallToolResult, RainStatsOut, error) { start, end, err := resolveOptionalRange(args.Start, args.End, 0) @@ -481,8 +490,13 @@ func registerCalendarTools(srv *mcp.Server, st *store.Store) { if start > 0 { out.From = localDate(start) } - if rs.DaysObserved == 0 { + switch { + case rs.Observations == 0: out.Note = "no observations in this range" + case rs.RainReadings == 0: + out.Note = "no rain readings in this range; rainfall is unknown, not measured zero" + case rs.RainReadings < rs.Observations: + out.Note = "partial rain coverage: total and observed spells use reported readings only; sample counts do not establish continuous coverage" } return nil, out, nil }) @@ -492,7 +506,7 @@ func registerClimateTools(srv *mcp.Server, st *store.Store) { addAppTool(srv, &mcp.Tool{ Name: "pressure_trend", Title: "Barometric tendency", - Description: "Return the change in station pressure over a trailing window. The default is 3 hours. The accepted range is 1 second through 24 hours.", + Description: "Compare the latest station pressure with the nearest eligible earlier reading to the window start. Samples must be at least half the window apart. Return the actual span, change, and normalized three-hour rate. The default is 3 hours; the accepted range is 1 second through 24 hours.", Annotations: &mcp.ToolAnnotations{ReadOnlyHint: true, OpenWorldHint: new(false)}, }, func(ctx context.Context, _ *mcp.CallToolRequest, args PressureTrendArgs) (*mcp.CallToolResult, PressureTrendOut, error) { windowHours := args.WindowHours @@ -798,7 +812,7 @@ func registerTrendAndQueryTools(srv *mcp.Server, st *store.Store) { addAppTool(srv, &mcp.Tool{ Name: "temperature_trend", Title: "Warming / cooling trend", - Description: "Fit a temperature trend from monthly anomalies across the full archive. Results include °F per decade, R², and the largest anomalies. A short archive returns no slope.", + Description: "Fit a common temperature trend with separate calendar-month baselines and equal weight per monthly mean. Results include °F per decade, within-month R², and the largest anomalies. A slope needs a repeated calendar month. Flat repeated readings return zero slope without R².", Annotations: &mcp.ToolAnnotations{ReadOnlyHint: true, OpenWorldHint: new(false)}, }, func(ctx context.Context, _ *mcp.CallToolRequest, _ NoArgs) (*mcp.CallToolResult, TemperatureTrendOut, error) { tt, err := st.TemperatureTrend(ctx) diff --git a/internal/mcpapp/rain_coverage_test.go b/internal/mcpapp/rain_coverage_test.go new file mode 100644 index 0000000..8c23445 --- /dev/null +++ b/internal/mcpapp/rain_coverage_test.go @@ -0,0 +1,131 @@ +package mcpapp + +import ( + "encoding/json" + "errors" + "math" + "path/filepath" + "reflect" + "slices" + "strings" + "testing" + "time" + + "github.com/lennrt/tempestkeep/pkg/tempest/model" + "github.com/lennrt/tempestkeep/pkg/tempest/store" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +func TestRainStatsSchemaAndCoverage(t *testing.T) { + for _, tc := range []struct { + name string + rain []*float64 + readings int + total *float64 + note string + }{ + {"empty", nil, 0, nil, "no observations"}, + {"missing", []*float64{nil, nil}, 0, nil, "no rain readings"}, + {"measured zero", []*float64{new(0.0), new(0.0)}, 2, new(0.0), ""}, + {"partial zero", []*float64{new(0.0), nil}, 1, new(0.0), "partial rain coverage"}, + {"partial positive", []*float64{new(25.4), nil}, 1, new(1.0), "partial rain coverage"}, + {"reported positive", []*float64{new(25.4), new(12.7)}, 2, new(1.5), ""}, + } { + t.Run(tc.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "archive.sqlite") + writer, err := store.OpenWriter(t.Context(), path) + if err != nil { + t.Fatal(err) + } + base := time.Date(2025, time.June, 1, 12, 0, 0, 0, time.Local) + rows := []model.DeviceObs{ + {Epoch: base.AddDate(0, 0, -1).Unix(), RainMm: new(100.0)}, + {Epoch: base.AddDate(0, 0, 1).Unix(), RainMm: new(100.0)}, + } + for i, rain := range tc.rain { + rows = append(rows, model.DeviceObs{Epoch: base.Unix() + int64(i*60), RainMm: rain}) + } + _, insertErr := writer.InsertObs(t.Context(), 456, rows) + if err := errors.Join(insertErr, writer.Close()); err != nil { + t.Fatal(err) + } + cs := connectArchiveServer(t, t.Context(), path) + listed, err := cs.ListTools(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + found := false + for _, tool := range listed.Tools { + if tool.Name != "rain_stats" { + continue + } + found = true + encoded, err := json.Marshal(tool.OutputSchema) + if err != nil { + t.Fatal(err) + } + var schema struct { + Properties map[string]json.RawMessage `json:"properties"` + Required []string `json:"required"` + } + if err := json.Unmarshal(encoded, &schema); err != nil { + t.Fatal(err) + } + var totalSchema struct { + Types []string `json:"type"` + } + if err := json.Unmarshal(schema.Properties["total_in"], &totalSchema); err != nil { + t.Fatalf("nullable total schema: %s: %v", encoded, err) + } + if !slices.Contains(totalSchema.Types, "null") || !slices.Contains(totalSchema.Types, "number") { + t.Fatalf("total schema must permit number and null: %s", encoded) + } + for _, name := range []string{"total_in", "observations", "rain_readings"} { + if !slices.Contains(schema.Required, name) { + t.Fatalf("%s missing from required schema fields: %s", name, encoded) + } + } + } + if !found { + t.Fatal("rain_stats tool absent") + } + result, err := cs.CallTool(t.Context(), &mcp.CallToolParams{Name: "rain_stats", Arguments: map[string]any{"start": "2025-06-01", "end": "2025-06-01"}}) + if err != nil || result.IsError { + t.Fatalf("rain call: error=%v result=%+v", err, result) + } + var structured map[string]any + decodeStructured(t, result, &structured) + value, exists := structured["total_in"] + if !exists || (tc.total == nil && value != nil) { + t.Fatalf("missing total must be explicit null: %+v", structured) + } + if tc.total != nil { + got, numeric := value.(float64) + if !numeric || math.Abs(got-*tc.total) > 1e-9 { + t.Fatalf("total=%v, want%v", value, *tc.total) + } + } + if structured["observations"] != float64(len(tc.rain)) || structured["rain_readings"] != float64(tc.readings) { + t.Fatalf("wrong range sample counts: %+v", structured) + } + note, _ := structured["note"].(string) + if tc.note == "" && note != "" || tc.note != "" && !strings.Contains(note, tc.note) { + t.Fatalf("coverage note=%q, want%q", note, tc.note) + } + if len(result.Content) != 1 { + t.Fatalf("expected one ordinary result: %+v", result.Content) + } + plain, ok := result.Content[0].(*mcp.TextContent) + if !ok { + t.Fatal("ordinary MCP content is not text") + } + var textResult map[string]any + if err := json.Unmarshal([]byte(plain.Text), &textResult); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(structured, textResult) { + t.Fatalf("ordinary/structured rain results differ: %s / %+v", plain.Text, structured) + } + }) + } +} diff --git a/internal/mcpapp/resources.go b/internal/mcpapp/resources.go index d6e39ba..74b4e44 100644 --- a/internal/mcpapp/resources.go +++ b/internal/mcpapp/resources.go @@ -195,15 +195,17 @@ and what the trend suggests. Cite the numbers you used.` are absent, explain that this server has read-only archive access and that tempestkeep collect can populate the archive outside this session. 2. If history is missing, call backfill_archive repeatedly until has_more is - false; omit end to resume the saved cursor between calls. + false. Omit both end and before_epoch to resume the saved cursor between calls. Report progress as you go (rows added, coverage so far). Completion uses an empty-history heuristic; older observations can exist beyond a long outage. Use explicit start and exclusive end dates for a known gap. 3. If observations exist, call sync_archive to fetch newer rows. Repeat while has_more is true. An empty archive needs backfill_archive first. 4. Finish with archive_status and summarize: total observations, date span, - freshness, and remaining gaps. An explicit end does not advance the shared - cursor; do not repeat the same explicit range expecting it to move backward. + freshness, and remaining gaps. An explicit end or before_epoch does not + advance the shared cursor. If an explicit call returns has_more, pass its + next_before as before_epoch and repeat start and max_days. Omit end on that + continuation. After an error, repeat the failed explicit request instead. Committed observations use INSERT OR IGNORE. Replaying a chunk does not add duplicate rows; repeated calls can still fetch older or newer windows.`}, diff --git a/internal/mcpapp/series_coverage_test.go b/internal/mcpapp/series_coverage_test.go new file mode 100644 index 0000000..7c49383 --- /dev/null +++ b/internal/mcpapp/series_coverage_test.go @@ -0,0 +1,77 @@ +package mcpapp + +import ( + "path/filepath" + "strings" + "testing" + "time" + + "github.com/lennrt/tempestkeep/pkg/tempest/model" + "github.com/lennrt/tempestkeep/pkg/tempest/store" +) + +func TestObservationSeriesReportsEventCoverage(t *testing.T) { + for _, complete := range []bool{false, true} { + name := "missing and partial" + if complete { + name = "measured zero" + } + t.Run(name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "archive.sqlite") + writer, err := store.OpenWriter(t.Context(), path) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + if err := writer.Close(); err != nil { + t.Error(err) + } + }) + base := time.Date(2024, time.January, 1, 12, 0, 0, 0, time.Local).Unix() + observations := []model.DeviceObs{ + {Epoch: base, AirTempC: new(10.0)}, + {Epoch: base + 300, RainMm: new(0.0), StrikeCount: new(0.0)}, + {Epoch: base + 360, RainMm: new(2.54)}, + } + if complete { + for i := range observations { + observations[i].RainMm = new(0.0) + observations[i].StrikeCount = new(0.0) + } + } + if _, err := writer.InsertObs(t.Context(), 456, observations); err != nil { + t.Fatal(err) + } + cs := connectArchiveServer(t, t.Context(), path) + var out GetObservationsOut + callTool(t, t.Context(), cs, "get_observations", map[string]any{ + "start": "2024-01-01", "end": "2024-01-01", "bucket_minutes": 5, + }, &out) + if len(out.Points) != 2 { + t.Fatalf("points = %+v, want 2", out.Points) + } + first, second := out.Points[0], out.Points[1] + if complete { + if first.RainReadings != 1 || first.LightningReadings != 1 || second.RainReadings != 2 || second.LightningReadings != 2 || out.Note != "" { + t.Fatalf("complete zero readings lost coverage: %+v", out) + } + } else if first.RainReadings != 0 || first.LightningReadings != 0 || second.RainReadings != 2 || second.LightningReadings != 1 || second.Obs != 2 || !strings.Contains(out.Note, "incomplete rain or lightning coverage") { + t.Fatalf("missing/partial readings lost coverage: %+v", out) + } + if first.RainIn != 0 || first.Strikes != 0 || second.Strikes != 0 { + t.Fatalf("numeric zero compatibility lost: %+v", out) + } + if !complete && second.RainIn != model.MmToInch(2.54) { + t.Fatalf("available rain total = %v, want %v", second.RainIn, model.MmToInch(2.54)) + } + if !complete { + callTool(t, t.Context(), cs, "get_observations", map[string]any{ + "start": "2024-01-01", "end": "2024-01-03", "bucket_minutes": 1, + }, &out) + if !strings.Contains(out.Note, "requested bucket_minutes was too fine") || !strings.Contains(out.Note, "incomplete rain or lightning coverage") { + t.Fatalf("resolution and coverage notices must coexist: %q", out.Note) + } + } + }) + } +} diff --git a/internal/mcpapp/server.go b/internal/mcpapp/server.go index 111d9b2..c0c2cf7 100644 --- a/internal/mcpapp/server.go +++ b/internal/mcpapp/server.go @@ -32,6 +32,11 @@ type Options struct { DBPath string ReadOnly bool + // DeviceID selects an accessible Tempest (ST) device and its default station. + // Zero preserves automatic discovery. Resolution is lazy; without a live + // client this option does not restrict archive-only reads. + DeviceID int + // Transport carries the JSON-RPC session. A nil Transport means stdio, // which is what the tempestkeep command uses. Tests supply an in-memory // transport from mcp.NewInMemoryTransports so the whole server, including @@ -44,6 +49,9 @@ func Run(ctx context.Context, opts Options) (err error) { if err := ctx.Err(); err != nil { return err } + if opts.DeviceID < 0 { + return fmt.Errorf("device id must be zero for discovery or positive") + } var ( live *liveSource @@ -59,7 +67,7 @@ func Run(ctx context.Context, opts Options) (err error) { } } if client != nil { - live = &liveSource{client: client} + live = &liveSource{client: client, selectedDeviceID: opts.DeviceID} } // Open the writer first. It creates the schema before the read handle opens. @@ -147,15 +155,19 @@ func readOnlyNote(readOnly bool) string { // liveSource resolves and caches one station and device. Failed lookups are not // cached, so later calls can retry. type liveSource struct { - client *api.Client - mu sync.Mutex - station *api.Station - deviceID int + client *api.Client + selectedDeviceID int // Immutable configuration; zero means automatic discovery. + mu sync.Mutex + station *api.Station + deviceID int } // resolveStation returns the cached station or resolves it. It is safe for // concurrent use. It caches only successful results. func (l *liveSource) resolveStation(ctx context.Context) (*api.Station, error) { + if err := ctx.Err(); err != nil { + return nil, err + } l.mu.Lock() if l.station != nil { station := l.station @@ -168,9 +180,9 @@ func (l *liveSource) resolveStation(ctx context.Context) (*api.Station, error) { if err != nil { return nil, err } - s, deviceID, ok := api.PickTempestDevice(stations) - if !ok { - return nil, fmt.Errorf("no stations found for this token") + s, deviceID, err := selectLiveDevice(stations, l.selectedDeviceID) + if err != nil { + return nil, err } l.mu.Lock() if l.station == nil { @@ -183,6 +195,28 @@ func (l *liveSource) resolveStation(ctx context.Context) (*api.Station, error) { return station, nil } +func selectLiveDevice(stations []api.Station, selected int) (*api.Station, int, error) { + if selected == 0 { + station, deviceID, ok := api.PickTempestDevice(stations) + if !ok { + return nil, 0, fmt.Errorf("no stations found for this token") + } + return station, deviceID, nil + } + for i := range stations { + for _, device := range stations[i].Devices { + if device.DeviceID != selected { + continue + } + if device.DeviceType != "ST" { + return nil, 0, fmt.Errorf("configured device is not a Tempest (ST) device") + } + return &stations[i], selected, nil + } + } + return nil, 0, fmt.Errorf("configured Tempest device not found for this token") +} + // resolveDevice returns the device id whose history the archive tools collect, // resolving the station first if needed. func (l *liveSource) resolveDevice(ctx context.Context) (int, error) { diff --git a/internal/mcpapp/source_identity_test.go b/internal/mcpapp/source_identity_test.go index 8966dc6..947115d 100644 --- a/internal/mcpapp/source_identity_test.go +++ b/internal/mcpapp/source_identity_test.go @@ -112,7 +112,9 @@ func TestCurrentConditionsArchivePressureFreshnessAndRate(t *testing.T) { pressureSpan, latestDelay int64 wantRate bool }{ - {name: "too little history", pressureSpan: 3*3600 - 1}, + {name: "too little history", pressureSpan: 3*3600/2 - 1}, + {name: "exact half window", pressureSpan: 3 * 3600 / 2, wantRate: true}, + {name: "short two hours", pressureSpan: 2 * 3600, wantRate: true}, {name: "exact three hours", pressureSpan: 3 * 3600, wantRate: true}, {name: "sparse six hours", pressureSpan: 6 * 3600, wantRate: true}, {name: "recent pressure", pressureSpan: 3 * 3600, latestDelay: 3599, wantRate: true}, @@ -156,7 +158,7 @@ func TestCurrentConditionsArchivePressureFreshnessAndRate(t *testing.T) { } // The dedicated historical tool retains the actual span and delta, // even when this trend cannot enrich the latest conditions response. - if tc.pressureSpan >= 3*3600 { + if tc.pressureSpan >= 3*3600/2 { var history PressureTrendOut callTool(t, t.Context(), cs, "pressure_trend", nil, &history) if history.At != pressureAt || math.Abs(history.ChangeInHg-model.MbToInHg(-6)) > 1e-9 { @@ -166,3 +168,39 @@ func TestCurrentConditionsArchivePressureFreshnessAndRate(t *testing.T) { }) } } + +func TestArchivePressureUsesNearestEligibleReading(t *testing.T) { + const latest = int64(1700000000) + path := filepath.Join(t.TempDir(), "archive.sqlite") + writer, err := store.OpenWriter(t.Context(), path) + if err != nil { + t.Fatal(err) + } + closeOnCleanup(t, writer) + if _, err := writer.InsertObs(t.Context(), 456, []model.DeviceObs{ + {Epoch: latest - 14400, PressureMb: new(1000.0)}, + {Epoch: latest - 10740, PressureMb: new(1010.0)}, + {Epoch: latest, PressureMb: new(1004.0), AirTempC: new(20.0)}, + }); err != nil { + t.Fatal(err) + } + if err := writer.Close(); err != nil { + t.Fatal(err) + } + cs := connectArchiveServer(t, t.Context(), path) + var conditions ConditionsOut + callTool(t, t.Context(), cs, "current_conditions", nil, &conditions) + wantRate := -6.0 * 10800 / 10740 + if conditions.PressureTrend != "falling rapidly" || conditions.PressureTrend3hInHg == nil || + math.Abs(*conditions.PressureTrend3hInHg-model.MbToInHg(wantRate)) > 1e-9 { + t.Fatalf("nearest pressure did not control current conditions: %+v", conditions) + } + var history PressureTrendOut + callTool(t, t.Context(), cs, "pressure_trend", nil, &history) + if history.Category != "falling rapidly" || history.At != latest || + math.Abs(history.WindowHours-10740.0/3600) > 1e-12 || + math.Abs(history.ChangeInHg-model.MbToInHg(-6)) > 1e-9 || + math.Abs(history.ChangeMbPer3h-wantRate) > 1e-9 { + t.Fatalf("nearest pressure history lost its actual span or normalized rate: %+v", history) + } +} diff --git a/internal/mcpapp/ui/app.html b/internal/mcpapp/ui/app.html index daf48c9..791807a 100644 --- a/internal/mcpapp/ui/app.html +++ b/internal/mcpapp/ui/app.html @@ -11,6 +11,7 @@ @media(max-width:740px){#app{padding:0 20px 18px}.topbar{min-height:66px;gap:12px}.edition{display:none}.heading{padding:22px 0 20px}h1{font-size:26px}.hero{gap:15px;padding:23px}.hero-value{font-size:30px}.hero-stat{padding-left:15px}.hero-stat .hero-value{font-size:22px}.metrics{gap:10px;grid-template-columns:repeat(2,minmax(0,1fr))}.metric{padding:15px 16px}.wind-layout{gap:10px;padding:15px}.table-tools{padding:14px}.panel-head{padding:17px 16px 0}.chart-wrap{padding:10px 10px 0}.chart-footer{padding:0 16px 14px}.table-bottom{padding:12px 14px}td{padding:10px 14px}th button{padding:11px 14px}} @media(max-width:480px){#app{padding:0 14px 16px}.brand{font-size:19px}.connection{font-size:10px}.heading{align-items:flex-start;gap:10px}.eyebrow{font-size:8px;letter-spacing:1.3px}h1{font-size:25px}.subtitle{font-size:10px;max-width:260px}.heading .button{font-size:10px;padding:5px 9px;min-height:32px;margin-top:15px}.hero{grid-template-columns:1fr 1fr;gap:22px 16px;padding:20px}.hero>div:first-child{grid-column:1/-1}.hero-stat{padding-left:0;border-left:0;border-top:1px solid #ffffff22;padding-top:15px}.hero-value{font-size:38px}.hero-stat .hero-value{font-size:24px}.hero-label{font-size:9px}.hero-note{font-size:10px}.metric-value{font-size:25px}.metric-label{font-size:10px}.metrics{gap:9px}.panel-head{flex-wrap:wrap;gap:11px}.panel h2{font-size:14px}.metric-select{max-width:100%;font-size:10px}.chart{height:180px}.chart-wrap{padding:10px 4px 0}.chart-footer{flex-wrap:wrap;gap:5px;font-size:9px}.table-tools{align-items:stretch;flex-direction:column;gap:10px}.search{width:100%}.search-wrap{width:100%}.table-bottom{align-items:flex-start;gap:8px}.pagination{gap:6px;white-space:nowrap}.wind-layout{grid-template-columns:1fr;padding:10px 20px 20px}.wind-chart{height:240px}.details dl{grid-template-columns:1fr 1.5fr;gap:9px 12px;padding:0 16px 17px}.details summary{padding:13px 16px}footer{flex-direction:column;gap:4px;font-size:9px}} @media(prefers-reduced-motion:no-preference){button{transition:background .12s,border-color .12s}} +.chart-cursor{stroke:var(--accent);stroke-width:1;stroke-dasharray:3 4;pointer-events:none}.chart-selection{fill:var(--accent);stroke:var(--surface);stroke-width:2;pointer-events:none}.chart-hit{cursor:crosshair;touch-action:pan-y}.chart-inspector{padding:3px 4px 16px;font-size:11px;min-width:0}.chart-inspector label{display:flex;justify-content:space-between;gap:12px;color:var(--muted)}.reading-position{font-variant-numeric:tabular-nums;white-space:nowrap}.chart-inspector input{display:block;width:100%;height:28px;margin:5px 0 7px;accent-color:var(--accent);cursor:pointer}.chart-reading{display:flex;justify-content:space-between;gap:6px 20px;flex-wrap:wrap;background:var(--soft);border:1px solid var(--border);border-radius:6px;padding:9px 11px;font-variant-numeric:tabular-nums;overflow-wrap:anywhere}.reading-time{color:var(--muted)}.reading-value{font-weight:600}.chart-inspector p{color:var(--muted);font-size:10px;margin:7px 0 0}@media(max-width:480px){.chart-inspector{padding:3px 11px 14px}.chart-reading{flex-direction:column;gap:4px}}