diff --git a/.bestpractices.json b/.bestpractices.json index 2e5d4a0..6ec7bd7 100644 --- a/.bestpractices.json +++ b/.bestpractices.json @@ -62,11 +62,11 @@ "vulnerability_report_response_status": "N/A", "vulnerability_report_response_justification": "The maintainer confirmed on 2026-09-05 that no private vulnerability reports were received in the preceding six months; the project advisory list was also empty. The policy requires acknowledgment within 14 days for future reports. https://github.com/lennrt/tempestkeep/blob/main/SECURITY.md https://github.com/lennrt/tempestkeep/blob/main/docs/openssf.md", "build_status": "Met", - "build_justification": "The source builds with Go 1.27.2 and make using CGO_ENABLED=0. Go and make are FLOSS; no proprietary build tool is required. https://github.com/lennrt/tempestkeep/blob/main/Makefile https://github.com/lennrt/tempestkeep/blob/main/README.md", + "build_justification": "The source builds with Go 1.27.3 and make using CGO_ENABLED=0. Go and make are FLOSS; no proprietary build tool is required. https://github.com/lennrt/tempestkeep/blob/main/Makefile https://github.com/lennrt/tempestkeep/blob/main/README.md", "build_common_tools_status": "Met", - "build_common_tools_justification": "The source builds with Go 1.27.2 and make using CGO_ENABLED=0. Go and make are FLOSS; no proprietary build tool is required. https://github.com/lennrt/tempestkeep/blob/main/Makefile https://github.com/lennrt/tempestkeep/blob/main/README.md", + "build_common_tools_justification": "The source builds with Go 1.27.3 and make using CGO_ENABLED=0. Go and make are FLOSS; no proprietary build tool is required. https://github.com/lennrt/tempestkeep/blob/main/Makefile https://github.com/lennrt/tempestkeep/blob/main/README.md", "build_floss_tools_status": "Met", - "build_floss_tools_justification": "The source builds with Go 1.27.2 and make using CGO_ENABLED=0. Go and make are FLOSS; no proprietary build tool is required. https://github.com/lennrt/tempestkeep/blob/main/Makefile https://github.com/lennrt/tempestkeep/blob/main/README.md", + "build_floss_tools_justification": "The source builds with Go 1.27.3 and make using CGO_ENABLED=0. Go and make are FLOSS; no proprietary build tool is required. https://github.com/lennrt/tempestkeep/blob/main/Makefile https://github.com/lennrt/tempestkeep/blob/main/README.md", "test_status": "Met", "test_justification": "The MIT-licensed Go test suite runs with make test or go test ./... -count=1 -timeout=5m, and in GitHub CI. https://github.com/lennrt/tempestkeep/blob/main/Makefile https://github.com/lennrt/tempestkeep/blob/main/CONTRIBUTING.md", "test_invocation_status": "Met", diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index b471478..e2e61a7 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -21,7 +21,7 @@ body: attributes: label: Environment description: Include the operating system, architecture, and `go version` when relevant. - placeholder: macOS arm64; go version go1.27.2 darwin/arm64 + placeholder: macOS arm64; go version go1.27.3 darwin/arm64 validations: required: true - type: textarea diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b13b581..204887f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,7 +74,7 @@ jobs: - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.27.2" + go-version: "1.27.3" check-latest: false cache: true @@ -88,7 +88,7 @@ jobs: run: go build ./... verify: - name: Go 1.27.2 verification + name: Go 1.27.3 verification runs-on: ubuntu-latest timeout-minutes: 25 steps: @@ -96,7 +96,7 @@ jobs: - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.27.2" + go-version: "1.27.3" check-latest: false cache: true @@ -130,7 +130,7 @@ jobs: - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.27.2" + go-version: "1.27.3" check-latest: false cache: true @@ -147,7 +147,7 @@ jobs: - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.27.2" + go-version: "1.27.3" check-latest: false cache: true @@ -171,7 +171,7 @@ jobs: - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.27.2" + go-version: "1.27.3" check-latest: false cache: true diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index e8ba6de..d30a26e 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -23,7 +23,7 @@ jobs: - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.27.2" + go-version: "1.27.3" check-latest: false cache: true diff --git a/.github/workflows/demo.yml b/.github/workflows/demo.yml index e41d590..6329220 100644 --- a/.github/workflows/demo.yml +++ b/.github/workflows/demo.yml @@ -19,7 +19,7 @@ jobs: - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.27.2" + go-version: "1.27.3" check-latest: false cache: true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e4e718e..52d0ea9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -21,7 +21,7 @@ jobs: - uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: - go-version: "1.27.2" + go-version: "1.27.3" check-latest: false cache: true diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e89160..1725fba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,58 @@ # Changelog +## 0.5.0 (proposed, unreleased) + +This development batch contains ten improvements: + +1. Pair temperature with humidity or wind from the same observations for + comfort calculations, so unrelated samples cannot create apparent extremes. +2. Preserve missing historical rainfall as null, expose sample counts, and + average rain normals over rain-contributing months with `rain_years`. + Keep missing rain buckets as gaps in the terminal day chart. +3. Create distinct nanosecond backup names, retry bounded collisions, and + retain both legacy and new names in chronological order. +4. Select the newest accepted live observation by timestamp, independent of + response order, with the first row winning equal timestamps. +5. Reuse the existing archive device for unattended CLI collection when no + explicit selector exists. New or unbound empty archives still discover a device. +6. Add read-only offline `status` text and JSON reports for archive freshness, + saved backfill state, and bounded internal gaps. +7. Show daily forecast high, low, and maximum rain probability in app cards. +8. Add bounded long-cell inspection and SQL text search beyond cell previews. +9. Preserve keyboard focus after changing the selected app dataset. +10. Reject explicit zero CLI collection device selectors before archive or API + access, consistent with the positive-ID contract. + +### Supporting security repair + +- Require Go 1.27.3 for builds and checks to fix + [GO-2026-6809](https://pkg.go.dev/vuln/GO-2026-6809) in the standard library. + Rebuild older binaries with the patched toolchain. This repair supports the + ten improvements above and does not change language dependencies. See + [ADR 0020](docs/adr/0020-go-security-patch.md). + +### Compatibility + +Go callers must handle nullable `DayStat.RainIn`, `PeriodStat.RainIn`, +`YearDay.RainIn`, `MonthNormal.AvgRainIn`, and `MonthNormal.AvgRainyDays`. +Historical JSON rain fields now encode numbers or explicit null. Additional +`rain_readings` and `rain_years` fields describe samples, not continuous coverage. +Partial months still contribute their available rain totals to normals. + +CLI collection without a selector now follows existing archive identity rather +than the first accessible live device. Nonempty zero environment selectors fail +for CLI collection. MCP retains its automatic zero environment selection rule. +Existing archives need no schema migration. Backup naming changes, while +retention continues to recognize legacy names. Dependencies remain unchanged. +Metadata reads now enforce the writer's existing 4,096-byte and NUL limits +in UTF-8 bytes, including when SQLite stores text as UTF-16. +Oversized, null, or NUL-containing stored values return `ErrInvalidArchive`. + +Active development, plugin, and app metadata target 0.5.0. Untagged fallback +builds report `v0.5.0-dev`. Historical release records below remain unchanged. +No tag, release, plugin publication, or merge is part of this development change. +Qualification still follows [RELEASING.md](RELEASING.md). + ## 0.4.0 (proposed, unreleased) ### Added diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c89cf29..bd22899 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -18,7 +18,7 @@ review; do not submit only a final source archive. ## Prerequisites -- Go 1.27.2. +- Go 1.27.3. - A Unix-like shell and make for the Makefile and shell scripts. - A C toolchain for race tests. - Network access to the Go module proxy for the first tool download. diff --git a/Makefile b/Makefile index c8fa011..c01c22e 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ NPM ?= npm VHS ?= vhs BIN_DIR ?= bin -GO_VERSION := 1.27.2 +GO_VERSION := 1.27.3 GOIMPORTS_VERSION := v0.44.0 GOLANGCI_LINT_VERSION := v2.14.0 ACTIONLINT_VERSION := v1.7.12 diff --git a/README.md b/README.md index 6c96a71..183e29c 100644 --- a/README.md +++ b/README.md @@ -36,8 +36,10 @@ credentials described below. | Explore | In the app | |---|---| +| Daily forecast | Read daily high, low, and maximum rain probability, then switch to hourly details. | | 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. | +| Archive and SQL results | Search rows, inspect long cells, sort columns, and move between table pages. | +| Several stations | Find device IDs beside their parent station names for use in configuration. | | 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. | @@ -45,12 +47,19 @@ credentials described below. *Synthetic table data in the local MCP Apps test host, captured with Playwright.* +![Daily forecast cards and table in the TempestKeep MCP App](docs/screenshots/mcp-app-forecast.png) + +*Synthetic daily forecast. Cards summarize the returned days, including the +highest rain probability. Missing values remain unavailable.* + 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. +Historical rainfall tables also distinguish missing rain, measured zero, and +partial totals. Their reading counts describe samples, not uninterrupted 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 @@ -94,7 +103,7 @@ See the [MCP guide](docs/mcp.md) for configuration, capabilities, and limits. ### Build -You need Go 1.27.2 and a local filesystem for SQLite. Live data and collection +You need Go 1.27.3 and a local filesystem for SQLite. Live data and collection also need a WeatherFlow personal access token. The build commands below use `make` and a Unix-like shell. The normal build uses pure Go. Race tests need a C toolchain. @@ -229,6 +238,7 @@ tempestkeep list-devices List stations and device identifiers. tempestkeep collect Create or update the archive. tempestkeep now Show current conditions and forecast. tempestkeep explore Explore archived days, months, and records. +tempestkeep status Inspect archive freshness and internal gaps. tempestkeep stats Print archive statistics. tempestkeep export Write CSV or JSON Lines to stdout. tempestkeep mcp Serve live and archived data over MCP stdio. @@ -253,10 +263,14 @@ Left/Right (or h/l) moves between periods, `d/w/m/y/r` selects a view, and Tab 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. +In the day view, a gap in the rain sparkline means that no rain reading exists. +The lowest block represents zero or a small positive reading. Partial summary +rain totals carry a `≥` marker. + `tempestkeep version` reports the build's injected version, then Go's module -version when available. If neither exists, it falls back to `v0.4.0-dev`. +version when available. If neither exists, it falls back to `v0.5.0-dev`. `make build` injects a version from Git tags or that development fallback. -Version 0.4.0 is the proposed next minor release. See [CHANGELOG.md](CHANGELOG.md) +Version 0.5.0 is the proposed next minor release. See [CHANGELOG.md](CHANGELOG.md) for its scope. This change does not publish a release. ## Archive behavior @@ -270,6 +284,15 @@ one transaction. Observation inserts use the `(device_id, epoch)` key, so replay does not create duplicate rows. Open-ended collection stores a cursor after each committed chunk and resumes from that cursor after interruption. +Without an explicit device selection, CLI collection reuses an existing +archive's device. New archives and empty archives without a saved device discover +the first accessible Tempest device. An empty archive with a saved device keeps +that device. Explicit zero device IDs fail before archive or API access. + +Use `tempestkeep status --format json` to inspect an archive without a token. +It reports freshness, saved backfill state, and up to ten internal gaps over +one hour. Sample timestamps do not establish continuous sensor coverage. + The default `tempestkeep collect` run creates a timestamped backup after a successful checkpoint. Backups live in the `backups` directory beside the archive. A private temporary copy becomes a snapshot without replacing an @@ -309,7 +332,7 @@ See [SECURITY.md](SECURITY.md) for private reporting and the ## Verification -Run the repository checks with Go 1.27.2: +Run the repository checks with Go 1.27.3: ```sh make fmtcheck # gofmt and goimports @@ -397,7 +420,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.4.0--dev-blue +[version-badge]: https://img.shields.io/badge/development-v0.5.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 00c5378..852fa67 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -9,7 +9,7 @@ remains disabled until a separate reviewed change enables an approved release. - Obtain explicit release approval. - Select one reviewed commit with a clean working tree. - Require all configured GitHub checks to pass for that commit. -- Use Go 1.27.2. +- Use Go 1.27.3. - Confirm that no credential, station data, archive, export, personal path, or raw API response is present in tracked, untracked, ignored, or generated files. @@ -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.4.0-dev` alone does not identify a source revision. +unique identifier; `v0.5.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 @@ -48,7 +48,7 @@ make integration e2e make release-check ``` -The Go version must be exactly 1.27.2. The first three commands must pass. The +The Go version must be exactly 1.27.3. The first three commands must pass. The last command creates local snapshot archives in `dist/` without publishing them. Inspect every archive. Confirm that it contains the `tempestkeep` binary, diff --git a/SUPPORT.md b/SUPPORT.md index 07a82b2..86e0002 100644 --- a/SUPPORT.md +++ b/SUPPORT.md @@ -12,7 +12,7 @@ Do not put sensitive station data in either channel. [docs/README.md](docs/README.md). 2. Read the [troubleshooting guide](docs/troubleshooting.md) for known recovery steps. 3. Run `tempestkeep help ` or inspect the MCP tool description. -4. Reproduce the problem with the default branch and Go 1.27.2 when practical. +4. Reproduce the problem with the default branch and Go 1.27.3 when practical. 5. Run the smallest relevant check from [CONTRIBUTING.md](CONTRIBUTING.md). ## Include diff --git a/cmd/tempestkeep/README.md b/cmd/tempestkeep/README.md index 1b49245..ce1aedc 100644 --- a/cmd/tempestkeep/README.md +++ b/cmd/tempestkeep/README.md @@ -6,7 +6,7 @@ one device. ## Build -Use Go 1.27.2 from the repository root: +Use Go 1.27.3 from the repository root: ```sh make tempestkeep @@ -24,6 +24,7 @@ tempestkeep list-devices List station and device data visible to the token. tempestkeep collect Create or update one device archive. tempestkeep now Show live or archived current conditions. tempestkeep explore Browse archive periods and records. +tempestkeep status Inspect archive freshness and internal gaps. tempestkeep stats Print an archive report. tempestkeep export Write CSV or JSON Lines. tempestkeep mcp Serve live and archived data over MCP stdio. @@ -75,6 +76,20 @@ 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). +## Archive status + +Run `bin/tempestkeep status --db ./tempest.sqlite` without a token or network. +Use `--format json` for structured output. Only `text` and `json` are accepted. +The command opens an existing archive read-only and does not create a missing file. + +The report includes observation count, first and last local RFC3339 timestamps, +newest age in seconds, and the saved backfill completion marker. An empty archive +returns null timestamps and age in JSON. Fresh means an age from 0 through +3,599 seconds. Future observations are not fresh. The report lists at most ten +largest internal gaps strictly over 3,600 seconds. It does not include gaps +before the first observation or after the last observation. These bounds and +sample counts do not establish continuous coverage or sensor availability. + ## Collection After setup, run: @@ -83,6 +98,15 @@ After setup, run: bin/tempestkeep collect ``` +Without `--device-id` or a nonempty `TEMPEST_DEVICE_ID`, collection reuses +the device of an existing archive. A new archive or an empty archive without a +saved device discovers the first accessible Tempest device. An empty archive with +a saved device keeps that device. An unidentifiable legacy archive requires an +explicit selector. Archive read errors do not fall back to discovery. Explicit selectors +must be positive. Zero, malformed, or negative values fail before archive or API +access. A positive flag overrides the environment. Selecting a different device +still fails the archive ownership check. + On a new archive, the command walks backward through available history. An interrupted backward walk resumes on the next run. Once backfill completes, later runs sync after the newest stored observation, called the watermark. @@ -138,6 +162,12 @@ After successful collection, the command checkpoints SQLite's write-ahead log a backup. Backups live in `backups` beside the archive, not necessarily beside the executable or working directory. +New snapshot names use `-YYYYMMDD-HHMMSS.nnnnnnnnn.sqlite` in UTC. +A collision advances the candidate timestamp by one nanosecond, with at most +100 candidates. Existing snapshots are never replaced. Retention recognizes +both this format and legacy second-resolution names, ordered by parsed time. +Unrelated files remain untouched. + The default retention is seven snapshots. `--backup-keep` accepts 0 through 365, and zero disables backups. `--no-backup` skips the snapshot for that run. A backup failure returns an error without undoing collected data. The backup @@ -174,6 +204,10 @@ Use Tab to change the month or year metric. Use Up/Down and Page Up/Page Down to Press `q`, Esc, or Ctrl+C to exit. See the [terminal controls](../../README.md#terminal-controls) for refresh keys and minimum widths. +In the day view, missing rain readings leave gaps in the sparkline. The lowest +block represents zero or a small positive reading. Summary totals use `≥` when +some stored observations lack rain readings. These counts do not establish continuous coverage. + Color is disabled when stdout is not a terminal. `NO_COLOR`, `TERM=dumb`, and `--no-color` also disable color. `stats` and `export` provide output that does not require the interactive explorer. diff --git a/cmd/tempestkeep/backup_collision_test.go b/cmd/tempestkeep/backup_collision_test.go new file mode 100644 index 0000000..ca997ea --- /dev/null +++ b/cmd/tempestkeep/backup_collision_test.go @@ -0,0 +1,123 @@ +package main + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestSnapshotSameClockPreservesEachCopy(t *testing.T) { + src := filepath.Join(t.TempDir(), "weather.sqlite") + now := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC) + seen := map[string]string{} + for i := range 3 { + content := fmt.Sprintf("synthetic snapshot %d", i) + if err := os.WriteFile(src, []byte(content), 0600); err != nil { + t.Fatal(err) + } + dest, err := snapshotAt(src, 7, now) + if err != nil { + t.Fatal(err) + } + if _, exists := seen[dest]; exists { + t.Fatalf("reused snapshot %q", dest) + } + seen[dest] = content + if got, err := os.ReadFile(dest); err != nil || string(got) != content { + t.Fatalf("snapshot=%q, error=%v", got, err) + } + } + for dest, content := range seen { + if got, err := os.ReadFile(dest); err != nil || string(got) != content { + t.Fatalf("prior snapshot changed: %q, %v", got, err) + } + } + if _, err := snapshotAt(src, 2, now); err != nil { + t.Fatal(err) + } + backupDir := filepath.Join(filepath.Dir(src), "backups") + entries, err := os.ReadDir(backupDir) + if err != nil || len(entries) != 2 { + t.Fatalf("retained entries=%d, error=%v", len(entries), err) + } + assertNoBackupTemps(t, backupDir) +} + +func assertNoBackupTemps(t *testing.T, dir string) { + t.Helper() + entries, err := os.ReadDir(dir) + if err != nil { + t.Fatal(err) + } + for _, entry := range entries { + if strings.Contains(entry.Name(), ".tmp-") { + t.Errorf("temporary file remains: %s", entry.Name()) + } + } +} + +func TestPruneMixedBackupFormatsByInstant(t *testing.T) { + dir := t.TempDir() + names := []string{"weather-20261101-120000.sqlite", "weather-20261101-120000.000000000.sqlite", "weather-20261101-120000.000000001.sqlite", "weather-20261101-120001.sqlite"} + for _, name := range names { + if err := os.WriteFile(filepath.Join(dir, name), []byte(name), 0600); err != nil { + t.Fatal(err) + } + } + unrelated := "weather-20261101-120000.1.sqlite" + if err := os.WriteFile(filepath.Join(dir, unrelated), nil, 0600); err != nil { + t.Fatal(err) + } + if err := pruneBackups(dir, "weather", 2); err != nil { + t.Fatal(err) + } + for _, name := range names[:2] { + if _, err := os.Stat(filepath.Join(dir, name)); !errors.Is(err, os.ErrNotExist) { + t.Errorf("old snapshot remains: %s (%v)", name, err) + } + } + for _, name := range append(names[2:], unrelated) { + if _, err := os.Stat(filepath.Join(dir, name)); err != nil { + t.Errorf("preserved snapshot %s: %v", name, err) + } + } +} + +func TestSnapshotCollisionLimitCleansTemporaryFiles(t *testing.T) { + dir := t.TempDir() + src := filepath.Join(dir, "weather.sqlite") + backupDir := filepath.Join(dir, "backups") + if err := os.WriteFile(src, []byte("new"), 0600); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(backupDir, 0700); err != nil { + t.Fatal(err) + } + now := time.Date(2026, 11, 1, 12, 0, 0, 0, time.UTC) + for i := range 100 { + name := "weather-" + now.Add(time.Duration(i)).Format("20060102-150405.000000000") + ".sqlite" + if err := os.WriteFile(filepath.Join(backupDir, name), []byte("old"), 0600); err != nil { + t.Fatal(err) + } + } + if _, err := snapshotAt(src, 7, now); err == nil { + t.Fatal("expected bounded collision error") + } + entries, err := os.ReadDir(backupDir) + if err != nil { + t.Fatal(err) + } + if len(entries) != 100 { + t.Fatalf("entries=%d, expected 100", len(entries)) + } + for _, entry := range entries { + if got, err := os.ReadFile(filepath.Join(backupDir, entry.Name())); err != nil || string(got) != "old" { + t.Fatalf("existing backup changed: %q, %v", got, err) + } + } + assertNoBackupTemps(t, backupDir) +} diff --git a/cmd/tempestkeep/collect.go b/cmd/tempestkeep/collect.go index 3b0b3bb..364354b 100644 --- a/cmd/tempestkeep/collect.go +++ b/cmd/tempestkeep/collect.go @@ -41,7 +41,7 @@ func cmdCollect(args []string) error { "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)") + deviceID := fs.Int("device-id", 0, "positive Tempest device id (or env TEMPEST_DEVICE_ID; archive device or discovery 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)") @@ -55,6 +55,9 @@ func cmdCollect(args []string) error { } setFlags := map[string]bool{} fs.Visit(func(f *flag.Flag) { setFlags[f.Name] = true }) + if setFlags["device-id"] && *deviceID <= 0 { + return usagef("--device-id must be positive") + } explicitRange := setFlags["start"] || setFlags["end"] var rangeStart, rangeEnd int64 if explicitRange { @@ -143,20 +146,9 @@ func cmdCollect(args []string) error { return err } - dev := *deviceID - if dev == 0 { - if e := os.Getenv("TEMPEST_DEVICE_ID"); e != "" { - // A malformed value must not silently fall through to discovery, - // which could pick a different device and split the archive. - n, perr := strconv.Atoi(e) - if perr != nil { - return fmt.Errorf("TEMPEST_DEVICE_ID must be an integer") - } - dev = n - } - } - if dev < 0 { - return fmt.Errorf("TEMPEST_DEVICE_ID must be positive") + dev, err := collectionDevice(ctx, *deviceID, os.Getenv("TEMPEST_DEVICE_ID"), dbPath) + if err != nil { + return err } if dev == 0 { _, discovered, err := client.FindTempestDevice(ctx) @@ -251,6 +243,62 @@ func cmdCollect(args []string) error { return nil } +// collectionDevice resolves configured selectors before inspecting an existing +// archive read-only. Zero means discovery is needed; inspection never creates it. +func collectionDevice(ctx context.Context, explicit int, environment, path string) (int, error) { + if explicit > 0 { + return explicit, nil + } + if environment != "" { + device, err := strconv.Atoi(environment) + if err != nil || device <= 0 { + return 0, errors.New("TEMPEST_DEVICE_ID must be a positive integer") + } + return device, nil + } + if _, err := os.Lstat(path); errors.Is(err, os.ErrNotExist) { + return 0, nil + } else if err != nil { + return 0, errors.New("cannot inspect collection archive") + } + return existingCollectionDevice(ctx, path) +} + +func existingCollectionDevice(ctx context.Context, path string) (_ int, err error) { + s, err := store.Open(ctx, path) + if err != nil { + return 0, err + } + defer func() { err = errors.Join(err, s.Close()) }() + // Use the shared bounded reader, including its database-encoding handling + // and support for legacy archives without a metadata table. + raw, bound, err := s.Meta(ctx, "archive_device_id") + if err != nil { + return 0, err + } + if bound { + device, parseErr := strconv.Atoi(raw) + if parseErr != nil || device <= 0 { + return 0, fmt.Errorf("%w: archive has invalid device metadata", store.ErrInvalidArchive) + } + return device, nil + } + // Store.Open already rejects mixed device IDs. Query only one value, + // including for old archives that predate persisted device binding. + rows, err := s.Query(ctx, "SELECT device_id FROM obs_st LIMIT 1", 1) + if err != nil { + return 0, errors.Join(errors.New("cannot infer archive device; supply --device-id explicitly for legacy archives"), err) + } + if len(rows.Rows) == 0 { + return 0, nil + } + device, ok := rows.Rows[0][0].(int64) + if !ok || device <= 0 || int64(int(device)) != device { + return 0, fmt.Errorf("%w: archive has invalid device identity", store.ErrInvalidArchive) + } + return int(device), 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. @@ -389,6 +437,10 @@ func span(c store.Coverage) string { // snapshot copies the archive into ./backups with a UTC timestamp and prunes all // but the newest keep snapshots. keep <= 0 disables snapshots. func snapshot(dbPath string, keep int) (string, error) { + return snapshotAt(dbPath, keep, time.Now()) +} + +func snapshotAt(dbPath string, keep int, now time.Time) (string, error) { if keep <= 0 { return "", nil } @@ -407,12 +459,31 @@ func snapshot(dbPath string, keep int) (string, error) { return "", err } stem := stem(filepath.Base(dbPath)) - stamp := time.Now().UTC().Format("20060102-150405") - dest := filepath.Join(dir, fmt.Sprintf("%s-%s.sqlite", stem, stamp)) - if err := copyFile(dbPath, dest); err != nil { - return "", err + // Advance only the candidate name on collision. Publication still uses a + // hard link, so even concurrent creators cannot replace another snapshot. + for attempt := range 100 { + stamp := now.UTC().Add(time.Duration(attempt)).Format(backupTimestampLayout) + dest := filepath.Join(dir, fmt.Sprintf("%s-%s.sqlite", stem, stamp)) + if err := copyFile(dbPath, dest); err != nil { + if errors.Is(err, os.ErrExist) { + continue + } + return "", err + } + return dest, pruneBackups(dir, stem, keep) + } + return "", errors.New("backup name collision limit reached") +} + +const backupTimestampLayout = "20060102-150405.000000000" + +func backupTimestamp(stamp string) (time.Time, bool) { + for _, layout := range []string{backupTimestampLayout, "20060102-150405"} { + if instant, err := time.Parse(layout, stamp); err == nil && instant.Format(layout) == stamp { + return instant, true + } } - return dest, pruneBackups(dir, stem, keep) + return time.Time{}, false } func pruneBackups(dir, stem string, keep int) (err error) { @@ -432,24 +503,33 @@ func pruneBackups(dir, stem string, keep int) (err error) { return fmt.Errorf("backup directory exceeds %d entries", maxBackupEntries) } prefix := stem + "-" - var names []string + type backup struct { + name string + instant time.Time + } + var backups []backup for _, entry := range entries { name := entry.Name() if !entry.Type().IsRegular() || !strings.HasPrefix(name, prefix) || !strings.HasSuffix(name, ".sqlite") { continue } stamp := strings.TrimSuffix(strings.TrimPrefix(name, prefix), ".sqlite") - if _, err := time.Parse("20060102-150405", stamp); err == nil { - names = append(names, name) + if instant, ok := backupTimestamp(stamp); ok { + backups = append(backups, backup{name: name, instant: instant}) } } - if len(names) <= keep { + if len(backups) <= keep { return nil } - sort.Strings(names) + sort.Slice(backups, func(i, j int) bool { + if backups[i].instant.Equal(backups[j].instant) { + return backups[i].name < backups[j].name + } + return backups[i].instant.Before(backups[j].instant) + }) var removeErrors []error - for _, name := range names[:len(names)-keep] { - if err := os.Remove(filepath.Join(dir, name)); err != nil && !errors.Is(err, os.ErrNotExist) { + for _, backup := range backups[:len(backups)-keep] { + if err := os.Remove(filepath.Join(dir, backup.name)); err != nil && !errors.Is(err, os.ErrNotExist) { removeErrors = append(removeErrors, err) } } diff --git a/cmd/tempestkeep/collect_selection_test.go b/cmd/tempestkeep/collect_selection_test.go new file mode 100644 index 0000000..22750db --- /dev/null +++ b/cmd/tempestkeep/collect_selection_test.go @@ -0,0 +1,248 @@ +package main + +import ( + "database/sql" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + + "github.com/lennrt/tempestkeep/pkg/tempest/model" + + "github.com/lennrt/tempestkeep/pkg/tempest/store" +) + +func TestCollectExplicitZeroBeforeConfiguration(t *testing.T) { + t.Chdir(t.TempDir()) + if err := os.WriteFile(".env", []byte("invalid dotenv\n"), 0600); err != nil { + t.Fatal(err) + } + path := filepath.Join(t.TempDir(), "absent.sqlite") + if err := cmdCollect([]string{"--db", path, "--device-id=0"}); !isUsageErr(err) { + t.Fatalf("error=%v, want usage", err) + } + if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("created archive: %v", err) + } +} + +func TestCollectPreservesArchiveDeviceDespiteStationOrder(t *testing.T) { + t.Chdir(t.TempDir()) + path := filepath.Join(t.TempDir(), "archive.sqlite") + w, err := store.OpenWriter(t.Context(), path) + if err != nil { + t.Fatal(err) + } + if err := w.BindDevice(t.Context(), 456); err != nil { + t.Fatal(err) + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + var discovery, observations atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if strings.HasSuffix(r.URL.Path, "/stations") { + discovery.Add(1) + if _, err := fmt.Fprint(w, `{"stations":[{"station_id":1,"devices":[{"device_id":789,"device_type":"ST"}]}]}`); err != nil { + t.Error(err) + } + return + } + observations.Add(1) + if !strings.HasSuffix(r.URL.Path, "/observations/device/456") { + t.Errorf("unexpected observation path %s", r.URL.Path) + } + if _, err := fmt.Fprint(w, `{"obs":[]}`); err != nil { + t.Error(err) + } + })) + t.Cleanup(srv.Close) + configureCollectionRangeTest(t, srv.URL) + t.Setenv("TEMPEST_DEVICE_ID", "") + args := []string{"--db", path, "--start=2025-01-01", "--end=2025-01-01", "--no-backup", "--quiet"} + if err := cmdCollect(args); err != nil { + t.Fatalf("collect existing archive: %v", err) + } + if discovery.Load() != 0 || observations.Load() == 0 { + t.Fatalf("discovery=%d observations=%d", discovery.Load(), observations.Load()) + } + // Explicit selection still wins, and writer binding rejects it before HTTP. + n := observations.Load() + if err := cmdCollect(append(args, "--device-id=789")); !errors.Is(err, store.ErrDeviceMismatch) { + t.Fatalf("mismatch=%v", err) + } + if observations.Load() != n { + t.Fatal("mismatched explicit selector made observation requests") + } +} + +func TestCollectionDeviceResolution(t *testing.T) { + for _, tc := range []struct { + name, setup string + want int + fail bool + }{ + {"missing", "missing", 0, false}, + {"empty unbound", "empty", 0, false}, + {"empty bound", "bound", 456, false}, + {"legacy rows", "legacy", 456, false}, + {"unidentifiable legacy", "unknown", 0, true}, + {"invalid metadata", "invalid", 0, true}, + {"oversized metadata", "oversized", 0, true}, + {"no metadata table", "no-meta", 456, false}, + {"mixed rows", "mixed", 0, true}, + {"corrupt file", "corrupt", 0, true}, + {"directory", "directory", 0, true}, + } { + t.Run(tc.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "archive.sqlite") + switch tc.setup { + case "missing": + case "directory": + if err := os.Mkdir(path, 0700); err != nil { + t.Fatal(err) + } + case "corrupt": + if err := os.WriteFile(path, []byte("not sqlite"), 0600); err != nil { + t.Fatal(err) + } + default: + w, err := store.OpenWriter(t.Context(), path) + if err != nil { + t.Fatal(err) + } + if tc.setup != "empty" { + if _, err := w.InsertObs(t.Context(), 456, []model.DeviceObs{{Epoch: 1700000000}}); err != nil { + t.Fatal(err) + } + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + db, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + switch tc.setup { + case "bound": + _, err = db.ExecContext(t.Context(), "DELETE FROM obs_st") + case "legacy": + _, err = db.ExecContext(t.Context(), "DELETE FROM meta WHERE key='archive_device_id'") + case "unknown": + _, err = db.ExecContext(t.Context(), "DELETE FROM meta WHERE key='archive_device_id'") + if err == nil { + _, err = db.ExecContext(t.Context(), "ALTER TABLE obs_st RENAME COLUMN device_id TO legacy_device") + } + case "oversized": + _, err = db.ExecContext(t.Context(), "UPDATE meta SET value=? WHERE key='archive_device_id'", strings.Repeat("9", 4097)) + case "no-meta": + _, err = db.ExecContext(t.Context(), "DROP TABLE meta") + case "invalid": + _, err = db.ExecContext(t.Context(), "UPDATE meta SET value='0' WHERE key='archive_device_id'") + case "mixed": + _, err = db.ExecContext(t.Context(), "INSERT INTO obs_st (device_id,epoch) VALUES (789,1700000060)") + } + if err != nil { + t.Fatal(err) + } + if err := db.Close(); err != nil { + t.Fatal(err) + } + } + got, err := collectionDevice(t.Context(), 0, "", path) + if (err != nil) != tc.fail || (!tc.fail && got != tc.want) { + t.Fatalf("device=%d error=%v; want %d fail=%v", got, err, tc.want, tc.fail) + } + if tc.setup == "missing" { + if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("selection created file: %v", err) + } + } + // Explicit selectors must not inspect even malformed archives or environments. + if got, err := collectionDevice(t.Context(), 123, "bad", path); err != nil || got != 123 { + t.Fatalf("explicit precedence: %d %v", got, err) + } + if got, err := collectionDevice(t.Context(), 0, "789", path); err != nil || got != 789 { + t.Fatalf("environment precedence: %d %v", got, err) + } + }) + } + for _, value := range []string{"0", "-1", "bad"} { + if _, err := collectionDevice(t.Context(), 0, value, "unused"); err == nil { + t.Errorf("accepted environment %q", value) + } + } +} + +func TestCollectFreshArchiveDiscovers(t *testing.T) { + t.Chdir(t.TempDir()) + var discovery, observations atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if strings.HasSuffix(r.URL.Path, "/stations") { + discovery.Add(1) + if _, err := fmt.Fprint(w, `{"stations":[{"station_id":1,"devices":[{"device_id":456,"device_type":"ST"}]}]}`); err != nil { + t.Error(err) + } + return + } + observations.Add(1) + if _, err := fmt.Fprint(w, `{"obs":[]}`); err != nil { + t.Error(err) + } + })) + t.Cleanup(srv.Close) + configureCollectionRangeTest(t, srv.URL) + t.Setenv("TEMPEST_DEVICE_ID", "") + path := filepath.Join(t.TempDir(), "fresh.sqlite") + if err := cmdCollect([]string{"--db", path, "--start=2025-01-01", "--end=2025-01-01", "--no-backup", "--quiet"}); err != nil { + t.Fatal(err) + } + if discovery.Load() != 1 || observations.Load() != 1 { + t.Fatalf("discovery=%d observations=%d", discovery.Load(), observations.Load()) + } + got, err := collectionDevice(t.Context(), 0, "", path) + if err != nil || got != 456 { + t.Fatalf("new archive identity=%d error=%v", got, err) + } +} + +func TestCollectionDeviceMetadataUsesSharedReader(t *testing.T) { + for _, tc := range []struct { + name, encoding, table string + device int + }{ + {"case-insensitive legacy metadata table", "UTF-8", "META", 456}, + {"UTF-16le identity", "UTF-16le", "meta", int(^uint(0) >> 1)}, + {"UTF-16be identity", "UTF-16be", "meta", int(^uint(0) >> 1)}, + } { + t.Run(tc.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "archive.sqlite") + db, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + _, schemaErr := db.ExecContext(t.Context(), fmt.Sprintf("PRAGMA encoding='%s'; CREATE TABLE %s (key TEXT PRIMARY KEY, value TEXT NOT NULL)", tc.encoding, tc.table)) + if err := errors.Join(schemaErr, db.Close()); err != nil { + t.Fatal(err) + } + w, err := store.OpenWriter(t.Context(), path) + if err != nil { + t.Fatal(err) + } + if err := errors.Join(w.BindDevice(t.Context(), tc.device), w.Close()); err != nil { + t.Fatal(err) + } + got, err := collectionDevice(t.Context(), 0, "", path) + if err != nil || got != tc.device { + t.Fatalf("archive device=%d want=%d error=%v", got, tc.device, err) + } + }) + } +} diff --git a/cmd/tempestkeep/display_boundary_test.go b/cmd/tempestkeep/display_boundary_test.go index 1a71e45..ee1a301 100644 --- a/cmd/tempestkeep/display_boundary_test.go +++ b/cmd/tempestkeep/display_boundary_test.go @@ -127,13 +127,13 @@ func TestDaysInCountsCalendarDaysAcrossSpringForward(t *testing.T) { func TestWeekViewKeepsRainWhenTemperatureIsMissing(t *testing.T) { day := time.Now().Format(time.DateOnly) - text := renderWeekView([]store.DayStat{{Day: day, Obs: 12, RainIn: 1.25, PeakGustMph: new(18.0)}}, 0) + text := renderWeekView([]store.DayStat{{Day: day, Obs: 12, RainIn: new(1.25), PeakGustMph: new(18.0)}}, 0) if strings.Contains(text, "no observations") || !strings.Contains(text, "1.25") || !strings.Contains(text, "18") { t.Fatalf("missing temperature hid other observations:\n%s", text) } start, _, _ := periodRange(viewWeek, 0, time.Now()) text = renderWeekView([]store.DayStat{ - {Day: start.Format(time.DateOnly), Obs: 12, RainIn: 1.25}, + {Day: start.Format(time.DateOnly), Obs: 12, RainIn: new(1.25)}, {Day: start.AddDate(0, 0, 1).Format(time.DateOnly), Obs: 12, TempMinF: new(55.0), TempMaxF: new(70.0)}, }, 0) rows := strings.Split(text, "\n") diff --git a/cmd/tempestkeep/explore_views.go b/cmd/tempestkeep/explore_views.go index 00e334d..ec68d30 100644 --- a/cmd/tempestkeep/explore_views.go +++ b/cmd/tempestkeep/explore_views.go @@ -32,7 +32,7 @@ var heatMetrics = []heatMetric{ func(v, _, _ float64) lipgloss.Color { return tempColor(v) }, "%.0f°"}, {"low °F", func(d store.DayStat) *float64 { return d.TempMinF }, func(v, _, _ float64) lipgloss.Color { return tempColor(v) }, "%.0f°"}, - {"rain", func(d store.DayStat) *float64 { v := d.RainIn; return &v }, + {"rain", func(d store.DayStat) *float64 { return d.RainIn }, rainColor, "%.2f in"}, {"gust", func(d store.DayStat) *float64 { return d.PeakGustMph }, gustColor, "%.0f mph"}, @@ -72,12 +72,9 @@ func renderDayView(d dayData) string { continue } temps[i] = p.TempAvgF - if p.RainIn > 0 { + if p.RainReadings > 0 { v := p.RainIn rain[i] = &v - } else if p.Obs > 0 { - zero := 0.0 - rain[i] = &zero } wind[i] = p.WindMph solar[i] = p.SolarAvgWm2 @@ -141,7 +138,7 @@ func (d dayData) statLine() string { valF(s.TempMaxF, "hi %.0f°"), valF(s.TempMinF, "lo %.0f°"), valF(s.TempAvgF, "avg %.0f°"), - fmt.Sprintf("rain %.2f in", s.RainIn), + historicalRainLabel(s.RainIn, s.RainReadings, s.Obs), valF(s.PeakGustMph, "gust %.0f mph"), }) } @@ -201,7 +198,7 @@ func renderWeekView(days []store.DayStat, offset int) string { rangeBand(lo, hi, scaleLo, scaleHi, bandW, tempColor) + lipgloss.NewStyle().Foreground(tempColor(hi)).Render(fmt.Sprintf(" %-5s", fmt.Sprintf("%.0f°", hi))) } - line += faint().Render(" rain ") + rainCell(d.RainIn, 0) + line += faint().Render(" rain ") + rainCell(d.RainIn, 0, d.RainReadings < d.Obs) if d.PeakGustMph != nil { line += faint().Render(" gust ") + fmt.Sprintf("%.0f", *d.PeakGustMph) } @@ -214,8 +211,16 @@ func renderWeekView(days []store.DayStat, offset int) string { // rainCell prints a daily rain amount width columns wide (0 = natural width), // dimming the zeros so wet days pop. Padding happens before styling: a %*s // over the styled string would count the ANSI escapes as width and pad nothing. -func rainCell(in float64, width int) string { - s := fmt.Sprintf("%*.2f", width, in) +func rainCell(value *float64, width int, partial bool) string { + if value == nil { + return faint().Render(fmt.Sprintf("%*s", width, gapDot)) + } + in := *value + s := fmt.Sprintf("%.2f", in) + if partial { + s = "≥" + s + } + s = fmt.Sprintf("%*s", width, s) if in == 0 { return faint().Render(s) } @@ -234,17 +239,22 @@ func orFallback(a, b *float64) float64 { func weekStats(days []store.DayStat) string { var hi, lo, gust *float64 rain, rainy := 0.0, 0 + var reads, obs int64 for _, d := range days { hi, lo = maxPtrVal(hi, d.TempMaxF), minPtrVal(lo, d.TempMinF) gust = maxPtrVal(gust, d.PeakGustMph) - rain += d.RainIn - if d.RainIn >= 0.01 { + reads += d.RainReadings + obs += d.Obs + if d.RainIn != nil { + rain += *d.RainIn + } + if d.RainIn != nil && *d.RainIn >= 0.01 { rainy++ } } return statRow([]string{ valF(hi, "hi %.0f°"), valF(lo, "lo %.0f°"), - fmt.Sprintf("rain %.2f in", rain), + historicalRainLabel(historicalRainTotal(rain, reads), reads, obs), pluralN(rainy, "rainy day"), valF(gust, "gust %.0f mph"), }) @@ -296,11 +306,16 @@ func renderMonthView(days []store.DayStat, offset int, metric heatMetric) string stats = append(stats, "") var mhi, mlo, mgust *float64 rain, rainy, observed := 0.0, 0, 0 + var reads, obs int64 for _, d := range days { mhi, mlo = maxPtrVal(mhi, d.TempMaxF), minPtrVal(mlo, d.TempMinF) mgust = maxPtrVal(mgust, d.PeakGustMph) - rain += d.RainIn - if d.RainIn >= 0.01 { + reads += d.RainReadings + obs += d.Obs + if d.RainIn != nil { + rain += *d.RainIn + } + if d.RainIn != nil && *d.RainIn >= 0.01 { rainy++ } if d.Obs > 0 { @@ -309,7 +324,7 @@ func renderMonthView(days []store.DayStat, offset int, metric heatMetric) string } stats = append(stats, statRow([]string{valF(mhi, "hi %.0f°"), valF(mlo, "lo %.0f°")}), - statRow([]string{fmt.Sprintf("rain %.2f in", rain), pluralN(rainy, "rainy day")}), + statRow([]string{historicalRainLabel(historicalRainTotal(rain, reads), reads, obs), pluralN(rainy, "rainy day")}), statRow([]string{valF(mgust, "gust %.0f mph")}), statRow([]string{fmt.Sprintf("observed %d/%d days", observed, daysIn(start, end))}), ) @@ -427,7 +442,9 @@ func monthStrip(months []store.PeriodStat, start time.Time) string { rainHi := 0.0 for _, p := range months { byMonth[p.Period] = p - rainHi = max(rainHi, p.RainIn) + if p.RainIn != nil { + rainHi = max(rainHi, *p.RainIn) + } } head, temp, rain := strings.Repeat(" ", 6), faint().Render(fmt.Sprintf("%-6s", "temp")), faint().Render(fmt.Sprintf("%-6s", "rain")) for m := 1; m <= 12; m++ { @@ -444,11 +461,15 @@ func monthStrip(months []store.PeriodStat, start time.Time) string { } else { temp += faint().Render(gapDot) + " " } + if p.RainIn == nil { + rain += faint().Render(gapDot) + " " + continue + } idx := 0 if rainHi > 0 { - idx = int(norm(p.RainIn, 0, rainHi) * float64(len(blocks8)-1)) + idx = int(norm(*p.RainIn, 0, rainHi) * float64(len(blocks8)-1)) } - rain += lipgloss.NewStyle().Foreground(rainColor(p.RainIn, 0, rainHi)). + rain += lipgloss.NewStyle().Foreground(rainColor(*p.RainIn, 0, rainHi)). Render(string(blocks8[idx])) + " " } return strings.Join([]string{head, temp, rain}, "\n") @@ -458,14 +479,19 @@ func monthStrip(months []store.PeriodStat, start time.Time) string { func yearStats(days []store.DayStat) string { var hi, lo, gust *float64 rain := 0.0 + var reads, obs int64 for _, d := range days { hi, lo = maxPtrVal(hi, d.TempMaxF), minPtrVal(lo, d.TempMinF) gust = maxPtrVal(gust, d.PeakGustMph) - rain += d.RainIn + reads += d.RainReadings + obs += d.Obs + if d.RainIn != nil { + rain += *d.RainIn + } } return statRow([]string{ valF(hi, "hi %.0f°"), valF(lo, "lo %.0f°"), - fmt.Sprintf("rain %.2f in", rain), + historicalRainLabel(historicalRainTotal(rain, reads), reads, obs), valF(gust, "gust %.0f mph"), }) } @@ -530,7 +556,7 @@ func renderRecordsView(rd recordsData) string { } for _, yd := range rd.thisDay { line := fmt.Sprintf(" %-6d %s %s %s", - yd.Year, tempCell(yd.TempMaxF), tempCell(yd.TempMinF), rainCell(yd.RainIn, 8)) + yd.Year, tempCell(yd.TempMaxF), tempCell(yd.TempMinF), rainCell(yd.RainIn, 8, yd.RainReadings < yd.Obs)) if yd.Year == hiYear && hiRec != nil { line += faint().Render(" ← record high") } @@ -604,3 +630,19 @@ func pluralN(n int, noun string) string { return fmt.Sprintf("%d %ss", n, noun) } } + +func historicalRainTotal(total float64, reads int64) *float64 { + if reads == 0 { + return nil + } + return &total +} +func historicalRainLabel(total *float64, reads, obs int64) string { + if total == nil { + return "rain unavailable" + } + if reads < obs { + return fmt.Sprintf("rain ≥%.2f in", *total) + } + return fmt.Sprintf("rain %.2f in", *total) +} diff --git a/cmd/tempestkeep/history_rain_coverage_test.go b/cmd/tempestkeep/history_rain_coverage_test.go new file mode 100644 index 0000000..d3e05c9 --- /dev/null +++ b/cmd/tempestkeep/history_rain_coverage_test.go @@ -0,0 +1,80 @@ +package main + +import ( + "strings" + "testing" + "time" + + "github.com/lennrt/tempestkeep/pkg/tempest/store" +) + +func TestHistoricalRainDisplayCoverage(t *testing.T) { + if got := weekStats([]store.DayStat{{Obs: 2}}); !strings.Contains(got, "rain unavailable") { + t.Fatalf("missing rain: %s", got) + } + if got := weekStats([]store.DayStat{{Obs: 2, RainReadings: 1, RainIn: new(0.0)}}); !strings.Contains(got, "rain ≥0.00 in") { + t.Fatalf("partial dry rain: %s", got) + } + if got := rainCell(nil, 0, false); !strings.Contains(got, gapDot) { + t.Fatalf("missing cell: %s", got) + } +} + +func TestHistoricalRainCellsShowPartialCoverage(t *testing.T) { + for _, total := range []float64{0, 1.25} { + for _, readings := range []int64{1, 2} { + day := store.DayStat{Day: "2024-01-15", Obs: 2, RainReadings: readings, RainIn: &total} + history := store.YearDay{Year: 2024, Obs: 2, RainReadings: readings, RainIn: &total} + for _, output := range []string{renderWeekView([]store.DayStat{day}, 0), renderRecordsView(recordsData{thisDay: []store.YearDay{history}})} { + if strings.Contains(output, "≥") != (readings < 2) { + t.Fatalf("total=%v readings=%d partial coverage lost: %s", total, readings, output) + } + } + } + } +} + +func TestDayRainSparklinePreservesMissingAndReportedReadings(t *testing.T) { + start := time.Date(2024, 1, 15, 0, 0, 0, 0, time.Local) + for _, tc := range []struct { + name string + readings int64 + total float64 + want string + }{ + {"missing", 0, 0, gapDot}, + {"measured zero", 2, 0, string(blocks8[0])}, + {"partial zero", 1, 0, string(blocks8[0])}, + {"partial positive", 1, 1.25, string(blocks8[len(blocks8)-1])}, + } { + t.Run(tc.name, func(t *testing.T) { + output := renderDayView(dayData{ + points: []store.SeriesPoint{{ + Epoch: start.Unix(), Obs: 2, RainReadings: tc.readings, RainIn: tc.total, + }}, + stat: &store.DayStat{ + Day: start.Format(time.DateOnly), Obs: 2, RainReadings: tc.readings, + RainIn: historicalRainTotal(tc.total, tc.readings), + }, + }) + if tc.readings == 0 && !strings.Contains(output, "rain unavailable") || tc.readings == 1 && !strings.Contains(output, "rain ≥") { + t.Fatalf("missing day coverage: %s", output) + } + for line := range strings.SplitSeq(output, "\n") { + chart, found := strings.CutPrefix(line, faint().Render("rain ")) + if !found { + continue + } + want := tc.want + if tc.readings == 0 { + want = faint().Render(want) + } + if tc.readings == 0 && !strings.HasPrefix(chart, want) || tc.readings > 0 && !strings.Contains(chart, want) { + t.Fatalf("rain sparkline = %q, want first reading %q", chart, tc.want) + } + return + } + t.Fatalf("missing rain sparkline: %s", output) + }) + } +} diff --git a/cmd/tempestkeep/main.go b/cmd/tempestkeep/main.go index 0878201..f7690c6 100644 --- a/cmd/tempestkeep/main.go +++ b/cmd/tempestkeep/main.go @@ -133,6 +133,7 @@ var commands = map[string]func([]string) error{ "collect": cmdCollect, "export": cmdExport, "stats": cmdStats, + "status": cmdStatus, "list-devices": cmdListDevices, "mcp": cmdMCP, } @@ -360,6 +361,7 @@ Archive collect build or refresh local history explore browse day, week, month, year, and record views stats print a climate summary (text or JSON) + status inspect archive coverage, progress, and gaps offline export stream observations as CSV or JSON Lines Utilities diff --git a/cmd/tempestkeep/now.go b/cmd/tempestkeep/now.go index f6127ad..61a190c 100644 --- a/cmd/tempestkeep/now.go +++ b/cmd/tempestkeep/now.go @@ -156,7 +156,7 @@ func fillArchiveRainToday(ctx context.Context, st *store.Store, d *dashboard, no return nil } rain := days[len(days)-1].RainIn - d.rainTodayIn = &rain + d.rainTodayIn = rain return nil } diff --git a/cmd/tempestkeep/status.go b/cmd/tempestkeep/status.go new file mode 100644 index 0000000..87f5c02 --- /dev/null +++ b/cmd/tempestkeep/status.go @@ -0,0 +1,132 @@ +package main + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "strings" + "time" + + "github.com/lennrt/tempestkeep/pkg/tempest/collect" + "github.com/lennrt/tempestkeep/pkg/tempest/config" + "github.com/lennrt/tempestkeep/pkg/tempest/store" +) + +const statusCoverageNote = "Stored observations and internal gaps do not establish continuous coverage or sensor availability." + +type archiveStatusReport struct { + Observations int64 `json:"observations"` + FirstObs *string `json:"first_obs"` + LastObs *string `json:"last_obs"` + LastObsAgeSeconds *int64 `json:"last_obs_age_seconds"` + Fresh bool `json:"fresh"` + BackfillComplete bool `json:"backfill_complete"` + GapThreshold int64 `json:"gap_threshold_seconds"` + GapLimit int `json:"gap_limit"` + Gaps []store.Gap `json:"gaps"` + Note string `json:"note"` +} + +func cmdStatus(args []string) (err error) { + ctx, stop := signalContext() + defer stop() + fs := flag.NewFlagSet("status", flag.ContinueOnError) + describe(fs, "tempestkeep status: inspect archive coverage, freshness, backfill state, and\nthe ten largest internal gaps over one hour. Read-only; no token or network needed.", + "tempestkeep status --db ./tempest.sqlite", + "tempestkeep status --format json | jq .gaps") + db := fs.String("db", "", "path to the tempest.sqlite archive (or env TEMPEST_DB)") + format := fs.String("format", "text", "output format: text or json") + if err := parseFlags(fs, args); err != nil { + return err + } + *format = strings.ToLower(*format) + if *format != "text" && *format != "json" { + return usagef("--format must be text or json") + } + if err := config.LoadDotenv(ctx, ".env"); err != nil { + return err + } + path, err := config.ResolveDB(ctx, *db) + if err != nil { + return err + } + st, err := store.Open(ctx, path) + if err != nil { + return err + } + defer func() { err = errors.Join(err, st.Close()) }() + report, err := readArchiveStatus(ctx, st, time.Now()) + if err != nil { + return err + } + out := bufio.NewWriter(os.Stdout) + defer func() { err = errors.Join(err, out.Flush()) }() + return writeArchiveStatus(out, report, *format) +} + +func readArchiveStatus(ctx context.Context, st *store.Store, now time.Time) (archiveStatusReport, error) { + r := archiveStatusReport{GapThreshold: 3600, GapLimit: 10, Gaps: []store.Gap{}, Note: statusCoverageNote} + cov, err := st.Coverage(ctx) + if err != nil { + return r, err + } + r.Observations = cov.Count + if cov.MinEpoch.Valid && cov.MaxEpoch.Valid { + r.FirstObs = new(time.Unix(cov.MinEpoch.Int64, 0).Local().Format(time.RFC3339)) + r.LastObs = new(time.Unix(cov.MaxEpoch.Int64, 0).Local().Format(time.RFC3339)) + r.LastObsAgeSeconds = new(now.Unix() - cov.MaxEpoch.Int64) + r.Fresh = *r.LastObsAgeSeconds >= 0 && *r.LastObsAgeSeconds < r.GapThreshold + } + gaps, err := st.Gaps(ctx, r.GapThreshold, r.GapLimit) + if err != nil { + return r, err + } + r.Gaps = append(r.Gaps, gaps...) + marker, exists, err := st.Meta(ctx, collect.MetaBackfillComplete) + if err != nil { + return r, err + } + if exists && marker != "0" && marker != "1" { + return r, fmt.Errorf("%w: archive backfill completion state is invalid", collect.ErrInvalidCheckpoint) + } + r.BackfillComplete = marker == "1" + return r, nil +} + +func writeArchiveStatus(w io.Writer, r archiveStatusReport, format string) error { + if format == "json" { + enc := json.NewEncoder(w) + enc.SetIndent("", " ") + return enc.Encode(r) + } + out := textOutput{writer: w} + out.printf("Archive status\nObservations: %d\n", r.Observations) + if r.LastObs == nil { + out.println("Archive is empty; no observation timestamps are available.") + } else { + out.printf("First: %s\nLast: %s\nNewest age: %d seconds\n", *r.FirstObs, *r.LastObs, *r.LastObsAgeSeconds) + out.printf("Fresh (age 0..3599 seconds): %s\n", yesNo(r.Fresh)) + } + out.printf("Backfill complete: %s\n", yesNo(r.BackfillComplete)) + out.printf("Largest internal gaps over %d seconds (up to %d):\n", r.GapThreshold, r.GapLimit) + if len(r.Gaps) == 0 { + out.println(" No qualifying internal gaps.") + } + for _, gap := range r.Gaps { + out.printf(" %s to %s: %d seconds\n", gap.FromLocal, gap.ToLocal, gap.Seconds) + } + out.println(r.Note) + return out.err +} + +func yesNo(value bool) string { + if value { + return "yes" + } + return "no" +} diff --git a/cmd/tempestkeep/status_test.go b/cmd/tempestkeep/status_test.go new file mode 100644 index 0000000..0af52ca --- /dev/null +++ b/cmd/tempestkeep/status_test.go @@ -0,0 +1,204 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/lennrt/tempestkeep/pkg/tempest/collect" + "github.com/lennrt/tempestkeep/pkg/tempest/model" + "github.com/lennrt/tempestkeep/pkg/tempest/store" +) + +func runStatus(t *testing.T, args ...string) (string, string, int) { + t.Helper() + f, err := os.Create(filepath.Join(t.TempDir(), "status.txt")) + if err != nil { + t.Fatal(err) + } + defer func() { + if err := f.Close(); err != nil { + t.Error(err) + } + }() + previous := os.Stdout + os.Stdout = f + defer func() { os.Stdout = previous }() + var stderr bytes.Buffer + code := run(append([]string{"status"}, args...), f, &stderr) + if _, err := f.Seek(0, io.SeekStart); err != nil { + t.Fatal(err) + } + data, err := io.ReadAll(f) + if err != nil { + t.Fatal(err) + } + return string(data), stderr.String(), code +} + +func statusArchive(t *testing.T, epochs []int64, marker string) string { + t.Helper() + path := filepath.Join(t.TempDir(), "archive.sqlite") + w, err := store.OpenWriter(t.Context(), path) + if err != nil { + t.Fatal(err) + } + var rows []model.DeviceObs + for _, epoch := range epochs { + rows = append(rows, model.DeviceObs{Epoch: epoch}) + } + _, insertErr := w.InsertObs(t.Context(), 123, rows) + var metaErr error + if marker != "" { + metaErr = w.SetMeta(t.Context(), collect.MetaBackfillComplete, marker) + } + if err := errors.Join(insertErr, metaErr, w.Close()); err != nil { + t.Fatal(err) + } + return path +} + +func TestE2EOfflineArchiveStatus(t *testing.T) { + t.Chdir(t.TempDir()) + t.Setenv("TEMPEST_TOKEN", "") + t.Setenv("TEMPEST_API_BASE", "invalid-must-not-be-used") + base := int64(1700000000) + path := statusArchive(t, []int64{base, base + 3600, base + 10801}, "1") + before, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + out, stderr, code := runStatus(t, "--db", path, "--format", "json") + if code != exitOK || stderr != "" { + t.Fatalf("status=%d stderr=%q output=%q", code, stderr, out) + } + var got struct { + Observations int64 `json:"observations"` + FirstObs *string `json:"first_obs"` + LastObs *string `json:"last_obs"` + BackfillComplete bool `json:"backfill_complete"` + GapThreshold int64 `json:"gap_threshold_seconds"` + GapLimit int `json:"gap_limit"` + Gaps []store.Gap `json:"gaps"` + } + if err := json.Unmarshal([]byte(out), &got); err != nil { + t.Fatal(err) + } + if got.Observations != 3 || !got.BackfillComplete || got.FirstObs == nil || got.LastObs == nil || got.GapThreshold != 3600 || got.GapLimit != 10 { + t.Fatalf("incorrect status: %s", out) + } + if len(got.Gaps) != 1 || got.Gaps[0].From != base+3600 || got.Gaps[0].To != base+10801 || got.Gaps[0].Seconds != 7201 { + t.Fatalf("gap threshold/boundaries: %+v", got.Gaps) + } + out, stderr, code = runStatus(t, "--db", path) + if code != exitOK || stderr != "" || !strings.Contains(out, "7201 seconds") || !strings.Contains(out, "Backfill complete: yes") || !strings.Contains(out, "continuous coverage") { + t.Fatalf("text status=%d stderr=%q output=%q", code, stderr, out) + } + if strings.Contains(out, "Archive is empty") || strings.Contains(out, "No qualifying internal gaps") || !strings.Contains(out, "First: "+*got.FirstObs) || !strings.Contains(out, "Last: "+*got.LastObs) { + t.Fatalf("populated status hides timestamps or denies its gaps: %s", out) + } + after, err := os.ReadFile(path) + if err != nil || !bytes.Equal(before, after) { + t.Fatalf("read-only status changed archive: %v", err) + } +} + +func TestE2EEmptyArchiveStatus(t *testing.T) { + t.Chdir(t.TempDir()) + path := statusArchive(t, nil, "") + out, stderr, code := runStatus(t, "--db", path, "--format", "json") + if code != exitOK || stderr != "" { + t.Fatalf("status=%d stderr=%q", code, stderr) + } + var got map[string]any + if err := json.Unmarshal([]byte(out), &got); err != nil { + t.Fatal(err) + } + for _, key := range []string{"first_obs", "last_obs", "last_obs_age_seconds"} { + if value, ok := got[key]; !ok || value != nil { + t.Errorf("empty %s=%v exists=%v", key, value, ok) + } + } + gaps, ok := got["gaps"].([]any) + if !ok || len(gaps) != 0 || got["observations"] != float64(0) || got["fresh"] != false { + t.Fatalf("empty status: %s", out) + } + out, stderr, code = runStatus(t, "--db", path) + if code != exitOK || stderr != "" || !strings.Contains(out, "Archive is empty") || !strings.Contains(out, "No qualifying internal gaps") || strings.Contains(out, "Newest age:") { + t.Fatalf("empty text status=%d stderr=%q output=%q", code, stderr, out) + } +} + +func TestStatusRejectsInvalidFormatBeforeIO(t *testing.T) { + t.Chdir(t.TempDir()) + if err := os.WriteFile(".env", []byte("invalid dotenv line"), 0o600); err != nil { + t.Fatal(err) + } + path := filepath.Join(t.TempDir(), "missing", "archive.sqlite") + out, stderr, code := runStatus(t, "--db", path, "--format", "yaml") + if code != exitUsage || out != "" || !strings.Contains(stderr, "--format") { + t.Fatalf("status=%d out=%q stderr=%q", code, out, stderr) + } + if _, err := os.Stat(filepath.Dir(path)); !os.IsNotExist(err) { + t.Fatalf("status created path: %v", err) + } +} + +func TestStatusMissingArchiveDoesNotCreate(t *testing.T) { + t.Chdir(t.TempDir()) + path := filepath.Join(t.TempDir(), "missing", "archive.sqlite") + out, stderr, code := runStatus(t, "--db", path) + if code != exitFailure || out != "" || stderr == "" { + t.Fatalf("status=%d out=%q stderr=%q", code, out, stderr) + } + if _, err := os.Stat(filepath.Dir(path)); !os.IsNotExist(err) { + t.Fatalf("status created path: %v", err) + } +} + +func TestArchiveStatusFreshnessAndErrors(t *testing.T) { + base := int64(1700000000) + path := statusArchive(t, []int64{base}, "0") + st, err := store.Open(t.Context(), path) + if err != nil { + t.Fatal(err) + } + closeOnCleanup(t, st) + for _, age := range []int64{-1, 0, 3599, 3600, 7200} { + r, err := readArchiveStatus(t.Context(), st, time.Unix(base+age, 0)) + if err != nil || r.LastObsAgeSeconds == nil || *r.LastObsAgeSeconds != age || r.Fresh != (age >= 0 && age < 3600) { + t.Fatalf("age=%d report=%+v err=%v", age, r, err) + } + for _, format := range []string{"text", "json"} { + if err := writeArchiveStatus(failedOutput{}, r, format); !errors.Is(err, io.ErrClosedPipe) { + t.Fatalf("%s output error = %v", format, err) + } + } + } + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if _, err := readArchiveStatus(ctx, st, time.Now()); !errors.Is(err, context.Canceled) { + t.Fatalf("cancellation = %v", err) + } + if err := st.Close(); err != nil { + t.Fatal(err) + } + if _, err := readArchiveStatus(t.Context(), st, time.Now()); !errors.Is(err, store.ErrClosed) { + t.Fatalf("closed = %v", err) + } + bad, err := store.Open(t.Context(), statusArchive(t, nil, "invalid")) + if err != nil { + t.Fatal(err) + } + closeOnCleanup(t, bad) + if _, err := readArchiveStatus(t.Context(), bad, time.Now()); !errors.Is(err, collect.ErrInvalidCheckpoint) { + t.Fatalf("completion error = %v", err) + } +} diff --git a/docs/README.md b/docs/README.md index 5d0c902..e0b1255 100644 --- a/docs/README.md +++ b/docs/README.md @@ -15,8 +15,9 @@ your archive and default live station: 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. + The flag overrides the environment. MCP defaults to the first accessible + Tempest device. CLI collection reuses an existing archive's device and + discovers a device for a new archive or an empty archive without a saved 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. @@ -27,6 +28,11 @@ default or the archive. See [device selection and capabilities](mcp.md#capabilit [MCP configuration](mcp.md#build-and-connect), and the [searchable device view](mcp-apps.md#read-charts-and-tables). +![Synthetic station devices filtered by name](screenshots/mcp-app-devices.png) + +*The Devices table keeps each device beside its parent station. This example +uses synthetic stations in the local MCP Apps test host.* + ## Explore weather in your conversation In a host that supports MCP Apps, ask for a forecast, daily summary, wind rose, @@ -35,6 +41,8 @@ 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. | +| Read a daily forecast | Compare daily high, low, and maximum rain probability, then switch to hourly details. | +| Inspect a long SQL value | Search up to 65,536 characters per cell and open its text inspector. | | 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. | @@ -46,6 +54,9 @@ explains controls, limits, and host support. ## Repair and reuse an archive +- **Inspect offline coverage.** Run `tempestkeep status --format json` for + freshness, backfill state, and up to ten internal gaps over one hour. + See [archive status](../cmd/tempestkeep/README.md#archive-status). - **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. @@ -110,7 +121,7 @@ See [offline startup and capabilities](mcp.md#start-and-stop) and - [MCP Apps ADR](adr/0006-mcp-apps.md): embedded views, protocol compatibility, browser boundaries, and the proposed 0.3.0 release. -- [Go patch toolchain ADR](adr/0007-go-patch-toolchain.md): the Go 1.27.2 pin and +- [Go patch toolchain ADR](adr/0007-go-patch-toolchain.md): the historical Go 1.27.2 pin and qualification of the updated toolchain. - [Archive recovery and coverage ADR](adr/0008-archive-recovery-and-coverage.md): @@ -126,6 +137,23 @@ See [offline startup and capabilities](mcp.md#start-and-stop) and - [Rain summary coverage ADR](adr/0012-rain-summary-coverage.md): nullable totals, sample counts, and missing/partial rain in reports and interactive views. +- [Paired comfort ADR](adr/0013-paired-comfort-readings.md): matching sensor + inputs before calculating apparent temperature and dew point. +- [Unique backup ADR](adr/0014-unique-archive-backups.md): bounded collision + handling and retention across old and new snapshot names. +- [Result exploration ADR](adr/0015-bounded-result-exploration.md): daily + forecast cards, cell inspection, and dataset keyboard focus. +- [Offline status ADR](adr/0016-offline-archive-status.md): read-only coverage, + freshness, saved backfill state, and bounded internal gaps. +- [Historical rain ADR](adr/0017-historical-rain-coverage.md): nullable totals, + sample counts, and rain-contributing years in normals. +- [Collection identity and live order ADR](adr/0018-preserve-collection-device-and-live-order.md): + automatic CLI device selection, positive selectors, and newest live readings. +- [Go security patch ADR](adr/0020-go-security-patch.md): the active Go 1.27.3 + pin, GO-2026-6809 fix, and preservation of historical check records. +- [Next development version ADR](adr/0019-next-development-version.md): the + 0.5.0 target and preserved publication boundaries. + ## Review correctness and security - [Correctness properties](testing/properties.md): guarantees converted into diff --git a/docs/adr/0013-paired-comfort-readings.md b/docs/adr/0013-paired-comfort-readings.md new file mode 100644 index 0000000..391ef6d --- /dev/null +++ b/docs/adr/0013-paired-comfort-readings.md @@ -0,0 +1,29 @@ +# ADR 0013: Paired comfort readings + +Status: Proposed + +## Context + +Independent sensor means can combine a temperature-only row with a +humidity-only row and report a heat index or dew point never supported by a +complete observation. The same problem affects cold temperature and wind. + +## Decision + +Within each existing 15-minute epoch bucket, calculate temperature and humidity +means from exactly the rows carrying both values. Use those paired means for +dew point and, when their temperature is at least 80°F, heat index. Calculate +temperature and wind means from exactly the rows carrying both values; when +their temperature is at most 50°F, use them for wind chill. Keep the existing +mild-air fallback from all available temperature samples when their mean lies +strictly between 50°F and 80°F. Each available apparent-temperature candidate +contributes to the daily minimum and maximum. Pairing does not cross buckets. +Measured zero remains a value. Missing required pairs produce no corresponding +derived reading. A bucket with temperature still counts as an observed day. + +## Consequences + +No schema, dependency, public signature, or JSON field changes. Historical +comfort values can change when sensors have different sample coverage. +Quarter-hour aggregation remains an estimate; pairing does not turn it into +instantaneous extremes. Reads remain on the read-only Store connection. diff --git a/docs/adr/0014-unique-archive-backups.md b/docs/adr/0014-unique-archive-backups.md new file mode 100644 index 0000000..97747f0 --- /dev/null +++ b/docs/adr/0014-unique-archive-backups.md @@ -0,0 +1,25 @@ +# ADR 0014: Unique archive backup names + +## Status + +Proposed. + +## Context + +Post-collection snapshots use second-precision names and atomic no-overwrite +publication. A second backup in the same second fails because its name exists. + +## Decision + +Use fixed UTC nanosecond-precision names. On collision, advance the candidate +instant by one nanosecond, up to 100 attempts. Keep atomic hard-link publication, +private permissions, temporary-file cleanup, and bounded directory reads. +Recognize both old and new names for retention. Compare parsed timestamps and +use filename order only when timestamps tie. + +## Consequences + +New backup filenames include a fractional second. Legacy backups still rotate. +An occupied candidate cannot be overwritten. Exhausted retries return an error. +Clock rollback retains the existing timestamp-based retention limitation. +No archive schema, public Go API, or runtime dependency changes. diff --git a/docs/adr/0015-bounded-result-exploration.md b/docs/adr/0015-bounded-result-exploration.md new file mode 100644 index 0000000..47b3962 --- /dev/null +++ b/docs/adr/0015-bounded-result-exploration.md @@ -0,0 +1,24 @@ +# ADR 0015: Bounded result exploration + +Status: proposed + +## Context + +SQL cell previews truncate strings before search and do not expose the hidden +suffix. Dataset selection replaces the focused button. Daily forecasts offer +charts and tables without daily summary cards. + +## Decision + +Keep compact previews and add an accessible native modal for long SQL strings. +Search and expanded inspection share a 65,536-character per-cell limit. Disclose +that limit when received values exceed it. Keep existing row and column limits, +render untrusted strings as text, and preserve raw tool results. Restore focus +on dataset changes and after modal dismissal. Show daily forecast high, low, +maximum rain probability, and returned day count using available values. + +## Consequences + +SQL search can find more received text while remaining bounded. Oversized values +still require inspection through the original tool result. UI changes add no +network requests, runtime dependencies, tool schemas, or archive writes. diff --git a/docs/adr/0016-offline-archive-status.md b/docs/adr/0016-offline-archive-status.md new file mode 100644 index 0000000..2c9dfb3 --- /dev/null +++ b/docs/adr/0016-offline-archive-status.md @@ -0,0 +1,44 @@ +# ADR 0016: Offline archive status command + +Status: proposed + +## Context + +The CLI repairs selected archive dates, but only MCP exposes the largest gaps. +The stats command runs climate analyses and does not report collection progress. +Terminal users and scripts need a short read-only inspection before a repair. + +## Decision + +Add `tempestkeep status --db PATH --format text|json`. Reuse Store.Coverage, +Store.Gaps, and Store.Meta. Open only an existing archive and perform no network +requests. Report stored observation count, first/last timestamps, newest-row age, +freshness, saved backfill completion, and up to ten largest gaps over one hour. + +Use a fixed one-hour freshness threshold. A future observation is not fresh. +JSON encodes absent timestamps and age as null, and absent gaps as an empty array. +The existing completion marker accepts only absent, 0, or 1. Reject other values +with the existing invalid-checkpoint error. Validate format before configuration. + +## Consequences + +This adds a command and a JSON shape without changing a public Go API or archive +schema. Output does not expose the archive path or credentials. Stored sample +counts and internal gaps do not prove continuous coverage or sensor availability. +The fixed gap limit and threshold appear in the output. First and last gaps +outside the stored observation range cannot be inferred. + +Independent review found that an externally modified metadata value could exceed +the writer's existing 4,096-byte limit. Both metadata readers now bound the SQL +projection and enforce that same UTF-8 byte limit after conversion. SQLite BLOB +casts measure the database encoding. The SQL bound is 8,192 encoded bytes so +valid values in UTF-16 archives remain readable. The projected UTF-8 string +contains at most 12,288 bytes. The reader rejects values over 4,096 UTF-8 bytes. +Materialize one matching metadata value before checking its size. This keeps +legacy views with nondeterministic expressions from changing the value between +the guard and projection. The limit bounds Go strings returned by the driver; +it does not bound SQLite's internal work to evaluate an external schema. +Null and NUL-containing values also return ErrInvalidArchive. Ordinary invalid +completion markers still return ErrInvalidCheckpoint. Store.Meta still supports +missing legacy metadata tables. This is an intentional read-validation change without an API shape +change, schema migration, or new limit. diff --git a/docs/adr/0017-historical-rain-coverage.md b/docs/adr/0017-historical-rain-coverage.md new file mode 100644 index 0000000..a7a858b --- /dev/null +++ b/docs/adr/0017-historical-rain-coverage.md @@ -0,0 +1,21 @@ +# ADR 0017: Historical rain sample coverage + +Status: Proposed + +## Context +Historical summaries reported zero when every rain measurement was missing. Rain normals counted +such months as dry. + +## Decision +DayStat, PeriodStat and YearDay RainIn become *float64, encoded as a number or explicit null. +They retain Obs and expose RainReadings. MonthNormal AvgRainIn and AvgRainyDays become *float64 +and RainYears counts contributing months across years. Missing-rain months do not enter rain +averages. RainyDays remains a count of observed rainy days. + +## Consequences +Go clients must handle pointers; JSON clients must handle null. Existing archives and SI storage +remain unchanged. Partial readings produce available sums. Terminal summaries mark partial sums +with ≥; JSON carries the exact sample counts. Counts never establish temporal completeness and +partial months remain eligible for normals. Temperature normal denominators remain unchanged. +The terminal day rain sparkline leaves buckets without rain readings as gaps. It preserves +reported zero and available partial sums; the day's summary states missing or partial coverage. diff --git a/docs/adr/0018-preserve-collection-device-and-live-order.md b/docs/adr/0018-preserve-collection-device-and-live-order.md new file mode 100644 index 0000000..74d6bca --- /dev/null +++ b/docs/adr/0018-preserve-collection-device-and-live-order.md @@ -0,0 +1,27 @@ +# ADR 0018: Preserve collection device and select newest live readings + +Status: proposed + +Collection without a flag or environment device selector previously discovered +the first live device on every run. Station reordering could break a scheduled +run against an archive already bound to another device. + +Use existing archive identity before discovery. Positive explicit flags override +environment settings. A nonempty environment selector must also be positive. +Reject explicit nonpositive flags before loading configuration. A missing archive +or an empty unbound archive still discovers. Read-only archive inspection must +fail closed on invalid data. Legacy rows with device IDs retain that identity; +legacy archives without a usable identity require an explicit selector. Writer +binding remains the final ownership check, including concurrent changes. + +Read persisted identity through the shared bounded metadata reader. This keeps +selection consistent with writer binding in UTF-16 archives and for legacy +metadata tables whose names differ only in letter case. + +Live latest observations use the largest validated timestamp, independent of +response order. The first row wins a timestamp tie. Validate every row before +returning a result, so an older malformed row still rejects the response. + +No schema, public signature, credential output, or runtime dependency changes. +Supplying zero explicitly now fails instead of requesting discovery; omit the +selector to use archive identity or discovery. diff --git a/docs/adr/0019-next-development-version.md b/docs/adr/0019-next-development-version.md new file mode 100644 index 0000000..0143315 --- /dev/null +++ b/docs/adr/0019-next-development-version.md @@ -0,0 +1,23 @@ +# ADR 0019: Next development version + +Status: proposed + +## Context + +The merged 0.4.0 development baseline precedes this batch of ten improvements. +The batch changes public rain nullability, collection selection, backup names, +and interactive forecast and table behavior. It adds an offline status command. + +## Decision + +Set the development version source and plugin manifest to 0.5.0. The app build +reads that same source. Untagged fallback builds report `v0.5.0-dev`. Preserve +linker and Go module version precedence. Preserve historical changelog, ADR, +and qualification evidence. Record the ten improvements and compatibility +effects in the new changelog section. Do not update dependencies for this bump. + +## Consequences + +Version 0.5.0 is a proposed development target. This decision does not authorize +a tag, release, plugin publication, deployment, or merge. Release qualification +and publication remain separate maintainer decisions under RELEASING.md. diff --git a/docs/adr/0020-go-security-patch.md b/docs/adr/0020-go-security-patch.md new file mode 100644 index 0000000..10851de --- /dev/null +++ b/docs/adr/0020-go-security-patch.md @@ -0,0 +1,27 @@ +# ADR 0020: Go security patch + +Status: proposed + +## Context + +The final vulnerability check found GO-2026-6809 in Go 1.27.2. Go 1.27.3 +fixes this standard-library vulnerability. The Go release notes date the patch +to October 19, 2026. Earlier checks with 1.27.2 remain historical evidence. + +Sources: [Go vulnerability record](https://pkg.go.dev/vuln/GO-2026-6809) and +[Go release notes](https://go.dev/doc/devel/release#go1.27.3). + +## Decision + +Require Go 1.27.3 in the module, Makefile guard, CI, CodeQL, demo, release +qualification, and active contributor guidance. Update the current OpenSpec +context and patch requirement. Preserve old ADRs, release notes, proposals, +and dated test records. Keep all module and npm dependency versions unchanged. + +## Consequences + +Contributors must select Go 1.27.3. The exact-version guard rejects 1.27.2. +Rebuild binaries with the fixed toolchain and repeat vulnerability checks. +This supporting security repair does not add an eleventh feature, publish a +release, or certify earlier binaries. Archive formats and application APIs +remain unchanged. Release approval remains a separate maintainer decision. diff --git a/docs/architecture.md b/docs/architecture.md index 7f1e6f0..04cf78d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # Architecture -TempestKeep builds one Go 1.27.2 command over one shared core: +TempestKeep builds one Go 1.27.3 command over one shared core: - `tempestkeep` owns setup, collection, export, reports, and terminal views. - `tempestkeep mcp` exposes live and archived data over MCP stdio. @@ -103,6 +103,10 @@ the same ID. This rule prevents mixed-device aggregates. create or migrate a file. Both handles reject symlinks and file replacement during open. +Metadata readers enforce the writer's existing 4,096-byte and NUL limits. +SQL excludes oversized values before the driver creates a Go string. Oversized, +null, or NUL-containing metadata returns `ErrInvalidArchive`. + The read-only SQL operation accepts one `SELECT` or `WITH ... SELECT`. It also uses SQLite `query_only`. It limits query bytes, execution time, columns, rows, and returned bytes. Connection-level limits restrict large SQLite expressions @@ -125,8 +129,10 @@ writer, so other writers must remain stopped through that copy. The CLI copies the database to an owner-only temporary file, syncs it, and closes it. A filesystem hard link publishes the snapshot without replacing an -existing file. Rotation recognizes the exact timestamped filename format and -preserves unrelated files. Backups live beside the archive in `backups`. +existing file. New names include nine fractional second digits in UTC. Publication tries at +most 100 nanosecond candidates without replacing existing files. Rotation +recognizes both new names and legacy second-resolution names, orders parsed +timestamps, and preserves unrelated files. Backups live beside the archive in `backups`. ## Time and units diff --git a/docs/demo.md b/docs/demo.md index 8d8c517..6961325 100644 --- a/docs/demo.md +++ b/docs/demo.md @@ -27,7 +27,7 @@ samples with a wind speed. ## Run and verify -With Go 1.27.2 installed: +With Go 1.27.3 installed: ```sh make mcp-demo # paced terminal demonstration diff --git a/docs/mcp-apps.md b/docs/mcp-apps.md index 54c1e49..ad62c43 100644 --- a/docs/mcp-apps.md +++ b/docs/mcp-apps.md @@ -65,7 +65,16 @@ 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. +available to the host. Cell previews contain at most 2,048 characters. SQL text search and the cell +inspector cover at most 65,536 characters per cell. A notice identifies longer +values. Open a long cell to inspect its text in a modal dialog. Scroll with +the keyboard, then press Escape or use Close to return focus to its button. +Values remain text, including HTML-like strings. + +Daily forecast cards show daily high, low, and maximum rain probability. Missing +values remain unavailable and measured zero stays zero. Switching to hourly +forecasts restores hourly summary labels. Dataset selection keeps keyboard +focus on the selected control after rendering. Initial results do not steal focus. If a result is truncated, narrow its dates, reduce its selected columns, or use an aggregate query. The truncation notice remains visible during table @@ -83,6 +92,11 @@ The view reports missing and partial buckets, and keeps their counts in the tabl These counts describe samples, not continuous sensor uptime. Original tool results remain intact. Older results without counts retain their existing display. +Historical daily, month/year, and this-day views retain missing rain as `—`. +Their tables include `rain_readings` beside observation counts. Climate normals +show `rain_years` and explain that partial months can contribute available totals. +These counts do not establish complete calendar coverage. + 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 @@ -199,9 +213,12 @@ npm run app:screenshots ``` Playwright captures the embedded app in the local synthetic test host. The -generated files are [the weather preview](screenshots/mcp-app-weather.png) and -[the table preview](screenshots/mcp-app-table.png). Inspect both images before -committing them with a UI change. +generated files show [weather charts](screenshots/mcp-app-weather.png), +[SQL tables](screenshots/mcp-app-table.png), +[daily forecasts](screenshots/mcp-app-forecast.png), and +[station devices](screenshots/mcp-app-devices.png). Inspect each image before +committing it with a UI change. The Devices example filters by a synthetic station +name and keeps the parent station beside every device. These screenshots show fixture data and the app's layout. They are not captures of a production station or evidence of compatibility with a named third-party diff --git a/docs/mcp.md b/docs/mcp.md index 306a90f..2b8640c 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -6,7 +6,7 @@ input and output. This command does not start an HTTP server or open a port. ## Build and connect -Use Go 1.27.2 from the repository root: +Use Go 1.27.3 from the repository root: ```sh make tempestkeep @@ -75,6 +75,12 @@ 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. +CLI `collect` has a different automatic rule: it reuses an existing archive's +device. New archives and empty archives without a saved device discover the first +accessible Tempest device. An empty archive with a saved device keeps that device. +Use an explicit positive selector when an old archive has no usable identity. +MCP keeps its lazy live selection rule described above. + 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 @@ -83,6 +89,10 @@ 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. +For CLI collection, every nonempty environment ID, including zero, must be +positive. Explicit zero flags also fail before archive or API access. MCP +retains its zero environment value as automatic selection. + 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 @@ -94,6 +104,14 @@ belongs to that station. Missing or mismatched identity leaves those fields absent. Do not assume that live weather and a configured archive describe the same station. See the [query guide](querying.md) before combining their results. +Live observations select the greatest accepted timestamp rather than relying +on API row order. All rows still pass validation before selection. The first +row wins when several rows share the greatest timestamp. + +Historical rain results include nullable totals and sample counts. Rain normals +expose `rain_years` and nullable averages. See the +[query guide](querying.md) before comparing partial months or handling JSON null. + ## MCP Apps Supporting hosts can display interactive weather charts and tables for all diff --git a/docs/openssf.md b/docs/openssf.md index a6b8f9b..b757717 100644 --- a/docs/openssf.md +++ b/docs/openssf.md @@ -42,7 +42,7 @@ another project's copied answers. Recheck time-dependent claims on each update. ## Reproduce the engineering evidence -Use Go 1.27.2 and a C toolchain for race checks. No live WeatherFlow token is +Use Go 1.27.3 and a C toolchain for race checks. No live WeatherFlow token is needed: ```sh diff --git a/docs/public-api.txt b/docs/public-api.txt index ea2f71a..30a6492 100644 --- a/docs/public-api.txt +++ b/docs/public-api.txt @@ -353,13 +353,14 @@ type Coverage struct { MaxEpoch sql.NullInt64 } type DayStat struct { - Day string `json:"day"` // YYYY-MM-DD, local time - TempMinF *float64 `json:"temp_min_f,omitempty"` - TempMaxF *float64 `json:"temp_max_f,omitempty"` - TempAvgF *float64 `json:"temp_avg_f,omitempty"` - RainIn float64 `json:"rain_in"` - PeakGustMph *float64 `json:"peak_gust_mph,omitempty"` - Obs int64 `json:"obs"` + Day string `json:"day"` // YYYY-MM-DD, local time + TempMinF *float64 `json:"temp_min_f,omitempty"` + TempMaxF *float64 `json:"temp_max_f,omitempty"` + TempAvgF *float64 `json:"temp_avg_f,omitempty"` + RainIn *float64 `json:"rain_in"` + RainReadings int64 `json:"rain_readings"` + PeakGustMph *float64 `json:"peak_gust_mph,omitempty"` + Obs int64 `json:"obs"` } type DegreeDayParams struct { HeatingBaseF float64 // HDD base (US convention: 65°F) @@ -414,8 +415,9 @@ type MonthNormal struct { TempAvgF *float64 `json:"temp_avg_f,omitempty"` TempMinF *float64 `json:"temp_min_f,omitempty"` // average of the monthly lows TempMaxF *float64 `json:"temp_max_f,omitempty"` // average of the monthly highs - AvgRainIn float64 `json:"avg_rain_in"` - AvgRainyDays float64 `json:"avg_rainy_days"` + RainYears int64 `json:"rain_years"` + AvgRainIn *float64 `json:"avg_rain_in"` + AvgRainyDays *float64 `json:"avg_rainy_days"` } type Period uint8 const ( @@ -427,11 +429,12 @@ type PeriodStat struct { TempMinF *float64 `json:"temp_min_f,omitempty"` TempMaxF *float64 `json:"temp_max_f,omitempty"` TempAvgF *float64 `json:"temp_avg_f,omitempty"` - RainIn float64 `json:"rain_in"` + RainIn *float64 `json:"rain_in"` PeakGustMph *float64 `json:"peak_gust_mph,omitempty"` DaysObserved int64 `json:"days_observed"` RainyDays int64 `json:"rainy_days"` Obs int64 `json:"obs"` + RainReadings int64 `json:"rain_readings"` } type PressureStats struct { DaysObserved int64 `json:"days_observed"` @@ -640,12 +643,13 @@ func (w *Writer) Meta(ctx context.Context, key string) (string, bool, error) func (w *Writer) SetMeta(ctx context.Context, key, value string) error func (w *Writer) Watermark(ctx context.Context, deviceID int) (int64, bool, error) type YearDay struct { - Year int `json:"year"` - Day string `json:"day"` // YYYY-MM-DD, local time - TempMinF *float64 `json:"temp_min_f,omitempty"` - TempMaxF *float64 `json:"temp_max_f,omitempty"` - TempAvgF *float64 `json:"temp_avg_f,omitempty"` - RainIn float64 `json:"rain_in"` - PeakGustMph *float64 `json:"peak_gust_mph,omitempty"` - Obs int64 `json:"obs"` + Year int `json:"year"` + Day string `json:"day"` // YYYY-MM-DD, local time + TempMinF *float64 `json:"temp_min_f,omitempty"` + TempMaxF *float64 `json:"temp_max_f,omitempty"` + TempAvgF *float64 `json:"temp_avg_f,omitempty"` + RainIn *float64 `json:"rain_in"` + PeakGustMph *float64 `json:"peak_gust_mph,omitempty"` + Obs int64 `json:"obs"` + RainReadings int64 `json:"rain_readings"` } diff --git a/docs/querying.md b/docs/querying.md index bc6d9e7..adf16ad 100644 --- a/docs/querying.md +++ b/docs/querying.md @@ -190,6 +190,11 @@ sensor reading breaks the run. One valid reading lets a day qualify, so a reported spell does not imply complete sensor coverage throughout every day. `comfort_stats` calculates apparent temperature from 15-minute sensor means. +Heat index and dew point use temperature and humidity from the same rows. +Wind chill uses temperature and wind speed from the same rows. Unpaired +readings cannot create a derived value. Each candidate uses its own paired +temperature mean. Ordinary air-temperature summaries still use all temperature +readings. At or above 80°F, it needs humidity. At or below 50°F, it needs wind speed. Between those temperatures, it uses air temperature alone. Missing required readings leave the apparent value unavailable. These calculated extremes @@ -201,6 +206,20 @@ with zero and call the result observed weather. A day with a few observations can still contribute to a daily summary. Compare sample counts and covered dates before ranking days, months, or years. +Historical daily, month/year, and this-day summaries return `rain_in: null` +when no rain readings exist. Measured zero remains numeric zero. `obs` and +`rain_readings` expose sample counts. A partial range sums available readings. +A count below `obs` means some samples lack rain, not that the total is zero. + +Climate rain normals use only months with rain readings. `rain_years` counts +those contributing years for each calendar month, independently of temperature +years. Partial months still contribute their available totals. `avg_rain_in` +and `avg_rainy_days` are null when `rain_years` is zero. These are available +sample averages, not estimates of complete months. Go callers must handle +nullable `RainIn` fields on `DayStat`, `PeriodStat`, and `YearDay`, plus +nullable `MonthNormal.AvgRainIn` and `MonthNormal.AvgRainyDays`. JSON consumers +must accept explicit null rain fields and the additional sample counts. + `climate_normals` describes the available archive. It does not establish a standard long-term climate baseline. `temperature_trend` fits one slope with a separate baseline for each calendar month. Each usable monthly mean has equal diff --git a/docs/screenshots/mcp-app-devices.png b/docs/screenshots/mcp-app-devices.png new file mode 100644 index 0000000..93d9f0d Binary files /dev/null and b/docs/screenshots/mcp-app-devices.png differ diff --git a/docs/screenshots/mcp-app-forecast.png b/docs/screenshots/mcp-app-forecast.png new file mode 100644 index 0000000..fe49b36 Binary files /dev/null and b/docs/screenshots/mcp-app-forecast.png differ diff --git a/docs/screenshots/mcp-app-weather.png b/docs/screenshots/mcp-app-weather.png index 83a70ee..87b03b8 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 57234f9..4c30789 100644 --- a/docs/testing/properties.md +++ b/docs/testing/properties.md @@ -3,7 +3,7 @@ This catalog converts repository guarantees into test targets. A passing test is evidence for the tested case. It is not proof of the general property. -All commands require Go 1.27.2. Tests have finite timeouts. Focused fuzz tests +All commands require Go 1.27.3. Tests have finite timeouts. Focused fuzz tests store any failing input in the Go fuzz corpus so the failure can be replayed. | ID | Property | Faults and boundaries | Current verification | diff --git a/docs/threat-model.md b/docs/threat-model.md index 028fe0b..34de494 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -19,7 +19,7 @@ operating system, or GitHub as trusted implementations. ## Trust roots - The user and the local operating-system account. -- The Go 1.27.2 toolchain and Go checksum database. +- The Go 1.27.3 toolchain and Go checksum database. - The configured WeatherFlow HTTPS endpoint. - Full commit SHAs in GitHub Actions. - The repository's reviewed source and generated API snapshot. diff --git a/go.mod b/go.mod index 4c4c074..62de6e5 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/lennrt/tempestkeep -go 1.27.2 +go 1.27.3 // Direct dependencies of note: // - github.com/modelcontextprotocol/go-sdk (official MCP SDK) diff --git a/internal/mcpapp/history.go b/internal/mcpapp/history.go index bea9f82..65aa11c 100644 --- a/internal/mcpapp/history.go +++ b/internal/mcpapp/history.go @@ -331,9 +331,9 @@ func registerCalendarTools(srv *mcp.Server, st *store.Store) { if y.TempMinF != nil && (out.RecordLowF == nil || *y.TempMinF < *out.RecordLowF) { out.RecordLowF, out.RecordLowYear = y.TempMinF, y.Year } - if y.RainIn > 0 && (out.WettestRainIn == nil || y.RainIn > *out.WettestRainIn) { + if y.RainIn != nil && (out.WettestRainIn == nil || *y.RainIn > *out.WettestRainIn) { rain := y.RainIn - out.WettestRainIn, out.WettestYear = &rain, y.Year + out.WettestRainIn, out.WettestYear = rain, y.Year } } if len(years) == 0 { diff --git a/internal/mcpapp/history_rain_coverage_test.go b/internal/mcpapp/history_rain_coverage_test.go new file mode 100644 index 0000000..8c2e790 --- /dev/null +++ b/internal/mcpapp/history_rain_coverage_test.go @@ -0,0 +1,92 @@ +package mcpapp + +import ( + "encoding/json" + "errors" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + "github.com/lennrt/tempestkeep/pkg/tempest/model" + "github.com/lennrt/tempestkeep/pkg/tempest/store" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +func TestHistoricalRainWireCoverage(t *testing.T) { + for _, measured := range []bool{false, true} { + t.Run(map[bool]string{false: "missing", true: "measured zero"}[measured], func(t *testing.T) { + path := filepath.Join(t.TempDir(), "archive.sqlite") + w, e := store.OpenWriter(t.Context(), path) + if e != nil { + t.Fatal(e) + } + var rain *float64 + if measured { + rain = new(0.0) + } + _, e = w.InsertObs(t.Context(), 456, []model.DeviceObs{{Epoch: time.Date(2024, 1, 15, 12, 0, 0, 0, time.Local).Unix(), RainMm: rain}}) + if e = errors.Join(e, w.Close()); e != nil { + t.Fatal(e) + } + cs := connectArchiveServer(t, t.Context(), path) + listed, e := cs.ListTools(t.Context(), nil) + if e != nil { + t.Fatal(e) + } + for _, tc := range []struct { + name, array, total, count string + args map[string]any + }{ + {"this_day_in_history", "years", "rain_in", "rain_readings", map[string]any{"date": "01-15"}}, + {"period_summary", "periods", "rain_in", "rain_readings", map[string]any{"period": "month"}}, + {"climate_normals", "months", "avg_rain_in", "rain_years", nil}, + } { + var schema string + for _, tool := range listed.Tools { + if tool.Name == tc.name { + b, e := json.Marshal(tool.OutputSchema) + if e != nil { + t.Fatal(e) + } + schema = string(b) + } + } + if !strings.Contains(schema, `"`+tc.count+`"`) || !strings.Contains(schema, `"null"`) { + t.Fatalf("schema does not expose nullable rain/count: %s", schema) + } + result, e := cs.CallTool(t.Context(), &mcp.CallToolParams{Name: tc.name, Arguments: tc.args}) + if e != nil || result.IsError { + t.Fatalf("call %s: %v %+v", tc.name, e, result) + } + var structured map[string]any + decodeStructured(t, result, &structured) + rows := structured[tc.array].([]any) + row := rows[0].(map[string]any) + v, exists := row[tc.total] + if !exists || !measured && v != nil || measured && v != float64(0) { + t.Fatalf("%s total/count: %+v", tc.name, row) + } + count := float64(0) + if measured { + count = 1 + } + if row[tc.count] != count { + t.Fatalf("count: %+v", row) + } + plain, ok := result.Content[0].(*mcp.TextContent) + if !ok { + t.Fatal("missing plain text") + } + var decoded map[string]any + if e = json.Unmarshal([]byte(plain.Text), &decoded); e != nil { + t.Fatal(e) + } + if !reflect.DeepEqual(decoded, structured) { + t.Fatalf("plain and structured differ: %s", plain.Text) + } + } + }) + } +} diff --git a/internal/mcpapp/tools.go b/internal/mcpapp/tools.go index d142555..e297a39 100644 --- a/internal/mcpapp/tools.go +++ b/internal/mcpapp/tools.go @@ -357,7 +357,7 @@ func fillRainToday(ctx context.Context, st *store.Store, c *ConditionsOut) { return } rain := last.RainIn - c.RainTodayIn = &rain + c.RainTodayIn = rain } // fillPressureTrend adds the archive's barometric rate normalized to 3 hours. diff --git a/internal/mcpapp/ui/app.html b/internal/mcpapp/ui/app.html index 791807a..1bf3b74 100644 --- a/internal/mcpapp/ui/app.html +++ b/internal/mcpapp/ui/app.html @@ -12,6 +12,9 @@ @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}} +.cell-inspect{margin-left:10px;border:1px solid var(--border);border-radius:4px;background:var(--soft);padding:2px 6px;font-size:10px;color:var(--accent)}.cell-dialog{width:min(760px,calc(100% - 28px));max-height:85vh;padding:20px;border:1px solid var(--border);border-radius:12px;background:var(--surface);color:var(--ink);overflow:auto}.cell-dialog::backdrop{background:#0007}.cell-dialog-head{display:flex;justify-content:space-between;align-items:center;gap:16px}.cell-dialog h2{margin:0;font-size:18px}.cell-column{color:var(--muted);overflow-wrap:anywhere}.cell-value{font:12px/1.6 ui-monospace,monospace;white-space:pre-wrap;overflow-wrap:anywhere;max-height:55vh;overflow:auto;padding:12px;background:var(--soft);border:1px solid var(--border);border-radius:6px}.cell-value:focus-visible{outline:3px solid var(--accent);outline-offset:3px} + +.cell-preview{display:inline-block;max-width:220px;overflow:hidden;text-overflow:ellipsis;vertical-align:middle}