Compare commits
432 Commits
05b56d6ea6
...
v0.12.0
| Author | SHA1 | Date | |
|---|---|---|---|
| 53aa0b0a55 | |||
| fc8ddada9a | |||
| 13b06039b1 | |||
| b9080466a2 | |||
| 142f2f92e7 | |||
| 88fde0df7f | |||
| b985c5faac | |||
| d6829af32b | |||
| cd7b9aef2b | |||
| c3ebf06bd5 | |||
| 7884b9a6c3 | |||
| 17468cb8dd | |||
| 71b7a74d3d | |||
| 2c4c0bbd90 | |||
| 965f16d7a4 | |||
| fb891fad07 | |||
| 0516ee148d | |||
| e6450138c2 | |||
| 57aa27c9de | |||
| 166c4ce53b | |||
| 78fc461a75 | |||
| 5e492cf1fb | |||
| 79cba800ee | |||
| 302f5aba2d | |||
| 0314a302f1 | |||
| 707db5394c | |||
| 70cad789ea | |||
| 4b748c2e53 | |||
| 0b57d99a97 | |||
| 04b8358965 | |||
| f4e3a6f26c | |||
| 44ee389334 | |||
| ef2634c2cb | |||
| a18d5134c7 | |||
| 2bd921f247 | |||
| 360c665a3e | |||
| e2dd8d0e29 | |||
| e520ffb13b | |||
| f8beed04cf | |||
| 44af91cadf | |||
| a38d291f63 | |||
| 27849813db | |||
| 41b86109e3 | |||
| 13829cc65c | |||
| daf0c7efd7 | |||
| 9b4e53702b | |||
| 730929e2ed | |||
| 8e49ba88c7 | |||
| 8fafacf921 | |||
| 8bb7307f22 | |||
| c515529b3a | |||
| 3c1ebab289 | |||
| 2d956f7315 | |||
| 4d5a1d9709 | |||
| 1d3ea64541 | |||
| 706086e3de | |||
| 26a681e0b1 | |||
| 5139c1a586 | |||
| 0b869af75e | |||
| c3eeb298f0 | |||
| 6945306a2f | |||
| 4f52555389 | |||
| fa19452dec | |||
| 91e7e5f321 | |||
| 4bb3913276 | |||
| ab571cd8ab | |||
| 798e6f11c5 | |||
| c49c50bc8d | |||
| d328a1daa6 | |||
| 7ae3820e12 | |||
| a4ef76f17a | |||
| 5ed1e264fc | |||
| c025afcd1a | |||
| 2b06541ef8 | |||
| d92ff0ef48 | |||
| 880ad710ae | |||
| edde330390 | |||
| ae52606772 | |||
| 8a323d5574 | |||
| cfb64ded34 | |||
| 5ed448df11 | |||
| 725c1420dd | |||
| e5250bd6cb | |||
| 00fe0c3e96 | |||
| 6d2c097657 | |||
| e7c7262404 | |||
| 151c536cb9 | |||
| 2b1fb26e7d | |||
| 3c7383e2ce | |||
| eed47b4f68 | |||
| 6c185b8d0e | |||
| faf547e4a8 | |||
| acb476a142 | |||
| 606b4423f1 | |||
| 1716702c99 | |||
| e0229d9c90 | |||
| ccf6b66880 | |||
| b489c56a48 | |||
| d39e42de30 | |||
| d642791c10 | |||
| 236e3d16c4 | |||
| 4fa873983d | |||
| de1ae896b3 | |||
| 6173e50d25 | |||
| 3bca2f41f7 | |||
| af9cb0c0dc | |||
| 20c82776dc | |||
| f364ce773d | |||
| 0dc6a06cd3 | |||
| 2af6a5cfd2 | |||
| 0c4c575eea | |||
| 114f7f5f85 | |||
| 328c7a5693 | |||
| fe176a2abc | |||
| ab9218b124 | |||
| 8d6ab0eb56 | |||
| 76cd399c76 | |||
| bf1746a756 | |||
| 28bdc04fba | |||
| b67fae886e | |||
| 71a2eae87b | |||
| bd34ec57f8 | |||
| 97215ddb9b | |||
| dd7881acfb | |||
| ece31567b8 | |||
| 7ffc3dc603 | |||
| 4bdba6f2b7 | |||
| b184ca7cbd | |||
| 62a12dd661 | |||
| ac8d618111 | |||
| 5ddd3ee19c | |||
| 8be9b020d4 | |||
| 7f5a9c0357 | |||
| 7d591487e4 | |||
| 1250247986 | |||
| 117c5336ba | |||
| c5ec4f83b2 | |||
| 39c097a710 | |||
| 993120a9f2 | |||
| c20e285d5f | |||
| acbe22dcad | |||
| cc97ae186c | |||
| 51c35f7c22 | |||
| f014a078ee | |||
| 8c19ad763b | |||
| 2dbba36bf0 | |||
| f302581722 | |||
| cf82633ab7 | |||
| 8d8cdbf3c5 | |||
| a206979307 | |||
| a6515c0e56 | |||
| 41df5058ba | |||
| e1bc174ea9 | |||
| 34c395d7e5 | |||
| 870b54a4a0 | |||
| 25782447eb | |||
| b96f40e5ca | |||
| 2c68d0a85f | |||
| a6d11c01e8 | |||
| 06b26d5e88 | |||
| 9a17a8de93 | |||
| 6064af2295 | |||
| a52a6ed22a | |||
| b0b703eab4 | |||
| e4e824ed41 | |||
| d5fcbfd20c | |||
| 2e0fb65a8b | |||
| 5e96790d85 | |||
| 35f4f82e94 | |||
| b605596bcb | |||
| 9303502b32 | |||
| f9eef80233 | |||
| c6f8570474 | |||
| 1130d807dc | |||
| ff2e664c62 | |||
| 2f3558cf33 | |||
| 154d31c3e8 | |||
| 6b1ff862f3 | |||
| 0c27fab384 | |||
| ad3b788f8c | |||
| 82acb8dc1a | |||
| 3aaddda676 | |||
| 7f989839cd | |||
| 27506168f8 | |||
| dc11e08e22 | |||
| fdddb5f08d | |||
| f78186b020 | |||
| 8dd604afb4 | |||
| 52bb17c8fa | |||
| 7952e4fb25 | |||
| 0281327365 | |||
| bf76eae301 | |||
| 0d47662cf9 | |||
| f4f009b904 | |||
| 3c1b753952 | |||
| bdbab48d10 | |||
| 16cc4b3f63 | |||
| 0ef861ed8f | |||
| 6ae7eb44cf | |||
| 8f6aa8aa8b | |||
| b8e889ad13 | |||
| 15ee4af1a1 | |||
| 4c606eb39f | |||
| 8d2ac163ae | |||
| 8709b5f4d8 | |||
| fd48ebecb8 | |||
| 021e5dd8b1 | |||
| 7adf5e1b08 | |||
| 455cc67d4c | |||
| dd3133ee2a | |||
| b3637cddd6 | |||
| 662db5e511 | |||
| 2ef91cf1b1 | |||
| 1d2f176977 | |||
| 2b3bcdd4f1 | |||
| a82f03feb8 | |||
| f1d4e38414 | |||
| 32060bd370 | |||
| 133f83f4ce | |||
| 42f0e16b02 | |||
| a2f0a2fc36 | |||
| 9f552cff6b | |||
| b913194fb4 | |||
| 3eccafad6b | |||
| a9d87bdbaa | |||
| 6f9255105d | |||
| c04e3c5599 | |||
| f15315f1b9 | |||
| 0ef6cd567e | |||
| b308ff4d6b | |||
| 5ecbc06c85 | |||
| 21e97f5d4e | |||
| 3900b3313b | |||
| 5d416cfc4a | |||
| 6532e8824a | |||
| d321492995 | |||
| b57110e5c8 | |||
| 482e83903c | |||
| 21a7748b2c | |||
| b36e198bfe | |||
| f9d6d42b1b | |||
| d9ab1e47ec | |||
| 4f755704d9 | |||
| a13f04fce5 | |||
| 1f5b347cd2 | |||
| 3639636813 | |||
| ca27d81163 | |||
| d74ba0f259 | |||
| 121f28fd29 | |||
| e3bcecc5c1 | |||
| 0884eb0ce5 | |||
| a27e870522 | |||
| d90801cff5 | |||
| 0f63159482 | |||
| 2792933833 | |||
| 9261431329 | |||
| 1bfd865333 | |||
| e5af7477af | |||
| 92fcbfcc05 | |||
| ff6aade42c | |||
| 4fac69c9f0 | |||
| 90ab6973e6 | |||
| 90a502f50e | |||
| 273f462e09 | |||
| 5361d5647b | |||
| d2e90da148 | |||
| 047ce32ac6 | |||
| 5896168a93 | |||
| fe9c40741a | |||
| 88004a1827 | |||
| a515b7e7d9 | |||
| 696454cf34 | |||
| 8c97788682 | |||
| 5203440ba0 | |||
| 3d452a120a | |||
| 4eece7cc8a | |||
| d0d0b698f9 | |||
| 4c4b01f265 | |||
| 58fe794227 | |||
| 63dfc0b55a | |||
| 1ddc33eb17 | |||
| 4a0238909b | |||
| 3d5f71e72d | |||
| 8ff5c44324 | |||
| 4e704e4f51 | |||
| 7b4c73d1e6 | |||
| 7efd8b5855 | |||
| 7cbc59d8a7 | |||
| 67b30dbad6 | |||
| cd8d77b37c | |||
| bb79232e3e | |||
| b4e0aadbef | |||
| 4fe0f40cef | |||
| 40b42f4bf3 | |||
| e8f1aa5caf | |||
| a02af0bce0 | |||
| ff2f8c16a3 | |||
| ace5577402 | |||
| 473f252aee | |||
| 74bd69834c | |||
| 98cab70b53 | |||
| dc0172ff82 | |||
| 0b41773017 | |||
| ddda42453f | |||
| 295f06915f | |||
| 120bce3391 | |||
| 386263784c | |||
| afe6803a63 | |||
| 5344c7880a | |||
| 74e32eb18e | |||
| ceb00ad45e | |||
| 7cd07c429b | |||
| 28b8391d53 | |||
| bb8de054dc | |||
| 9d6502460e | |||
| fcf1108641 | |||
| 185605fbf0 | |||
| 662d906997 | |||
| f6e20d1412 | |||
| 9e14a9b7c7 | |||
| 422430613c | |||
| 2a4ce64d6f | |||
| 316ab8f3fc | |||
| f6a68426e1 | |||
| bed2b84100 | |||
| b39ec1e4d3 | |||
| dd92e9b061 | |||
| 8d737395dc | |||
| b3f7c9c1f2 | |||
| d425132ae7 | |||
| 925d351341 | |||
| c4107490df | |||
| b38230bc35 | |||
| 1f5f9964e0 | |||
| b0d8c6983d | |||
| 55f0180599 | |||
| 5284033fb8 | |||
| 0b1423c90d | |||
| e6a4bb2d16 | |||
| c3a051d372 | |||
| 3482551360 | |||
| d7a72f8581 | |||
| c09b7410ce | |||
| 96ce0edd46 | |||
| 7cd68ff222 | |||
| 16680e3f61 | |||
| 3389d4fa93 | |||
| 0041845935 | |||
| 3bcccb4a7b | |||
| 2aba52f552 | |||
| f149563c68 | |||
| 276e4f1189 | |||
| cb42cad6a6 | |||
| ef044327c6 | |||
| d1d0df11a8 | |||
| c3da3af2f4 | |||
| 7b760a0823 | |||
| 1e9c29aa55 | |||
| 1ddd88231a | |||
| d665049f05 | |||
| 1af6169999 | |||
| 468197f7e0 | |||
| 816cfb24aa | |||
| 479d144592 | |||
| 0b516d9762 | |||
| 2483c2362d | |||
| 40639309b1 | |||
| eefb0681dc | |||
| 9501dad1dc | |||
| 24dba3bd60 | |||
| e9508089ab | |||
| 454f47b2b5 | |||
| d8b417458b | |||
| 195a130124 | |||
| 8577fc29e4 | |||
| d71c7e4d28 | |||
| 9bc8156615 | |||
| 183b23cf5a | |||
| 138bc4e7e4 | |||
| e2529cfdf2 | |||
| b982b27f84 | |||
| c573cd5b4d | |||
| c2758d7a91 | |||
| 64cae8c4d9 | |||
| a2ba6f5382 | |||
| 7c8d9191c1 | |||
| 9677835d84 | |||
| 63749a9572 | |||
| 9ff90d33fc | |||
| 942e8ff591 | |||
| 0b050256f9 | |||
| 8a762bf34f | |||
| 42defcf4b9 | |||
| 3e93a97d10 | |||
| 26e6f33cde | |||
| 1bc0739d31 | |||
| 8476dab844 | |||
| 745992886c | |||
| 8089f62806 | |||
| a34aec1dd2 | |||
| 448bd1e510 | |||
| 4e23e1e11f | |||
| 5d3b850e46 | |||
| 4f45dee332 | |||
| 1355605e70 | |||
| 7dc2ac9253 | |||
| 6915bf1ba2 | |||
| ac6ede8f9c | |||
| bcb4a64c68 | |||
| 7a970148f3 | |||
| 0759e1598f | |||
| 25ad8959a6 | |||
| 4f530b2b6a | |||
| f23af43013 | |||
| 62827cf56d | |||
| 5c9333feec | |||
| 88aaae3661 | |||
| 18fe82f441 | |||
| 108a1618f6 | |||
| 5d543b6b4d | |||
| 4c9d396f9b | |||
| 19513e42c1 | |||
| 53a4abd508 | |||
| b17a3591e0 | |||
| 7ac73f758b | |||
| e556ca5edc | |||
| cf8e1de3ff | |||
| caf21dfedd | |||
| d494550b20 | |||
| a885959d39 | |||
| 8c065751c2 | |||
| e5cd23de48 |
3
.gitignore
vendored
3
.gitignore
vendored
@@ -1,5 +1,5 @@
|
||||
# Compiled application binary
|
||||
weatherreporter
|
||||
/weatherreporter
|
||||
|
||||
# ---> Go
|
||||
# If you prefer the allow list template instead of the deny list, see community template:
|
||||
@@ -71,4 +71,3 @@ Icon
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
|
||||
97
.woodpecker/release.yml
Normal file
97
.woodpecker/release.yml
Normal file
@@ -0,0 +1,97 @@
|
||||
when:
|
||||
- event: tag
|
||||
|
||||
steps:
|
||||
- name: validate-release
|
||||
image: golang:1.26.5
|
||||
commands:
|
||||
- |
|
||||
set -eu
|
||||
|
||||
version="$CI_COMMIT_TAG"
|
||||
release_note="docs/releases/$version.md"
|
||||
|
||||
if ! printf '%s\n' "$version" |
|
||||
grep -Eq '^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$'
|
||||
then
|
||||
printf '%s\n' "invalid release tag: $version" >&2
|
||||
exit 1
|
||||
fi
|
||||
test -s "$release_note"
|
||||
test -z "$(git ls-files go.work go.work.sum)"
|
||||
test ! -e vendor
|
||||
if grep -Eq '^[[:space:]]*replace([[:space:]]|\()' go.mod
|
||||
then
|
||||
printf '%s\n' 'go.mod contains a replacement' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
GOWORK=off go test -count=1 ./...
|
||||
GOWORK=off go test -race -count=1 ./...
|
||||
GOWORK=off go vet ./...
|
||||
GOWORK=off go build ./...
|
||||
GOWORK=off go mod tidy -diff
|
||||
|
||||
unformatted=$(
|
||||
git ls-files '*.go' |
|
||||
while IFS= read -r go_file
|
||||
do
|
||||
gofmt -l "$go_file"
|
||||
done
|
||||
)
|
||||
test -z "$unformatted"
|
||||
git diff --check
|
||||
|
||||
- name: build-release-assets
|
||||
image: golang:1.26.5
|
||||
depends_on:
|
||||
- validate-release
|
||||
commands:
|
||||
- |
|
||||
set -eu
|
||||
|
||||
version="$CI_COMMIT_TAG"
|
||||
dist="dist"
|
||||
pkg="gitea.maximumdirect.net/eric/weatherreporter/cmd/weatherreporter"
|
||||
|
||||
rm -rf "$dist"
|
||||
mkdir -p "$dist"
|
||||
|
||||
build_binary() {
|
||||
goos="$1"
|
||||
goarch="$2"
|
||||
suffix="$3"
|
||||
output="$dist/weatherreporter-$version-$goos-$goarch$suffix"
|
||||
|
||||
CGO_ENABLED=0 GOOS="$goos" GOARCH="$goarch" \
|
||||
go build -trimpath -ldflags "-s -w -X gitea.maximumdirect.net/eric/weatherreporter/internal/buildinfo.Version=$version" \
|
||||
-o "$output" "$pkg"
|
||||
}
|
||||
|
||||
build_binary linux amd64 ""
|
||||
build_binary linux arm64 ""
|
||||
build_binary darwin amd64 ""
|
||||
build_binary darwin arm64 ""
|
||||
build_binary windows amd64 ".exe"
|
||||
build_binary windows arm64 ".exe"
|
||||
|
||||
host_binary="$dist/weatherreporter-$version-$(go env GOOS)-$(go env GOARCH)"
|
||||
test "$("$host_binary" --version)" = "weatherreporter $version"
|
||||
|
||||
- name: publish-release
|
||||
image: woodpeckerci/plugin-release:0.3.1
|
||||
depends_on:
|
||||
- build-release-assets
|
||||
settings:
|
||||
api_key:
|
||||
from_secret: GITEA_RELEASE_TOKEN
|
||||
files:
|
||||
- dist/weatherreporter-*
|
||||
title: Weatherreporter ${CI_COMMIT_TAG}
|
||||
note: docs/releases/${CI_COMMIT_TAG}.md
|
||||
checksum: sha256
|
||||
checksum-file: SHA256SUMS
|
||||
checksum-flatten: true
|
||||
file-exists: skip
|
||||
overwrite: false
|
||||
prerelease: false
|
||||
@@ -1,4 +1 @@
|
||||
Please carefully review the documents in `docs/policy` before making any changes to this repository.
|
||||
- `architecture.md` provides the canonical high-level architecture policy for this repository.
|
||||
- `development.md` provides more granular development policy for this repository.
|
||||
- `documentation.md` provides the canonical documentation policy for this repository.
|
||||
Please review `docs/development.md` for initial orientation in this repository and follow its task-specific reading guide.
|
||||
|
||||
29
README.md
29
README.md
@@ -1,2 +1,31 @@
|
||||
# weatherreporter
|
||||
|
||||
Weatherreporter is a Go CLI that turns normalized weather data into
|
||||
human-facing Markdown reports.
|
||||
|
||||
It produces a Markdown report at an operator-owned destination and can upload
|
||||
the completed output through Distributor. It can also compare explicitly
|
||||
selected Promptkit profiles against one shared prepared report and publish a
|
||||
local comparison bundle.
|
||||
|
||||
## Quickstart
|
||||
|
||||
```sh
|
||||
weatherreporter generate today
|
||||
```
|
||||
|
||||
Configure a Weather API endpoint first; see the
|
||||
[configuration reference](docs/config.md). The report is written to
|
||||
`today.md` in the current directory when `output.directory` is not configured.
|
||||
Set that configuration value for an ordinary publication directory, or use
|
||||
`--out` for one command. See the [CLI reference](docs/cli.md) and [operations
|
||||
guide](docs/operations.md) for command and operating details.
|
||||
|
||||
## Documentation
|
||||
|
||||
- [CLI reference](docs/cli.md)
|
||||
- [Configuration reference](docs/config.md)
|
||||
- [Operations guide](docs/operations.md)
|
||||
- [Comparison bundle contract](docs/integrations/comparison-bundle.md)
|
||||
- [Development guide](docs/development.md)
|
||||
- [Architecture policy](docs/policy/architecture.md)
|
||||
|
||||
31
cmd/weatherreporter/main.go
Normal file
31
cmd/weatherreporter/main.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/cli"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := runCommand(os.Args[1:], os.Stdout, os.Stderr, cli.Run); err != nil {
|
||||
fmt.Fprintf(os.Stderr, "weatherreporter: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func runCommand(args []string, stdout, stderr io.Writer, runner func(context.Context, []string, io.Writer, io.Writer) error) error {
|
||||
return runCommandWithSignalContext(args, stdout, stderr, runner, signal.NotifyContext)
|
||||
}
|
||||
|
||||
type signalContextFunc func(context.Context, ...os.Signal) (context.Context, context.CancelFunc)
|
||||
|
||||
func runCommandWithSignalContext(args []string, stdout, stderr io.Writer, runner func(context.Context, []string, io.Writer, io.Writer) error, signalContext signalContextFunc) error {
|
||||
ctx, stop := signalContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
return runner(ctx, args, stdout, stderr)
|
||||
}
|
||||
36
cmd/weatherreporter/main_test.go
Normal file
36
cmd/weatherreporter/main_test.go
Normal file
@@ -0,0 +1,36 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"syscall"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRunCommandBuildsCancelableSignalContext(t *testing.T) {
|
||||
var signals []os.Signal
|
||||
stopped := false
|
||||
signalContext := func(parent context.Context, requested ...os.Signal) (context.Context, context.CancelFunc) {
|
||||
signals = append([]os.Signal(nil), requested...)
|
||||
ctx, cancel := context.WithCancel(parent)
|
||||
cancel()
|
||||
return ctx, func() {
|
||||
stopped = true
|
||||
}
|
||||
}
|
||||
|
||||
err := runCommandWithSignalContext(nil, io.Discard, io.Discard, func(ctx context.Context, _ []string, _, _ io.Writer) error {
|
||||
return ctx.Err()
|
||||
}, signalContext)
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("runCommandWithSignalContext() error = %v, want context cancellation", err)
|
||||
}
|
||||
if len(signals) != 2 || signals[0] != os.Interrupt || signals[1] != syscall.SIGTERM {
|
||||
t.Fatalf("requested signals = %#v, want Interrupt and SIGTERM", signals)
|
||||
}
|
||||
if !stopped {
|
||||
t.Fatal("signal context stop function was not called")
|
||||
}
|
||||
}
|
||||
58
cmd/weatherreporter/main_unix_test.go
Normal file
58
cmd/weatherreporter/main_unix_test.go
Normal file
@@ -0,0 +1,58 @@
|
||||
//go:build unix
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRunCommandCancelsActionContextOnSignal(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
signal os.Signal
|
||||
}{
|
||||
{name: "Interrupt", signal: os.Interrupt},
|
||||
{name: "Terminate", signal: syscall.SIGTERM},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
started := make(chan struct{})
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- runCommand(nil, io.Discard, io.Discard, func(ctx context.Context, _ []string, _, _ io.Writer) error {
|
||||
close(started)
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
})
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-started:
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("runner did not receive an action context")
|
||||
}
|
||||
|
||||
process, err := os.FindProcess(os.Getpid())
|
||||
if err != nil {
|
||||
t.Fatalf("FindProcess() error = %v", err)
|
||||
}
|
||||
if err := process.Signal(tt.signal); err != nil {
|
||||
t.Fatalf("Signal(%v) error = %v", tt.signal, err)
|
||||
}
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("runCommand() error = %v, want context cancellation", err)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("interrupt did not cancel the action context")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
100
docs/adr/0001-stateless-execution.md
Normal file
100
docs/adr/0001-stateless-execution.md
Normal file
@@ -0,0 +1,100 @@
|
||||
# 0001: Make Weatherreporter Execution Stateless
|
||||
|
||||
Status: Accepted
|
||||
|
||||
Date: 2026-08-01
|
||||
|
||||
## Context
|
||||
|
||||
Weather reports are ephemeral products. Forecasts and current conditions change
|
||||
continuously, so the useful response to an old, failed, or superseded report is
|
||||
normally a new generation rather than replaying or inspecting a prior run.
|
||||
|
||||
The existing run-addressed workspace retains module snapshots, prompt inputs,
|
||||
execution receipts, generated text, rendered reports, metadata, and
|
||||
notification receipts. That provenance store accumulates operational history
|
||||
whose recovery and compatibility obligations are disproportionate to the value
|
||||
of an ephemeral weather report. It also exists solely to support local Recent
|
||||
Changes comparison for a rarely used report section.
|
||||
|
||||
The temporary roadmap that defined the feature scope and implementation plan
|
||||
has been retired under the repository's documentation lifecycle. The
|
||||
[architecture policy](../policy/architecture.md) defines the resulting system
|
||||
invariants; this decision records their durable rationale.
|
||||
|
||||
## Decision
|
||||
|
||||
Weatherreporter will operate as a stateless transformation pipeline:
|
||||
|
||||
```text
|
||||
Weather API input
|
||||
-> deterministic facts and modules
|
||||
-> Promptkit data package and generated text
|
||||
-> repository-owned Markdown rendering
|
||||
-> operator-owned report output
|
||||
-> optional Distributor upload
|
||||
```
|
||||
|
||||
Ordinary invocations will retain intermediate values only for the active
|
||||
process and will publish one operator-owned Markdown output atomically. A
|
||||
failed or canceled generation must not truncate or partially replace an
|
||||
existing selected output. Single-report Distributor notification follows
|
||||
successful publication; batch notification follows successful publication of
|
||||
every planned report.
|
||||
|
||||
Weatherreporter will remove local Recent Changes comparison instead of
|
||||
retaining application state to support it. It will remove run-addressed
|
||||
workspace artifacts, historical inspection, and backward-compatible workspace
|
||||
decoding. RunIDs may remain active correlation and Distributor idempotency
|
||||
values, but will not identify retained application history.
|
||||
|
||||
Explicit `--llm-debug-dir` capture remains the sole diagnostic-file exception.
|
||||
The operator selects and manages that secure location; ordinary execution does
|
||||
not create an implicit debug location or a general logging store, and debug
|
||||
capture must continue to exclude credentials.
|
||||
|
||||
Any future forecast comparison must use a structured product supplied by the
|
||||
Weather API rather than local Weatherreporter history. The proposed
|
||||
[Upstream Forecast Change Product](../roadmap/future.md#upstream-forecast-change-product)
|
||||
defines the required upstream direction. A future integration must not add a
|
||||
local snapshot fallback.
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
### Retain The Bounded Current-State Design
|
||||
|
||||
Retaining a managed workspace with current metadata, receipts, and snapshots
|
||||
would preserve inspection and local comparison, but keeps an application-owned
|
||||
history subsystem, artifact compatibility burden, and recovery surface that do
|
||||
not match the report lifecycle.
|
||||
|
||||
### Time-Based Retention
|
||||
|
||||
Expiring workspace material after a fixed period reduces accumulation but still
|
||||
requires retention policy, cleanup behavior, failure handling, and historical
|
||||
format support. It does not remove the mismatch between retained provenance and
|
||||
ephemeral report products.
|
||||
|
||||
### Bounded Run History
|
||||
|
||||
Keeping only a fixed number of prior runs limits storage volume but still makes
|
||||
Weatherreporter responsible for run selection, comparison, inspection, and
|
||||
state migration. It also creates arbitrary history gaps without establishing an
|
||||
authoritative forecast baseline.
|
||||
|
||||
## Consequences
|
||||
|
||||
The CLI, configuration, prompt-input, workspace, and inspection contracts will
|
||||
change together. Legacy workspace material will not be migrated, decoded, or
|
||||
automatically deleted; operators remain responsible for any desired cleanup.
|
||||
|
||||
Current action results will carry active identity, selected profile, safe
|
||||
effective model information, output location, notification result, and safe
|
||||
errors instead of historical artifact paths. Tests will protect atomic output,
|
||||
batch and notification ordering, explicit secure debug capture, and the
|
||||
absence of ordinary application-managed state.
|
||||
|
||||
This decision deliberately leaves the Weather API responsible for any future
|
||||
forecast-history comparison. It avoids a cache, archive, retention engine,
|
||||
manifest, resume mechanism, or replacement inspection surface in
|
||||
Weatherreporter.
|
||||
198
docs/cli.md
Normal file
198
docs/cli.md
Normal file
@@ -0,0 +1,198 @@
|
||||
# Weatherreporter CLI
|
||||
|
||||
`weatherreporter` generates Markdown weather reports, runs report batches, and
|
||||
compares explicitly selected Promptkit profiles against one prepared report. It
|
||||
has no command for inspecting prior runs or application-owned state.
|
||||
|
||||
## Shortest Useful Command
|
||||
|
||||
```sh
|
||||
weatherreporter generate today
|
||||
```
|
||||
|
||||
The command uses the configured Weather API and atomically writes `today.md`.
|
||||
With no configured output directory, it writes in the current directory. See
|
||||
the [configuration reference](config.md) to supply the required Weather API
|
||||
endpoint and choose an ordinary output directory.
|
||||
|
||||
## Commands And Usage
|
||||
|
||||
```text
|
||||
weatherreporter --help
|
||||
weatherreporter --version
|
||||
weatherreporter generate daily --date YYYY-MM-DD [--config PATH] [--units VALUE] [--tz NAME] [--out PATH] [--llm-debug-dir PATH] [--quiet]
|
||||
weatherreporter generate today [--config PATH] [--units VALUE] [--tz NAME] [--out PATH] [--date YYYY-MM-DD] [--llm-debug-dir PATH] [--quiet]
|
||||
weatherreporter generate tomorrow [--config PATH] [--units VALUE] [--tz NAME] [--out PATH] [--llm-debug-dir PATH] [--quiet]
|
||||
weatherreporter generate hourly [--config PATH] [--units VALUE] [--tz NAME] [--out PATH] [--llm-debug-dir PATH] [--quiet]
|
||||
weatherreporter run morning [--config PATH] [--units VALUE] [--tz NAME] [--out-dir PATH] [--llm-debug-dir PATH] [--quiet]
|
||||
weatherreporter run evening [--config PATH] [--units VALUE] [--tz NAME] [--out-dir PATH] [--llm-debug-dir PATH] [--quiet]
|
||||
weatherreporter compare REPORT --profile PROFILE --profile PROFILE [--config PATH] [--units VALUE] [--tz NAME] [--date YYYY-MM-DD] [--out-dir PATH] [--replace] [--llm-debug-dir PATH] [--quiet]
|
||||
```
|
||||
|
||||
`weatherreporter --version` prints the version embedded in the executable.
|
||||
Tagged release binaries report their semantic version tag; ordinary local
|
||||
builds report `development`.
|
||||
|
||||
| Command | Contract |
|
||||
| --- | --- |
|
||||
| `generate daily` | Requires `--date YYYY-MM-DD`; the date is interpreted in the effective report timezone. Its default filename is `daily-YYYY-MM-DD.md`. |
|
||||
| `generate today` | Accepts an optional `--date YYYY-MM-DD`; without it, the current local date in the effective report timezone is used. Its default filename is `today.md`. |
|
||||
| `generate tomorrow` | Uses the next local civil day and writes `tomorrow.md` by default. |
|
||||
| `generate hourly` | Covers the next six hours in the effective report timezone and writes `hourly.md` by default. It does not accept `--date`, `--hours`, or `--duration`. |
|
||||
| `run morning` and `run evening` | Run their defined report batches beneath the configured output directory, or the current directory when none is configured. `--out-dir` selects another directory. `--out` is not accepted. |
|
||||
| `compare REPORT` | Accepts `daily`, `today`, `tomorrow`, or `hourly`. It requires at least two distinct, nonblank `--profile` values in their supplied order. Daily requires `--date`; Today accepts it optionally; Tomorrow and Hourly do not accept it. |
|
||||
|
||||
`generate` accepts the four report command names shown above. `run` accepts
|
||||
only `morning` and `evening`. `compare` always requires explicit profile
|
||||
selection: `promptkit.profile` is not used as a comparison default. Batch
|
||||
membership and notification ordering are described in the
|
||||
[operations guide](operations.md).
|
||||
|
||||
## Output, Errors, And Quiet Mode
|
||||
|
||||
For `generate`, the report's default filename is placed beneath
|
||||
`output.directory` when configured, otherwise the current directory. `--out
|
||||
PATH` selects one complete output file instead. A relative path is resolved
|
||||
from the current directory; an absolute path is used as given. For a batch,
|
||||
the configured directory has the same role and `--out-dir PATH` selects its
|
||||
output directory instead. For `compare`, `--out-dir PATH` selects one exact
|
||||
bundle directory; otherwise the report-derived comparison directory is placed
|
||||
beneath the configured directory or current directory. `--replace` is required
|
||||
to replace an existing nonempty recognized comparison bundle. See the
|
||||
[configuration reference](config.md) for the field's validation and path rules
|
||||
and the [comparison bundle contract](integrations/comparison-bundle.md) for the
|
||||
bundle format.
|
||||
|
||||
Outputs are written atomically. A generation, rendering, write, or cancellation
|
||||
failure before publication leaves an existing destination unchanged. A
|
||||
notification failure occurs after publication, so the newly written output
|
||||
remains available.
|
||||
|
||||
`SIGINT` and `SIGTERM` cancel an active action. Weatherreporter lets that
|
||||
cancellation reach the action before exiting; when the action has a result, it
|
||||
emits the usual failed summary and exits nonzero. A canceled batch retains any
|
||||
reports that were already published, marks interrupted and unstarted reports
|
||||
as `canceled`, skips batch notification, and identifies cancellation separately
|
||||
from report failures.
|
||||
|
||||
Action commands (`generate`, `run`, and `compare`) write a JSON summary to
|
||||
stdout unless `--quiet` is set. `run` also writes compact per-report and batch
|
||||
status lines to stderr. A pre-run error, such as an invalid flag, missing
|
||||
required argument, or configuration-load failure, produces no partial JSON
|
||||
summary. When an action fails after it has produced a result, its summary has
|
||||
`"status": "failed"` and an `error` field.
|
||||
|
||||
`--quiet` is supported by action commands only. It suppresses action summaries
|
||||
and routine batch status output; it does not suppress command errors.
|
||||
|
||||
### Generate Summary
|
||||
|
||||
A generate summary identifies the command, report, run, generation time, valid
|
||||
period, prompt version, timezone, and status. Successful output has an absolute
|
||||
`outputPath`:
|
||||
|
||||
```json
|
||||
{
|
||||
"command": "generate",
|
||||
"reportId": "today",
|
||||
"promptId": "weather.today_generated_text",
|
||||
"promptVersion": "2.0.0",
|
||||
"runId": "20260529T120000.000000000Z_today",
|
||||
"status": "succeeded",
|
||||
"timezone": "America/Chicago",
|
||||
"outputPath": "/srv/weather/today.md"
|
||||
}
|
||||
```
|
||||
|
||||
When available, the summary also includes the effective `profileId`,
|
||||
`backendId`, `modelName`, `sourceWarnings`, `validationStatus`, requested
|
||||
`llmDebugPath`, and compact Distributor `notification` result. It does not
|
||||
include historical or transient artifact paths such as metadata, prompt input,
|
||||
raw generated text, render context, or notification receipts.
|
||||
|
||||
### Run Summary And Stderr
|
||||
|
||||
A run summary contains `command`, `batch`, `status`, `startedAt`, `finishedAt`,
|
||||
`total`, `succeeded`, `failed`, and a `reports` array. Each report item includes
|
||||
its identity, status, effective profile and model details when available,
|
||||
source warnings, validation status, and absolute `outputPath` after publication.
|
||||
The top-level summary may also contain a batch `notification` object and
|
||||
`error`. Batch status is `failed` if any report or the batch notification fails.
|
||||
The `total`, `succeeded`, and `failed` counters describe report items only, so
|
||||
a failed batch notification can leave `failed` at `0` while the top-level
|
||||
notification and action status are `failed`.
|
||||
|
||||
When cancellation stops a batch, the summary also includes a nonzero
|
||||
`canceled` count. Canceled reports have `"status": "canceled"`; they are not
|
||||
included in `failed`, and the action still has failed status and exits nonzero.
|
||||
|
||||
Without `--quiet`, batch status lines use this form:
|
||||
|
||||
```text
|
||||
report=today status=succeeded output="/srv/weather/reports/today.md"
|
||||
batch=morning total=2 succeeded=2 failed=0 canceled=0
|
||||
```
|
||||
|
||||
### Compare Summary
|
||||
|
||||
A comparison summary contains these fields in this order: `command`,
|
||||
`comparisonId`, `reportId`, `reportName`, `promptId`, `promptVersion`,
|
||||
`promptHash`, `status`, `startedAt`, `finishedAt`, `timezone`, `validPeriod`,
|
||||
`outputDirectory`, `manifestPath`, `dataPackagePath`, `total`, `succeeded`,
|
||||
`failed`, `results`, and optional `error`. Published artifact paths and each
|
||||
successful `results[].reportPath` are absolute. `results` preserves the
|
||||
supplied profile order and each item contains `position`, `profileId`, optional
|
||||
`backendId`, `modelName`, `status`, optional `validationStatus`, optional
|
||||
`reportPath`, optional `llmDebugPath`, and optional safe `error`.
|
||||
|
||||
The comparison status is `succeeded` only when every selected profile succeeds
|
||||
and the bundle is published. Individual profile failures still publish a
|
||||
complete partial bundle and return a failed command result. Cancellation or a
|
||||
failure before publication omits the artifact paths and returns a safe
|
||||
top-level error; the resolved `outputDirectory` and finalized timestamp remain
|
||||
when available. The safe error includes only a category and message: aggregate
|
||||
and unclassified application failures use `application`; cancellation uses
|
||||
`canceled`; deadlines use `deadline_exceeded`; prompt execution uses its
|
||||
published Promptkit category; destination failures use `destination_<kind>`;
|
||||
and committed cleanup failures use `publication_cleanup` with a message that
|
||||
states whether a complete prior bundle, partial remnants, or no prior bundle
|
||||
remains, or that recovery state could not be inspected. It does not expose
|
||||
provider diagnostics, filesystem causes, or recovery paths. See the
|
||||
[comparison bundle contract](integrations/comparison-bundle.md) for durable
|
||||
artifact fields and failure invariants.
|
||||
|
||||
If the bundle is published but cleanup of its replaced prior bundle fails, the
|
||||
summary still includes the published artifact paths and has status `failed`.
|
||||
Its JSON error is `publication_cleanup`; the returned command error identifies
|
||||
a recovery path only when cleanup left a sibling behind. Only a reported
|
||||
complete prior bundle is a rollback artifact.
|
||||
|
||||
## Flag Reference
|
||||
|
||||
| Flag | Accepted by | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `-h`, `--help` | top level, `compare` | Show help without loading configuration or contacting a provider. |
|
||||
| `--config PATH` | all commands | Load `PATH` instead of `/usr/local/etc/weatherreporter/config.yml`. |
|
||||
| `--units VALUE` | `generate`, `run`, `compare` | Override `weather_api.units` for this command. |
|
||||
| `--tz NAME` | `generate`, `run`, `compare` | Override `weather_api.timezone` for this command. |
|
||||
| `--out PATH` | every `generate` command | Write the report to this complete file destination instead of the configured or current-directory default. |
|
||||
| `--llm-debug-dir PATH` | every `generate`, `run`, and `compare` command | On Unix hosts, write requested sensitive prompt diagnostics under this absolute path. Other hosts fail closed when the flag is requested. |
|
||||
| `--profile PROFILE` | `compare` | Select one explicit profile. Repeat at least twice with distinct, nonblank IDs. |
|
||||
| `--out-dir PATH` | `run morning`, `run evening`, `compare` | Write batch reports beneath this directory, or select the exact comparison directory. |
|
||||
| `--replace` | `compare` | Authorize replacement of a recognized nonempty comparison bundle. |
|
||||
| `--quiet` | `generate`, `run`, `compare` | Suppress all action summaries and routine batch status output. |
|
||||
| `--date YYYY-MM-DD` | `generate daily`, `generate today`, `compare daily`, `compare today` | Required for Daily; optional for Today. |
|
||||
|
||||
Distributor notification is configured through `notify.distributor`; there are
|
||||
no Distributor-specific CLI flags. See the [configuration reference](config.md).
|
||||
|
||||
## Invocation Examples
|
||||
|
||||
```sh
|
||||
weatherreporter generate daily --date 2026-05-29
|
||||
weatherreporter generate today --out ./reports/today.md
|
||||
weatherreporter generate hourly --out /srv/weather/hourly.md
|
||||
weatherreporter generate today --llm-debug-dir /var/tmp/weatherreporter-debug
|
||||
weatherreporter run morning --out-dir ./reports --llm-debug-dir /var/tmp/weatherreporter-debug
|
||||
weatherreporter compare daily --date 2026-05-29 --profile weather-light --profile weather-balanced --out-dir ./comparison-daily-2026-05-29
|
||||
```
|
||||
259
docs/config.md
Normal file
259
docs/config.md
Normal file
@@ -0,0 +1,259 @@
|
||||
# Weatherreporter Configuration
|
||||
|
||||
Weatherreporter reads YAML configuration. The default path is:
|
||||
|
||||
```text
|
||||
/usr/local/etc/weatherreporter/config.yml
|
||||
```
|
||||
|
||||
If the default file is absent, Weatherreporter uses built-in defaults. An
|
||||
explicit `--config PATH` must exist. Values are applied in this order:
|
||||
|
||||
1. built-in defaults;
|
||||
2. the configuration file, when present; and
|
||||
3. the `--units` and `--tz` command-line overrides.
|
||||
|
||||
Environment variables do not override configuration fields. Output flags select
|
||||
operator-owned destinations for one command and do not change configuration.
|
||||
|
||||
## Maintained Examples
|
||||
|
||||
- [minimal-config.yml](../examples/minimal-config.yml) is the smallest useful
|
||||
collection and generation configuration.
|
||||
- [config.yml](../examples/config.yml) is a representative production-oriented
|
||||
configuration using synthetic endpoints and no credentials.
|
||||
- [weather-light-local-profile.yml](../examples/weather-light-local-profile.yml)
|
||||
is a complete endpoint-only override for the embedded `weather-light`
|
||||
profile.
|
||||
|
||||
The configuration examples are loaded by the configuration test suite. The
|
||||
profile example is inspected through the Promptkit adapter test suite.
|
||||
|
||||
## Minimal Configuration
|
||||
|
||||
```yaml
|
||||
weather_api:
|
||||
base_url: https://weather.api.example.com/
|
||||
```
|
||||
|
||||
`weather_api.base_url` is required for workflows that collect weather data.
|
||||
All omitted fields use their built-in defaults.
|
||||
|
||||
## Field Reference
|
||||
|
||||
### `weather_api`
|
||||
|
||||
| Field | Default | Rules |
|
||||
| --- | --- | --- |
|
||||
| `base_url` | empty | Absolute HTTP(S) Weather API URL. Required for collection and generation. |
|
||||
| `timeout` | `10s` | Must be greater than zero. |
|
||||
| `precision` | `0` | Must be zero or greater. Sent as the Weather API precision query value. |
|
||||
| `units` | `us` | Required Weather API units query value; `--units` overrides it for one command. |
|
||||
| `timezone` | `America/Chicago` | Required report and Weather API timezone; `--tz` overrides it for one command. |
|
||||
| `format` | `json` | Required and must be `json`. |
|
||||
|
||||
Timezone values may be IANA names, configured aliases such as `Chicago` and
|
||||
`Stl`, US timezone abbreviations, or signed UTC offsets such as `-5`, `+0930`,
|
||||
and `+09:30`. Numeric offsets require a sign, one or two hour digits, and an
|
||||
optional two-digit minute component with or without a colon. Hours must be
|
||||
from `00` through `23`, minutes from `00` through `59`, so the largest accepted
|
||||
offset magnitude is `23:59`.
|
||||
|
||||
### `location`
|
||||
|
||||
`location` supplies descriptive prompt context; it does not choose a Weather
|
||||
API endpoint or configure multiple forecast locations.
|
||||
|
||||
| Field | Default |
|
||||
| --- | --- |
|
||||
| `id` | `home` |
|
||||
| `name` | `Brentwood` |
|
||||
| `region` | `St. Louis Metro` |
|
||||
|
||||
The prompt-facing location timezone is derived from the effective
|
||||
`weather_api.timezone` after command-line overrides.
|
||||
|
||||
### `secrets`
|
||||
|
||||
`secrets.directory` defaults to empty, which disables secret loading. When it
|
||||
is set, every regular file directly in that directory is staged after the file
|
||||
and command-line overrides, then applied only after the complete configuration
|
||||
has validated successfully. A rejected load leaves the existing environment
|
||||
unchanged. A file basename must match
|
||||
`[A-Za-z_][A-Za-z0-9_]*`; it becomes an environment variable name, and the
|
||||
file contents replace any existing value. One trailing LF or CRLF is removed.
|
||||
|
||||
Missing directories, unreadable files, subdirectories, symlinks, non-regular
|
||||
files, and invalid names fail configuration loading. Put only secret values in
|
||||
this directory, never in the YAML file.
|
||||
|
||||
### `output`
|
||||
|
||||
`output.directory` selects the ordinary operator-owned publication directory
|
||||
for individual reports, batches, and the default parent of comparison bundles.
|
||||
|
||||
| Field | Default | Rules |
|
||||
| --- | --- | --- |
|
||||
| `directory` | empty | An omitted or empty value uses the invocation working directory. A nonempty value must contain at least one non-whitespace character. |
|
||||
|
||||
The configured value is preserved while configuration loads: it is not cleaned,
|
||||
made absolute, inspected, created, or expanded through environment variables or
|
||||
a home-directory shortcut. At execution, an absolute directory is used as
|
||||
given; a relative directory resolves from the invocation working directory, not
|
||||
from the configuration file's location. A missing directory is created when a
|
||||
report is successfully published. An existing non-directory or an uninspectable
|
||||
path fails output preflight before prompt inspection, weather collection, or
|
||||
publication.
|
||||
|
||||
For one `generate` command, `--out` is a complete file destination and takes
|
||||
precedence over `output.directory`. For `run`, `--out-dir` takes precedence.
|
||||
For `compare`, `--out-dir` selects its exact bundle directory; without it, the
|
||||
comparison's report-derived directory is placed beneath `output.directory`.
|
||||
Those explicit flags do not inspect or rebase beneath the configured directory.
|
||||
See the [CLI reference](cli.md) for command selection and the [operations
|
||||
guide](operations.md) for publication and failure handling.
|
||||
|
||||
### `notify.distributor`
|
||||
|
||||
Distributor notification is disabled by default. Its fields are:
|
||||
|
||||
| Field | Default | Rules when notification is enabled |
|
||||
| --- | --- | --- |
|
||||
| `enabled` | `false` | Activates Distributor notification validation. |
|
||||
| `endpoint` | `https://distributor.example.com` | Must be an absolute HTTP(S) base URL with a host and no userinfo, query, or fragment. A path prefix is allowed. |
|
||||
| `token_env` | `DISTRIBUTOR_UPLOAD_TOKEN` | Must name a valid environment variable. |
|
||||
| `timeout` | `30s` | Must be greater than zero. |
|
||||
| `failure_policy` | `error` | Must be `error`. |
|
||||
| `pipeline_id_template` | empty | Required single-report pipeline ID template. |
|
||||
| `bundle_id_template` | `weatherreporter.{location_id}.{report_id}` | Required single-report bundle ID template. |
|
||||
| `idempotency_key_template` | `{bundle_id}.{run_id}` | Required single-report idempotency-key template. |
|
||||
| `batch.enabled` | `true` | Activates batch notification validation when Distributor notification is enabled. |
|
||||
| `batch.pipeline_id_template` | `weatherreporter` | Required when batch notification is enabled. |
|
||||
| `batch.bundle_id_template` | `weatherreporter.{location_id}.{batch}` | Required when batch notification is enabled. |
|
||||
| `batch.idempotency_key_template` | `{bundle_id}.{batch_run_id}` | Required when batch notification is enabled. |
|
||||
|
||||
The upload token is read from the environment variable named by `token_env`.
|
||||
Use `secrets.directory` when a file-backed secret is appropriate.
|
||||
|
||||
When notification is enabled, Weatherreporter validates the Distributor endpoint
|
||||
before prompt inspection, weather collection, or output publication. Use an
|
||||
HTTP(S) base URL such as `https://distributor.example.com/archive`; do not put
|
||||
credentials, a query string, or a fragment in the endpoint.
|
||||
|
||||
When notification is enabled, each rendered single-report pipeline ID, bundle
|
||||
ID, and idempotency key must contain at least one non-whitespace character.
|
||||
|
||||
Single-report bundle templates accept `location_id`, `report_id`, `run_id`,
|
||||
`artifact_group`, `batch_output_name`, `valid_start_date`, `valid_end_date`,
|
||||
`valid_start_time`, `valid_end_time`, `valid_start_stamp`, `valid_end_stamp`,
|
||||
Pipeline and idempotency-key templates may also use `bundle_id`. Dates use
|
||||
`YYYY-MM-DD`; times use `HHMM`; and stamps use `YYYY-MM-DDTHHMM` in the
|
||||
effective report timezone.
|
||||
|
||||
Batch bundle and pipeline templates accept `location_id`, `batch`,
|
||||
`batch_run_id`, and `batch_started_date`; batch idempotency-key templates may
|
||||
also use `bundle_id`. `batch_started_date` is the batch start date in the
|
||||
effective report timezone.
|
||||
|
||||
`reports.<report>.distributor.path_templates` overrides the default ordered
|
||||
Distributor paths for that report. Each rendered path must be a unique relative
|
||||
path with `/` separators. Backslashes, empty segments, `.` and `..` segments,
|
||||
`manifest.json`, and the reserved Distributor sidecar basename are rejected.
|
||||
The default paths are:
|
||||
|
||||
| Report | Paths |
|
||||
| --- | --- |
|
||||
| `hourly` | `hourly/index.md` |
|
||||
| `daily` | `daily/{valid_start_date}/{run_id}.md`, `daily/{valid_start_date}/index.md` |
|
||||
| `today` | `daily/{valid_start_date}/{run_id}.md`, `daily/{valid_start_date}/index.md`, `today/index.md` |
|
||||
| `tomorrow` | `daily/{valid_start_date}/{run_id}.md`, `daily/{valid_start_date}/index.md`, `tomorrow/index.md` |
|
||||
|
||||
See the [operations guide](operations.md) for notification timing, uploaded
|
||||
output selection, and failure handling.
|
||||
|
||||
### `missing_source`
|
||||
|
||||
`missing_source.default` defaults to `warn` and accepts `error`, `warn`, or
|
||||
`none`. `missing_source.sources` optionally overrides that policy by source.
|
||||
Hourly forecast data is required for generated reports and cannot have a
|
||||
source-specific policy. Supported optional source keys are `observations`,
|
||||
`current`, `narrative`, `alerts`, `discussion`, `weather_story`, and
|
||||
`spc_convective_outlooks`; any other key is rejected.
|
||||
|
||||
### `promptkit`
|
||||
|
||||
Promptkit configuration selects the executor and prompt/profile checks for
|
||||
every `generate`, `run`, and `compare` command. A top-level `scriptorium:` configuration
|
||||
key is rejected with a migration error; it is not translated or ignored.
|
||||
|
||||
Prompt debug capture has no YAML setting. Use `--llm-debug-dir PATH` on an
|
||||
individual `generate`, `run`, or `compare` command when explicitly needed.
|
||||
See [optional prompt debug capture](operations.md#optional-prompt-debug-capture)
|
||||
for platform availability, security, and retention requirements.
|
||||
|
||||
| Field | Default | Rules |
|
||||
| --- | --- | --- |
|
||||
| `profile` | empty | Optional global profile selection for every report in one command. When empty, each exact prompt version selects its declared default. |
|
||||
| `profile_file` | empty | Optional external Promptkit profile file. It cannot be combined with `profile_dir`. A same-ID profile completely replaces Weatherreporter's embedded definition. |
|
||||
| `profile_dir` | empty | Optional external Promptkit profile directory. It cannot be combined with `profile_file`. A same-ID profile completely replaces Weatherreporter's embedded definition. |
|
||||
| `timeout` | `2m` | Must be greater than zero. |
|
||||
| `local.endpoint` | empty | Optional absolute URL for the conventional local backend. A blank endpoint leaves it unregistered. |
|
||||
| `local.concurrency_limit` | `1` | Maximum local backend concurrency. `0` is unlimited; negative values are invalid. |
|
||||
|
||||
`profile` selects an ID; `profile_file` and `profile_dir` supply definitions.
|
||||
They are separate decisions. An explicit `profile` applies to every selected
|
||||
report. Otherwise Hourly selects `weather-light`, while Daily, Today, and
|
||||
Tomorrow select `weather-balanced` through their exact `2.0.0` prompt
|
||||
definitions.
|
||||
|
||||
Promptkit resolves a selected profile definition from a test or embedding
|
||||
consumer's explicit in-memory profile, then the configured `profile_file` or
|
||||
`profile_dir`, then Weatherreporter's embedded catalog, and finally Promptkit's
|
||||
built-in catalog. Sources provide complete definitions; fields are never
|
||||
merged. A matching malformed external profile fails rather than using the
|
||||
embedded definition. The [Promptkit integration guide](integrations/promptkit.md)
|
||||
owns the catalog and precedence details.
|
||||
|
||||
To replace the default Hourly definition with a local OpenAI-compatible
|
||||
endpoint, set `profile_file` to a copy of
|
||||
[weather-light-local-profile.yml](../examples/weather-light-local-profile.yml).
|
||||
The example has no credential and should be edited for the local endpoint and
|
||||
model before use. An alternative profile may use `backend: local`; in that
|
||||
case `promptkit.local.endpoint` supplies the conventional local backend
|
||||
endpoint.
|
||||
|
||||
### `dayparts`
|
||||
|
||||
`dayparts` is a non-empty list of named local-time windows used in forecast
|
||||
derivation. Every item needs `name`, `start`, and `end`; start and end use
|
||||
`HH:MM`. Defaults are `overnight` (`00:00`–`06:00`), `morning`
|
||||
(`06:00`–`10:00`), `midday` (`10:00`–`15:00`), `afternoon`
|
||||
(`15:00`–`17:00`), and `evening` (`17:00`–`24:00`).
|
||||
|
||||
Names remain display text, but each name must have a distinct canonical
|
||||
identity. Canonicalization trims whitespace, lowercases letters, and collapses
|
||||
punctuation and whitespace to underscores; for example, `Morning`,
|
||||
`morning!`, and `morning` conflict. Planning recognizes the canonical
|
||||
identities `morning`, `afternoon`, `evening`, and `overnight` regardless of
|
||||
their display capitalization or punctuation.
|
||||
|
||||
### `reports`
|
||||
|
||||
`reports` optionally overrides a report's ordered deterministic modules and
|
||||
Distributor path templates. Omit a report entry to retain its defaults.
|
||||
|
||||
Supported report keys are `daily`, `today`, `tomorrow`, and `hourly`. Keys are
|
||||
trimmed, case-folded to lowercase, and normalize hyphens to underscores before
|
||||
lookup.
|
||||
|
||||
Each report entry can contain:
|
||||
|
||||
- `deterministic_modules`: an ordered list of module IDs, or objects with `id`
|
||||
and optional `options`.
|
||||
- `distributor.path_templates`: an optional, non-empty ordered list of
|
||||
Distributor paths for that report.
|
||||
|
||||
Unknown reports and modules, duplicate modules, incompatible report-module
|
||||
combinations, duplicate stanza names, invalid path templates, and invalid
|
||||
module options fail configuration loading. The accepted module IDs and module
|
||||
option contracts are documented in the [module contract internals](internal/module.md).
|
||||
88
docs/development.md
Normal file
88
docs/development.md
Normal file
@@ -0,0 +1,88 @@
|
||||
# Development
|
||||
|
||||
This is the first-read guide for people and coding agents working on
|
||||
Weatherreporter. It provides a concise repository orientation and routes each
|
||||
kind of change to its canonical documentation.
|
||||
|
||||
Weatherreporter is a Go CLI that collects normalized weather data, derives
|
||||
deterministic report facts and module snapshots, executes Promptkit for
|
||||
single-report generated text, renders Markdown reports, and can upload completed
|
||||
operator-owned outputs through Distributor. Start with the [README](../README.md) for product
|
||||
context and the [architecture policy](policy/architecture.md) for system
|
||||
boundaries and invariants.
|
||||
|
||||
## What To Read
|
||||
|
||||
| When working on | Read | Why |
|
||||
| --- | --- | --- |
|
||||
| Product behavior or the shortest useful workflow | [README](../README.md), [CLI reference](cli.md), and [operations guide](operations.md) | These own product orientation, invocation, and normal operation. |
|
||||
| Application shape, package boundaries, dependency direction, safety properties, or architectural invariants | [Architecture policy](policy/architecture.md) and relevant ADRs under `docs/adr/`, when present | Architecture defines the intended system; ADRs preserve significant decision rationale. |
|
||||
| Any documentation addition, revision, move, or removal | [Documentation policy](policy/documentation.md) | It defines canonical owners, audience boundaries, current-state rules, and document lifecycle. |
|
||||
| Adding, changing, reviewing, or deleting tests | [Testing policy](policy/testing.md) and focused package tests | The policy defines risk-based sufficiency, durable test boundaries, doubles, and test-maintenance criteria. |
|
||||
| CLI commands, flags, output, quiet mode, or command wiring | [CLI reference](cli.md) and [CLI internals](internal/cli.md) | The reference owns the user contract; the internal guide owns command composition and output flow. |
|
||||
| Configuration fields, defaults, loading, overrides, validation, or secrets | [Configuration reference](config.md), [architecture policy](policy/architecture.md), and tests under `internal/config` | These separate the user-visible contract, architectural rules, and executable behavior. |
|
||||
| Top-level generation, batch, comparison, collection, output publication, or notification workflow | [App orchestration internals](internal/app-orchestration.md), [comparison execution internals](internal/comparison-execution.md), and [comparison publication internals](internal/comparison-publication.md) | They own workflow ordering, concurrent profile execution, output publication, failure propagation, and orchestration invariants. |
|
||||
| Weather API transport, source envelopes, source warnings, or collection | [Weather API integration](integrations/weatherapi.md), [weather-data internals](internal/weather-data.md), and [collection internals](internal/collect.md) | These separate the external contract, normalized source facts, and app-facing collection behavior. |
|
||||
| Forecast periods, weather derivation, collected facts, or derived facts | [Forecast derivation internals](internal/forecast-derivation.md) and [fact contracts](internal/facts.md) | They own deterministic derivation and the fact boundaries used by reports. |
|
||||
| Report definitions, valid periods, report IDs, output naming, or batch composition | [Report registry internals](internal/report-registry.md) and [app orchestration internals](internal/app-orchestration.md) | Report definitions own selection and period rules; orchestration owns execution. |
|
||||
| Module IDs, module composition, briefing values, or prompt-facing exports | [Module contract internals](internal/module.md), [module builder internals](internal/briefing.md), and [prompt-input internals](internal/prompt-input.md) | These own module contracts, value construction, and the curated prompt-package boundary. |
|
||||
| Prompt execution, profiles, prepared report inputs, or result handling | `internal/promptexec`, the Promptkit adapter, [prepared report internals](internal/prepared-report.md), and [prompt-input internals](internal/prompt-input.md) | These separate the executor contract, immutable preparation, and input construction. |
|
||||
| Durable comparison bundles or their compatibility | [Comparison bundle contract](integrations/comparison-bundle.md) and [comparison publication internals](internal/comparison-publication.md) | The integration document owns the external schema; internals own how it is published. |
|
||||
| Generated-text schemas, validation, render contexts, templates, or Markdown rendering | [Generated-text internals](internal/generatedtext.md), [report-template internals](internal/reporttemplate.md), and [report template guide](templates.md) | These own structured text, renderer implementation, and the maintainer-facing template surface. |
|
||||
| Output destinations, atomic publication, prompt diagnosis, or legacy cleanup | [Operations guide](operations.md), [App orchestration internals](internal/app-orchestration.md), and [comparison publication internals](internal/comparison-publication.md) | Operations owns operator workflows; internals own implementation boundaries. |
|
||||
| Distributor bundles, uploads, notification results, or failures | [Distributor adapter internals](internal/distributor-adapter.md), [Distributor integration contracts](integrations/distributor/), and [operations guide](operations.md) | These separate adapter behavior, external contracts, and operational lifecycle. |
|
||||
| Maintained example configuration | [Configuration reference](config.md) and files under `examples/` | The reference owns field meaning; examples own complete copyable files. |
|
||||
| Release preparation, tagging, publication, or verification | [Release procedure](release.md) | It owns version selection, release-note preparation, candidate validation, tag publication, CI behavior, and post-publication checks. |
|
||||
| Proposed, deferred, or unimplemented work | Documents under `docs/roadmap/` | Future behavior and implementation status belong only in roadmaps until implemented. |
|
||||
|
||||
For an existing subsystem, inspect its focused internal document, package-local
|
||||
types, and tests before changing behavior. Use the package boundaries already
|
||||
present before introducing a new package or abstraction.
|
||||
|
||||
## Repository Map
|
||||
|
||||
| Area | Responsibility |
|
||||
| --- | --- |
|
||||
| `cmd/weatherreporter` | Binary entry point. |
|
||||
| `internal/cli` | Command parsing, flags, help, output, and command wiring. |
|
||||
| `internal/app` | Stateless generation, batches, comparisons, collection coordination, output publication, and notification. |
|
||||
| `internal/comparison` | Comparison identities, logical bundles, guarded destinations, and atomic bundle publication. |
|
||||
| `internal/config` | Configuration defaults, loading, precedence, secrets, and validation. |
|
||||
| `internal/adapters` | Weather API, Promptkit, and Distributor boundaries. |
|
||||
| `internal/weatherdata`, `internal/forecast`, `internal/facts` | Normalized source facts and deterministic derivation. |
|
||||
| `internal/report`, `internal/module`, `internal/briefing` | Report registry plus module and briefing contracts. |
|
||||
| `internal/promptinput`, `internal/generatedtext`, `internal/reporttemplate` | Prompt packages, generated-text validation, render contexts, and Markdown templates. |
|
||||
| `internal/fileutil`, `internal/timeutil` | Atomic output operations, clocks, dates, timezones, and periods. |
|
||||
| `docs` | User, operator, integration, internal, policy, and roadmap documentation. |
|
||||
| `examples` | Maintained copyable configuration. |
|
||||
|
||||
The [architecture policy](policy/architecture.md) is authoritative for
|
||||
normative boundaries. Focused documents under `docs/internal/` own detailed
|
||||
implemented subsystem behavior.
|
||||
|
||||
## Contributor Workflow
|
||||
|
||||
1. Read the documents and focused tests identified by the task guide.
|
||||
2. Use focused package checks while iterating.
|
||||
3. Run `gofmt -w` on changed Go files.
|
||||
4. Update the canonical documentation and maintained examples in the same
|
||||
change when behavior changes.
|
||||
5. Run repository-wide validation before considering the work complete.
|
||||
|
||||
Preserve actionable error context, keep secrets out of logs and fixtures, and
|
||||
avoid validation that requires live Weather API, Promptkit providers, or Distributor
|
||||
services. The architecture and testing policies own the detailed rules.
|
||||
|
||||
## Baseline Validation
|
||||
|
||||
Run:
|
||||
|
||||
```sh
|
||||
go test ./...
|
||||
go run ./cmd/weatherreporter --help
|
||||
git diff --check
|
||||
```
|
||||
|
||||
Use focused package tests during development and add broader or race-enabled
|
||||
checks when required by the [testing policy](policy/testing.md) and the risks of
|
||||
the change.
|
||||
103
docs/integrations/comparison-bundle.md
Normal file
103
docs/integrations/comparison-bundle.md
Normal file
@@ -0,0 +1,103 @@
|
||||
# Comparison Bundle Contract
|
||||
|
||||
A comparison bundle is the durable, flat artifact produced when one report is
|
||||
executed with multiple explicit Promptkit profiles. This document is the
|
||||
canonical contract for consumers of those bundles. Command invocation and JSON
|
||||
action summaries belong to the [CLI reference](../cli.md); destination handling
|
||||
and retention belong to the [operations guide](../operations.md).
|
||||
|
||||
## Version And Layout
|
||||
|
||||
The current and only supported manifest schema version is
|
||||
`weatherreporter.comparison.v1`. A bundle directory contains exactly these
|
||||
regular, non-symlinked files:
|
||||
|
||||
```text
|
||||
comparison.json
|
||||
data-package.yml
|
||||
NN-profile-slug.md
|
||||
```
|
||||
|
||||
`comparison.json` is the manifest and `data-package.yml` is the exact YAML
|
||||
input supplied to every selected profile. There is one Markdown file for each
|
||||
successful result and none for failed results. `NN` is the one-based selected
|
||||
profile position, zero padded to at least two digits (and widened only when
|
||||
needed for 100 or more profiles). The profile slug preserves ASCII letters,
|
||||
digits, `-`, and `_`; each run of other characters becomes one `-`; edge `-`
|
||||
and `_` characters are removed; the value is capped at 64 bytes; and an empty
|
||||
slug becomes `profile`. Logical profile IDs remain authoritative in the
|
||||
manifest.
|
||||
|
||||
All manifest paths are basenames relative to the bundle root. They never use
|
||||
path separators, `.` or `..`. The CLI reports absolute paths only after a
|
||||
bundle has been published.
|
||||
|
||||
## Manifest Schema
|
||||
|
||||
The manifest is UTF-8 JSON, encoded as two-space-indented JSON with one
|
||||
trailing newline. Its fields appear in this order:
|
||||
|
||||
```text
|
||||
schemaVersion, comparisonId, startedAt, finishedAt, reportId, validPeriod,
|
||||
timezone, promptId, promptVersion, promptHash, dataPackage, total, succeeded,
|
||||
failed, results
|
||||
```
|
||||
|
||||
`validPeriod` contains `start` and `end`; it is a nonempty half-open period.
|
||||
`dataPackage` contains `path` (always `data-package.yml`) and `sha256` (the
|
||||
lowercase, 64-character SHA-256 digest of that file's exact bytes). `results`
|
||||
is in the explicit profile-selection order. Its result-object fields appear in
|
||||
this order:
|
||||
|
||||
```text
|
||||
position, profileId, backendId, modelName, status, validationStatus,
|
||||
reportPath, error
|
||||
```
|
||||
|
||||
`startedAt` and `finishedAt` are nonzero UTC timestamps, and the latter is not
|
||||
earlier than the former. `validPeriod` retains its resolved time offset.
|
||||
`reportId`, `timezone`, prompt identity, model name, and comparison ID are
|
||||
nonblank. `promptHash` and `dataPackage.sha256` are lowercase SHA-256 digests.
|
||||
|
||||
## Result Invariants
|
||||
|
||||
`total` is at least two and equals the number of results. Positions are
|
||||
contiguous from one, profile IDs are distinct and nonblank, and
|
||||
`succeeded + failed == total`.
|
||||
|
||||
A successful result has `status: "succeeded"`, `validationStatus: "passed"`,
|
||||
a `reportPath` exactly equal to the canonical `NN-profile-slug.md` filename for
|
||||
its position, total, and logical profile ID, and no `error`. A failed result has
|
||||
`status: "failed"`, no `reportPath`, and an `error` object with nonblank
|
||||
`category` and `message`. Its validation status is absent, `failed`, or
|
||||
`skipped`. Error messages are valid UTF-8 and no longer than 1,024 bytes.
|
||||
`backendId` and `validationStatus` are omitted when unavailable.
|
||||
|
||||
Every successful Markdown file is declared by exactly one successful result.
|
||||
The directory contains no extra entries. Consumers can therefore verify the
|
||||
data-package digest and the full manifest-to-file mapping without scanning a
|
||||
larger workspace.
|
||||
|
||||
## Compatibility And Sensitivity
|
||||
|
||||
Weatherreporter recognizes a replaceable bundle only when it exactly satisfies
|
||||
the current version, schema, file set, file types, relative-path rules, and
|
||||
data-package digest. JSON field names are case-sensitive canonical names and a
|
||||
field may appear only once in each manifest object. It rejects unknown,
|
||||
case-variant, or duplicate fields; multiple JSON values; extra entries;
|
||||
symlinks; and future or otherwise unsupported versions. Treat a bundle that
|
||||
fails recognition as an ordinary directory, not as a compatible bundle.
|
||||
|
||||
When replacing a recognized bundle, cancellation observed before the new
|
||||
bundle is installed preserves the prior bundle rather than committing the
|
||||
replacement.
|
||||
|
||||
Cleanup of a prior bundle occurs only after its replacement is committed and
|
||||
does not affect the new bundle's compatibility. A cleanup error may identify a
|
||||
complete recovery bundle, partial remnants, no remaining sibling, or an
|
||||
uninspectable state; this operational state is not recorded in the manifest.
|
||||
|
||||
The manifest contains safe operational provenance, but `data-package.yml` and
|
||||
the generated Markdown can contain sensitive weather or location context. Do
|
||||
not assume these artifacts are safe for public distribution. Handle retention,
|
||||
access, and deletion according to the [operations guide](../operations.md).
|
||||
77
docs/integrations/distributor/api.md
Normal file
77
docs/integrations/distributor/api.md
Normal file
@@ -0,0 +1,77 @@
|
||||
# Distributor HTTP Upload Contract
|
||||
|
||||
Weatherreporter integrates with the HTTP upload API provided by
|
||||
`gitea.maximumdirect.net/eric/distributor v0.5.0`. It submits source bundles to
|
||||
a configured pipeline and reads the resulting run status. Configuration fields
|
||||
and notification lifecycle are documented in the [configuration reference](../../config.md)
|
||||
and [operations guide](../../operations.md).
|
||||
|
||||
## Upload Admission
|
||||
|
||||
Weatherreporter uses an absolute HTTP(S) endpoint with a host as a base URL.
|
||||
It allows a path prefix but rejects userinfo, query strings, and fragments
|
||||
before local report work begins. The client posts a gzip-compressed source
|
||||
bundle to:
|
||||
|
||||
```text
|
||||
POST /v1/pipelines/<pipeline_id>/upload
|
||||
Authorization: Bearer <token>
|
||||
Content-Type: application/gzip
|
||||
Idempotency-Key: <key>
|
||||
```
|
||||
|
||||
The authenticated token must be allowed to use the selected upload pipeline.
|
||||
A successful response is `202 Accepted` with JSON containing `run_id` and
|
||||
`status`. Acceptance means Distributor staged and validated the source bundle;
|
||||
it does not mean downstream destinations have published it.
|
||||
|
||||
The adapter requires nonblank pipeline ID, bundle ID, and idempotency key, plus
|
||||
at least one source-file mapping, before calling Distributor. It reads the bearer token from
|
||||
the configured environment variable and redacts that value from errors. Request
|
||||
construction and timeout handling belong to the [Distributor adapter](../../internal/distributor-adapter.md).
|
||||
|
||||
Weatherreporter reads at most 1 MiB from each Distributor response. An
|
||||
oversized response fails notification with a stable local diagnostic. Normal
|
||||
Weatherreporter results retain upload and status identity but do not repeat
|
||||
Distributor response bodies, status reports, or remote error text.
|
||||
|
||||
## Idempotency
|
||||
|
||||
Distributor scopes idempotency to the token, pipeline ID, and key. Keys must be
|
||||
non-empty ASCII values of at most 128 bytes using letters, digits, `.`, `_`,
|
||||
`-`, and `:`. Weatherreporter always supplies a rendered key; it does not rely
|
||||
on the client library's generated-key fallback.
|
||||
|
||||
Reusing a key for the same normalized source manifest returns the original
|
||||
accepted run. Reusing it for different content returns `409 Conflict`, which
|
||||
the adapter exposes as a Weatherreporter idempotency-conflict error. A distinct
|
||||
report or batch run therefore needs a distinct key; reuse a key only when
|
||||
retrying that same upload.
|
||||
|
||||
## Run Status And Retention
|
||||
|
||||
After acceptance, Weatherreporter reads:
|
||||
|
||||
```text
|
||||
GET /runs/<run_id>
|
||||
Authorization: Bearer <token>
|
||||
```
|
||||
|
||||
The status record provides `run_id`, `pipeline_id`, status timestamps, optional
|
||||
JSON `report`, and an `error` for failures. Statuses are `accepted`, `queued`,
|
||||
`running`, `succeeded`, and `failed`. A terminal `failed` status makes the
|
||||
notification fail; the adapter preserves the returned status details for the
|
||||
application to record.
|
||||
|
||||
Run and idempotency records are in-memory. Completed records expire according
|
||||
to Distributor's `server.http.retention`, and a Distributor restart removes
|
||||
retained status and idempotency state. Status polling decisions are internal
|
||||
orchestration behavior; see the
|
||||
[Distributor adapter](../../internal/distributor-adapter.md) and
|
||||
[application orchestration](../../internal/app-orchestration.md).
|
||||
|
||||
## Compatibility Reference
|
||||
|
||||
The upstream canonical HTTP wire contract is
|
||||
`docs/integrations/http-upload.md` in the Distributor repository. This page
|
||||
documents only the portion exercised by Weatherreporter.
|
||||
36
docs/integrations/distributor/pkg-bundle.md
Normal file
36
docs/integrations/distributor/pkg-bundle.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Distributor Source Bundle Mapping
|
||||
|
||||
Weatherreporter uses the source-bundle format through Distributor's
|
||||
`pkg/upload.UploadFiles` helper. It does not create bundle directories or call
|
||||
`pkg/bundle` directly. The helper creates a temporary bundle, writes and
|
||||
validates `manifest.json`, archives it, and removes the temporary bundle when
|
||||
the upload call returns.
|
||||
|
||||
## File Mappings
|
||||
|
||||
Every mapping pairs an operator-owned Markdown output with one bundle-relative
|
||||
path. A single-report notification maps its published output to each rendered
|
||||
path configured for that report. A batch notification combines mappings for
|
||||
every included published output and rejects duplicate bundle paths.
|
||||
|
||||
The report source is the output selected for that command; the application does
|
||||
not scan local directories. It renders notification paths after publication;
|
||||
see the [operations guide](../../operations.md) and the
|
||||
[Distributor adapter](../../internal/distributor-adapter.md) for the boundary.
|
||||
|
||||
Bundle paths must be clean, relative, slash-separated paths. They cannot be
|
||||
empty or absolute, contain backslashes, empty segments, `.` or `..`, or use
|
||||
`manifest.json` or `.distributor.json` as a basename. The mapped source must be
|
||||
a regular file. File mapping order is preserved and affects the bundle digest.
|
||||
|
||||
The bundle manifest uses schema version `1`, carries the rendered bundle ID and
|
||||
creation time, and records each mapped file's path, SHA-256 digest, and size.
|
||||
Destination routing, publication, and Distributor-managed destination state are
|
||||
not source-bundle fields.
|
||||
|
||||
## Compatibility Reference
|
||||
|
||||
The upstream canonical file-format contract is
|
||||
`docs/integrations/source-bundle.md` in the Distributor repository. It defines
|
||||
the complete manifest and archive format; this page records only the mapping and
|
||||
path constraints Weatherreporter relies on.
|
||||
56
docs/integrations/distributor/pkg-upload.md
Normal file
56
docs/integrations/distributor/pkg-upload.md
Normal file
@@ -0,0 +1,56 @@
|
||||
# Distributor Upload Client Contract
|
||||
|
||||
Weatherreporter uses `gitea.maximumdirect.net/eric/distributor/pkg/upload` at
|
||||
the pinned module version `v0.5.0`. It constructs one client per notification
|
||||
attempt and calls `UploadFiles`, followed by `Status` for the accepted run.
|
||||
|
||||
## Client And Upload
|
||||
|
||||
The adapter constructs the client with the prevalidated HTTP(S) endpoint,
|
||||
bearer token, and an HTTP client whose timeout is the configured Distributor
|
||||
timeout. The endpoint may include a path prefix but never userinfo, a query, or
|
||||
a fragment. It passes no custom retry options, so the pinned client's defaults
|
||||
apply: three attempts, 100 ms base delay, and one-second maximum delay.
|
||||
The adapter bounds every response to 1 MiB before handing it to the pinned
|
||||
client. A response above that boundary is rejected as a local overflow rather
|
||||
than decoding or retaining a prefix.
|
||||
|
||||
For each notification, Weatherreporter calls `UploadFiles` with:
|
||||
|
||||
- the rendered pipeline ID;
|
||||
- the rendered bundle ID as the source manifest ID;
|
||||
- the report or batch generation time as `Created`;
|
||||
- the published-output-to-bundle-path mappings described in the
|
||||
[bundle mapping contract](pkg-bundle.md); and
|
||||
- a rendered idempotency key.
|
||||
|
||||
It leaves bundle validation enabled. `UploadFiles` creates the temporary source
|
||||
bundle and sends it as a gzip-compressed tar archive; Weatherreporter does not
|
||||
call `UploadBundle` or submit prebuilt bundle roots.
|
||||
|
||||
## Retry, Conflict, And Status
|
||||
|
||||
The pinned upload client retries only `503 Service Unavailable` and retryable
|
||||
network failures. It does not retry successful `202` responses or other HTTP
|
||||
errors. Because every Weatherreporter request supplies an idempotency key, a
|
||||
retry keeps the same upload identity.
|
||||
|
||||
The client decodes the accepted upload result (`run_id`, `status`) and the run
|
||||
status record. A `409` response is an upstream idempotency conflict; the
|
||||
adapter translates it to its own conflict error without exposing the token.
|
||||
|
||||
The adapter then calls `Status` for the accepted run. A terminal `failed`
|
||||
status is a notification failure. A status lookup failure or a timeout before a
|
||||
terminal status remains attached to the otherwise accepted upload as diagnostic
|
||||
status information. Normal diagnostics use local status classifications; they
|
||||
do not expose remote response text or the status report. Polling cadence, final
|
||||
failure handling, and redaction are internal behavior documented in the
|
||||
[Distributor adapter](../../internal/distributor-adapter.md) and
|
||||
[application orchestration](../../internal/app-orchestration.md).
|
||||
|
||||
## Compatibility Reference
|
||||
|
||||
The upstream package workflow is documented in
|
||||
`docs/consumers/pkg-upload.md` in the Distributor repository. Weatherreporter
|
||||
uses only the client construction, `UploadFiles`, retry/conflict behavior, and
|
||||
`Status` operations described here.
|
||||
60
docs/integrations/promptkit.md
Normal file
60
docs/integrations/promptkit.md
Normal file
@@ -0,0 +1,60 @@
|
||||
# Promptkit Integration
|
||||
|
||||
Weatherreporter uses Promptkit for all generated-text reports. The four logical prompts are `weather.daily_generated_text`, `weather.today_generated_text`, `weather.tomorrow_generated_text`, and `weather.hourly_generated_text`, each at version `2.0.0`. Their prompt assets, generated-text JSON Schemas, and Weatherreporter profile catalog are embedded by `internal/promptassets`.
|
||||
|
||||
## Logical Profile Catalog
|
||||
|
||||
Prompt definitions select a stable Weatherreporter profile ID. The embedded definitions currently use Promptkit's `openrouter` backend:
|
||||
|
||||
| Profile ID | Model | Reasoning effort | Timeout | Service tier | Default reports |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| `weather-light` | `deepseek/deepseek-v4-flash` | Provider default | 180 seconds | `flex` | Hourly |
|
||||
| `weather-balanced` | `~google/gemini-flash-latest` | `high` | 240 seconds | `flex` | Daily, Today, Tomorrow |
|
||||
| `weather-deep` | `~anthropic/claude-sonnet-latest` | `high` | 240 seconds | `flex` | None |
|
||||
|
||||
The `~` prefix is part of each OpenRouter rolling-alias model ID. The embedded profiles intentionally omit endpoints, credentials, temperature, `top_p`, and output-token limits.
|
||||
|
||||
## Selection And Active Execution
|
||||
|
||||
Before weather collection, Weatherreporter validates the report's exact generated-text report/schema/template catalog binding, prompt version and hash, output contract, and selected profile. Active profiles must resolve a nonblank backend and model identity. A nonblank `promptkit.profile` selects one profile ID for every report in the command; otherwise the prompt's declared default selects it. Promptkit resolves the selected definition in this order:
|
||||
|
||||
1. explicit in-memory profiles used by an embedding consumer or test;
|
||||
2. the configured `profile_file` or `profile_dir`;
|
||||
3. Weatherreporter's embedded fallback profiles; and
|
||||
4. Promptkit's built-in catalog.
|
||||
|
||||
A source falls through only when the selected ID is absent. Each source supplies a complete definition, so profile fields are not merged. A malformed matching operator definition is an error and does not fall back.
|
||||
|
||||
Profiles that require a direct API key are unsupported; a profile that reports `APIKeyEnv` requires a nonblank value in that environment variable. Active results retain the selected logical profile ID and resolved backend and model. Ordinary errors, summaries, logs, and outputs exclude endpoints, credentials, rendered messages, schemas, request bodies, response bodies, and complete parameter maps.
|
||||
|
||||
Promptkit receives the YAML data package as an inline input and returns structured JSON that Weatherreporter validates before rendering its own Markdown template. Before accepting that JSON, Weatherreporter requires exactly one preparation callback and reconciles its prompt/profile/backend/model and rendered/input hashes with the inspected identity and completed result. The callback output contract and completed validation must use the report's expected JSON Schema mode and path. The package contains only reviewed prompt-facing warning summaries, never source transport or provenance details. Safe active provenance remains in memory. Content-rich diagnostics are opt-in through `--llm-debug-dir`; see [operations](../operations.md) for retention and permissions.
|
||||
|
||||
When capture is enabled, its preparation artifact projects a provider endpoint
|
||||
to its scheme and host and retains only reviewed execution settings. Provider
|
||||
extras and URL user information, paths, queries, and fragments are omitted.
|
||||
Capture storage remains confined to the operator-selected debug root; an unsafe
|
||||
filesystem path causes the requested execution to fail. Host availability and
|
||||
operator handling are documented in the
|
||||
[operations guide](../operations.md#optional-prompt-debug-capture).
|
||||
|
||||
## Comparison Execution
|
||||
|
||||
For `compare`, Weatherreporter validates the report's generated-text catalog
|
||||
binding, one exact prompt, and every explicitly selected profile before weather
|
||||
collection. It prepares one deterministic YAML
|
||||
data package, retains immutable copies of the report inputs, and executes every
|
||||
profile against the same exact data-package bytes. Each profile remains an
|
||||
independent Promptkit execution: one provider, provenance, or validation failure does not
|
||||
stop its peers, while caller cancellation applies to every in-flight execution.
|
||||
|
||||
Weatherreporter starts selected profile executions concurrently and does not
|
||||
add an application-level concurrency limit. Promptkit owns backend capacity and
|
||||
any profile or backend concurrency policy. A shared Weatherreporter executor
|
||||
must safely accept those concurrent `Execute` calls. The durable comparison output and
|
||||
its compatibility rules are defined by the
|
||||
[comparison bundle contract](comparison-bundle.md); the user-facing command
|
||||
contract is in the [CLI reference](../cli.md).
|
||||
|
||||
The generated-text schemas require `summary`, `forecast_discussion`, and `precipitation_timing`, and reject additional properties. Promptkit results are accepted only when their raw JSON is at most 64 KiB; the adapter drops larger results before copying them into Weatherreporter's execution values or debug artifacts. The validator also limits total generated prose to 20,000 characters, with 4,000-character summary and timing fields, a 12,000-character Hourly discussion, and at most 12 day-style paragraphs of 4,000 characters each. Prompts return an empty string for `precipitation_timing` when the deterministic package contains no precipitation windows.
|
||||
|
||||
Prompt/profile configuration and the maintained local override example are owned by the [configuration reference](../config.md). Adapter construction and mapping are documented in the [Promptkit adapter internals](../internal/promptkit-adapter.md).
|
||||
@@ -1,114 +0,0 @@
|
||||
# weatherreporter Subprocess Integration
|
||||
|
||||
## Purpose
|
||||
|
||||
This document defines the supported subprocess contract for weatherreporter invoking Scriptorium through the public CLI.
|
||||
|
||||
This is a CLI contract, not an internal Go package integration.
|
||||
|
||||
## Supported Commands
|
||||
|
||||
weatherreporter should invoke:
|
||||
|
||||
- `scriptorium run`
|
||||
- `scriptorium render`
|
||||
|
||||
Use `run` for generation.
|
||||
|
||||
Use `render` for preflight/debug output without LLM execution.
|
||||
|
||||
## Recommended Invocation Shapes
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
scriptorium run \
|
||||
--prompt <prompt_id> \
|
||||
--input data_package=<path> \
|
||||
--out <artifact_path>
|
||||
```
|
||||
|
||||
Render:
|
||||
|
||||
```bash
|
||||
scriptorium render \
|
||||
--prompt <prompt_id> \
|
||||
--input data_package=<path> \
|
||||
--format json
|
||||
```
|
||||
|
||||
weatherreporter may add:
|
||||
|
||||
- `--config <path>`
|
||||
- `--profile <profile_id>`
|
||||
- repeatable `--input name=path`
|
||||
- repeatable `--var name=value`
|
||||
- runtime overrides when explicitly needed (`--model`, `--llm-base-url`, `--timeout`, etc.)
|
||||
|
||||
## Config And Directory Behavior
|
||||
|
||||
weatherreporter can rely on resolved app config or pass explicit paths.
|
||||
|
||||
- default config search order:
|
||||
1. `/usr/local/etc/scriptorium/config.yml`
|
||||
2. `/etc/scriptorium/config.yml`
|
||||
- explicit `--config` requires file existence and valid syntax
|
||||
- CLI flags override config values
|
||||
|
||||
## Profile Selection
|
||||
|
||||
Profile selection follows runner behavior:
|
||||
|
||||
1. explicit `--profile`
|
||||
2. prompt `default_profile`
|
||||
3. error if neither is available
|
||||
|
||||
weatherreporter should treat prompt/profile IDs as deployment configuration, not hardcoded logic.
|
||||
|
||||
## Input And Variable Contract
|
||||
|
||||
- Inputs use repeated `--input name=path`.
|
||||
- Input names must match prompt definition input names.
|
||||
- Variables use repeated `--var name=value` for small metadata values.
|
||||
- Prefer file inputs for large content.
|
||||
|
||||
## Environment Contract
|
||||
|
||||
- Pass through required API-key environment variables referenced by `api_key_env`.
|
||||
- Never pass raw API keys via CLI arguments.
|
||||
- Keep subprocess environment scoped to required variables.
|
||||
|
||||
## Output And Error Handling
|
||||
|
||||
`run`:
|
||||
|
||||
- stdout: artifact body unless `--out` is used
|
||||
- `--out`: writes artifact to file
|
||||
- stderr: success summary and errors
|
||||
|
||||
`render`:
|
||||
|
||||
- stdout: prepared-run output unless `--out` is used
|
||||
- stderr: errors
|
||||
|
||||
weatherreporter should capture stdout and stderr separately.
|
||||
|
||||
## Exit Status Contract
|
||||
|
||||
- `0`: success
|
||||
- `1`: parse/config/load/render/generation/IO/runtime error
|
||||
- `2`: run completed but validation failed
|
||||
|
||||
A `run` exit code `2` can still produce output (stdout or `--out`).
|
||||
|
||||
## Security Notes
|
||||
|
||||
- Treat generated artifacts and stderr logs as potentially sensitive.
|
||||
- Avoid logging full rendered prompts by default in production contexts.
|
||||
- Use controlled output paths and access controls for persisted artifacts.
|
||||
|
||||
## Canonical References
|
||||
|
||||
- CLI behavior: [CLI reference](https://gitea.maximumdirect.net/eric/scriptorium/docs/cli.md)
|
||||
- Config behavior: [Configuration reference](https://gitea.maximumdirect.net/eric/scriptorium/docs/config.md)
|
||||
- Operations and failure handling: [Operations guide](https://gitea.maximumdirect.net/eric/scriptorium/docs/operations.md), [Troubleshooting](https://gitea.maximumdirect.net/eric/scriptorium/docs/troubleshooting.md)
|
||||
@@ -1,354 +1,154 @@
|
||||
# weatherapi External API
|
||||
# Weather API Integration
|
||||
|
||||
This document describes the public HTTP API exposed by `weatherapi` for external consumers.
|
||||
Weatherreporter fetches normalized weather inputs from a configured Weather API
|
||||
base URL. This guide defines the HTTP contract the service must satisfy; it is
|
||||
not a general Weather API reference. Configuration values are defined in the
|
||||
[configuration reference](../config.md). Normalization and collection behavior
|
||||
are documented in [Weather data internals](../internal/weather-data.md) and
|
||||
[Collection internals](../internal/collect.md).
|
||||
|
||||
## Base URL
|
||||
## Base URL And Requests
|
||||
|
||||
The service is typically served at your deployment host, for example:
|
||||
`weather_api.base_url` must be an absolute HTTP(S) URL. Weatherreporter joins
|
||||
each endpoint path to the configured base URL path, so a service hosted under a
|
||||
path prefix must keep that prefix available. Requests use `GET` and carry the
|
||||
configured timeout on every HTTP attempt.
|
||||
|
||||
- `https://weather.api.rakestrawhome.com`
|
||||
Every request sends `format` and, except where noted below, `units`. The
|
||||
configured format must be `json`.
|
||||
|
||||
All paths below are relative to the service root.
|
||||
Before retrieving sources, Weatherreporter requests `/conditions/current` with
|
||||
the same `format`, `units`, and `precision` query parameters used for current
|
||||
conditions. After a readable 2xx response, it retains that response for the
|
||||
normal current-conditions source step rather than making a second identical
|
||||
request. Failure after the readiness request's internal retry budget stops the
|
||||
fetch before source requests begin.
|
||||
|
||||
## Common Conventions
|
||||
## Endpoints And Query Parameters
|
||||
|
||||
### Response envelope
|
||||
The adapter makes one source request for each endpoint, subject to retry on
|
||||
transient failures. A successful readiness request supplies the current
|
||||
conditions source response. The remaining independent source requests run
|
||||
concurrently, then their results are processed in the source order shown below.
|
||||
This keeps source provenance, missing-source policy, and surfaced errors
|
||||
deterministic regardless of response order.
|
||||
|
||||
All endpoints return a top-level envelope:
|
||||
| Source | Endpoint | Query parameters | Availability |
|
||||
| --- | --- | --- | --- |
|
||||
| Observations | `/observations` | `format`, `units`, `precision` | Optional |
|
||||
| Current conditions | `/conditions/current` | `format`, `units`, `precision` | Optional |
|
||||
| Hourly forecast | `/forecast/hourly` | `format`, `units`, `precision`, `tz` | Required |
|
||||
| Narrative forecast | `/forecast/narrative` | `format`, `units`, `precision`, `tz` | Optional |
|
||||
| Active alerts | `/alerts/active` | `format`, `units` | Optional; `data: null` means checked with no active alerts |
|
||||
| Forecast discussion | `/discussion` | `format`, `units`, `tz` | Optional |
|
||||
| Weather story | `/weatherstories/latest` | `format` | Optional |
|
||||
| SPC convective outlooks | `/outlooks/convective` | `format`, `tz` | Optional; non-null empty lists are checked empty data |
|
||||
|
||||
- `data`: endpoint payload or `null` when no current/latest resource is available.
|
||||
`precision` comes from `weather_api.precision`; `tz` comes from
|
||||
`weather_api.timezone`. Weatherreporter does not call day-slice forecast or
|
||||
discussion-subsection endpoints.
|
||||
|
||||
JSON example:
|
||||
## Response Envelope
|
||||
|
||||
Each endpoint response must be JSON with a top-level `data` member:
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {"...": "..."}
|
||||
"data": {}
|
||||
}
|
||||
```
|
||||
|
||||
### Output format
|
||||
|
||||
Supported via `format` query parameter (case-insensitive):
|
||||
|
||||
- `json` (default)
|
||||
- `xml`
|
||||
- `text`
|
||||
|
||||
### Units
|
||||
|
||||
Supported via `units` query parameter (case-insensitive):
|
||||
|
||||
- `metric` (default)
|
||||
- `us`
|
||||
|
||||
Endpoints that include unit-based numeric fields return either metric or US field variants depending on this value.
|
||||
|
||||
### Precision
|
||||
|
||||
Supported where documented via `precision` query parameter:
|
||||
|
||||
- integer range: `0` to `2`
|
||||
- controls decimal rounding of numeric output fields
|
||||
|
||||
### Timezone (`tz` / `TZ`)
|
||||
|
||||
Supported where documented:
|
||||
|
||||
- accepted values include:
|
||||
- IANA timezone names (example: `America/Chicago`)
|
||||
- common US abbreviations (example: `CDT`, `EST`)
|
||||
- UTC offsets in `±H`, `±HH`, or `±HH:MM` (example: `-5`, `+09:30`)
|
||||
- aliases including `Chicago` and `Stl`
|
||||
- `tz` and `TZ` are treated equivalently
|
||||
- if both are provided, they must match exactly or the request fails
|
||||
|
||||
Timezone affects datetime rendering and day-slice filtering for `/today` and `/tomorrow` forecast routes.
|
||||
|
||||
### Query validation
|
||||
|
||||
- Unknown query parameters are rejected with `400 Bad Request`.
|
||||
- Invalid parameter values are rejected with `400 Bad Request`.
|
||||
|
||||
Error response body follows the service error envelope; exact fields may vary by error type.
|
||||
|
||||
## Endpoints
|
||||
|
||||
## `GET /observations`
|
||||
|
||||
Returns the latest weather observation.
|
||||
|
||||
Query parameters:
|
||||
|
||||
- `units`: `metric` | `us`
|
||||
- `format`: `json` | `xml` | `text`
|
||||
- `precision`: `0..2`
|
||||
|
||||
Response `data` fields:
|
||||
|
||||
- `stationId` (string, optional)
|
||||
- `stationName` (string, optional)
|
||||
- `timestamp` (RFC3339 datetime, required)
|
||||
- `conditionCode` (integer WMO code, required)
|
||||
- `isDay` (boolean, optional)
|
||||
- `textDescription` (string, optional)
|
||||
- Metric mode fields:
|
||||
- `temperatureC`, `dewpointC`, `windSpeedKmh`, `windGustKmh`, `barometricPressurePa`, `visibilityMeters`, `relativeHumidityPercent`, `apparentTemperatureC` (number, optional)
|
||||
- `windDirectionDegrees` (number, optional)
|
||||
- US mode fields:
|
||||
- `temperatureF`, `dewpointF`, `windSpeedMph`, `windGustMph`, `barometricPressureInHg`, `visibilityMiles`, `relativeHumidityPercent`, `apparentTemperatureF` (number, optional)
|
||||
- `windDirectionDegrees` (number, optional)
|
||||
- `presentWeather` (array, optional)
|
||||
|
||||
## `GET /alerts/active`
|
||||
|
||||
Returns the latest active alert run.
|
||||
|
||||
Query parameters:
|
||||
|
||||
- `units`: `metric` | `us` (accepted; does not materially alter alert payload)
|
||||
- `format`: `json` | `xml` | `text`
|
||||
|
||||
Response `data` fields:
|
||||
|
||||
- Weather alert run object from canonical model (includes run metadata and active alerts list).
|
||||
|
||||
## `GET /conditions/current`
|
||||
|
||||
Returns current conditions synthesized from latest observation/forecast data.
|
||||
|
||||
Query parameters:
|
||||
|
||||
- `units`: `metric` | `us`
|
||||
- `format`: `json` | `xml` | `text`
|
||||
- `precision`: `0..2`
|
||||
|
||||
Response `data` fields:
|
||||
|
||||
- Common:
|
||||
- `conditionText` (string, optional)
|
||||
- `isDay` (boolean, optional)
|
||||
- `relativeHumidityPercent` (number, optional)
|
||||
- `windDirectionDegrees` (number, optional)
|
||||
- Metric mode:
|
||||
- `temperatureC`, `apparentTemperatureC`, `dewpointC`, `windSpeedKmh` (number, optional)
|
||||
- US mode:
|
||||
- `temperatureF`, `apparentTemperatureF`, `dewpointF`, `windSpeedMph` (number, optional)
|
||||
|
||||
## Forecast endpoints
|
||||
|
||||
- `GET /forecast/hourly`
|
||||
- `GET /forecast/hourly/today`
|
||||
- `GET /forecast/hourly/tomorrow`
|
||||
- `GET /forecast/narrative`
|
||||
- `GET /forecast/narrative/today`
|
||||
- `GET /forecast/narrative/tomorrow`
|
||||
|
||||
Query parameters:
|
||||
|
||||
- `units`: `metric` | `us`
|
||||
- `format`: `json` | `xml` | `text`
|
||||
- `precision`: `0..2`
|
||||
- `tz` or `TZ`: timezone selector
|
||||
|
||||
Day-slice routes:
|
||||
|
||||
- `/today` returns periods with `period.startTime` in the current calendar day for the resolved timezone.
|
||||
- `/tomorrow` returns periods with `period.startTime` in the next calendar day for the resolved timezone.
|
||||
|
||||
Response `data` fields:
|
||||
|
||||
- Run-level:
|
||||
- `locationId` (string, optional)
|
||||
- `locationName` (string, optional)
|
||||
- `issuedAt` (RFC3339 datetime, required)
|
||||
- `updatedAt` (RFC3339 datetime, optional)
|
||||
- `product` (string, required; e.g. `hourly`, `narrative`)
|
||||
- `latitude`, `longitude` (number, optional)
|
||||
- Metric mode: `elevationMeters` (number, optional)
|
||||
- US mode: `elevationFeet` (number, optional)
|
||||
- `periods` (array, required)
|
||||
- Period fields:
|
||||
- `startTime`, `endTime` (RFC3339 datetime, required)
|
||||
- `name` (string, optional)
|
||||
- `isDay` (boolean, optional)
|
||||
- `conditionCode` (integer WMO code, optional)
|
||||
- `textDescription` (string, optional)
|
||||
- Metric mode (optional):
|
||||
- `temperatureC`, `temperatureCMin`, `temperatureCMax`, `dewpointC`, `windSpeedKmh`, `windGustKmh`, `barometricPressurePa`, `visibilityMeters`, `apparentTemperatureC`, `cloudCoverPercent`, `probabilityOfPrecipitationPercent`, `precipitationAmountMm`, `snowfallDepthMM`, `uvIndex`, `relativeHumidityPercent`, `windDirectionDegrees`
|
||||
- US mode (optional):
|
||||
- `temperatureF`, `temperatureFMin`, `temperatureFMax`, `dewpointF`, `windSpeedMph`, `windGustMph`, `barometricPressureInHg`, `visibilityMiles`, `apparentTemperatureF`, `cloudCoverPercent`, `probabilityOfPrecipitationPercent`, `precipitationAmountIn`, `snowfallDepthIn`, `uvIndex`, `relativeHumidityPercent`, `windDirectionDegrees`
|
||||
|
||||
Notes:
|
||||
|
||||
- Narrative periods may omit `conditionCode`.
|
||||
- Text format uses forecast-specific templates (`hourly` and `narrative`).
|
||||
|
||||
## Discussion endpoints
|
||||
|
||||
- `GET /discussion`
|
||||
- `GET /discussion/key-messages`
|
||||
- `GET /discussion/short-term`
|
||||
- `GET /discussion/long-term`
|
||||
|
||||
Query parameters:
|
||||
|
||||
- `units`: `metric` | `us` (accepted; does not materially alter discussion payload)
|
||||
- `format`: `json` | `xml` | `text`
|
||||
- `tz` or `TZ`: timezone selector
|
||||
|
||||
Response `data` fields:
|
||||
|
||||
- `/discussion`:
|
||||
- `officeId` (string, optional)
|
||||
- `officeName` (string, optional)
|
||||
- `product` (string, required)
|
||||
- `issuedAt` (RFC3339 datetime, required)
|
||||
- `updatedAt` (RFC3339 datetime, optional)
|
||||
- `keyMessages` (array of string)
|
||||
- `shortTerm` (object, optional)
|
||||
- `longTerm` (object, optional)
|
||||
- `/discussion/key-messages`:
|
||||
- `officeId`, `officeName`, `product`, `issuedAt`, `updatedAt`
|
||||
- `keyMessages` (array of string)
|
||||
- `/discussion/short-term`:
|
||||
- `officeId`, `officeName`, `product`, `issuedAt`, `updatedAt`
|
||||
- `shortTerm` (object, optional)
|
||||
- `/discussion/long-term`:
|
||||
- `officeId`, `officeName`, `product`, `issuedAt`, `updatedAt`
|
||||
- `longTerm` (object, optional)
|
||||
|
||||
Discussion section object fields:
|
||||
|
||||
- `title` (string, optional)
|
||||
- `narrative` (string, optional)
|
||||
- `issuedAt` (RFC3339 datetime, optional)
|
||||
|
||||
## Examples
|
||||
|
||||
### Observation (JSON, metric)
|
||||
|
||||
```http
|
||||
GET /observations?format=json&units=metric&precision=1
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"stationId": "KSTL",
|
||||
"timestamp": "2026-05-29T14:00:00Z",
|
||||
"conditionCode": 3,
|
||||
"isDay": true,
|
||||
"textDescription": "Partly cloudy",
|
||||
"temperatureC": 24.4,
|
||||
"windSpeedKmh": 17.2,
|
||||
"relativeHumidityPercent": 56.0
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Alerts (JSON)
|
||||
|
||||
```http
|
||||
GET /alerts/active?format=json
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"asOf": "2026-05-29T14:00:00Z",
|
||||
"alerts": []
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Current conditions (JSON, US)
|
||||
|
||||
```http
|
||||
GET /conditions/current?format=json&units=us&precision=1
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"conditionText": "Partly cloudy",
|
||||
"isDay": true,
|
||||
"temperatureF": 75.9,
|
||||
"apparentTemperatureF": 76.1,
|
||||
"windSpeedMph": 10.7,
|
||||
"relativeHumidityPercent": 56.0
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Forecast narrative (JSON, optional `conditionCode`)
|
||||
|
||||
```http
|
||||
GET /forecast/narrative?format=json&units=metric&precision=1&tz=America/Chicago
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"locationId": "nws-lsx-grid-90-74",
|
||||
"issuedAt": "2026-05-29T10:30:00-05:00",
|
||||
"product": "narrative",
|
||||
"periods": [
|
||||
{
|
||||
"startTime": "2026-05-29T13:00:00-05:00",
|
||||
"endTime": "2026-05-29T19:00:00-05:00",
|
||||
"name": "Today",
|
||||
"isDay": true,
|
||||
"textDescription": "Partly sunny, with a high near 81.",
|
||||
"temperatureC": 27.2,
|
||||
"windSpeedKmh": 18.0,
|
||||
"probabilityOfPrecipitationPercent": 10.0
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Forecast hourly today (text)
|
||||
|
||||
```http
|
||||
GET /forecast/hourly/today?format=text&units=us&precision=1&tz=CDT
|
||||
```
|
||||
|
||||
```text
|
||||
<plain text forecast output>
|
||||
```
|
||||
|
||||
### Discussion key messages (JSON)
|
||||
|
||||
```http
|
||||
GET /discussion/key-messages?format=json&tz=Chicago
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"data": {
|
||||
"officeId": "LSX",
|
||||
"product": "discussion",
|
||||
"issuedAt": "2026-05-29T09:25:00-05:00",
|
||||
"keyMessages": [
|
||||
"Scattered showers possible this evening.",
|
||||
"Warmer temperatures this weekend."
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Invalid timezone error example
|
||||
|
||||
```http
|
||||
GET /forecast/narrative?tz=not-a-timezone
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"error": {
|
||||
"code": "invalid_parameter",
|
||||
"message": "tz must be a valid timezone"
|
||||
}
|
||||
}
|
||||
```
|
||||
An absent `data` member is treated as a missing source. For ordinary sources,
|
||||
`data: null` is also missing. The active-alert exception is listed above: its
|
||||
explicit `null` payload represents an empty alert result.
|
||||
|
||||
Hourly forecast data must be present and contain at least one `period`. Every
|
||||
hourly period needs nonzero `startTime` and `endTime` values, with `endTime`
|
||||
after `startTime`; a missing, malformed, empty, or invalidly bounded hourly
|
||||
product fails collection. The remaining sources follow the configured
|
||||
missing-source policy. Under `error`, collection fails; under `warn`, the
|
||||
source is omitted and an inspectable warning is recorded; under `none`, the
|
||||
source is omitted without a warning. A per-source policy overrides the default.
|
||||
See [Configuration](../config.md) for policy settings and [Weather data
|
||||
internals](../internal/weather-data.md) for recorded source metadata.
|
||||
|
||||
Malformed top-level JSON envelopes and HTTP failures are direct request errors.
|
||||
Malformed `data` for an optional source follows its missing-source policy.
|
||||
|
||||
## Payload Fields Used
|
||||
|
||||
Weatherreporter decodes only the fields below; additional upstream fields are
|
||||
ignored. Timestamps must be JSON values accepted by Go's `time.Time` decoder.
|
||||
|
||||
### Observations And Current Conditions
|
||||
|
||||
`/observations` uses `stationId`, `stationName`, `timestamp`, `conditionCode`,
|
||||
`isDay`, `textDescription`, `temperatureC`, `temperatureF`, `dewpointC`,
|
||||
`dewpointF`, `windSpeedKmh`, `windSpeedMph`, `windGustKmh`, `windGustMph`,
|
||||
`windDirectionDegrees`, `barometricPressurePa`, `barometricPressureInHg`,
|
||||
`visibilityMeters`, `visibilityMiles`, `relativeHumidityPercent`,
|
||||
`apparentTemperatureC`, `apparentTemperatureF`, and `presentWeather`.
|
||||
|
||||
`/conditions/current` uses `conditionText`, `isDay`,
|
||||
`relativeHumidityPercent`, `windDirectionDegrees`, `temperatureC`,
|
||||
`temperatureF`, `apparentTemperatureC`, `apparentTemperatureF`, `dewpointC`,
|
||||
`dewpointF`, `windSpeedKmh`, and `windSpeedMph`.
|
||||
|
||||
### Hourly And Narrative Forecasts
|
||||
|
||||
Both forecast endpoints use run-level `locationId`, `locationName`, `issuedAt`,
|
||||
`updatedAt`, `product`, `latitude`, `longitude`, `elevationMeters`,
|
||||
`elevationFeet`, and `periods`.
|
||||
|
||||
Each `periods` item uses `startTime`, `endTime`, `name`, `isDay`,
|
||||
`conditionCode`, `textDescription`, `temperatureC`, `temperatureF`,
|
||||
`temperatureCMin`, `temperatureFMin`, `temperatureCMax`, `temperatureFMax`,
|
||||
`dewpointC`, `dewpointF`, `windSpeedKmh`, `windSpeedMph`, `windGustKmh`,
|
||||
`windGustMph`, `windDirectionDegrees`, `barometricPressurePa`,
|
||||
`barometricPressureInHg`, `visibilityMeters`, `visibilityMiles`,
|
||||
`apparentTemperatureC`, `apparentTemperatureF`, `cloudCoverPercent`,
|
||||
`probabilityOfPrecipitationPercent`, `precipitationAmountMm`,
|
||||
`precipitationAmountIn`, `snowfallDepthMM`, `snowfallDepthIn`, `uvIndex`, and
|
||||
`relativeHumidityPercent`.
|
||||
|
||||
### Alerts, Discussion, And Weather Story
|
||||
|
||||
`/alerts/active` uses the `asOf` timestamp and keeps each item in `alerts` as
|
||||
an alert payload. Weatherreporter does not require a separate alert-item schema
|
||||
at this integration boundary.
|
||||
|
||||
`/discussion` uses `officeId`, `officeName`, `product`, `issuedAt`,
|
||||
`updatedAt`, `keyMessages`, and the `shortTerm` and `longTerm` sections. Each
|
||||
section uses `qualifier`, `text`, and `issuedAt`.
|
||||
|
||||
`/weatherstories/latest` uses `officeId`, `startTime`, `endTime`, `updatedAt`,
|
||||
`title`, `description`, `altText`, `priority`, `order`, and `downloadUrl`.
|
||||
|
||||
### SPC Convective Outlooks
|
||||
|
||||
`/outlooks/convective` uses run-level `locationId`, `locationName`, `asOf`,
|
||||
`issuedAt`, `updatedAt`, `product`, `outlooks`, and `discussions`.
|
||||
|
||||
Each outlook uses `id`, `provider`, `product`, `day`, `outlookType`, `label`,
|
||||
`labelText`, `forecaster`, `severityRank`, `validFrom`, `validTo`, `issuedAt`,
|
||||
`expiresAt`, `sourceUrl`, `imageUrl`, `containsLocation`, and GeoJSON
|
||||
`geometry`. Each discussion uses `day`, `headline`, `summary`, `discussion`,
|
||||
and `updatedAt`.
|
||||
|
||||
## Timeouts, Retries, And Failures
|
||||
|
||||
The configured Weather API timeout applies to each warmup and source HTTP
|
||||
attempt. Weatherreporter retries transient transport and response-read failures
|
||||
and these response statuses: `408`, `429`, `500`, `502`, `503`, and `504`.
|
||||
It does not retry other HTTP statuses, malformed envelopes, missing data, or
|
||||
payload decoding failures. A canceled context also stops an in-progress retry
|
||||
delay.
|
||||
|
||||
The adapter accepts response bodies up to 10 MiB and rejects larger bodies
|
||||
before decoding. A non-2xx response reports its relative endpoint and status,
|
||||
without including upstream response text. Request construction, response-limit,
|
||||
read, and decode failures include endpoint context in their errors.
|
||||
|
||||
Retry counts and delays are adapter behavior rather than Weather API request
|
||||
parameters. Do not depend on a particular attempt count when implementing the
|
||||
service.
|
||||
|
||||
72
docs/internal/app-orchestration.md
Normal file
72
docs/internal/app-orchestration.md
Normal file
@@ -0,0 +1,72 @@
|
||||
# Application Orchestration Internals
|
||||
|
||||
`internal/app` owns stateless report generation, batch execution, comparison
|
||||
orchestration, atomic output publication, and notification coordination after
|
||||
`internal/cli` has parsed arguments and loaded configuration. The user contract
|
||||
is owned by the [CLI reference](../cli.md) and [operations guide](../operations.md).
|
||||
|
||||
## Single-Report Flow
|
||||
|
||||
`GenerateDetailed` resolves the requested report and output destination before initializing an optional explicit debug writer. An explicit output file wins; otherwise the configured output directory is used, falling back to the captured working directory. Output preflight validates the final filename, permits only an absent or regular final destination, and validates the bounded same-directory temporary form without creating a missing parent. It then validates the report's generated-text catalog binding, exact Promptkit prompt, and selected profile before collecting weather data. The resolved profile, backend, and model are carried in the active result.
|
||||
|
||||
The workflow builds facts, a module snapshot, briefing metadata, and the YAML prompt package in memory. It executes Promptkit only against the inspected prompt and profile, reconciles the preparation callback and completed result with that identity and the prepared report schema, validates the returned generated text, builds a render context, and renders Markdown. `fileutil` writes the completed Markdown through a same-directory temporary file, rechecks the final destination and context after close and immediately before the atomic rename. Only after that write succeeds does single-report notification run.
|
||||
|
||||
Failures return an active partial result with safe identity, profile, warning, validation, debug, and output information when available. After rendering and immediately before publication, the workflow checks for cancellation or deadline expiry. Any failure before publication leaves an existing destination unchanged. A notification failure retains the newly published output.
|
||||
|
||||
## Batches
|
||||
|
||||
`RunBatchDetailed` selects an explicit output directory first, otherwise the configured directory and then the captured working directory. It does this before creating at most one explicit debug writer or validating generated-text catalog, prompt, and profile candidates for the selected batch. It collects once, calculates the data-dependent plan, then validates and retains the final output path for every planned report before invoking the same generation core sequentially.
|
||||
|
||||
Each item has an independent result. A failed item does not stop later items; successful items retain their published output paths. Per-report notification is suppressed during a batch. Batch notification runs only after every planned report has published successfully. It is skipped when any item failed. Batch result counters count report items only; a batch notification failure is represented by the top-level notification result and still produces a failed batch outcome.
|
||||
|
||||
Cancellation and deadline expiry stop the sequential loop before another report
|
||||
starts. Completed report results and published paths remain successful; the
|
||||
interrupted and unstarted planned reports have `canceled` status and are counted
|
||||
separately from failed reports. The batch notification result records that
|
||||
delivery was skipped, and the returned error retains the original context cause
|
||||
for callers and CLI projection.
|
||||
|
||||
## Comparisons
|
||||
|
||||
`CompareDetailed` validates ordered explicit profile IDs, resolves the report,
|
||||
and preflights the exact bundle destination before initializing optional prompt
|
||||
debugging, prompt inspection, or collection. It then validates the report's
|
||||
generated-text catalog binding, inspects the one prompt and every selected
|
||||
profile, collects once, and delegates shared report
|
||||
construction to the prepared-report flow. It does not accept a notifier.
|
||||
|
||||
Once the destination is resolved, the partial result retains its absolute
|
||||
output directory even when later preflight, debug initialization, inspection,
|
||||
collection, or preparation fails. Every initialized result is finalized with a
|
||||
finished timestamp. If prompt inspection succeeds before a later profile
|
||||
inspection fails, the partial result retains the resolved prompt ID, version,
|
||||
and hash. Artifact paths are added only after publication commits.
|
||||
|
||||
The comparison execution core starts each inspected profile independently,
|
||||
keeps results in selection order, and waits for all started work. Every profile
|
||||
reconciles its callback and completion provenance before its JSON can be
|
||||
rendered. Independent profile failures are recorded and do not stop peers; a
|
||||
completed profile failure remains recorded if cancellation happens later.
|
||||
Context cancellation marks only unfinished or cancellation-terminated work and
|
||||
prevents publication. Details of
|
||||
prepared values, execution and debugging, and publication are documented in [prepared report
|
||||
internals](prepared-report.md), [comparison execution
|
||||
internals](comparison-execution.md), and [comparison publication
|
||||
internals](comparison-publication.md).
|
||||
|
||||
When publication has committed its new bundle, application results contain the
|
||||
absolute manifest, data-package, and successful report paths even if removal of
|
||||
the previous sibling backup then fails. That cleanup failure is still returned
|
||||
as an operational error rather than treating the new bundle as unpublished;
|
||||
the returned error identifies the observed recovery state and includes a path
|
||||
only when cleanup left a sibling behind.
|
||||
|
||||
## Boundaries And Verification
|
||||
|
||||
The package does not parse flags, load YAML, implement transport, construct provider SDKs, or define report-period policy. Prompt, profile, weather, and Distributor implementations remain behind project-owned contracts.
|
||||
|
||||
Focused checks:
|
||||
|
||||
```sh
|
||||
go test ./internal/app ./internal/collect
|
||||
```
|
||||
103
docs/internal/briefing.md
Normal file
103
docs/internal/briefing.md
Normal file
@@ -0,0 +1,103 @@
|
||||
# Module Builder Internals
|
||||
|
||||
`internal/briefing` builds typed module outputs from resolved report context,
|
||||
collected facts, and derived facts. It owns the module registry, including
|
||||
module support, fact requirements, option types, missing-data policy, builders,
|
||||
and prompt-export hooks. It does not collect data, derive periods, write a
|
||||
snapshot, construct YAML, invoke Promptkit, or render a report.
|
||||
|
||||
## Registry and construction
|
||||
|
||||
Every `ModuleDefinition` declares an ID, stanza name, default option value,
|
||||
required collected and derived facts, supported report IDs, missing-data
|
||||
behavior, duplicate policy, builder, and optional prompt exporter. The
|
||||
briefing-owned fact-requirement vocabulary supplies each prerequisite's stable
|
||||
identity, category, and availability predicate; registry construction rejects
|
||||
unknown requirements and requirements listed under the wrong category.
|
||||
|
||||
`BuildModule` first verifies the requested module, report compatibility, and
|
||||
option shape. It then applies the declared missing-data behavior:
|
||||
|
||||
- `omit` returns no output for unavailable optional facts;
|
||||
- `error` returns the missing fact requirements; and
|
||||
- `empty` allows the builder to emit an explicit checked-empty value.
|
||||
|
||||
Unsupported `warn` behavior, missing builders, duplicate registry IDs or
|
||||
stanza names, output ID or stanza mismatches, and exporter failures all return
|
||||
errors with module context. A successful builder gets a pass-through prompt
|
||||
value unless its definition supplies an exporter.
|
||||
|
||||
## Built value families
|
||||
|
||||
Source-oriented builders shape report metadata, current conditions, narrative
|
||||
and hourly forecasts, alert digest, SPC outlooks and discussion, area forecast
|
||||
discussion, and weather story. Derived builders shape daily and daypart
|
||||
summaries, precipitation timing, outdoor windows, and the report-specific
|
||||
Daily, Today, and Tomorrow planning values.
|
||||
|
||||
The daily summary preserves generic feels-like values as
|
||||
`apparent_temperature_max_f`; it does not label them as a heat index. Daypart
|
||||
temperature phrases retain below-zero meaning, including through temperature
|
||||
trends that cross zero. Outdoor windows add a 25-point risk penalty and an
|
||||
explicit reason for each snow, ice, or fog indicator. Equal scores retain input
|
||||
order for both best and worst windows.
|
||||
|
||||
The module registry preserves rich values for templates and snapshots while
|
||||
curating prompt exports where needed. In particular, source warnings are a
|
||||
metadata summary, checked-empty alerts and SPC outlooks remain distinct from
|
||||
missing sources, and prompt-safe SPC values omit geometry and other
|
||||
template-only or source details. The complete module composition is in
|
||||
[module internals](module.md); fact derivation is in [fact contracts](facts.md).
|
||||
Alert digests are built from selected alert items and source provenance, not a
|
||||
provider response envelope.
|
||||
|
||||
Derived daypart-summary maps use the forecast package's canonical daypart
|
||||
identity and reject any collision instead of replacing an earlier value.
|
||||
Planning applies the same identity when recognizing morning, afternoon,
|
||||
evening, and overnight windows; display labels remain separate and preserve
|
||||
configured text with rune-safe first-letter capitalization.
|
||||
|
||||
The embedded SPC background-definition asset records its authoritative sources,
|
||||
source update dates, and maintainer review schedule. Its categorical
|
||||
`official_description` values transcribe the [SPC convective-outlook risk
|
||||
table](https://www.spc.noaa.gov/about/outlooks/); its Conditional Intensity
|
||||
Group entries follow the [SPC conditional-intensity
|
||||
reference](https://www.spc.noaa.gov/exper/conditional-intensity-information).
|
||||
`plain_language` values are Weatherreporter summaries. Weatherreporter
|
||||
maintainers review the asset annually and whenever either source changes.
|
||||
|
||||
`area_forecast_discussion` accepts an optional typed section filter. Accepted
|
||||
typed option pointers are normalized to the declared value type before builder
|
||||
execution. Planning modules are report-specific: `daily_planning` supports Daily,
|
||||
`today_planning` supports Today, and `tomorrow_planning` supports Tomorrow.
|
||||
|
||||
## Missing data and boundaries
|
||||
|
||||
Optional current conditions, narrative products, discussions, and weather
|
||||
stories may be omitted. A weather story is usable only when it has non-blank
|
||||
displayable content (title, description, alternate text, or download URL) or a
|
||||
valid start/end period; otherwise collection applies its optional-source policy
|
||||
and the module is omitted. Required derived modules fail when their declared facts
|
||||
are unavailable. Empty alert and outlook runs can still produce checked-empty
|
||||
modules. SPC discussion is omitted unless a retained categorical outlook meets
|
||||
the package's severity criterion and matching discussion text exists.
|
||||
|
||||
`ModuleContext` carries the effective units, timezone, location context, and
|
||||
prepared identity. Report preparation creates that one `PreparedIdentity` for
|
||||
the shared report identity, timing, configuration context, and source warnings
|
||||
before module construction. The metadata module projects its matching fields
|
||||
from that value and retains its prompt-safe shape. Field defaults are owned by
|
||||
[configuration](../config.md), and prompt-package layout is owned by [prompt
|
||||
input](prompt-input.md).
|
||||
|
||||
## Verification and invariants
|
||||
|
||||
Focused tests cover source and derived values, registry validation, option
|
||||
handling, prompt exporters, support rules, and missing-data behavior:
|
||||
|
||||
```sh
|
||||
go test ./internal/briefing
|
||||
```
|
||||
|
||||
Builders emit structured facts, never report prose. The app collects their
|
||||
outputs into an in-memory module snapshot for prompt input and rendering.
|
||||
21
docs/internal/cli.md
Normal file
21
docs/internal/cli.md
Normal file
@@ -0,0 +1,21 @@
|
||||
# CLI Internals
|
||||
|
||||
`internal/cli` parses terminal arguments, loads configuration, constructs app requests, and translates app results to bounded JSON summaries. The public contract belongs in the [CLI reference](../cli.md).
|
||||
|
||||
The root `--version` flag reports the build version supplied by `internal/buildinfo`. Tagged release builds replace its development default at link time.
|
||||
|
||||
The executable derives its action context from `SIGINT` and `SIGTERM` and
|
||||
passes it to `Runner.Run`. Signal cancellation therefore uses the same action,
|
||||
summary, and error paths as other context cancellation.
|
||||
|
||||
For each `generate`, `run`, or `compare` action, `Runner` constructs one project-owned Promptkit executor after request preflight and configuration loading. It captures an absolute working directory, resolves only a relative explicit output override against it, and passes the working directory, loaded configuration, resolved override, and any `--llm-debug-dir` request to the app. The raw configured fallback remains in the configuration for app-owned destination selection. `run` uses the same explicit-resolution rule for `--out-dir`.
|
||||
|
||||
The CLI dispatches generation, batch, and comparison actions. It has no persisted-run or inspection dispatch. Generation and batch summaries include report identity, status, output path, effective profile/backend/model, source warnings, validation, requested debug path, and notification result when available. Comparison summaries retain their ordered profile results and published bundle paths when available. All summaries intentionally exclude prompt input, raw generated text, render context, endpoints, credentials, and full Distributor payloads. A failed action with a partial result still emits its safe summary before its error is returned unless `--quiet` is set.
|
||||
|
||||
CLI code owns report-date flag acceptance and date resolution, but not report
|
||||
composition, weather collection, output publication, provider execution, or
|
||||
notification policy. Focused checks:
|
||||
|
||||
```sh
|
||||
go test ./internal/cli
|
||||
```
|
||||
36
docs/internal/collect.md
Normal file
36
docs/internal/collect.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Collection Internals
|
||||
|
||||
`internal/collect` is the small application-facing boundary that obtains one
|
||||
normalized Weather API bundle. The external HTTP contract belongs in the
|
||||
[Weather API integration guide](../integrations/weatherapi.md); normalized
|
||||
source values belong in [weather-data internals](weather-data.md).
|
||||
|
||||
## Contract
|
||||
|
||||
`Run` receives a context and effective configuration in `Request`. It creates
|
||||
the Weather API adapter, calls `FetchBundle`, and returns the adapter's
|
||||
normalized bundle in `Result`. Adapter construction errors are wrapped as
|
||||
weather-collection setup errors and fetch errors as bundle-collection errors.
|
||||
|
||||
The package neither chooses reports nor derives facts, builds modules, invokes
|
||||
Promptkit, writes files, or sends notifications. Request scheduling, endpoint
|
||||
retrieval, response limits, and source-level warnings belong to the Weather
|
||||
API adapter and its integration contract.
|
||||
|
||||
## Application Use
|
||||
|
||||
`internal/app` owns the `Collector` interface used by report workflows and
|
||||
tests. Its default implementation delegates to `collect.Run`; callers may
|
||||
substitute a collector at that boundary. Application orchestration owns
|
||||
collection timing, reuse across a workflow, and the handling of nil collection
|
||||
results. See [app orchestration internals](app-orchestration.md) for that
|
||||
flow.
|
||||
|
||||
## Verification
|
||||
|
||||
Focused package tests cover a successful fetch and wrapping failures from
|
||||
adapter construction and bundle retrieval:
|
||||
|
||||
```sh
|
||||
go test ./internal/collect
|
||||
```
|
||||
32
docs/internal/comparison-execution.md
Normal file
32
docs/internal/comparison-execution.md
Normal file
@@ -0,0 +1,32 @@
|
||||
# Comparison Execution Internals
|
||||
|
||||
The comparison execution core receives an already prepared report and an
|
||||
already inspected, ordered profile list. It initializes an outcome for every
|
||||
selected profile, launches each started profile in its own goroutine, and
|
||||
waits for every started goroutine before returning. Results retain the supplied
|
||||
selection order even though execution completes in an arbitrary order.
|
||||
|
||||
Every profile uses the exact inspected prompt identity and a private copy of
|
||||
the same prepared data package. Provider, generated-text validation, rendering,
|
||||
or debug-write failure becomes that profile's safe failed outcome and does not
|
||||
cancel its peers. The shared executor must support those concurrent `Execute`
|
||||
calls. The application deliberately imposes no additional semaphore: Promptkit
|
||||
owns backend capacity. A profile failure completed before a later cancellation
|
||||
remains its original safe outcome; cancellation or a deadline marks only
|
||||
unfinished or cancellation-terminated outcomes as skipped or failed, joins work,
|
||||
and prevents bundle publication.
|
||||
|
||||
When debugging is enabled, each execution receives a deterministic reference
|
||||
derived from the comparison identity, ordered profile position, and safe
|
||||
profile slug. This keeps concurrent captures separate. The debug writer itself
|
||||
owns secure-root validation and file permissions. It safely creates shared
|
||||
missing ancestors during concurrent writes, then rejects symlink and non-
|
||||
directory components. Operational retention and sensitivity are documented in
|
||||
the [operations guide](../operations.md). This secure writer is enabled only on
|
||||
Unix hosts; comparison fails before execution when another host requests debug
|
||||
capture.
|
||||
|
||||
The output result and its safe errors are converted into the durable contract
|
||||
only by comparison publication. See [comparison publication
|
||||
internals](comparison-publication.md) and the external [comparison bundle
|
||||
contract](../integrations/comparison-bundle.md).
|
||||
47
docs/internal/comparison-publication.md
Normal file
47
docs/internal/comparison-publication.md
Normal file
@@ -0,0 +1,47 @@
|
||||
# Comparison Publication Internals
|
||||
|
||||
`internal/comparison` separates the logical bundle from filesystem mechanics.
|
||||
The application builds a validated manifest, exact shared data-package bytes,
|
||||
and only the Markdown files for successful profiles. The durable layout,
|
||||
schema, and compatibility rules are owned by the [comparison bundle
|
||||
contract](../integrations/comparison-bundle.md).
|
||||
|
||||
Recognition first token-validates the manifest's object fields, rejecting
|
||||
unknown, case-variant, and duplicate names before decoding its typed schema.
|
||||
Manifest validation derives each successful report filename from its ordered
|
||||
position, total profile count, and logical profile ID; logical-bundle and
|
||||
filesystem validation then require that exact path and file set.
|
||||
|
||||
Destination planning is read-only. It requires an exact absolute target that
|
||||
is neither the filesystem root nor the working directory, rejects unsafe
|
||||
symlinks and non-directories, accepts a missing or empty directory, and permits
|
||||
replacement only for a recognized current bundle. Publication rechecks the
|
||||
destination namespace and type immediately before it writes a private sibling
|
||||
staging directory. For replacement, it moves the prior bundle to a private
|
||||
sibling backup, fully reauthorizes that moved entry, checks for cancellation,
|
||||
and restores it if cancellation or installing the new bundle prevents
|
||||
replacement. If guarded restoration fails, the error retains the prior bundle's
|
||||
recovery path.
|
||||
|
||||
Planning also validates the final component and the bounded fixed names used
|
||||
for private staging and backup siblings. A destination that cannot form those
|
||||
names is rejected before publication creates a missing parent directory; a
|
||||
maximum-length valid destination remains usable because transaction siblings do
|
||||
not incorporate its basename.
|
||||
|
||||
The new bundle is committed only after the staged directory has been installed
|
||||
at the target. From that point its artifact paths are authoritative: a failure
|
||||
to remove the retained sibling backup does not roll back the new bundle.
|
||||
After a cleanup failure, publication inspects the sibling without masking the
|
||||
original filesystem cause. Its inspectable cleanup result distinguishes a
|
||||
complete recognized recovery bundle, partial remnants, an absent sibling, or
|
||||
an uninspectable state. A recovery path is reported only when something
|
||||
remains; only a complete recognized bundle is suitable for rollback recovery.
|
||||
|
||||
The application preflights before prompt inspection and collection. Publication
|
||||
performs its transaction-boundary checks and final moved-destination
|
||||
authorization before installation. A cancellation or any failure before the
|
||||
commit leaves the prior destination untouched. Completed bundles include
|
||||
partial profile results; comparison publication never coordinates Distributor
|
||||
notification. Operator-facing lifecycle and cleanup are in the
|
||||
[operations guide](../operations.md).
|
||||
71
docs/internal/distributor-adapter.md
Normal file
71
docs/internal/distributor-adapter.md
Normal file
@@ -0,0 +1,71 @@
|
||||
# Distributor Adapter Internals
|
||||
|
||||
`internal/adapters/distributor` translates a local delivery request into the
|
||||
Distributor Go client's upload and status calls, then returns a local delivery
|
||||
result. The external API, authentication, and idempotency contract is owned by
|
||||
the [Distributor API guide](../integrations/distributor/api.md) and
|
||||
[Distributor bundle guide](../integrations/distributor/pkg-bundle.md).
|
||||
|
||||
## Client construction
|
||||
|
||||
`Client` holds the endpoint, the name of the environment variable containing
|
||||
the token, an optional timeout, and an injectable upstream-client factory.
|
||||
`New` validates its configuration before creating the adapter. For each upload,
|
||||
the adapter reads the token from the configured environment variable and builds
|
||||
the upstream client with that endpoint, token, and an HTTP client whose timeout
|
||||
matches the local positive timeout. Its transport reads at most 1 MiB from any
|
||||
Distributor response before the pinned client decodes it; an oversized response
|
||||
is a distinct local failure and does not trigger an extra upload attempt.
|
||||
|
||||
The upstream client is an implementation dependency, not a source of
|
||||
application configuration: retry ownership, pipeline selection, path
|
||||
templates, and report rendering are defined by
|
||||
[configuration](../config.md) and [application orchestration](app-orchestration.md).
|
||||
|
||||
## Upload translation
|
||||
|
||||
Before calling the dependency, `Upload` validates the endpoint and token
|
||||
configuration plus the local pipeline ID, bundle ID, idempotency key, and every
|
||||
file's source and bundle paths. It maps the request as follows:
|
||||
|
||||
| Local request | Distributor client value |
|
||||
| --- | --- |
|
||||
| Pipeline ID | Upload pipeline identifier |
|
||||
| Bundle ID | Bundle identifier |
|
||||
| Idempotency key | Upload idempotency key |
|
||||
| File source and bundle paths | Bundle file entries |
|
||||
| Creation timestamp | Bundle creation time |
|
||||
|
||||
The call inherits the caller's context and applies the configured positive
|
||||
timeout. The adapter does not read report files, construct bundle layouts, or
|
||||
persist notification artifacts.
|
||||
|
||||
## Status and errors
|
||||
|
||||
An accepted upload is followed by one status request. When a timeout is
|
||||
configured, a nonterminal result is polled until `succeeded` or `failed`, or
|
||||
until the context ends. The translated `UploadResult` contains the run ID,
|
||||
status, and `RunStatus`, including pipeline ID and lifecycle timestamps.
|
||||
Remote response bodies, status reports, and remote error text are not retained
|
||||
in normal results. HTTP failures retain a local typed status-code and
|
||||
retryability classification; conflicts retain the local idempotency-conflict
|
||||
type.
|
||||
|
||||
Status lookup or polling errors are preserved in `UploadResult.StatusError` so
|
||||
the caller can report an accepted-but-unconfirmed delivery, using a bounded
|
||||
repository-owned diagnostic rather than remote text. A terminal failed run
|
||||
returns that result and an error. Upload failures return no result. Upstream
|
||||
idempotency conflicts become the local `IdempotencyConflictError`, which adds
|
||||
endpoint, pipeline, bundle, idempotency, and file-path context while redacting
|
||||
the token.
|
||||
|
||||
## Verification
|
||||
|
||||
Focused tests cover configuration validation, request mapping, response size
|
||||
boundaries, safe diagnostics, timeouts and polling, status translation, conflict
|
||||
handling, and token redaction. A local HTTP server exercises the production
|
||||
upload and status boundary:
|
||||
|
||||
```sh
|
||||
go test ./internal/adapters/distributor
|
||||
```
|
||||
71
docs/internal/facts.md
Normal file
71
docs/internal/facts.md
Normal file
@@ -0,0 +1,71 @@
|
||||
# Fact Contracts Internals
|
||||
|
||||
`internal/facts` is the deterministic boundary between a collected weather
|
||||
bundle and report-scoped facts. It preserves normalized source values and then
|
||||
selects and summarizes the values needed for one resolved report. Provider
|
||||
transport and normalized bundle semantics belong to
|
||||
[weather-data internals](weather-data.md); report identity and valid-period
|
||||
selection belong to [report registry internals](report-registry.md).
|
||||
|
||||
## Collected facts
|
||||
|
||||
`BuildCollected` projects a `weatherdata.Bundle` into `CollectedFacts`. It
|
||||
retains the fetched timestamp and every normalized product: observations,
|
||||
current conditions, hourly, narrative, alerts, discussion, daily, weather
|
||||
story, and convective outlook data. Source provenance and warnings are copied
|
||||
into their own slices so downstream consumers can inspect data completeness
|
||||
without treating it as an ordinary weather fact.
|
||||
|
||||
Alert facts retain individual alert payloads for period selection together with
|
||||
their copied source provenance; they do not retain a provider response envelope.
|
||||
|
||||
A nil bundle produces an empty collected value. Collection itself, missing
|
||||
source policy, and source hashes are outside this package.
|
||||
|
||||
## Report-scoped derivation
|
||||
|
||||
`BuildDerived` requires a valid resolved period and a valid report timezone. It
|
||||
uses half-open period overlap to select hourly, narrative, daily, and alert
|
||||
data; it also derives precipitation timing. Convective outlooks are retained
|
||||
only when their valid interval overlaps the report period, with discussions
|
||||
kept for represented outlook days. Both collections are sorted deterministically.
|
||||
It rejects collected hourly data with a precipitation probability outside the
|
||||
finite 0 through 100 percentage domain before constructing derived facts.
|
||||
|
||||
Report identity controls the summary shape:
|
||||
|
||||
| Report family | Derived summary |
|
||||
| --- | --- |
|
||||
| Hourly | Rolling-period selections and precipitation timing; no daily or daypart summary |
|
||||
| Daily, Today, Tomorrow | One local civil-day summary and its dayparts |
|
||||
|
||||
`DaypartSummaries` is collected from the resulting daily summaries.
|
||||
The detailed grouping, daypart-window, and alert rules are owned by
|
||||
[forecast derivation](forecast-derivation.md).
|
||||
Daily alert overlaps remain scoped to the civil day, while overnight daypart
|
||||
summaries retain alerts that overlap their complete next-day window.
|
||||
|
||||
## Missing data and failures
|
||||
|
||||
Optional normalized products remain nil or yield empty selections; the package
|
||||
does not create substitute values. A present convective-outlook run with no
|
||||
matching outlooks produces non-nil empty outlook and discussion slices, while
|
||||
a missing run produces nil slices.
|
||||
|
||||
Derivation fails for an invalid report period, invalid timezone, unsupported
|
||||
report ID, or when a requested daily summary has no hourly forecast data.
|
||||
Invalid daypart definitions surface from forecast derivation. The package does
|
||||
not access the CLI, filesystem, subprocesses, or network.
|
||||
|
||||
## Verification and invariants
|
||||
|
||||
Focused tests cover collected-fact separation, report-period selection,
|
||||
hourly behavior, daily summaries, and convective outlook selection:
|
||||
|
||||
```sh
|
||||
go test ./internal/facts
|
||||
```
|
||||
|
||||
Facts are derived once for a resolved report from already collected data.
|
||||
They remain reusable structured values for prompt input and template
|
||||
presentation, which are owned elsewhere.
|
||||
47
docs/internal/forecast-derivation.md
Normal file
47
docs/internal/forecast-derivation.md
Normal file
@@ -0,0 +1,47 @@
|
||||
# Forecast Derivation Internals
|
||||
|
||||
`internal/forecast` deterministically selects and summarizes normalized
|
||||
forecast data. It has no transport, filesystem, CLI, subprocess, or report
|
||||
registry dependency. The report-scoped caller is [fact
|
||||
contracts](facts.md), which owns the choice of data required by each report.
|
||||
|
||||
## Daily Derivation
|
||||
|
||||
`BuildDailySummary` builds one summary for one local civil day. The facts
|
||||
layer calls it for Daily, Today, and Tomorrow reports; it does not provide a
|
||||
multi-day or arbitrary-period summary constructor. `timeutil.Period` supplies
|
||||
the shared half-open overlap rule used while selecting source values.
|
||||
|
||||
`ResolveDayparts` turns configured local clock ranges into windows. A range
|
||||
whose end is not after its start continues into the next civil day. The
|
||||
available daypart and timezone settings are defined in the
|
||||
[configuration reference](../config.md).
|
||||
|
||||
The summary keeps selected hourly and narrative values, the discussion,
|
||||
source warnings and provenance, alert overlaps, and one summary for each
|
||||
resolved daypart. Daypart summaries derive their measurements, conditions,
|
||||
weather indicators, and precipitation timing from normalized forecast
|
||||
periods. `BuildPrecipTiming` is also available to the facts layer for a
|
||||
report's selected hourly periods.
|
||||
|
||||
## Boundaries And Failures
|
||||
|
||||
Daily-summary construction requires a bundle with hourly forecast data,
|
||||
valid precipitation probabilities, and valid daypart definitions. Optional
|
||||
normalized products remain absent when unavailable. Invalid alerts are ignored
|
||||
while valid overlaps are selected for the relevant day or daypart window.
|
||||
|
||||
Thresholds, text classification, unit normalization, and alert selection are
|
||||
package implementation rules. Report identity, period selection, and the
|
||||
resulting derived-fact shape are owned by [fact contracts](facts.md); external
|
||||
source semantics are owned by [weather-data internals](weather-data.md).
|
||||
|
||||
## Verification
|
||||
|
||||
Focused `internal/forecast` tests exercise daily and overnight dayparts,
|
||||
summary derivation, invalid precipitation data, precipitation timing, and
|
||||
alert overlap handling. `internal/facts` tests cover the report-scoped caller:
|
||||
|
||||
```sh
|
||||
go test ./internal/forecast ./internal/facts
|
||||
```
|
||||
76
docs/internal/generatedtext.md
Normal file
76
docs/internal/generatedtext.md
Normal file
@@ -0,0 +1,76 @@
|
||||
# Generated Text Internals
|
||||
|
||||
`internal/generatedtext` validates the structured prose produced for generated-
|
||||
text reports and turns validated prose plus rich module values into typed render
|
||||
contexts. It owns the catalog that pairs a generated-text report definition
|
||||
with its validator, schema ID, template ID, and context builder. The complete
|
||||
maintainer-facing context fields belong to [report templates](../templates.md).
|
||||
|
||||
## Catalog and validation
|
||||
|
||||
The Daily, Today, Tomorrow, and Hourly report definitions each use structured
|
||||
generated text. `LookupDefinition` requires the exact report, schema, and
|
||||
template triple and rejects unknown IDs, unsupported pairs, and a pair that
|
||||
belongs to another report before the run begins. A handler validates and
|
||||
normalizes raw JSON into a typed value, loads its canonical schema through
|
||||
`internal/promptassets`, builds a render context, and renders through
|
||||
`internal/reporttemplate`.
|
||||
|
||||
Daily, Today, and Tomorrow use a day-style value with required trimmed summary
|
||||
and one or more nonblank discussion paragraphs. Hourly requires trimmed summary
|
||||
and a single trimmed discussion string. Every form also requires the
|
||||
`precipitation_timing` field; an empty string means there is no supported timing
|
||||
prose to render. Typed decoding requires the exact lowercase JSON field names,
|
||||
rejects missing, duplicate, case-variant, and unknown fields, and checks field
|
||||
shapes; no general-purpose JSON Schema engine is used at runtime.
|
||||
|
||||
The validator accepts at most 64 KiB of raw JSON before it allocates typed
|
||||
values. Its JSON Schemas and typed checks limit `summary` and
|
||||
`precipitation_timing` to 4,000 characters each. Hourly
|
||||
`forecast_discussion` is limited to 12,000 characters. Day-style discussion
|
||||
accepts at most 12 paragraphs of at most 4,000 characters each. Across all
|
||||
prose fields, one report may contain at most 20,000 characters. These bounds
|
||||
apply before trimming, filtering, normalization, and template rendering.
|
||||
|
||||
Malformed JSON and field values return short, content-safe errors. They name
|
||||
only canonical fields where useful and never echo provider values or unknown
|
||||
field names. The Promptkit adapter also drops an oversized provider result
|
||||
before copying it into execution or debug state; direct executor implementations
|
||||
receive the same enforcement in this package.
|
||||
|
||||
## Render contexts
|
||||
|
||||
The catalog's report-specific builders receive the prepared report identity, a
|
||||
rich module snapshot, derived facts needed to order dayparts, and the matching
|
||||
validated generated text. They require the identity's report ID to match the
|
||||
selected builder. When the optional metadata stanza is present, every shared
|
||||
identity field must agree with that prepared authority before context
|
||||
construction continues. Builders then decode the module stanzas needed by the
|
||||
template and build typed Daily, Today, Tomorrow, or Hourly contexts. Contexts
|
||||
expose only display-ready report values, generated prose, and module values;
|
||||
they do not expose complete collected or derived fact bundles. Ordered slices
|
||||
remain the template iteration surface rather than maps.
|
||||
|
||||
Optional source stanzas become nil or fallback context fields. Today also
|
||||
computes whether its ordered dayparts contain a displayable condition so the
|
||||
template can render either rows or its explicit no-details fallback. Missing
|
||||
required stanzas, type-decoding failures, conflicting identity values, invalid
|
||||
metadata, or a generated-text type that does not match the chosen handler fail
|
||||
before template execution. Prompt packages, raw Promptkit output handling, and
|
||||
template asset lookup remain outside this package.
|
||||
|
||||
## Verification and invariants
|
||||
|
||||
Focused tests cover the catalog, each report-specific validator, normalization,
|
||||
schema/template mismatches, context construction, optional modules, and typed
|
||||
stanza errors:
|
||||
|
||||
```sh
|
||||
go test ./internal/generatedtext
|
||||
```
|
||||
|
||||
Generated text supplies prose slots only; deterministic weather facts remain in
|
||||
module and fact values. The renderer applies its plain-text policy to every
|
||||
generated prose insertion, preserving ordinary text and paragraph breaks while
|
||||
preventing provider text from creating Markdown or HTML structure. Every report
|
||||
definition must resolve to exactly one supported catalog pair.
|
||||
67
docs/internal/module.md
Normal file
67
docs/internal/module.md
Normal file
@@ -0,0 +1,67 @@
|
||||
# Module Contract Internals
|
||||
|
||||
`internal/module` defines the envelope between report composition,
|
||||
module builders, in-memory snapshots, templates, and prompt packages. It
|
||||
does not define a report, execute a builder, or choose prompt-export policy;
|
||||
those responsibilities belong to [report registry](report-registry.md) and
|
||||
[briefing](briefing.md).
|
||||
|
||||
## Outputs and snapshots
|
||||
|
||||
Each `Output` has a module ID, stanza name, rich `Value`, and runtime-only
|
||||
`PromptValue`. `DataPackageValue` returns the prompt value when present and
|
||||
otherwise the rich value. This permits custom prompt exports without shrinking
|
||||
the template value.
|
||||
|
||||
`NewSnapshot` builds and validates the ordered in-memory snapshot. Its JSON
|
||||
representation carries a package-owned schema marker, IDs, stanza names, and rich values only;
|
||||
`PromptValue` is deliberately excluded. `StanzaValue` decodes a named rich
|
||||
stanza into a caller-supplied type, reporting a missing stanza separately from
|
||||
a decoding error.
|
||||
|
||||
Snapshots reject missing schema versions, empty IDs or stanza names, and
|
||||
duplicate IDs or stanza names. Output order is caller-owned and preserved.
|
||||
|
||||
## Registered IDs and default composition
|
||||
|
||||
The registered IDs are `metadata`, `current_conditions`,
|
||||
`narrative_forecast`, `hourly_forecast`, `derived_daily_summary`,
|
||||
`derived_daypart_summaries`, `precip_timing`, `alert_digest`,
|
||||
`spc_convective_outlooks`, `area_forecast_discussion`,
|
||||
`spc_convective_discussion`, `weather_story`, `outdoor_windows`,
|
||||
`today_planning`, `tomorrow_planning`, and `daily_planning`.
|
||||
|
||||
The registry declares these ordered default compositions:
|
||||
|
||||
| Report | Ordered modules |
|
||||
| --- | --- |
|
||||
| Daily | metadata, current conditions, narrative forecast, daily summary, daypart summaries, precipitation timing, alert digest, SPC outlooks, AFD (long term), SPC discussion, weather story, outdoor windows, daily planning, hourly forecast |
|
||||
| Today | metadata, current conditions, narrative forecast, daily summary, daypart summaries, precipitation timing, alert digest, SPC outlooks, AFD, SPC discussion, weather story, outdoor windows, hourly forecast, today planning |
|
||||
| Tomorrow | metadata, current conditions, narrative forecast, daily summary, daypart summaries, precipitation timing, alert digest, SPC outlooks, AFD, SPC discussion, weather story, outdoor windows, tomorrow planning, hourly forecast |
|
||||
| Hourly | metadata, current conditions, hourly forecast, precipitation timing, alert digest, SPC outlooks, AFD (key messages and short term), SPC discussion, weather story |
|
||||
|
||||
The only non-empty default option is the AFD section selection. It accepts a
|
||||
`sections` list; omitted or empty selects all available sections. Report
|
||||
definitions may narrow it as shown above. Option shape and report compatibility
|
||||
are validated by the briefing registry. Accepted typed option pointers are
|
||||
canonicalized to the declared value type before a module builder receives them.
|
||||
|
||||
## Rich and prompt-facing values
|
||||
|
||||
Rich values remain available to module snapshots and render contexts.
|
||||
Briefing attaches custom prompt exports only for current conditions, hourly
|
||||
forecast, and derived daypart summaries; all other current builders use
|
||||
pass-through values. The prompt package owns how exported stanzas are grouped
|
||||
and serialized; see [prompt input](prompt-input.md).
|
||||
|
||||
## Verification and invariants
|
||||
|
||||
Focused tests cover snapshot validation and order, typed stanza lookup, and
|
||||
prompt-value fallback:
|
||||
|
||||
```sh
|
||||
go test ./internal/module
|
||||
```
|
||||
|
||||
Module IDs and stanza names are stable, every emitted output has one of each,
|
||||
and this package never imports the report registry.
|
||||
37
docs/internal/prepared-report.md
Normal file
37
docs/internal/prepared-report.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# Prepared Report Internals
|
||||
|
||||
`internal/app` validates the report's generated-text catalog binding during
|
||||
prompt inspection, before collection, and carries the resulting handler into
|
||||
`preparedReport` construction after collection. This is the immutable boundary
|
||||
shared by ordinary report generation and profile comparison; it is not a
|
||||
durable artifact.
|
||||
|
||||
Preparation first establishes one `PreparedIdentity` for the report run, report
|
||||
and prompt IDs, variant, generation time, units, timezone, valid period,
|
||||
location, and source warnings. It passes that identity to the configured module
|
||||
snapshot, curated prompt-input package, serialized YAML, generated-text render
|
||||
context, and generated-text definition. Each boundary projects only the fields
|
||||
it needs from that prepared authority.
|
||||
|
||||
Preparation deep-copies mutable facts, snapshots, identity, and data-package
|
||||
bytes before returning them. Consumers receive independent copies so one
|
||||
execution cannot change another's input or rendering context.
|
||||
|
||||
Before accepting generated JSON, the execution boundary reconciles the prepared
|
||||
report definition, inspected prompt hash and selected profile identity, the one
|
||||
preparation callback, and the completed Promptkit result. The callback and
|
||||
completion must agree on prompt, profile, backend, model, and rendered/input
|
||||
hashes; the callback output and completed validation must name the prepared
|
||||
report's JSON Schema. A mismatch produces no rendered Markdown and leaves
|
||||
results with only the inspected safe identity.
|
||||
|
||||
Single-report generation executes one prepared profile and publishes its
|
||||
Markdown. Comparison prepares once, gives every selected profile the same YAML
|
||||
bytes, and only then assembles the resulting logical bundle. The prompt-input
|
||||
shape is owned by [prompt-input internals](prompt-input.md); profile execution
|
||||
semantics are owned by [Promptkit integration](../integrations/promptkit.md).
|
||||
|
||||
Catalog incompatibility stops prompt inspection before weather collection or
|
||||
model work. Preparation failure has no publication side effects. Tests for this
|
||||
boundary cover catalog-preflight ordering, mutation isolation, byte equality,
|
||||
and reuse by both execution paths.
|
||||
36
docs/internal/prompt-input.md
Normal file
36
docs/internal/prompt-input.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Prompt Input Internals
|
||||
|
||||
`internal/promptinput` turns prepared report metadata and an ordered module
|
||||
snapshot into the YAML data package passed to Promptkit. The externally visible
|
||||
prompt and inline-input contract is owned by the [Promptkit integration
|
||||
guide](../integrations/promptkit.md); preparation of the inputs is owned by
|
||||
[prepared report internals](prepared-report.md).
|
||||
|
||||
## Package Construction
|
||||
|
||||
`Build` projects report identity, the report-local current date, source-warning
|
||||
summaries, and each snapshot output's prompt-facing value into a package. It
|
||||
does not expose source transport or provenance details. The module snapshot
|
||||
defines stanza order and selects curated prompt values; the corresponding
|
||||
module contracts are documented in [module internals](module.md) and [briefing
|
||||
internals](briefing.md).
|
||||
|
||||
`MarshalYAML` validates the package before serializing it. Serialization emits
|
||||
the metadata stanza first, then groups the remaining recognized stanzas in the
|
||||
package's fixed category order while preserving snapshot order within a
|
||||
category. `Validate` enforces the supported schema version, required report
|
||||
identity and period values, and a nonempty, complete ordered briefing.
|
||||
|
||||
This package does not collect weather, choose an output destination, execute a
|
||||
provider, or persist data packages. The application passes its in-memory YAML
|
||||
to the Promptkit adapter as part of prepared report execution.
|
||||
|
||||
## Verification
|
||||
|
||||
Focused tests cover package construction, report-local dates, validation,
|
||||
curated snapshot exports, deterministic YAML grouping, and safe source-warning
|
||||
projection:
|
||||
|
||||
```sh
|
||||
go test ./internal/promptinput
|
||||
```
|
||||
17
docs/internal/promptkit-adapter.md
Normal file
17
docs/internal/promptkit-adapter.md
Normal file
@@ -0,0 +1,17 @@
|
||||
# Promptkit Adapter Internals
|
||||
|
||||
`internal/adapters/promptkit` maps Weatherreporter's project-owned executor contract to Promptkit. The CLI maps `promptkit` configuration to a `PromptExecutorConfig` and constructs one executor per action. Promptkit dependency types do not escape the adapter.
|
||||
|
||||
The adapter supplies Weatherreporter's embedded prompt, schema, and fallback profile filesystems to each engine. Promptkit resolves configured operator profile sources, the embedded fallback catalog, and its built-in catalog; the adapter does not parse profile YAML, merge sources, or probe endpoints.
|
||||
|
||||
The adapter exposes exact prompt and profile validation plus prepared execution. It maps safe prompt identity, logical profile, effective backend/model, preparation, execution, validation, and optional debug values into `promptexec`. `Execute` passes the YAML package as an inline Promptkit input; it does not construct a filesystem URI or write a package file.
|
||||
|
||||
The application uses the preparation callback to record active safe provenance in memory and optionally writes content-rich diagnostics only through an explicit debug writer. The adapter returns raw output for application validation and rendering. It does not retain application state, render Markdown, choose report definitions, or send Distributor notifications.
|
||||
|
||||
Focused tests:
|
||||
|
||||
```sh
|
||||
go test ./internal/adapters/promptkit ./internal/cli ./internal/app
|
||||
```
|
||||
|
||||
The public logical prompt/profile/schema contract is owned by the [Promptkit integration guide](../integrations/promptkit.md).
|
||||
38
docs/internal/report-registry.md
Normal file
38
docs/internal/report-registry.md
Normal file
@@ -0,0 +1,38 @@
|
||||
# Report Registry Internals
|
||||
|
||||
`internal/report` owns the in-process registry of report identities and the
|
||||
resolution of a report's valid period. Command names and configuration aliases
|
||||
belong to the [CLI reference](../cli.md) and [configuration
|
||||
reference](../config.md), respectively.
|
||||
|
||||
## Registry And Resolution
|
||||
|
||||
`DefaultRegistry` supplies the maintained definitions. `Lookup` returns a
|
||||
definition by its internal ID, while `Resolve` combines it with a request time,
|
||||
location, and optional date to produce `Resolved`. The result carries the
|
||||
definition, generation time, timezone, and resolved valid period; its metadata
|
||||
and output-name helpers keep derived identity values consistent for callers.
|
||||
|
||||
Definitions carry the internal collaborators needed downstream: prompt and
|
||||
template identity, module configuration, output naming, Distributor path
|
||||
templates, and fixed batch eligibility. The external prompt contract is owned
|
||||
by the [Promptkit integration guide](../integrations/promptkit.md), template
|
||||
surface by the [report template guide](../templates.md), and published
|
||||
Distributor paths by the [Distributor bundle guide](../integrations/distributor/pkg-bundle.md).
|
||||
|
||||
`WithModuleOverrides` returns an independently cloned registry with replacement
|
||||
module configuration for recognized report IDs. The application owns batch
|
||||
planning and data-dependent inclusion; see [app orchestration
|
||||
internals](app-orchestration.md).
|
||||
|
||||
The registry never collects weather data, parses CLI flags, writes output,
|
||||
executes Promptkit, or delivers a report.
|
||||
|
||||
## Verification
|
||||
|
||||
Focused tests protect retained report definitions, period resolution, Daily
|
||||
run-ID disambiguation, and rejection of retired command or configuration names:
|
||||
|
||||
```sh
|
||||
go test ./internal/report
|
||||
```
|
||||
56
docs/internal/reporttemplate.md
Normal file
56
docs/internal/reporttemplate.md
Normal file
@@ -0,0 +1,56 @@
|
||||
# Report Template Internals
|
||||
|
||||
`internal/reporttemplate` embeds and renders the repository's native Markdown
|
||||
templates. The current template IDs are `daily`, `today`, `tomorrow`, and
|
||||
`hourly`. The template files, partials, and complete render-context field
|
||||
reference are maintained in
|
||||
[report templates](../templates.md).
|
||||
|
||||
## Assets and lookup
|
||||
|
||||
The package embeds top-level templates and shared partials. `Template` returns
|
||||
the requested embedded template and fails with the requested ID when it is
|
||||
unknown or unreadable.
|
||||
|
||||
Generated-text schemas and Promptkit definitions are owned by
|
||||
`internal/promptassets`; report-template owns Markdown source only. Report
|
||||
definitions select IDs, while [generated-text internals](generatedtext.md)
|
||||
verifies the supported schema/template pairing.
|
||||
|
||||
## Rendering
|
||||
|
||||
`Render` loads the top-level template, creates a `text/template` with helper
|
||||
functions and `missingkey=error`, parses the template, parses every shared
|
||||
partial, and executes the result against the typed render context. This makes
|
||||
missing context fields, bad template syntax, unreadable partials, and execution
|
||||
failures actionable with template or partial context.
|
||||
|
||||
Top-level templates decide which shared partials they invoke. The current
|
||||
partials cover daypart forecast variants, alert digest, and precipitation
|
||||
timing. Template code receives curated typed contexts rather than raw data
|
||||
packages or complete fact bundles, and it must not reimplement weather
|
||||
selection or generated-text validation. Context construction rejects
|
||||
report-identity disagreements before template execution. Every generated-prose
|
||||
insertion uses the `plainText` helper. It retains ordinary prose and paragraph
|
||||
breaks but renders Markdown/HTML syntax, code indentation, and control
|
||||
characters as safe text, so the repository templates remain the sole owners of
|
||||
report structure.
|
||||
|
||||
## Boundaries and verification
|
||||
|
||||
This package does not collect weather data, build modules, validate generated
|
||||
text, construct contexts, resolve report definitions, write state, execute
|
||||
Promptkit, or upload reports. It produces Markdown bytes for application
|
||||
orchestration to persist.
|
||||
|
||||
Focused tests cover template lookup, rendering, partial behavior, daypart
|
||||
fallbacks, missing keys, and malformed context:
|
||||
|
||||
```sh
|
||||
go test ./internal/reporttemplate
|
||||
```
|
||||
|
||||
Embedded templates stay as separate files and shared fragments stay under the
|
||||
partial directory. Generated-text schemas are embedded separately by
|
||||
`internal/promptassets` and describe prose slots rather than deterministic
|
||||
weather facts.
|
||||
76
docs/internal/weather-data.md
Normal file
76
docs/internal/weather-data.md
Normal file
@@ -0,0 +1,76 @@
|
||||
# Weather Data Internals
|
||||
|
||||
`internal/weatherdata` owns the normalized, wire-independent weather bundle
|
||||
that passes from collection through rendering. The Weather API
|
||||
adapter translates provider responses into these types; its request, response,
|
||||
and availability contract is documented in the
|
||||
[Weather API integration guide](../integrations/weatherapi.md).
|
||||
|
||||
## Bundle contract
|
||||
|
||||
`Bundle` has a collection timestamp (`FetchedAt`), source provenance
|
||||
(`Sources`), and collection-level warnings (`Warnings`). Its product fields are
|
||||
optional so an allowed missing source can be represented without manufacturing
|
||||
weather data.
|
||||
|
||||
| Field | Normalized product |
|
||||
| --- | --- |
|
||||
| `Observation` | Station observation |
|
||||
| `Current` | Current conditions |
|
||||
| `Hourly` | Hourly forecast periods |
|
||||
| `Narrative` | Narrative forecast |
|
||||
| `Alerts` | Active-alert check, including an explicitly empty result |
|
||||
| `Discussion` | Forecast discussion and its time-range sections |
|
||||
| `Daily` | Daily forecast periods when supplied |
|
||||
| `WeatherStory` | Latest weather story |
|
||||
| `SPCConvectiveOutlooks` | Convective outlook run, discussions, and GeoJSON geometry |
|
||||
|
||||
The bundle carries values rather than provider request details. Consumers use
|
||||
it to construct report facts and data packages; they should not infer a
|
||||
provider endpoint or retry policy from the normalized types. See
|
||||
[collection](collect.md) for assembly and
|
||||
[report templates](../templates.md) for the values exposed to authors.
|
||||
|
||||
An alert run retains its check time and individual alert payloads for overlap
|
||||
selection. Its source entry retains provider provenance; the full provider
|
||||
envelope is not carried into the normalized bundle.
|
||||
|
||||
## Source provenance
|
||||
|
||||
Every checked source is represented by a `Source` entry. The record identifies
|
||||
the source (`Name`), request location and query (`Endpoint`, `Query`), fetch
|
||||
time, provider issue and update times when available, a SHA-256 digest of the
|
||||
source data, and whether the source was unavailable (`Missing`). Its warnings
|
||||
stay with that source in addition to the bundle-level warning list.
|
||||
|
||||
An empty product can be meaningful checked data. For example, an explicit
|
||||
empty alerts result is not missing and retains its source hash. A source is
|
||||
marked missing only when the adapter's missing-source policy treats the
|
||||
response or parsing failure as unavailable. The policy itself belongs to the
|
||||
[configuration reference](../config.md).
|
||||
|
||||
Accepted hourly forecast periods always have nonzero start and end times, with
|
||||
the end after the start. Collection rejects a required hourly product that does
|
||||
not meet those bounds before it enters downstream derivation.
|
||||
|
||||
## Warning semantics
|
||||
|
||||
`SourceWarning` has a source name, stable code, severity, explanatory message,
|
||||
endpoint, and `CompletenessImpact`. When collection proceeds with a warning,
|
||||
the same warning appears in `Source.Warnings` and `Bundle.Warnings` so both
|
||||
local provenance and whole-run consumers see it. A policy that treats a missing
|
||||
source as an error returns no partial bundle.
|
||||
|
||||
Warnings describe data completeness, not rendering or delivery failures.
|
||||
Those failures are reported by [application orchestration](app-orchestration.md).
|
||||
|
||||
## Boundaries and verification
|
||||
|
||||
This package defines data shapes and has no HTTP client, configuration loader,
|
||||
filesystem access, or template behavior. Focused tests cover the normalized
|
||||
types and the Weather API adapter verifies translation into them:
|
||||
|
||||
```sh
|
||||
go test ./internal/weatherdata
|
||||
go test ./internal/adapters/weatherapi
|
||||
```
|
||||
227
docs/operations.md
Normal file
227
docs/operations.md
Normal file
@@ -0,0 +1,227 @@
|
||||
# Weatherreporter Operations
|
||||
|
||||
This guide covers normal output handling, Distributor notification, secure
|
||||
prompt diagnostics, and cleanup of legacy application state. See the [CLI
|
||||
reference](cli.md) for command syntax and the [configuration reference](config.md)
|
||||
for fields, defaults, and notification templates.
|
||||
|
||||
## Normal Operation
|
||||
|
||||
After configuring a Weather API endpoint, generate one report:
|
||||
|
||||
```sh
|
||||
weatherreporter generate today
|
||||
```
|
||||
|
||||
With no configured output directory, the command writes `today.md` in the
|
||||
current directory. Set `output.directory` to use one ordinary publication
|
||||
directory for reports, or choose a one-command operator-owned file with
|
||||
`--out`; a relative path is resolved from the current directory and an absolute
|
||||
path is used directly. The explicit flag takes precedence over the configured
|
||||
directory. Weatherreporter renders in memory and atomically replaces the
|
||||
selected destination only after generation and rendering succeed. It does not
|
||||
create a default workspace, metadata, receipts, or intermediate output files.
|
||||
|
||||
A missing configured directory is created only as part of successful report
|
||||
publication. If its existing path is not a directory or cannot be inspected,
|
||||
the command stops before prompt inspection or weather collection, leaving any
|
||||
existing report unchanged. See the [configuration reference](config.md) for the
|
||||
field definition and validation rules.
|
||||
|
||||
Before a destination is published, provider, validation, rendering, write, and
|
||||
cancellation failures leave an existing report unchanged. A notification
|
||||
failure happens after publication, so retain and use the completed Markdown
|
||||
file while resolving the delivery error. The JSON result identifies the
|
||||
absolute output path and active profile, backend, model, warnings, validation,
|
||||
debug, and notification information; see the [CLI reference](cli.md) for its
|
||||
exact fields.
|
||||
|
||||
Weatherreporter validates the final output filename before prompt inspection or
|
||||
weather collection. A valid long filename is published through a short,
|
||||
same-directory temporary sibling, so temporary naming does not shorten the
|
||||
operator-selected destination. A rejected filename does not create a missing
|
||||
parent directory. The final destination itself must be absent or a regular
|
||||
file: symlinks, directories, named pipes, sockets, and other special objects
|
||||
are rejected before prompt inspection or weather collection. The destination is
|
||||
checked again immediately before the atomic replacement; cancellation or a
|
||||
deadline at that point leaves the prior report unchanged and skips notification.
|
||||
|
||||
`SIGINT` and `SIGTERM` request orderly cancellation of an active action. The
|
||||
command lets cancellation and related cleanup finish before it exits; use the
|
||||
usual failed result or error to determine whether an output was published.
|
||||
|
||||
## Batch Outputs And Distributor Notification
|
||||
|
||||
Run a scheduled batch with an explicit output directory when appropriate:
|
||||
|
||||
```sh
|
||||
weatherreporter run morning --out-dir ./reports
|
||||
```
|
||||
|
||||
Without `--out-dir`, batch reports are written beneath `output.directory` when
|
||||
configured, otherwise the current directory. The explicit directory applies
|
||||
only to that command and takes precedence over the configured fallback.
|
||||
Morning runs Today, Tomorrow, and every eligible dated Daily Report; evening
|
||||
runs Tomorrow and the same eligible Daily Reports. Eligible Daily dates begin
|
||||
after tomorrow and require complete hourly coverage for their local civil day.
|
||||
A batch collects once, determines the complete report set, and validates every
|
||||
final output destination before executing its first report prompt. A destination
|
||||
collision, such as a directory named `tomorrow.md`, stops the batch before any
|
||||
report output is created or replaced. After successful validation, each selected
|
||||
report processes independently and successful outputs remain available if
|
||||
another report fails. If cancellation or a deadline is observed during the
|
||||
sequence, Weatherreporter stops before starting another report. It retains
|
||||
already published files, marks interrupted and unstarted reports as canceled in
|
||||
the result, and skips batch notification.
|
||||
|
||||
When `notify.distributor.enabled` and batch notification are enabled,
|
||||
Weatherreporter sends one Distributor upload only after every selected output
|
||||
exists. If an item fails, the batch notification is skipped and successful
|
||||
files remain at their selected destinations. A batch notification failure also
|
||||
leaves all successfully published report files in place. Distributor source
|
||||
files are those operator-owned Markdown outputs; rendered bundle paths and
|
||||
delivery status appear in the result, not in a local notification receipt.
|
||||
Remote Distributor response text is not included in command output. Instead,
|
||||
notification failures use stable local diagnostics while retaining the upload
|
||||
and status identities needed to investigate delivery with Distributor.
|
||||
Report counters count report items only. A batch notification failure therefore
|
||||
returns a failed batch status even when all report counters show success; the
|
||||
top-level notification result contains the delivery diagnostic.
|
||||
|
||||
For a single report, Distributor notification follows the atomic output write.
|
||||
Enabled notification configuration, including the HTTP(S) endpoint and
|
||||
templates, is validated before report processing. A malformed endpoint does not
|
||||
collect weather data, generate a report, publish output, or invoke Distributor.
|
||||
See the [configuration reference](config.md) for endpoint, pipeline, bundle,
|
||||
idempotency-key, and per-report path templates.
|
||||
|
||||
## Comparison Bundles
|
||||
|
||||
Use `compare` when an operator needs to evaluate explicit Promptkit profiles
|
||||
against the same report input. The command writes one flat, operator-owned
|
||||
bundle directory and never sends a Distributor notification. Command syntax,
|
||||
profile validation, JSON output, and exit behavior belong to the
|
||||
[CLI reference](cli.md); the durable file contract belongs to the
|
||||
[comparison bundle contract](integrations/comparison-bundle.md).
|
||||
|
||||
The output destination follows the normal `output.directory` fallback. An
|
||||
explicit `--out-dir` takes precedence and names the exact bundle directory,
|
||||
not a parent to be combined with another name. The standard names are derived
|
||||
from the report output name, such as `comparison-today` and
|
||||
`comparison-daily-2026-05-29`; see the [configuration reference](config.md)
|
||||
for output-directory resolution.
|
||||
|
||||
A comparison bundle contains the shared data package, a manifest, and one
|
||||
Markdown file for every successful profile. Treat all of these files as
|
||||
potentially sensitive: the data package and generated reports can contain
|
||||
location or forecast context. Weatherreporter creates no application-owned
|
||||
history, retention store, or cleanup job. Retain, archive, or remove only the
|
||||
specific bundle directories your operating policy permits.
|
||||
|
||||
The destination is preflighted before prompt inspection and collection, then
|
||||
rechecked immediately before an atomic publish. A missing or empty directory
|
||||
is usable. A nonempty directory can be replaced only when `--replace` is given
|
||||
and it is recognized as a current Weatherreporter comparison bundle; ordinary
|
||||
directories, symlinks, and unsafe destinations are rejected. Cancellation and
|
||||
all failures before publication preserve an existing bundle, including a
|
||||
cancellation observed while a replacement is being prepared. If guarded
|
||||
restoration cannot complete, the error names the retained sibling bundle for
|
||||
manual recovery. Profile failures are different: the command publishes a
|
||||
complete partial bundle, with failed profiles represented in the manifest and
|
||||
no Markdown file for those profiles.
|
||||
Comparison preflight also checks that private publication siblings can be
|
||||
formed. An infeasible destination name is rejected before a missing parent
|
||||
directory is created.
|
||||
|
||||
## Local Prompt Profile Override
|
||||
|
||||
Hourly normally selects the embedded `weather-light` profile. To use a local
|
||||
OpenAI-compatible model without changing prompts or application code, copy
|
||||
[weather-light-local-profile.yml](../examples/weather-light-local-profile.yml),
|
||||
set its `endpoint` and `model` for the local server, and configure the copy as
|
||||
`promptkit.profile_file`. The profile file's `weather-light` definition
|
||||
completely replaces the embedded definition; it does not affect a report that
|
||||
selects another profile ID.
|
||||
|
||||
Prompt and profile validation occurs before weather collection. A malformed
|
||||
profile file, missing required credential, or unsupported selected backend
|
||||
stops the command before collection. A reachable profile can still fail later
|
||||
if its local model endpoint is unavailable; Weatherreporter does not switch to
|
||||
a remote profile.
|
||||
|
||||
## Optional Prompt Debug Capture
|
||||
|
||||
Use `--llm-debug-dir` only when content-rich prompt diagnostics are required:
|
||||
|
||||
```sh
|
||||
weatherreporter generate today --llm-debug-dir /var/tmp/weatherreporter-debug
|
||||
```
|
||||
|
||||
The directory must be absolute. Requested captures are written with restrictive
|
||||
permissions beneath the supplied directory, organized by report and run. They
|
||||
can contain rendered prompts and generated output, so limit access to trusted
|
||||
operators and remove the captures when they are no longer needed. Comparison
|
||||
captures additionally identify each selected profile so concurrent executions
|
||||
remain distinct. Normal output, summaries, and routine logs omit that sensitive
|
||||
content. Debug capture is never created for an ordinary command without
|
||||
`--llm-debug-dir`.
|
||||
|
||||
Secure prompt debug capture is currently available only on Unix hosts, where
|
||||
Weatherreporter can keep every traversal and write anchored to opened directory
|
||||
descriptors without following symbolic links. On other platforms, requesting
|
||||
`--llm-debug-dir` fails before prompt inspection, weather collection, or
|
||||
provider execution; ordinary commands without the flag remain available.
|
||||
|
||||
Preparation captures retain only the provider endpoint origin and reviewed
|
||||
execution settings. URL user information, paths, queries, fragments, and
|
||||
unrecognized provider parameters are omitted.
|
||||
|
||||
Capture writes are confined to the requested root and fail if an unsafe
|
||||
filesystem component prevents secure artifact creation.
|
||||
|
||||
If capture creation or writing fails, the affected run fails rather than
|
||||
silently continuing without the requested diagnostics.
|
||||
|
||||
## Diagnosing Failures
|
||||
|
||||
Start with the command error and JSON summary. For a report generation failure,
|
||||
the selected destination was not replaced; for a notification failure, inspect
|
||||
the completed destination and the notification result. For a batch failure,
|
||||
use the per-report statuses and retain successful output files. For a comparison
|
||||
failure, inspect the published manifest when its path is present: individual
|
||||
profile failures retain their safe result and successful Markdown files, while
|
||||
cancellation and pre-publication errors leave the prior destination unchanged.
|
||||
|
||||
If a replacement commits but cleanup of its prior sibling backup fails, the new
|
||||
bundle remains valid and its artifact paths appear in the failed command
|
||||
summary. The summary records a safe `publication_cleanup` error that indicates
|
||||
whether a complete prior bundle remains, only partial remnants remain, or no
|
||||
prior bundle remains; it also identifies when the sibling cannot be inspected.
|
||||
The returned command error includes a recovery path only when a sibling remains.
|
||||
Preserve a complete recognized recovery bundle until it has been inspected and
|
||||
cleaned up manually; partial remnants are not a rollback artifact. Do not
|
||||
remove the new bundle to retry cleanup.
|
||||
|
||||
Enable explicit debug capture only when content-rich Promptkit diagnostics are
|
||||
necessary.
|
||||
|
||||
Weatherreporter does not retain runs for later inspection, resume failed work,
|
||||
or provide automatic cleanup, archival, remote state, daemon operation, or
|
||||
automatic storm monitoring.
|
||||
|
||||
## Manual Cleanup Of Legacy Workspaces
|
||||
|
||||
Older installations may have a directory named `workspace` containing reports,
|
||||
snapshots, prompt inputs, or notification records from previous versions.
|
||||
Current commands neither read nor update it. After confirming that no separate
|
||||
retention requirement applies, remove that specific legacy directory manually;
|
||||
do not use a broad cleanup command that could remove current operator outputs.
|
||||
|
||||
For example, from the directory that contains the old directory:
|
||||
|
||||
```sh
|
||||
rm -rf ./workspace
|
||||
```
|
||||
|
||||
This removal cannot be recovered by Weatherreporter. Keep or archive any
|
||||
historical files that are still needed before deleting them.
|
||||
@@ -1,109 +1,99 @@
|
||||
# Architecture
|
||||
# Architecture Policy
|
||||
|
||||
This document defines the development principles for this Go project. It is inward-facing: developers and LLM coding agents should use it to preserve the project’s shape, boundaries, and invariants as the code evolves.
|
||||
## Purpose
|
||||
|
||||
## weatherreporter
|
||||
`weatherreporter` is a deterministic weather briefing and report-preparation application. It consumes normalized weather data from the internal weatherfeeder-backed API, derives report-specific briefing packages, compares those packages against prior snapshots, and invokes an external prompt runner to produce human-facing reports.
|
||||
This policy defines Weatherreporter's system shape, ownership, dependency direction,
|
||||
and safety invariants. The [development guide](../development.md) owns the
|
||||
package inventory; focused documents in `docs/internal/` own implementation detail.
|
||||
|
||||
The application should keep meteorological data selection, daypart grouping, threshold detection, forecast-period resolution, and recent-change comparison inside Go domain packages. LLM prompts should receive curated briefing packages rather than raw unbounded source payloads wherever practical.
|
||||
## System Shape
|
||||
|
||||
Report types must be defined through a registry or equivalent mechanism. Each report definition should declare its report ID, prompt ID, valid-period resolver, briefing builder, comparison strategy, and output naming behavior. Avoid scattering report-type conditionals across CLI and orchestration code.
|
||||
Weatherreporter is a deterministic weather-report CLI. It collects normalized
|
||||
weather data, derives facts and modules, builds a curated YAML data package,
|
||||
executes exact-version Promptkit prompts, validates structured generated prose,
|
||||
and renders repository-owned Markdown in memory. Completed Markdown is
|
||||
atomically published to an operator-owned output destination and may then be
|
||||
uploaded through Distributor.
|
||||
|
||||
Generated reports must be associated with explicit metadata, including report type, location, generation time, valid period, source product timestamps or hashes, briefing snapshot path, and output path. Recent Changes must be based on structured snapshot comparison rather than comparison of rendered Markdown report text.
|
||||
An explicit profile comparison prepares one report input once, executes the
|
||||
same exact prompt and data package across selected profiles concurrently, and
|
||||
atomically publishes one operator-owned comparison bundle. It remains local:
|
||||
it does not create application state or send a Distributor notification.
|
||||
|
||||
`scriptorium` is an external adapter, not domain logic. Subprocess execution must be isolated under `internal/adapters/scriptorium`, use context-aware execution, avoid shell interpolation, capture actionable stderr, and keep scriptorium-specific flags from leaking into domain packages.
|
||||
The supported report products are Daily, Today, Tomorrow, and Hourly. A batch
|
||||
collects once, validates its complete candidate prompt/profile set before
|
||||
collection, then determines and validates every planned output destination
|
||||
before executing reports sequentially with one executor. It continues after
|
||||
independent report failures and sends a batch notification only after every
|
||||
planned report succeeds.
|
||||
|
||||
## Project Shape
|
||||
## Ownership And Boundaries
|
||||
|
||||
Default to a small, explicit, dependency-light Go application. Keep the design modular enough to test and change safely, but do not add abstraction unless it protects a real boundary or enables a real extension point.
|
||||
- `internal/cli` owns command parsing, help, summaries, and one executor
|
||||
construction per action.
|
||||
- `internal/config` owns defaults, loading, validation, and secret loading.
|
||||
- `internal/app` owns in-memory workflow order, partial results, atomic output
|
||||
publication, and notification coordination through project-owned contracts.
|
||||
- `internal/comparison` owns comparison identity, durable logical bundle
|
||||
validation, safe destination recognition, and atomic bundle publication.
|
||||
- Deterministic domain packages own weather derivation, report periods, modules,
|
||||
generated-text validation, and template contexts.
|
||||
- `internal/adapters/weatherapi`, `internal/adapters/promptkit`, and
|
||||
`internal/adapters/distributor` own their external dependency mechanics.
|
||||
|
||||
Business/domain logic should live outside CLI, transport, and external-adapter packages.
|
||||
Dependency-specific Promptkit types remain inside its adapter. The application
|
||||
does not parse flags, construct provider clients, or render provider output
|
||||
directly.
|
||||
|
||||
## Dependency Policy
|
||||
## Prompt Execution Invariants
|
||||
|
||||
Prefer the Go standard library where practical.
|
||||
- Prompts receive curated module packages, never unbounded raw weather payloads.
|
||||
- Every execution validates the exact prompt version and output contract before
|
||||
collection. The selected profile is configured explicitly or declared by the
|
||||
prompt; unsupported direct-key profiles and missing reported credentials fail
|
||||
before collection.
|
||||
- Prompt and profile validation completes before weather collection. Raw output
|
||||
is validated before template rendering.
|
||||
- Comparison validates every explicit profile before collection, prepares one
|
||||
immutable report input, and delegates backend capacity to Promptkit rather
|
||||
than adding an application-wide execution limit.
|
||||
- Generated text fills defined prose slots only. Deterministic facts remain
|
||||
authoritative and repository-owned templates produce all Markdown output.
|
||||
- Sensitive rendered prompts, schemas, input bodies, provider endpoints, and
|
||||
credentials never enter normal summaries or logs. They are written only to
|
||||
an explicit secure debug root when requested.
|
||||
|
||||
Use external dependencies only when justified by correctness, security, interoperability, or substantial complexity reduction. Good reasons include complex security-sensitive behavior, such as HTML sanitization, or widely used de facto standards, such as YAML parsing.
|
||||
## Output, Notification, And Testing Invariants
|
||||
|
||||
Avoid dependencies for small conveniences. Do not let external dependency types leak across internal package boundaries unless the dependency is itself the explicit public contract of that package.
|
||||
- Normal execution is stateless: it keeps weather data, prompt input, generated
|
||||
text, and render context in memory and creates no application-owned durable
|
||||
state.
|
||||
- Markdown writes are atomic at an operator-selected destination. A
|
||||
pre-publication failure, including cancellation observed immediately before
|
||||
publication, does not replace an existing destination; a notification failure
|
||||
does not remove a newly published output.
|
||||
- A single-report final destination is either absent or a regular file.
|
||||
Symlinks and special filesystem objects are rejected during preflight and
|
||||
rechecked immediately before the atomic replacement.
|
||||
- Configuration or explicit CLI input selects that operator-owned destination;
|
||||
it does not create an application-owned state boundary.
|
||||
- Comparison bundles are flat, versioned operator outputs. Their guarded
|
||||
replacement accepts only a recognized current bundle; cancellation and every
|
||||
pre-publication failure preserve a prior bundle, while individual profile
|
||||
failures can publish a complete partial bundle.
|
||||
- Distributor uploads use only the published Markdown output, never a scan of
|
||||
local files. Single notification follows publication; batch notification
|
||||
follows publication of every selected report. Batch counters describe report
|
||||
outcomes only; a failed batch notification is represented separately at the
|
||||
batch level.
|
||||
- Comparison never invokes Distributor notification.
|
||||
- Profile comparison supports operator review only: it does not score, rank,
|
||||
select, resample, or replay profile executions.
|
||||
- Default tests are deterministic, offline, and use Promptkit/provider fakes
|
||||
rather than live provider calls. See the [testing policy](testing.md).
|
||||
|
||||
## Package Layout
|
||||
|
||||
Use this layout unless the project has a documented reason to differ:
|
||||
|
||||
- `internal/app`: application orchestration and top-level use cases.
|
||||
- `internal/cli`: CLI command definitions, flags, argument parsing, and command wiring.
|
||||
- `internal/config`: configuration structs, defaults, loading, precedence, and validation.
|
||||
- `internal/adapters/<name>`: adapters for external CLIs, APIs, databases, object stores, or libraries.
|
||||
- `internal/api`: HTTP API handlers and request/response types, when the application exposes an HTTP API.
|
||||
- `internal/transport/http`: HTTP client code, when the application calls HTTP services.
|
||||
|
||||
Package-private implementation constants may live near the package that owns them, preferably in `constants.go` when useful.
|
||||
|
||||
## Configuration
|
||||
|
||||
Centralize configuration loading, processing, precedence, defaults, and validation in `internal/config`.
|
||||
|
||||
The goal is to make configuration discoverable and avoid implicit or hidden operational values. User-visible defaults and cross-package operational defaults should be defined in `internal/config/defaults.go`.
|
||||
|
||||
Unless documented otherwise, precedence is:
|
||||
|
||||
1. CLI flags
|
||||
2. environment variables
|
||||
3. configuration file
|
||||
4. built-in defaults
|
||||
|
||||
Prefer YAML configuration unless the project has a strong reason to use another format. Config files should be discovered at `/usr/local/etc/<app_name>/config.yml`, with a CLI override via `--config`.
|
||||
|
||||
Configuration files should not contain raw secrets unless the application is explicitly designed for that. Prefer environment variables or secret files for secrets.
|
||||
|
||||
## Adapters and External Integrations
|
||||
|
||||
Use a hexagonal architecture style for external integrations.
|
||||
|
||||
External adapters belong under `internal/adapters/<name>`. If an adapter uses an external dependency, that dependency’s interface must not leak outside the adapter package. Other packages should interact only with the adapter’s API, so the dependency can be swapped, upgraded, or removed without touching unrelated code.
|
||||
|
||||
Adapters should be thin. Domain decisions belong in application/domain packages, not inside adapter glue.
|
||||
|
||||
## Modules, Stages, and Registries
|
||||
|
||||
When the application has stages or modules, each major stage/module should live in its own package and have an explicit input/output contract.
|
||||
|
||||
The orchestrator should be able to compose, skip, resume, or run individual stages/modules when their prerequisites are satisfied. Ordering should be explicit: use a default sequence, dependency graph, or documented orchestration rule.
|
||||
|
||||
If users can select modules, stages, validators, renderers, or adapters, selection should go through a registry or equivalent mechanism rather than scattered conditionals.
|
||||
|
||||
## Embedded Assets
|
||||
|
||||
Store embedded JSON schemas, Markdown prompts, templates, and similar assets as separate files, not inline string literals, unless there is a strong reason otherwise.
|
||||
|
||||
## Errors and Logging
|
||||
|
||||
Errors should be actionable and preserve context. Wrap errors with operation and path/resource context. CLI code should convert internal errors into concise user-facing messages.
|
||||
|
||||
Errors and logs must not expose secrets.
|
||||
|
||||
Use structured logging where practical. Logs should describe operations, paths, external calls, retries, and failure causes, but should not include large user data by default.
|
||||
|
||||
## Context, Timeouts, and Cancellation
|
||||
|
||||
Long-running operations should accept `context.Context`. External calls, subprocesses, HTTP requests, storage operations, and multi-stage workflows should respect cancellation and timeouts.
|
||||
|
||||
## State, Files, and Safety
|
||||
|
||||
If the application writes durable state, writes should be atomic where practical. Multi-step workflows should preserve enough state to support inspection, retry, or resume after failure.
|
||||
|
||||
Code that deletes, moves, or overwrites files must use narrow, explicit paths. Avoid broad parent-directory operations. Cleanup that can cause data loss must be opt-in.
|
||||
|
||||
## Testing
|
||||
|
||||
Core logic should be testable without real external services. Use fakes, fixtures, or local test doubles for adapters where practical.
|
||||
|
||||
Config examples should be load-tested. Important CLI workflows should have parser or command tests. Stage/module contracts should have focused tests that do not require running the full application unless end-to-end coverage is intentional.
|
||||
|
||||
## Documentation
|
||||
|
||||
Documentation should follow the project documentation policy. Keep user docs focused on implemented behavior. Put future, planned, or aspirational work only under `docs/roadmap/`.
|
||||
|
||||
When changing architecture, config, CLI behavior, adapters, or stage/module contracts, update the relevant docs and examples in the same change.
|
||||
## Non-Goals
|
||||
|
||||
Weatherreporter is not a weather-data ingestion service, general LLM
|
||||
orchestration framework, plugin platform, HTTP service, multi-user job system,
|
||||
or a replacement for Promptkit or Distributor.
|
||||
|
||||
@@ -1,691 +0,0 @@
|
||||
# Weatherreporter Package Layout
|
||||
|
||||
This document defines the proposed package layout for `weatherreporter`, a Go application that prepares human-facing weather reports from normalized weather data collected by `weatherfeeder` and rendered through `scriptorium`.
|
||||
|
||||
The application should remain a small, explicit, dependency-light Go program. Domain logic should live outside CLI, transport, and external-adapter packages. External systems should be isolated behind narrow adapters. Report-specific behavior should be selected through a registry or equivalent mechanism rather than scattered conditionals.
|
||||
|
||||
## Architectural Summary
|
||||
|
||||
`weatherreporter` is a deterministic weather briefing and report-preparation application. It should:
|
||||
|
||||
1. Fetch normalized weather data from a single configured internal weather API endpoint backed by `weatherfeeder`.
|
||||
2. Derive report-specific briefing packages from the normalized forecast bundle.
|
||||
3. Compare current briefing snapshots against prior comparable snapshots to produce optional Recent Changes.
|
||||
4. Build structured prompt input data packages for a specific report type.
|
||||
5. Invoke `scriptorium` as an external prompt runner.
|
||||
6. Persist the rendered Markdown report, briefing snapshot, prompt input package, and generation metadata.
|
||||
|
||||
The preferred data flow is:
|
||||
|
||||
```text
|
||||
weatherfeeder-backed internal API
|
||||
-> weather API adapter
|
||||
-> forecast bundle
|
||||
-> report-specific briefing builder
|
||||
-> recent-change comparison
|
||||
-> prompt input data package
|
||||
-> scriptorium subprocess adapter
|
||||
-> Markdown report + metadata + stored snapshot
|
||||
```
|
||||
|
||||
The application should not treat the LLM as the source of weather facts. The Go code should select the relevant data, compute daypart and period summaries, attach alerts and NWS context, identify meaningful changes, and send the LLM a curated briefing package. The LLM should synthesize and phrase the report for humans.
|
||||
|
||||
## Proposed Directory Layout
|
||||
|
||||
```text
|
||||
cmd/weatherreporter/
|
||||
main.go
|
||||
|
||||
internal/app/
|
||||
generate.go
|
||||
scheduled.go
|
||||
storm.go
|
||||
|
||||
internal/cli/
|
||||
root.go
|
||||
generate.go
|
||||
run.go
|
||||
inspect.go
|
||||
|
||||
internal/config/
|
||||
config.go
|
||||
defaults.go
|
||||
load.go
|
||||
validate.go
|
||||
|
||||
internal/adapters/weatherapi/
|
||||
client.go
|
||||
types.go
|
||||
|
||||
internal/adapters/scriptorium/
|
||||
runner.go
|
||||
types.go
|
||||
|
||||
internal/forecast/
|
||||
bundle.go
|
||||
dayparts.go
|
||||
derive.go
|
||||
select.go
|
||||
thresholds.go
|
||||
|
||||
internal/report/
|
||||
definition.go
|
||||
registry.go
|
||||
period.go
|
||||
daily.go
|
||||
tomorrow.go
|
||||
three_day.go
|
||||
weekend.go
|
||||
storm.go
|
||||
|
||||
internal/briefing/
|
||||
package.go
|
||||
daily.go
|
||||
tomorrow.go
|
||||
three_day.go
|
||||
weekend.go
|
||||
storm.go
|
||||
|
||||
internal/changes/
|
||||
compare.go
|
||||
thresholds.go
|
||||
summary.go
|
||||
|
||||
internal/state/
|
||||
store.go
|
||||
filesystem.go
|
||||
metadata.go
|
||||
|
||||
internal/promptinput/
|
||||
build.go
|
||||
schema.go
|
||||
|
||||
internal/timeutil/
|
||||
clock.go
|
||||
periods.go
|
||||
```
|
||||
|
||||
This layout can be simplified during early prototyping if a package has only one file, but the package boundaries should remain conceptually stable.
|
||||
|
||||
## Dependency Direction
|
||||
|
||||
The intended dependency direction is:
|
||||
|
||||
```text
|
||||
cmd/weatherreporter
|
||||
-> internal/cli
|
||||
-> internal/app
|
||||
-> internal/config
|
||||
-> internal/report
|
||||
-> internal/briefing
|
||||
-> internal/forecast
|
||||
-> internal/changes
|
||||
-> internal/state
|
||||
-> internal/adapters/*
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
- `cmd/weatherreporter` should only bootstrap the CLI.
|
||||
- `internal/cli` should parse commands and flags, then call `internal/app`.
|
||||
- `internal/app` should orchestrate workflows but avoid embedding detailed forecast logic.
|
||||
- `internal/adapters/*` should not contain domain policy.
|
||||
- `internal/forecast`, `internal/report`, `internal/briefing`, and `internal/changes` should be testable without real external services.
|
||||
- `internal/state` should expose a storage interface so filesystem state can later be replaced or supplemented.
|
||||
- `scriptorium` details should not leak outside `internal/adapters/scriptorium`.
|
||||
|
||||
## Package Responsibilities
|
||||
|
||||
### `cmd/weatherreporter`
|
||||
|
||||
Entry point for the compiled binary.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Construct the root command from `internal/cli`.
|
||||
- Execute the command.
|
||||
- Handle final process exit behavior.
|
||||
|
||||
Non-responsibilities:
|
||||
|
||||
- No configuration loading details.
|
||||
- No forecast logic.
|
||||
- No direct calls to weather APIs, state stores, or `scriptorium`.
|
||||
|
||||
### `internal/cli`
|
||||
|
||||
Defines the user-facing command tree, flags, arguments, and command wiring.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Define commands such as:
|
||||
- `weatherreporter generate daily`
|
||||
- `weatherreporter generate tomorrow`
|
||||
- `weatherreporter generate three-day`
|
||||
- `weatherreporter generate weekend`
|
||||
- `weatherreporter generate storm`
|
||||
- `weatherreporter run morning`
|
||||
- `weatherreporter run evening`
|
||||
- `weatherreporter inspect snapshot`
|
||||
- Use the Go standard library for CLI parsing unless future complexity justifies a dependency.
|
||||
- Parse flags such as `--config`, `--units`, `--tz`, `--out`, optional Daily `--date`, and storm `--start`/`--end`, then convert them into app-layer request structs.
|
||||
- Load configuration through `internal/config`.
|
||||
- Present concise user-facing errors.
|
||||
|
||||
Non-responsibilities:
|
||||
|
||||
- No report-building logic.
|
||||
- No direct subprocess execution.
|
||||
- No direct weather API calls.
|
||||
- No state comparison logic.
|
||||
|
||||
Suggested command shape:
|
||||
|
||||
```text
|
||||
weatherreporter generate daily --date 2026-05-29 --out ./daily.md
|
||||
weatherreporter generate tomorrow --out ./tomorrow.md
|
||||
weatherreporter generate three-day --out ./three_day.md
|
||||
weatherreporter generate weekend --out ./weekend.md
|
||||
weatherreporter generate storm --start 2026-05-29T18:00 --end 2026-05-30T06:00 --out ./storm.md
|
||||
weatherreporter run morning
|
||||
weatherreporter run evening
|
||||
```
|
||||
|
||||
The MVP should not expose location selection. Source `locationId` and `locationName` values returned by the weather API may be retained as provenance.
|
||||
|
||||
For `generate daily`, `--date` is optional. When provided, it must use `YYYY-MM-DD`; when omitted, it resolves to the current local date in the configured timezone.
|
||||
|
||||
### `internal/config`
|
||||
|
||||
Owns configuration structures, defaults, loading, precedence, and validation.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Define application configuration structs.
|
||||
- Provide built-in defaults in `defaults.go`.
|
||||
- Load YAML configuration from `/usr/local/etc/weatherreporter/config.yml` or a CLI-supplied path.
|
||||
- Use `gopkg.in/yaml.v3` for YAML parsing.
|
||||
- Apply precedence rules.
|
||||
- Validate required settings.
|
||||
- Normalize paths, durations, report settings, weather API units/timezone, missing-source policy, and daypart definitions.
|
||||
|
||||
Suggested configuration areas:
|
||||
|
||||
- Weather API base URL, timeout, units, timezone, precision, and missing-source policy.
|
||||
- `scriptorium` binary, config path, profile, timeout, and optional extra arguments.
|
||||
- Workspace and output directories.
|
||||
- Report enablement and output naming.
|
||||
- Daypart definitions.
|
||||
- Recent-change thresholds.
|
||||
|
||||
Initial defaults:
|
||||
|
||||
- Weather API units: `us`.
|
||||
- Weather API timezone: `Chicago`.
|
||||
- Weather API format: `json`.
|
||||
- Missing-source policy: `warn`.
|
||||
|
||||
Missing-source policy should support a global default and per-source overrides. Valid policy values are `error`, `warn`, and `none`.
|
||||
|
||||
Non-responsibilities:
|
||||
|
||||
- No command execution.
|
||||
- No HTTP calls.
|
||||
- No report-building logic.
|
||||
|
||||
### `internal/app`
|
||||
|
||||
Application orchestration and top-level use cases.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Implement use cases such as:
|
||||
- Generate one report.
|
||||
- Run the morning batch.
|
||||
- Run the evening batch.
|
||||
- Generate a manual storm report.
|
||||
- Coordinate config, weather API adapter, report registry, briefing builders, state store, change comparison, prompt input builder, and `scriptorium` runner.
|
||||
- Enforce workflow order.
|
||||
- Ensure each generation run persists enough artifacts for inspection and future comparison.
|
||||
|
||||
The core generation workflow should be approximately:
|
||||
|
||||
```text
|
||||
resolve report definition
|
||||
resolve valid period
|
||||
fetch current weather bundle
|
||||
build current briefing package
|
||||
load prior comparable briefing snapshot
|
||||
compute recent changes
|
||||
build prompt input data package
|
||||
write data package
|
||||
run scriptorium render preflight
|
||||
invoke scriptorium run
|
||||
persist report metadata, briefing snapshot, data package, preflight output, and rendered report
|
||||
```
|
||||
|
||||
Non-responsibilities:
|
||||
|
||||
- No detailed daypart calculations.
|
||||
- No direct parsing of NWS text unless delegated to domain packages.
|
||||
- No direct shell command construction outside the `scriptorium` adapter.
|
||||
|
||||
### `internal/adapters/weatherapi`
|
||||
|
||||
HTTP adapter for the internal weather API backed by `weatherfeeder`.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Fetch normalized weather data from the configured API base URL.
|
||||
- Fan out to multiple weather API endpoints and assemble one internal `forecast.Bundle`.
|
||||
- Decode API responses into adapter-owned DTOs or directly into stable internal types if those types are intentionally owned by `weatherreporter`.
|
||||
- Apply request timeouts and context cancellation.
|
||||
- Apply configured query defaults, including `format=json`, `units=us`, and `tz=Chicago` unless overridden.
|
||||
- Fetch full `/forecast/hourly` and `/forecast/narrative` products, not day-slice endpoints, so Go domain code owns report-period selection.
|
||||
- Record per-source provenance: endpoint, query, fetch time, issued/updated time when available, SHA-256 over canonical/minified raw `data` JSON, warnings, and missing-source status.
|
||||
- Represent source warnings as first-class records with source name, code, severity, message, endpoint, and completeness impact.
|
||||
- Require hourly forecast data for normal scheduled reports.
|
||||
- Apply missing-source policy for `data:null`, malformed non-required sections, or unavailable upstream products.
|
||||
- Return actionable errors containing endpoint and operation context.
|
||||
|
||||
Initial data categories:
|
||||
|
||||
- Latest observation.
|
||||
- Current conditions.
|
||||
- Hourly forecast data.
|
||||
- NWS narrative forecast periods.
|
||||
- NWS alerts.
|
||||
- NWS forecast discussion.
|
||||
|
||||
Stubbed source slots until upstream support exists:
|
||||
|
||||
- Daily forecast data.
|
||||
- NWS weather story.
|
||||
|
||||
Non-responsibilities:
|
||||
|
||||
- No daypart grouping.
|
||||
- No Recent Changes comparison.
|
||||
- No prompt input construction.
|
||||
- No `scriptorium` calls.
|
||||
|
||||
### `internal/adapters/scriptorium`
|
||||
|
||||
Subprocess adapter for invoking `scriptorium`.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Provide a narrow runner interface, such as:
|
||||
|
||||
```go
|
||||
type Runner interface {
|
||||
Render(ctx context.Context, req RenderRequest) (*RenderResult, error)
|
||||
Run(ctx context.Context, req RunRequest) (*RunResult, error)
|
||||
}
|
||||
```
|
||||
|
||||
- Execute `scriptorium render` for preflight/debug output without LLM generation.
|
||||
- Execute `scriptorium run` for report generation.
|
||||
- Run `scriptorium render` as an always-on preflight before `scriptorium run` for MVP generated reports.
|
||||
- Pass arguments as an argv slice, not through a shell.
|
||||
- Pass large prompt input as `--input data_package=<path>`.
|
||||
- Capture stdout/stderr with reasonable size limits.
|
||||
- Treat nonzero exits as actionable errors, including exit code `2` from `run`, which may still produce output.
|
||||
- Keep all `scriptorium`-specific flag details inside the adapter.
|
||||
|
||||
Suggested command forms:
|
||||
|
||||
```text
|
||||
scriptorium render \
|
||||
--prompt weather.daily_report \
|
||||
--input data_package=./workspace/data-packages/daily/2026-05-29T050000-0500.data_package.json \
|
||||
--format json
|
||||
|
||||
scriptorium run \
|
||||
--prompt weather.daily_report \
|
||||
--input data_package=./workspace/data-packages/daily/2026-05-29T050000-0500.data_package.json \
|
||||
--out ./workspace/reports/daily/2026-05-29T050000-0500.md
|
||||
```
|
||||
|
||||
Non-responsibilities:
|
||||
|
||||
- No weather logic.
|
||||
- No report registry logic.
|
||||
- No decision about which prompt to run.
|
||||
|
||||
Future note:
|
||||
|
||||
- A native LLM client can later replace or supplement this adapter behind a similar interface.
|
||||
|
||||
### `internal/forecast`
|
||||
|
||||
Core forecast-domain processing.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Define the normalized `Bundle` consumed by report builders.
|
||||
- Group hourly forecast data into configured dayparts.
|
||||
- Compute derived facts, including:
|
||||
- Temperature ranges.
|
||||
- Apparent-temperature ranges, if available.
|
||||
- Max precipitation probability.
|
||||
- Peak wind and wind gusts.
|
||||
- Precipitation windows.
|
||||
- Thunder mentions.
|
||||
- Snow/ice/freezing risk indicators.
|
||||
- Alert overlap with relevant periods.
|
||||
- Select forecast elements relevant to a report period.
|
||||
- Provide threshold helpers for impact detection.
|
||||
|
||||
Non-responsibilities:
|
||||
|
||||
- No CLI behavior.
|
||||
- No external API calls.
|
||||
- No rendered prose.
|
||||
- No direct `scriptorium` calls.
|
||||
|
||||
### `internal/report`
|
||||
|
||||
Report definitions, registry, period resolution, and report-level contracts.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Define report IDs and report definition contracts.
|
||||
- Register report types and variants.
|
||||
- Resolve valid periods for each report.
|
||||
- Associate report types with prompt IDs.
|
||||
- Define comparison strategies and output naming behavior.
|
||||
|
||||
Suggested report definitions:
|
||||
|
||||
```text
|
||||
daily_today -> prompt weather.daily_report
|
||||
daily_tomorrow -> prompt weather.daily_report
|
||||
three_day -> prompt weather.three_day_outlook
|
||||
weekend -> prompt weather.weekend_outlook
|
||||
storm -> prompt weather.storm_report
|
||||
```
|
||||
|
||||
`weather.daily_report` should be the standard prompt for one local civil day, regardless of whether that day is today or tomorrow.
|
||||
|
||||
A report definition should describe:
|
||||
|
||||
- Report ID.
|
||||
- Human-readable name.
|
||||
- Prompt ID.
|
||||
- Valid-period resolver.
|
||||
- Briefing builder ID or function.
|
||||
- Recent-change comparison strategy.
|
||||
- Default output naming pattern.
|
||||
- Whether the report participates in morning or evening scheduled batches.
|
||||
|
||||
Non-responsibilities:
|
||||
|
||||
- No detailed forecast computation.
|
||||
- No state storage.
|
||||
- No subprocess execution.
|
||||
|
||||
### `internal/briefing`
|
||||
|
||||
Builds report-specific briefing packages from forecast bundles and report definitions.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Convert a forecast bundle into a report-specific structured briefing package.
|
||||
- Keep each report's briefing shape explicit and testable.
|
||||
- Attach relevant NWS narrative periods, alerts, forecast discussion context, and weather story context when available.
|
||||
- Include metadata such as schema version, configured units/timezone, source warnings, and source provenance.
|
||||
- Provide inputs suitable for `scriptorium` data packages.
|
||||
|
||||
Report-specific builders should exist for:
|
||||
|
||||
- Daily Report.
|
||||
- Tomorrow Planning Brief.
|
||||
- 3-Day Outlook.
|
||||
- Weekend Outlook.
|
||||
- Storm Report.
|
||||
|
||||
Non-responsibilities:
|
||||
|
||||
- No external API fetching.
|
||||
- No final prose rendering.
|
||||
- No state persistence, except through app orchestration.
|
||||
|
||||
Design note:
|
||||
|
||||
- This package is the architectural center of the application. A clean briefing package makes `scriptorium` a renderer rather than a source of weather reasoning.
|
||||
|
||||
### `internal/changes`
|
||||
|
||||
Structured comparison of current and prior briefing snapshots.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Compare current briefing packages against prior comparable snapshots.
|
||||
- Apply meaningful-change thresholds.
|
||||
- Produce compact structured change summaries for prompt input data packages.
|
||||
- Avoid comparison of rendered Markdown report text.
|
||||
|
||||
Comparable snapshot matching should be declared by each report definition. Daily Today, Daily Tomorrow, and compatible date slices from multi-day reports may compare by same valid local date when the report registry marks them compatible. Weekend compares by same weekend window. Storm compares by explicit event window.
|
||||
|
||||
Meaningful changes may include:
|
||||
|
||||
- Temperature changes crossing configured thresholds.
|
||||
- Precipitation probability changes by category.
|
||||
- Precipitation timing shifts.
|
||||
- New, canceled, extended, upgraded, or expanded alerts.
|
||||
- Wind gust threshold crossings.
|
||||
- Snow/ice/freezing risk changes.
|
||||
- Severe-weather wording or risk changes.
|
||||
- Confidence or uncertainty changes, if represented in structured briefing data.
|
||||
|
||||
Non-responsibilities:
|
||||
|
||||
- No fetching prior state directly unless mediated through app/state contracts.
|
||||
- No final report prose.
|
||||
- No external calls.
|
||||
|
||||
### `internal/state`
|
||||
|
||||
Durable state store for reports, snapshots, data packages, preflight output, metadata, and comparison lookup.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Persist generated report metadata.
|
||||
- Persist briefing snapshots.
|
||||
- Persist prompt input data packages.
|
||||
- Persist `scriptorium render` preflight output for generated reports.
|
||||
- Locate prior comparable snapshots for Recent Changes.
|
||||
- Track RunID as generation timestamp plus report ID.
|
||||
- Use timestamped managed report names to avoid overwriting prior runs for the same valid period.
|
||||
- Use atomic writes where practical.
|
||||
- Keep filesystem layout narrow and predictable.
|
||||
|
||||
Initial backend:
|
||||
|
||||
- Filesystem state.
|
||||
|
||||
Potential future backend:
|
||||
|
||||
- SQLite or another state database, behind the same store interface.
|
||||
|
||||
Suggested state layout:
|
||||
|
||||
```text
|
||||
workspace/
|
||||
snapshots/
|
||||
daily/
|
||||
2026-05-30/
|
||||
2026-05-29T050000-0500.briefing.json
|
||||
2026-05-29T050000-0500.metadata.json
|
||||
three-day/
|
||||
weekend/
|
||||
storm/
|
||||
reports/
|
||||
daily/
|
||||
2026-05-29T050000-0500.md
|
||||
three-day/
|
||||
weekend/
|
||||
storm/
|
||||
data-packages/
|
||||
daily/
|
||||
2026-05-29T050000-0500.data_package.json
|
||||
preflight/
|
||||
daily/
|
||||
2026-05-29T050000-0500.render.json
|
||||
```
|
||||
|
||||
Non-responsibilities:
|
||||
|
||||
- No weather derivation.
|
||||
- No report prose generation.
|
||||
- No CLI formatting decisions.
|
||||
|
||||
### `internal/promptinput`
|
||||
|
||||
Builds the final data package passed to `scriptorium`.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Combine report metadata, briefing package, Recent Changes, selected source context, and source warnings into a prompt input document.
|
||||
- Validate required data package fields before invoking `scriptorium`.
|
||||
- Keep data package schemas explicit enough to test.
|
||||
- Write data package files to the workspace when requested by the app layer.
|
||||
|
||||
Non-responsibilities:
|
||||
|
||||
- No weather API calls.
|
||||
- No forecast derivation.
|
||||
- No subprocess execution.
|
||||
|
||||
### `internal/timeutil`
|
||||
|
||||
Time, clock, and period helpers.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Provide an injectable clock for deterministic tests.
|
||||
- Resolve local dates using the configured report timezone.
|
||||
- Handle daypart spans, including overnight windows.
|
||||
- Normalize valid periods.
|
||||
- Provide helpers for recurring scheduled batches.
|
||||
|
||||
Non-responsibilities:
|
||||
|
||||
- No report-specific forecast logic unless delegated by `internal/report`.
|
||||
- No external calls.
|
||||
|
||||
## Report Types and Valid-Period Identity
|
||||
|
||||
Each generated report must be associated with explicit metadata:
|
||||
|
||||
- RunID.
|
||||
- Report type.
|
||||
- Report variant, if applicable.
|
||||
- Generation time.
|
||||
- Configured report timezone.
|
||||
- Valid period start.
|
||||
- Valid period end.
|
||||
- Source location ID/name when provided by upstream.
|
||||
- Source product timestamps and/or SHA-256 hashes.
|
||||
- Source warnings.
|
||||
- Briefing snapshot path.
|
||||
- Prompt input data package path.
|
||||
- Preflight output path.
|
||||
- Rendered report path.
|
||||
|
||||
All valid periods should use the configured local timezone, default `Chicago`, and half-open `[start,end)` intervals.
|
||||
|
||||
Initial valid-period rules:
|
||||
|
||||
- Daily Today: current local civil day, `[00:00, next 00:00)`.
|
||||
- Daily Tomorrow: next local civil day.
|
||||
- 3-Day Outlook: generation time through local midnight after the second following local civil day.
|
||||
- Weekend Outlook: Monday through Thursday covers Saturday 00:00 to Monday 00:00; Friday and Saturday cover `max(generation time, Friday 18:00)` to Monday 00:00; scheduled Sunday morning skips Weekend Outlook.
|
||||
- Manual Storm Report: requires explicit `--start` and `--end`; accept `YYYY-MM-DDTHH:MM` interpreted in the configured timezone and RFC3339 timestamps with explicit offsets.
|
||||
|
||||
The valid period should identify what weather period the report covers, independent of when the report was generated.
|
||||
|
||||
Examples:
|
||||
|
||||
- A 5 PM Tomorrow Planning Brief for Saturday and a 5 AM Saturday Daily Report both cover the same valid date.
|
||||
- A Saturday Weekend Outlook covers the remaining weekend, while a Friday Weekend Outlook may cover Friday evening through Sunday night.
|
||||
- A Storm Report covers an explicit forecast event window, not a fixed calendar day.
|
||||
|
||||
This identity is required for reliable Recent Changes behavior.
|
||||
|
||||
## Scheduled Batch Semantics
|
||||
|
||||
The app should support scheduled batches but should not need to be a daemon in the initial version.
|
||||
|
||||
Suggested batches:
|
||||
|
||||
```text
|
||||
morning:
|
||||
- daily_today
|
||||
- three_day
|
||||
- weekend, except Sunday
|
||||
|
||||
evening:
|
||||
- daily_tomorrow
|
||||
```
|
||||
|
||||
Scheduled batches should continue independent reports after a report failure. The CLI should return nonzero if any report failed and should emit an aggregate run summary.
|
||||
|
||||
External scheduling should be handled by systemd timers, cron, or another orchestrator. `weatherreporter` should simply provide deterministic commands that can be scheduled.
|
||||
|
||||
## Storm Report Direction
|
||||
|
||||
The initial version should support manual Storm Report generation:
|
||||
|
||||
```text
|
||||
weatherreporter generate storm --start 2026-05-29T18:00 --end 2026-05-30T06:00
|
||||
```
|
||||
|
||||
Future storm monitoring should use a staged design:
|
||||
|
||||
```text
|
||||
incoming weather data
|
||||
-> deterministic candidate detector
|
||||
-> LLM event evaluator
|
||||
-> storm lifecycle state
|
||||
-> storm report generation or skip decision
|
||||
```
|
||||
|
||||
Potential storm lifecycle states:
|
||||
|
||||
```text
|
||||
none -> monitoring -> active_report -> escalated -> deescalating -> resolved
|
||||
```
|
||||
|
||||
This future behavior should not be built before the core scheduled reports are stable, but the package layout should leave room for it.
|
||||
|
||||
## Testing Expectations
|
||||
|
||||
Core tests should not require real external services.
|
||||
|
||||
Priority test areas:
|
||||
|
||||
- Configuration loading and validation, including defaults for `units=us`, `tz=Chicago`, and missing-source policy `warn`.
|
||||
- Standard-library CLI command parsing, including `--units`, `--tz`, and storm `--start`/`--end`.
|
||||
- Weather API fan-out, source provenance, `data:null`, and missing-source policy behavior.
|
||||
- Daypart grouping, especially overnight periods.
|
||||
- Valid-period resolution for each report type.
|
||||
- Briefing package construction from fixtures.
|
||||
- Recent Changes threshold behavior and compatible snapshot matching.
|
||||
- Prior snapshot lookup.
|
||||
- `scriptorium` adapter behavior using a fake executable or command runner, including both `render` and `run` with `--input data_package=<path>`.
|
||||
- Batch partial-failure behavior and aggregate exit status.
|
||||
|
||||
## Design Invariants
|
||||
|
||||
Preserve these invariants as the project evolves:
|
||||
|
||||
- Weather facts come from normalized source data, not from the LLM.
|
||||
- The LLM receives curated briefing packages, not unbounded raw weather payloads.
|
||||
- Recent Changes are based on structured snapshot comparison, not Markdown diffing.
|
||||
- Report types are registered or otherwise centrally defined.
|
||||
- External integrations are thin adapters.
|
||||
- CLI code wires workflows but does not own domain logic.
|
||||
- The first durable state backend is filesystem-based and inspectable.
|
||||
- `scriptorium` is an adapter boundary, not an application dependency that leaks across packages.
|
||||
@@ -1,356 +1,230 @@
|
||||
# Go Project Documentation Policy
|
||||
# Documentation Policy
|
||||
|
||||
## Purpose
|
||||
|
||||
Project documentation must help four audiences:
|
||||
|
||||
1. users who need to run the application;
|
||||
2. administrators/operators who need to configure and operate it;
|
||||
3. developers who need to understand and change it safely;
|
||||
4. LLM coding agents that need clear scope, boundaries, and invariants.
|
||||
|
||||
Docs should be accurate, concise, task-oriented, and organized by audience. Prefer links to canonical docs over repetition.
|
||||
This policy assigns each Weatherreporter documentation topic to one canonical
|
||||
owner. Its goal is to keep documentation accurate, concise, discoverable, and
|
||||
resistant to drift for users, operators, developers, integrators, maintainers,
|
||||
and coding agents.
|
||||
|
||||
## Core Rules
|
||||
|
||||
### 1. Keep docs concise
|
||||
|
||||
Each document should cover a defined scope and only the essentials for that scope.
|
||||
|
||||
Avoid:
|
||||
- long background explanations;
|
||||
- repeated reference material;
|
||||
- implementation detail in user-facing docs;
|
||||
- aspirational language outside roadmap docs;
|
||||
- verbose examples where one minimal example is clearer.
|
||||
|
||||
### 2. Document only implemented behavior outside roadmap files
|
||||
|
||||
Unimplemented, planned, aspirational, experimental, or future work may be described only under:
|
||||
|
||||
- `docs/roadmap/`
|
||||
|
||||
No other documentation file, including `README.md`, should describe code, features, modules, stages, commands, config fields, or behaviors that do not currently exist.
|
||||
|
||||
If a feature is partial, non-roadmap docs may describe only the implemented portion and its current boundary.
|
||||
|
||||
### 3. Use canonical homes
|
||||
|
||||
Each type of information should have one canonical location.
|
||||
|
||||
Canonical homes:
|
||||
|
||||
- project purpose and quickstart: `README.md`
|
||||
- development principles: `docs/policy/architecture.md`
|
||||
- configuration reference: `docs/config.md`
|
||||
- CLI reference: `docs/cli.md`
|
||||
- operations and recovery: `docs/operations.md`
|
||||
- troubleshooting: `docs/troubleshooting.md`
|
||||
- implemented internals: `docs/internal/`
|
||||
- future work: `docs/roadmap/`
|
||||
- contributor workflow: `docs/policy/development.md`
|
||||
- copyable examples: `examples/`
|
||||
|
||||
Other files should summarize briefly and link to the canonical source.
|
||||
|
||||
### 4. Keep examples real
|
||||
|
||||
Examples should be valid, maintained, and free of secrets.
|
||||
|
||||
Where practical:
|
||||
- example configs should load successfully;
|
||||
- example commands should match real CLI syntax;
|
||||
- important examples should be covered by tests.
|
||||
|
||||
## Documentation Profiles
|
||||
|
||||
All projects require:
|
||||
|
||||
- `README.md`
|
||||
- `docs/policy/architecture.md`
|
||||
|
||||
Additional docs depend on the project.
|
||||
|
||||
### Small library
|
||||
|
||||
Recommended:
|
||||
- `docs/policy/development.md`, if contributor conventions are non-obvious
|
||||
|
||||
### Simple CLI
|
||||
|
||||
Required:
|
||||
- `docs/cli.md`
|
||||
|
||||
Recommended:
|
||||
- `docs/policy/development.md`
|
||||
|
||||
### Config-driven CLI
|
||||
|
||||
Required:
|
||||
- `docs/cli.md`
|
||||
- `docs/config.md`
|
||||
|
||||
Recommended:
|
||||
- `examples/`
|
||||
- `docs/policy/development.md`
|
||||
|
||||
### Stateful or operator-facing application
|
||||
|
||||
Required:
|
||||
- `docs/cli.md`, if CLI-based
|
||||
- `docs/config.md`, if config-driven
|
||||
- `docs/operations.md`
|
||||
|
||||
Recommended:
|
||||
- `docs/troubleshooting.md`
|
||||
- `examples/`
|
||||
- `docs/policy/development.md`
|
||||
|
||||
### Modular, staged, service-oriented, or orchestration application
|
||||
|
||||
Required:
|
||||
- `docs/cli.md`, if CLI-based
|
||||
- `docs/config.md`, if config-driven
|
||||
- `docs/operations.md`
|
||||
- `docs/internal/`
|
||||
- `docs/policy/development.md`
|
||||
|
||||
Recommended:
|
||||
- `docs/troubleshooting.md`
|
||||
- validated examples under `examples/`
|
||||
|
||||
## Required Documents
|
||||
|
||||
### README.md
|
||||
|
||||
**Audience:** users, administrators, operators
|
||||
|
||||
The README is the outward-facing project orientation page.
|
||||
|
||||
It should include, in order:
|
||||
|
||||
1. concise description;
|
||||
2. elevator pitch;
|
||||
3. shortest useful command or usage example;
|
||||
4. links to targeted docs.
|
||||
|
||||
The README should be short. It is not a manual.
|
||||
|
||||
The “shortest useful command” means the simplest command that performs the project’s core use case. (It does not mean `app --help`.)
|
||||
|
||||
### docs/policy/architecture.md
|
||||
|
||||
**Audience:** developers, LLM coding agents
|
||||
|
||||
`docs/policy/architecture.md` is required for every project.
|
||||
|
||||
It is an inward-facing development policy document. It should describe how the project is intended to be built and changed.
|
||||
|
||||
It should include:
|
||||
|
||||
- project shape;
|
||||
- core design principles;
|
||||
- package and boundary philosophy;
|
||||
- state/persistence philosophy, if applicable;
|
||||
- external integration philosophy, if applicable;
|
||||
- error-handling and logging principles;
|
||||
- testing expectations;
|
||||
- documentation expectations;
|
||||
- architectural invariants;
|
||||
- explicit non-goals, if useful.
|
||||
|
||||
For small projects, this file may be brief. It may simply state that the project is intentionally narrow, monolithic, and dependency-light.
|
||||
|
||||
### docs/policy/development.md
|
||||
|
||||
**Audience:** developers, LLM coding agents
|
||||
|
||||
Required for projects maintained by humans and LLM coding agents.
|
||||
|
||||
It should include:
|
||||
|
||||
- repository layout;
|
||||
- build/test commands;
|
||||
- coding conventions;
|
||||
- dependency policy;
|
||||
- how to add config fields;
|
||||
- how to add CLI flags;
|
||||
- how to add stages/modules/adapters, if applicable;
|
||||
- how to update examples;
|
||||
- documentation update expectations.
|
||||
|
||||
### docs/config.md
|
||||
|
||||
**Audience:** administrators, operators, advanced users
|
||||
|
||||
Required for applications with configuration files.
|
||||
|
||||
It should include, in order:
|
||||
|
||||
1. config file locations and discovery precedence;
|
||||
2. minimal working config;
|
||||
3. production-oriented config;
|
||||
4. full configuration reference;
|
||||
5. secrets handling, if applicable;
|
||||
6. links to maintained examples.
|
||||
|
||||
The full configuration reference should be canonical.
|
||||
|
||||
### docs/cli.md
|
||||
|
||||
**Audience:** users, administrators, operators
|
||||
|
||||
Required for CLI applications.
|
||||
|
||||
It should include, in order:
|
||||
|
||||
1. shortest useful command;
|
||||
2. command overview;
|
||||
3. complete flag reference;
|
||||
4. common workflows;
|
||||
5. diagnostic or recovery commands, if applicable.
|
||||
|
||||
Explain when commands are useful, not just their syntax.
|
||||
|
||||
### docs/operations.md
|
||||
|
||||
**Audience:** administrators, operators
|
||||
|
||||
Required for applications that maintain state, support resume behavior, run multiple stages, write durable artifacts, use remote storage, or require recovery procedures.
|
||||
|
||||
It should cover:
|
||||
|
||||
- normal workflow;
|
||||
- filesystem layout;
|
||||
- remote storage layout, if applicable;
|
||||
- logs and manifests;
|
||||
- resume/retry behavior;
|
||||
- cleanup behavior;
|
||||
- archive/backup behavior;
|
||||
- safe recovery procedures;
|
||||
- operational caveats.
|
||||
|
||||
### docs/troubleshooting.md
|
||||
|
||||
**Audience:** administrators, operators
|
||||
|
||||
Recommended once recurring failure modes exist.
|
||||
|
||||
Each entry should include:
|
||||
|
||||
- symptom;
|
||||
- likely cause;
|
||||
- diagnostic command or inspection step;
|
||||
- safe fix;
|
||||
- relevant links.
|
||||
|
||||
### docs/internal/
|
||||
|
||||
**Audience:** developers, LLM coding agents
|
||||
|
||||
Required for modular, staged, service-oriented, or orchestration projects.
|
||||
|
||||
This directory describes implemented internal components. It is not the roadmap.
|
||||
|
||||
Use one file per major component where useful.
|
||||
|
||||
Each component doc should include:
|
||||
|
||||
1. purpose;
|
||||
2. inputs and outputs;
|
||||
3. boundaries;
|
||||
4. config fields used;
|
||||
5. external adapters used;
|
||||
6. state or manifest behavior, if applicable;
|
||||
7. skip/resume behavior, if applicable;
|
||||
8. failure behavior;
|
||||
9. tests to inspect before changing;
|
||||
10. architectural invariants.
|
||||
|
||||
### docs/roadmap/
|
||||
|
||||
**Audience:** maintainers, developers, LLM coding agents
|
||||
|
||||
This is the only place for planned, future, aspirational, experimental, or unimplemented work.
|
||||
|
||||
Roadmap docs should clearly distinguish:
|
||||
|
||||
- proposed work;
|
||||
- accepted plans;
|
||||
- deferred ideas;
|
||||
- rejected ideas;
|
||||
- implementation prompts or task breakdowns, if useful.
|
||||
|
||||
Roadmap docs should not be confused with current behavior.
|
||||
|
||||
### docs/integrations/
|
||||
|
||||
**Audience:** developers, LLM coding agents
|
||||
|
||||
Required for projects that depend on external CLIs, APIs, services, protocols, or file formats where the integration contract is important to maintain.
|
||||
|
||||
This directory contains concise, versioned reference notes for external integration contracts. It should document only the parts of the external system that this project actually uses.
|
||||
|
||||
Use one file per integration where useful.
|
||||
|
||||
## Examples Directory
|
||||
|
||||
Projects with non-trivial configuration or workflows should include `examples/`.
|
||||
|
||||
Useful examples include:
|
||||
|
||||
- minimal working config;
|
||||
- production-oriented config;
|
||||
- full annotated config;
|
||||
- local development config;
|
||||
- remote/object-storage config;
|
||||
- minimal session/input file.
|
||||
|
||||
Examples should be valid, maintained, tested when practical, and linked from relevant docs.
|
||||
|
||||
## Security and Privacy
|
||||
|
||||
Docs and examples must not include:
|
||||
|
||||
- real API keys;
|
||||
- tokens;
|
||||
- passwords;
|
||||
- private keys;
|
||||
- private environment dumps;
|
||||
- sensitive user data;
|
||||
- raw private transcripts;
|
||||
- private infrastructure details unless intentionally public.
|
||||
|
||||
Document secret-handling mechanisms, not actual secret values.
|
||||
|
||||
## Maintenance Rules
|
||||
|
||||
When docs change, verify the affected behavior.
|
||||
|
||||
Where practical:
|
||||
|
||||
- load example config files in tests;
|
||||
- test CLI examples or command parser behavior;
|
||||
- validate documented flags against real flags;
|
||||
- remove stale references;
|
||||
- update links after renames;
|
||||
- keep roadmap content out of non-roadmap docs.
|
||||
|
||||
If documentation and code disagree, fix the documentation and/or open a roadmap item; do not leave aspirational behavior in current-behavior docs.
|
||||
|
||||
Documentation is complete only when it matches the current code.
|
||||
|
||||
## Documentation Change Checklist
|
||||
|
||||
Before merging documentation changes, verify:
|
||||
|
||||
- README is concise and orientation-focused.
|
||||
- `docs/policy/architecture.md` describes development principles.
|
||||
- Future work appears only under `docs/roadmap/`.
|
||||
- User-facing docs avoid unnecessary internals.
|
||||
- Developer-facing docs preserve boundaries and invariants.
|
||||
- Config examples match the schema.
|
||||
- CLI examples match real commands and flags.
|
||||
- Defaults appear in the canonical config reference.
|
||||
- No secrets or private data are included.
|
||||
- Links are accurate.
|
||||
### One Canonical Documentation Owner
|
||||
|
||||
Each authoritative fact belongs in one canonical document or documentation
|
||||
area. A non-owning document may give a short, stable summary for orientation,
|
||||
but it must link to the canonical owner instead of maintaining a second
|
||||
definition.
|
||||
|
||||
Volatile details include commands, flags, configuration fields and defaults,
|
||||
report and module IDs, schemas, file names, paths, status and exit behavior,
|
||||
retry behavior, and runtime guarantees. If readers could reasonably treat a
|
||||
statement as a contract, its exact documentation belongs with the owner named
|
||||
in this policy.
|
||||
|
||||
Executable sources of truth and documentation owners serve different purposes.
|
||||
Code, schemas, and embedded assets determine runtime behavior. The canonical
|
||||
document owns the corresponding explanation or reference for readers. Both may
|
||||
necessarily express the same contract, but other documentation should summarize
|
||||
and link rather than create another complete reference. When implementation and
|
||||
documentation disagree, verify the intended behavior and update them together.
|
||||
|
||||
### Current State, Decisions, And Future Work
|
||||
|
||||
Outside `docs/roadmap/`, documentation describes implemented behavior only.
|
||||
Partial features may be described only to their implemented boundary.
|
||||
|
||||
An accepted architecture decision may describe an approved direction before it
|
||||
is implemented, but acceptance is not evidence that the behavior exists.
|
||||
Current-state documents change when the implementation lands. Temporary
|
||||
roadmaps own future work, sequencing, and implementation status; they do not
|
||||
replace durable policies, decisions, or current contracts.
|
||||
|
||||
### Audience And Detail
|
||||
|
||||
Write for the document's stated audience and include only the detail needed for
|
||||
its owned topic. User and operator documentation should not expose incidental
|
||||
implementation detail. Developer documentation should link to user-facing and
|
||||
external contracts instead of restating them.
|
||||
|
||||
### Links
|
||||
|
||||
Use descriptive link text and repository-relative links for repository
|
||||
documents. Link to the canonical owner rather than to a duplicate summary.
|
||||
Check every added or changed link, and repair or remove links when their target
|
||||
moves or is retired.
|
||||
|
||||
### Examples And Code Fences
|
||||
|
||||
Complete copyable files belong in `examples/` when maintained examples exist.
|
||||
Documentation may use the smallest illustrative snippet needed for its owned
|
||||
topic, but should link to a maintained example instead of embedding a second
|
||||
complete copy.
|
||||
|
||||
Examples must be valid, secret-free, and tested where practical. Commands,
|
||||
flags, configuration, imports, and Go snippets must match implemented behavior.
|
||||
Use a language tag on fenced code blocks, and identify fragments that are
|
||||
illustrative rather than directly runnable.
|
||||
|
||||
### Security And Privacy
|
||||
|
||||
Documentation and examples must not contain real credentials, private keys,
|
||||
private environment dumps, sensitive source material, or private
|
||||
infrastructure details unless intentionally public. Document secret-handling
|
||||
mechanisms, not secret values.
|
||||
|
||||
## Canonical Ownership
|
||||
|
||||
| Topic | Canonical owner | Owned content | Content owned elsewhere |
|
||||
| --- | --- | --- | --- |
|
||||
| Product orientation and minimal quickstart | `README.md` | What Weatherreporter is, why it is useful, one shortest successful invocation, and links onward. | Complete command reference, configuration reference, operational procedures, architecture, and implementation detail. |
|
||||
| Contributor workflow and package inventory | `docs/development.md` | Repository layout, local workflow, validation commands, coding conventions, task-specific change guidance, dependency workflow, and repository hygiene. | Architectural invariants, user-facing contracts, detailed subsystem behavior, and future work. |
|
||||
| Current application architecture | `docs/policy/architecture.md` | System shape, normative ownership, dependency direction, package boundaries, invariants, safety properties, and non-goals. | Concrete implementation mechanics, contributor procedures, decision history, and future work. |
|
||||
| Documentation organization | `docs/policy/documentation.md` | Documentation ownership, audience boundaries, maintenance rules, and document lifecycle. | Application architecture and runtime behavior. |
|
||||
| Testing policy | `docs/policy/testing.md` | Test philosophy, risk-based sufficiency, stable test boundaries, doubles, coverage guidance, regression policy, and criteria for adding, rewriting, or deleting tests. | Subsystem behavior, application contracts, subsystem-specific test inventories, and implementation plans. |
|
||||
| Release procedure | `docs/release.md` | Version policy, release preparation, validation, tagging, automated publication, verification, failure handling, and release ordering. | General contributor workflow, product contracts, release-specific change summaries, and implementation history. |
|
||||
| Release notes | `docs/releases/` | One versioned, changelog-style summary for each release, including compatibility and operator action. The file at the tagged commit supplies the corresponding Gitea release body. | Current CLI, configuration, operations, integration, architecture, and internal contracts; release procedure; implementation plans. |
|
||||
| CLI contract | `docs/cli.md` | Commands, arguments, flags, invocation semantics, stdout and stderr behavior, summaries, and exit behavior. | Configuration field definitions, complete operating procedures, runtime filesystem layout, and command implementation. |
|
||||
| Configuration contract | `docs/config.md` | Discovery and precedence, fields, defaults, secrets, validation rules, and user-selectable values. | Complete example files, CLI syntax, output lifecycle, and loading implementation. |
|
||||
| Operations | `docs/operations.md` | Normal output handling, atomic replacement, notification behavior, diagnosis, explicit debug capture, manual legacy-workspace cleanup, permissions, and operational caveats. | Complete CLI syntax, configuration field definitions, logical external contracts, and implementation mechanics. |
|
||||
| Report template surface | `docs/templates.md` | Implemented template files and partials, render-context fields, editing rules, and maintainer-facing template examples. | Weather derivation, module implementation, generated-text validation internals, and operator procedures. |
|
||||
| External and durable integration contracts | `docs/integrations/` | Weather API, Promptkit, Distributor, external formats and protocols, durable logical paths and schemas, compatibility behavior, and upstream or downstream responsibilities. | Physical runtime placement and lifecycle, internal transformations, CLI syntax, and configuration defaults. |
|
||||
| Internal subsystem behavior | `docs/internal/` | Implementation flow, internal collaborators and state transitions, package-local guarantees and failures, and relevant tests. | Global architecture invariants, user-facing contracts, external schemas, operator procedures, and future package plans. |
|
||||
| Architectural decision history | `docs/adr/`, when repository-local decisions require records | Significant decisions, context, alternatives, rationale, consequences, and supersession history. | Current behavior reference, implementation status, and task sequencing. |
|
||||
| Temporary feature roadmaps | `docs/roadmap/`, while planned work needs coordination | Proposed, accepted, deferred, or rejected work; sequencing; gates; implementation status; and task breakdowns. | Implemented behavior reference and durable decision rationale. |
|
||||
| Complete copyable artifacts | `examples/` | Maintained configuration and other files intended to be copied or run. | Field-by-field reference, command reference, and prose explanation. |
|
||||
|
||||
Conditional owners do not require placeholder files or directories. If
|
||||
Weatherreporter introduces a new public API, consumer interface, release
|
||||
process, or other durable documentation responsibility, update this policy to
|
||||
assign its canonical owner when that responsibility is introduced.
|
||||
|
||||
## Boundary Rules
|
||||
|
||||
### Orientation, Architecture, And Internals
|
||||
|
||||
The README owns product orientation. The development policy routes contributors
|
||||
and owns the concise current package inventory. Architecture owns normative
|
||||
structure and invariants. Focused internal documents own implementation
|
||||
behavior. These documents may link to one another but must not maintain
|
||||
parallel package or behavior references.
|
||||
|
||||
### Commands, Configuration, And Operations
|
||||
|
||||
CLI documentation answers how to invoke Weatherreporter and what its command
|
||||
interface does. Configuration documentation answers what settings mean.
|
||||
Operations answers how to handle operator-owned outputs and runtime failures,
|
||||
including diagnosis, explicit debug capture, and safe legacy cleanup.
|
||||
|
||||
When a workflow crosses these topics, place the complete procedure with the
|
||||
document that owns the task and link to the other contracts. Do not duplicate
|
||||
complete flag, field, or path references to make a workflow self-contained.
|
||||
|
||||
### Templates, Integrations, And Implementation
|
||||
|
||||
Template documentation defines the maintainer-facing rendering surface.
|
||||
Integration documentation defines externally observable shapes, logical paths,
|
||||
protocols, and compatibility behavior. Internal documentation explains how
|
||||
Weatherreporter produces, transforms, or consumes those contracts.
|
||||
|
||||
Internal documents may name a command, field, template value, path, or protocol
|
||||
to identify a dependency, but must link to its canonical documentation for the
|
||||
complete definition.
|
||||
|
||||
### Release Procedure And Release Notes
|
||||
|
||||
The release procedure owns how a maintainer prepares, publishes, verifies, and
|
||||
recovers from a Weatherreporter release. Release notes under `docs/releases/`
|
||||
own the concise historical summary for one version and are the checked-in
|
||||
source for its generated Gitea release body.
|
||||
|
||||
Release notes are not current-state reference documents. They may summarize
|
||||
what changed and link to durable documentation, but they must not become a
|
||||
second command, configuration, operations, integration, architecture, or
|
||||
internal reference. Correct the applicable canonical owner in the same change
|
||||
when a release changes an implemented contract.
|
||||
|
||||
The release note at a published tag and the Gitea release generated from it are
|
||||
historical records. Later corrections on `main` do not rewrite that published
|
||||
record. Material release errors require the failure handling defined by the
|
||||
release procedure rather than moving a published tag or overwriting its
|
||||
release.
|
||||
|
||||
### Executable Authority
|
||||
|
||||
CLI parsing and help generation are the executable authority for accepted
|
||||
commands and flags. Configuration structs, defaults, loading, and validation
|
||||
are the executable authority for configuration behavior. Schemas and embedded
|
||||
assets are the executable authority for validated formats and template
|
||||
execution. Tests protect selected contracts and invariants but do not become a
|
||||
second documentation reference merely by asserting them.
|
||||
|
||||
Canonical documentation must be checked against these authorities whenever the
|
||||
corresponding behavior changes.
|
||||
|
||||
### Security Topics
|
||||
|
||||
This policy owns what documentation and examples may contain. Architecture owns
|
||||
application security boundaries and invariants. Configuration owns
|
||||
credential-supply mechanisms. Operations owns permissions and handling of
|
||||
sensitive runtime artifacts. Integration documents own consumer-visible
|
||||
security contracts. Internal documents own implementation mechanisms only.
|
||||
|
||||
## Architecture Decision Records
|
||||
|
||||
Use sequentially numbered ADR filenames such as
|
||||
`0001-record-architecture-decisions.md`. Follow the lightweight Nygard format:
|
||||
|
||||
1. title;
|
||||
2. status;
|
||||
3. date;
|
||||
4. context;
|
||||
5. decision;
|
||||
6. alternatives considered;
|
||||
7. consequences.
|
||||
|
||||
Use one of these statuses:
|
||||
|
||||
- **Proposed:** the decision is under consideration and may change;
|
||||
- **Accepted:** the decision is approved, whether or not implementation is
|
||||
complete;
|
||||
- **Rejected:** the proposed decision was considered and not adopted;
|
||||
- **Superseded:** a later accepted ADR replaces the accepted decision.
|
||||
|
||||
A proposed ADR transitions to Accepted or Rejected. An Accepted ADR transitions
|
||||
to Superseded only when a later Accepted ADR replaces it. An ADR may be created
|
||||
as Accepted when the decision has already been made.
|
||||
|
||||
Treat the decision content of an Accepted ADR as immutable. A changed decision
|
||||
requires a later ADR rather than a rewrite of the accepted record. A Superseded
|
||||
ADR must link to its replacement, and the replacement must link back. Rejected
|
||||
architectural alternatives belong in the ADR; rejected feature ideas belong in
|
||||
a roadmap when they need to be retained.
|
||||
|
||||
## Document Lifecycle
|
||||
|
||||
Create durable current-state documentation with the implementation it
|
||||
describes. Update its canonical owner in the same change when behavior changes.
|
||||
If ownership moves, remove the old definition and leave a link where navigation
|
||||
remains useful.
|
||||
|
||||
Roadmaps are temporary coordination documents. When their work is complete,
|
||||
record completion, move any still-useful decisions or contracts to their
|
||||
durable owners, update incoming links, and archive or remove the roadmap
|
||||
according to repository practice. Do not preserve completed roadmaps as a
|
||||
second current-state reference.
|
||||
|
||||
Release notes are durable historical summaries rather than temporary roadmaps.
|
||||
Keep them concise, retain them after publication, and keep current contracts in
|
||||
their canonical owners.
|
||||
|
||||
Before completing documentation work:
|
||||
|
||||
- verify affected behavior and examples;
|
||||
- check commands, flags, fields, defaults, schemas, paths, and identifiers
|
||||
against their implementation;
|
||||
- keep unimplemented behavior in a roadmap, subject to the ADR exception;
|
||||
- validate links and fenced examples;
|
||||
- confirm non-owning documents summarize and link rather than redefine;
|
||||
- remove stale or unsupported claims; and
|
||||
- confirm that no secrets or sensitive private data were added.
|
||||
|
||||
337
docs/policy/testing.md
Normal file
337
docs/policy/testing.md
Normal file
@@ -0,0 +1,337 @@
|
||||
# Testing Policy
|
||||
|
||||
## Purpose
|
||||
|
||||
Our tests exist to make **incorrect changes expensive and correct changes
|
||||
cheap**.
|
||||
|
||||
We do not optimize for test count, line coverage, exhaustive isolation, or the
|
||||
fewest possible tests. We optimize for sufficient confidence in important
|
||||
behavior while imposing as little unnecessary friction as possible on future
|
||||
development.
|
||||
|
||||
## Every Test Has A Cost
|
||||
|
||||
Every test has an immediate cost and a continuing lifetime cost. It must be
|
||||
written, reviewed, executed, understood, diagnosed when it fails, updated when
|
||||
legitimate behavior changes, and maintained as fixtures and dependencies
|
||||
evolve.
|
||||
|
||||
Tests also create cognitive and architectural friction. They can constrain
|
||||
refactoring, duplicate policy, slow feedback, add noise to failures, and cause
|
||||
harmless implementation changes to require unrelated suite edits.
|
||||
|
||||
A test is warranted when the confidence it provides justifies those costs.
|
||||
Apply that judgment at two levels:
|
||||
|
||||
1. **Per test:** What realistic defect does this test detect, how consequential
|
||||
would it be, and is that protection worth the test's lifetime cost?
|
||||
2. **Across the suite:** Does this collection provide materially more
|
||||
confidence than a smaller, simpler suite would?
|
||||
|
||||
Prefer a lean suite that provides sufficient confidence in the risks that
|
||||
matter without redundant or low-value tests. Some friction is intentional:
|
||||
tests should make dangerous changes, such as corrupting state, breaking
|
||||
compatibility, violating security boundaries, or reintroducing subtle defects,
|
||||
require deliberate review. They should not make ordinary internal changes
|
||||
needlessly expensive.
|
||||
|
||||
Maintenance cost is not a reason to omit testing by default. When omitting a
|
||||
plausible test, be able to explain why the protected failure is low-risk,
|
||||
already covered, obvious, reversible, or cheaper to detect elsewhere. Favor
|
||||
testing when failure would be consequential, subtle, or difficult to observe.
|
||||
|
||||
## Default Testing Style
|
||||
|
||||
Use a classical or Detroit-style approach:
|
||||
|
||||
- Test observable behavior, resulting state, contracts, and invariants.
|
||||
- Use real internal collaborators when they are fast and deterministic.
|
||||
- Use fakes, stubs, or mocks primarily at expensive, nondeterministic,
|
||||
destructive, or external boundaries.
|
||||
- Prefer package-level behavioral tests over tests coupled to private helpers
|
||||
or internal call sequences.
|
||||
- Test exact collaborator interactions only when the interaction itself is a
|
||||
requirement.
|
||||
|
||||
Weatherreporter's important seams include clocks, Promptkit executors, HTTP
|
||||
services, Distributor uploads, filesystem roots, environment-backed secrets, and any
|
||||
future source of randomness or nondeterminism.
|
||||
|
||||
## Execution Requirements
|
||||
|
||||
The [development guide](../development.md) owns baseline repository validation.
|
||||
The default test suite is:
|
||||
|
||||
```sh
|
||||
go test ./...
|
||||
```
|
||||
|
||||
Run race-enabled tests when a change affects concurrent execution, goroutine
|
||||
lifecycle, shared mutable state, or cancellation coordination. Use a focused
|
||||
package command while iterating and `go test -race ./...` when the risk crosses
|
||||
package boundaries.
|
||||
|
||||
Tests in the default suite must be deterministic, offline, and independent of
|
||||
real credentials. They must not invoke live Weather API, Promptkit providers, or
|
||||
Distributor services or depend on other mutable external infrastructure.
|
||||
Tests that require live infrastructure must be explicitly opt-in and clearly
|
||||
separated from the default suite.
|
||||
|
||||
Control clocks, environment variables, filesystem roots, and machine-specific
|
||||
state when they affect behavior. Tests must be safe to repeat and must not
|
||||
depend on execution order or state left by an earlier test. Tests that modify
|
||||
process-global state may remain serial; use `t.Parallel()` only when the test
|
||||
and its collaborators are actually safe to run concurrently.
|
||||
|
||||
## Test Types And Assets
|
||||
|
||||
Use each test type where it protects a distinct risk:
|
||||
|
||||
- Unit and package tests protect focused domain behavior and invariants through
|
||||
the narrowest stable boundary.
|
||||
- Contract tests protect CLI behavior, configuration, durable artifacts,
|
||||
schemas, templates, integration formats, compatibility, and stable error
|
||||
identity.
|
||||
- Integration tests use real deterministic collaborators when correctness
|
||||
depends on their interaction, while replacing live or nondeterministic
|
||||
external boundaries.
|
||||
- App and CLI tests protect representative assembled generation, batch, atomic
|
||||
output, and notification workflows.
|
||||
- Fixtures must be minimal, synthetic, versioned with the behavior they
|
||||
exercise, and free of credentials or private data.
|
||||
- Golden files are appropriate only when the complete output is intentionally
|
||||
stable and semantic review of updates is practical.
|
||||
- Failure-path tests should cover consequential malformed input, dependency
|
||||
failure, cancellation, partial results, and recovery behavior.
|
||||
|
||||
## What Deserves Tests
|
||||
|
||||
Prioritize tests for:
|
||||
|
||||
1. CLI, configuration, artifact, template, integration, and package contracts.
|
||||
2. Meteorological domain rules and important invariants.
|
||||
3. Boundary conditions and malformed input.
|
||||
4. Failure handling, cancellation, retries, recovery, and partial success.
|
||||
5. Serialization, schemas, compatibility, and round trips.
|
||||
6. Previously observed or plausible regressions.
|
||||
7. Representative app and CLI workflows.
|
||||
|
||||
A package-level contract is behavior relied upon by another package or major
|
||||
collaborator, not every observable implementation detail.
|
||||
|
||||
For data integrity, destructive operations, compatibility, security,
|
||||
concurrency, idempotency, or recovery, presume that durable tests are required
|
||||
unless the behavior is already credibly protected at another layer.
|
||||
|
||||
Do not add tests merely because a function, branch, or line exists. Do not add
|
||||
a test when the same meaningful risk is already adequately protected
|
||||
elsewhere.
|
||||
|
||||
## Choose The Right Boundary
|
||||
|
||||
Test through the narrowest stable boundary that expresses the behavior clearly.
|
||||
That may be:
|
||||
|
||||
- a small pure function when dense domain logic is clearest there;
|
||||
- a package operation when several internal collaborators jointly produce the
|
||||
behavior; or
|
||||
- a larger integration or app boundary when correctness emerges from
|
||||
interaction.
|
||||
|
||||
Do not force every behavior through oversized workflow tests. Do not test every
|
||||
private helper merely because it exists. Choose the boundary that provides
|
||||
durable confidence with the least incidental coupling.
|
||||
|
||||
## Test Behavior, Not Implementation
|
||||
|
||||
A test should protect a decision, contract, or invariant, not memorialize the
|
||||
current implementation. Before adding or retaining a test, ask:
|
||||
|
||||
> What realistic defect would this test catch?
|
||||
|
||||
A test is suspect when its main purpose is to detect that someone changed a
|
||||
private constant, renamed or split a helper, reordered equivalent operations,
|
||||
changed incidental formatting, replaced one correct algorithm with another, or
|
||||
refactored private structure without changing behavior.
|
||||
|
||||
Refactoring should normally require no test edits unless the changed structure
|
||||
is itself contractual. A test can be factually correct and still have negative
|
||||
value when the behavior it protects is too incidental to justify its future
|
||||
cost.
|
||||
|
||||
Use these expectations when evaluating failures:
|
||||
|
||||
| Change | Expected effect on tests |
|
||||
| --- | --- |
|
||||
| Internal refactor that preserves behavior | Existing tests should normally remain unchanged and pass. |
|
||||
| Internal default change with no contractual significance | Tests should normally derive expectations from configuration or relationships rather than duplicate the old value. |
|
||||
| Intentional change to user-visible behavior, policy, schema, or compatibility | Relevant tests should be reviewed and changed deliberately. |
|
||||
| Accidental contract or invariant violation | Tests should fail; fix production code rather than rewriting tests to accept the defect. |
|
||||
|
||||
A failing test is not necessarily a test that should be edited. Many tests may
|
||||
correctly fail because of one production defect. The maintenance smell is a
|
||||
correct internal change that requires unrelated expectation changes throughout
|
||||
the suite.
|
||||
|
||||
## Separate Mechanism From Policy
|
||||
|
||||
Do not duplicate configurable thresholds and defaults throughout the suite.
|
||||
Test mechanisms relationally: a configured valid value is accepted, a value
|
||||
outside the permitted relationship is rejected, and runtime behavior respects
|
||||
the configured value.
|
||||
|
||||
Test an exact default when its literal value is itself a documented user,
|
||||
operational, safety, protocol, or compatibility contract. The same distinction
|
||||
applies to timeouts, capacities, retry counts, ranges, thresholds, and output
|
||||
limits.
|
||||
|
||||
When concurrency limits are introduced, distinguish configuration enforcement
|
||||
from runtime enforcement. Validate accepted and rejected settings separately
|
||||
from measuring whether observed peak concurrency respects the configured
|
||||
limit.
|
||||
|
||||
## Avoid Semantic Duplication
|
||||
|
||||
Each behavior should have a clear test owner:
|
||||
|
||||
- CLI parser tests own arguments, flags, and command construction.
|
||||
- Config tests own loading, precedence, defaults, secrets, and validation.
|
||||
- Domain tests own weather transformations and invariants.
|
||||
- Adapter tests own HTTP, Promptkit/provider, and upload boundaries.
|
||||
- Orchestrator tests own workflow ordering, output publication, partial success,
|
||||
and failure propagation.
|
||||
- Filesystem tests own atomic writes and destination-preservation behavior.
|
||||
- Template and generated-text tests own schemas, render contexts, and rendered
|
||||
output contracts.
|
||||
|
||||
Higher-level tests should not repeat every lower-level case. Tests that are
|
||||
individually reasonable may still be collectively redundant; assess the
|
||||
marginal protection of each additional test.
|
||||
|
||||
## Use Test Doubles Deliberately
|
||||
|
||||
Choose the least elaborate double that provides the required control or
|
||||
observation:
|
||||
|
||||
1. Prefer real collaborators when they are fast and deterministic.
|
||||
2. Use small in-memory fakes when realistic stateful behavior helps.
|
||||
3. Use stubs when a dependency only needs controlled responses.
|
||||
4. Use mocks when the interaction itself is contractual.
|
||||
|
||||
Mocks are appropriate for requirements such as uploading exactly once,
|
||||
notifying only after output publication, propagating cancellation to Promptkit, or
|
||||
avoiding an external call after an earlier workflow failure. Do not use mocks
|
||||
merely to isolate every object or reproduce the implementation's call graph.
|
||||
|
||||
## Go-Specific Guidance
|
||||
|
||||
Use:
|
||||
|
||||
- table-driven tests for meaningful behavioral categories and boundaries;
|
||||
- `t.TempDir()` for real filesystem behavior;
|
||||
- `httptest.Server` for realistic Weather API interactions;
|
||||
- test-controlled clocks for periods and RunIDs;
|
||||
- fake Promptkit executors or provider clients for Promptkit behavior;
|
||||
- fake upload clients for Distributor behavior;
|
||||
- fuzz tests when parsers, normalization, or path handling have a broad and
|
||||
consequential input space;
|
||||
- golden files only when complete output stability is intentional; and
|
||||
- a small number of representative app and CLI workflow tests.
|
||||
|
||||
Avoid exact error-string assertions unless wording is contractual. Prefer
|
||||
`errors.Is`, `errors.As`, typed errors, structured fields, or the smallest
|
||||
stable semantic fragment that identifies the failure. At CLI boundaries,
|
||||
prefer structured summaries, exit behavior, and stable classifications over
|
||||
snapshots of complete diagnostic wording.
|
||||
|
||||
Golden-file updates must require an explicit local flag. Ordinary validation
|
||||
must never update golden files automatically, and maintainers must inspect the
|
||||
semantic diff before accepting an update.
|
||||
|
||||
Keep tests readable and direct. Helpers and fixture frameworks must earn their
|
||||
maintenance cost; do not build elaborate infrastructure for small or isolated
|
||||
needs.
|
||||
|
||||
## Coverage
|
||||
|
||||
Coverage is a diagnostic, not a target. Use it to find untested critical
|
||||
branches and unexpectedly weak packages. Do not write low-value tests solely
|
||||
to increase a percentage or infer quality from coverage alone.
|
||||
|
||||
Pure domain logic will often warrant higher coverage than CLI wiring or thin
|
||||
external adapters. Uneven coverage is acceptable when it reflects risk.
|
||||
|
||||
## Regression Tests
|
||||
|
||||
A bug fix should normally include a regression test that fails before the fix
|
||||
and passes afterward. Prefer the narrowest durable test of the violated
|
||||
contract or invariant.
|
||||
|
||||
Retain the test when the defect could realistically recur and its consequences
|
||||
justify the ongoing cost. Remove or consolidate it if the design makes
|
||||
recurrence implausible or a stronger invariant test subsumes it.
|
||||
|
||||
## Deleting Or Rewriting Tests
|
||||
|
||||
Tests are maintained code, not permanent historical artifacts. Delete or
|
||||
rewrite a test when its maintenance cost exceeds the confidence it provides.
|
||||
Candidates include tests that:
|
||||
|
||||
- require edits after harmless internal changes;
|
||||
- assert private constants without protecting a real contract;
|
||||
- duplicate the same policy across several layers;
|
||||
- verify mock choreography rather than outcomes;
|
||||
- snapshot large amounts of incidental output;
|
||||
- protect risks already covered more effectively elsewhere; or
|
||||
- are flaky, misleading, obsolete, or no longer correspond to a plausible
|
||||
failure.
|
||||
|
||||
Test removal must be deliberate and within the scope of the change. Identify
|
||||
the behavior the test protected and show that the behavior is covered more
|
||||
effectively elsewhere or that the failure is no longer plausible enough to
|
||||
justify durable coverage. Replace several brittle tests with one stronger
|
||||
behavior or invariant test when appropriate.
|
||||
|
||||
Do not delete or weaken a test merely because it fails after a production
|
||||
change. First determine whether the failure exposes an accidental regression,
|
||||
an intentional contract change, or an implementation-coupled assertion.
|
||||
|
||||
## Reviewing A Proposed Test
|
||||
|
||||
When a proposed test's value or durability is not self-evident, ask:
|
||||
|
||||
1. What realistic defect would it catch, and how consequential is that defect?
|
||||
2. Is the behavior already protected elsewhere?
|
||||
3. Which layer should own the test?
|
||||
4. Does it assert a durable contract or incidental implementation detail?
|
||||
5. What should cause it to fail, and what legitimate changes should not?
|
||||
6. Could a smaller or more direct test protect the same risk?
|
||||
7. What ongoing maintenance, execution, and diagnostic cost will it impose?
|
||||
|
||||
Written answers are not required for every routine test. Do not add a test when
|
||||
its expected lifetime cost exceeds its expected protective value.
|
||||
|
||||
## Definition Of Sufficient
|
||||
|
||||
A suite is sufficient when:
|
||||
|
||||
- important contracts and invariants are protected;
|
||||
- meaningful boundaries and failure modes are exercised;
|
||||
- consequential regressions are credibly protected against silent recurrence;
|
||||
- data integrity, destructive operations, compatibility, security,
|
||||
concurrency, idempotency, and recovery receive risk-appropriate protection;
|
||||
- external boundaries have realistic local integration coverage;
|
||||
- representative complete workflows are tested;
|
||||
- failures provide useful signal rather than redundant noise; and
|
||||
- legitimate internal changes usually do not require test edits.
|
||||
|
||||
Sufficiency is a risk judgment, not a coverage percentage or test count.
|
||||
Reassess it as Weatherreporter, its users, and the consequences of failure
|
||||
evolve.
|
||||
|
||||
The governing rule is:
|
||||
|
||||
> Test heavily where failure is consequential, subtle, or difficult to detect
|
||||
> after the fact. Test lightly where failure is obvious, reversible, and
|
||||
> inexpensive.
|
||||
269
docs/release.md
Normal file
269
docs/release.md
Normal file
@@ -0,0 +1,269 @@
|
||||
# Release Procedure
|
||||
|
||||
## Release Model
|
||||
|
||||
Weatherreporter publishes executable binaries through tagged commits on
|
||||
`main`. Releases use stable semantic-version tags in the form
|
||||
`vMAJOR.MINOR.PATCH`. The current pipeline does not publish prereleases.
|
||||
|
||||
Every release has one nonempty, version-matched note at
|
||||
`docs/releases/<tag>.md`. After the tag is pushed, the Woodpecker release
|
||||
pipeline validates the tagged source, builds six binaries, creates SHA-256
|
||||
checksums, and creates the corresponding Gitea release. The pipeline uses the
|
||||
checked-in release note as the Gitea release body and does not overwrite an
|
||||
existing release.
|
||||
|
||||
Before `v1.0.0`, a minor release may deliberately change user-facing
|
||||
interfaces when its release note explains the compatibility impact and
|
||||
required operator action. Patch releases must not intentionally break the
|
||||
documented CLI, configuration, durable artifact, or integration contracts in
|
||||
their minor line.
|
||||
|
||||
Published tags and their generated releases are immutable. Never move, reuse,
|
||||
or delete a published tag, and never manually overwrite the release produced
|
||||
from it.
|
||||
|
||||
## Select The Version And Write The Release Note
|
||||
|
||||
Choose an unpublished version and export it as `RELEASE_VERSION`. Run the
|
||||
commands in this procedure from the Weatherreporter repository root in one
|
||||
POSIX shell:
|
||||
|
||||
```sh
|
||||
export RELEASE_VERSION=vMAJOR.MINOR.PATCH
|
||||
```
|
||||
|
||||
Create `docs/releases/$RELEASE_VERSION.md` with this structure:
|
||||
|
||||
```markdown
|
||||
# Weatherreporter vMAJOR.MINOR.PATCH
|
||||
|
||||
This release ...
|
||||
|
||||
## Summary
|
||||
|
||||
Summarize the release's purpose and most important outcomes.
|
||||
|
||||
## Compatibility
|
||||
|
||||
State compatibility with the preceding release and identify any changed CLI,
|
||||
configuration, durable artifact, integration, or operating contract.
|
||||
|
||||
## Upgrade
|
||||
|
||||
State the operator actions required to upgrade, or state that no special
|
||||
action is required.
|
||||
|
||||
## Changes
|
||||
|
||||
Describe the material user-visible, operational, and maintainer-visible
|
||||
changes. Link to canonical documentation for exact current contracts.
|
||||
```
|
||||
|
||||
The note is a concise changelog and adoption aid, not a replacement for current
|
||||
documentation. Update every affected canonical document in the same candidate
|
||||
commit. Do not include credentials, private infrastructure details, or claims
|
||||
that are not true of the candidate.
|
||||
|
||||
Require the version, path, heading, and minimum sections before continuing:
|
||||
|
||||
```sh
|
||||
set -eu
|
||||
|
||||
: "${RELEASE_VERSION:?export an unpublished vMAJOR.MINOR.PATCH version}"
|
||||
if ! printf '%s\n' "$RELEASE_VERSION" |
|
||||
grep -Eq '^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$'
|
||||
then
|
||||
printf '%s\n' "invalid release version: $RELEASE_VERSION" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
RELEASE_NOTE="docs/releases/$RELEASE_VERSION.md"
|
||||
export RELEASE_NOTE
|
||||
|
||||
test -s "$RELEASE_NOTE"
|
||||
grep -Fx "# Weatherreporter $RELEASE_VERSION" "$RELEASE_NOTE"
|
||||
grep -Fx '## Summary' "$RELEASE_NOTE"
|
||||
grep -Fx '## Compatibility' "$RELEASE_NOTE"
|
||||
grep -Fx '## Upgrade' "$RELEASE_NOTE"
|
||||
grep -Fx '## Changes' "$RELEASE_NOTE"
|
||||
```
|
||||
|
||||
## Validate The Candidate
|
||||
|
||||
Run the same substantive checks enforced by the tag pipeline before committing
|
||||
the release note:
|
||||
|
||||
```sh
|
||||
test -z "$(git ls-files go.work go.work.sum)"
|
||||
test ! -e vendor
|
||||
if grep -Eq '^[[:space:]]*replace([[:space:]]|\()' go.mod
|
||||
then
|
||||
printf '%s\n' 'go.mod contains a replacement' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
GOWORK=off go test -count=1 ./...
|
||||
GOWORK=off go test -race -count=1 ./...
|
||||
GOWORK=off go vet ./...
|
||||
GOWORK=off go build ./...
|
||||
GOWORK=off go mod tidy -diff
|
||||
|
||||
unformatted=$(
|
||||
git ls-files '*.go' |
|
||||
while IFS= read -r go_file
|
||||
do
|
||||
gofmt -l "$go_file"
|
||||
done
|
||||
)
|
||||
test -z "$unformatted"
|
||||
git diff --check
|
||||
git diff --cached --check
|
||||
```
|
||||
|
||||
Follow every added or changed Markdown link and confirm that its local target
|
||||
exists. Review the candidate for generated binaries, test output, credentials,
|
||||
temporary files, replacements, vendored dependencies, and other files that do
|
||||
not belong in source control.
|
||||
|
||||
## Publish The Candidate Commit
|
||||
|
||||
Commit the release note and any final current-state documentation updates, then
|
||||
push `main` through the ordinary repository workflow:
|
||||
|
||||
```sh
|
||||
git add "$RELEASE_NOTE"
|
||||
git commit -m "Document Weatherreporter $RELEASE_VERSION"
|
||||
git push origin main
|
||||
```
|
||||
|
||||
Do not tag an uncommitted or unpushed candidate. Record and export the exact
|
||||
candidate commit after the push:
|
||||
|
||||
```sh
|
||||
RELEASE_COMMIT=$(git rev-parse --verify 'HEAD^{commit}')
|
||||
export RELEASE_COMMIT
|
||||
```
|
||||
|
||||
## Guard And Tag The Candidate
|
||||
|
||||
Run this guard immediately before creating the tag. It requires a clean
|
||||
checkout on synchronized `main`, valid module hygiene, the version-matched
|
||||
release note, and an unpublished local and remote tag:
|
||||
|
||||
```sh
|
||||
check_release_candidate() {
|
||||
test "$(git branch --show-current)" = main
|
||||
test -z "$(git status --porcelain)"
|
||||
|
||||
gowork_value=$(go env GOWORK)
|
||||
case "$gowork_value" in
|
||||
''|off) ;;
|
||||
*)
|
||||
printf '%s\n' "active Go workspace: $gowork_value" >&2
|
||||
return 1
|
||||
;;
|
||||
esac
|
||||
|
||||
test -z "$(git ls-files go.work go.work.sum)"
|
||||
test ! -e vendor
|
||||
if grep -Eq '^[[:space:]]*replace([[:space:]]|\()' go.mod
|
||||
then
|
||||
printf '%s\n' 'go.mod contains a replacement' >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
test -s "$RELEASE_NOTE"
|
||||
grep -Fx "# Weatherreporter $RELEASE_VERSION" "$RELEASE_NOTE"
|
||||
|
||||
git fetch origin main --tags
|
||||
test "$RELEASE_COMMIT" = \
|
||||
"$(git rev-parse --verify 'refs/remotes/origin/main^{commit}')"
|
||||
|
||||
if git show-ref --verify --quiet "refs/tags/$RELEASE_VERSION"
|
||||
then
|
||||
printf '%s\n' "local tag already exists: $RELEASE_VERSION" >&2
|
||||
return 1
|
||||
fi
|
||||
if test -n "$(
|
||||
git ls-remote --tags origin \
|
||||
"refs/tags/$RELEASE_VERSION" \
|
||||
"refs/tags/$RELEASE_VERSION^{}"
|
||||
)"
|
||||
then
|
||||
printf '%s\n' "remote tag already exists: $RELEASE_VERSION" >&2
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
check_release_candidate
|
||||
```
|
||||
|
||||
Create a lightweight tag, matching Weatherreporter's existing release tags,
|
||||
and bind it explicitly to the guarded commit:
|
||||
|
||||
```sh
|
||||
git tag "$RELEASE_VERSION" "$RELEASE_COMMIT"
|
||||
test "$(git cat-file -t "refs/tags/$RELEASE_VERSION")" = commit
|
||||
test "$(git rev-parse --verify "refs/tags/$RELEASE_VERSION^{commit}")" = \
|
||||
"$RELEASE_COMMIT"
|
||||
git show --no-patch --decorate "refs/tags/$RELEASE_VERSION"
|
||||
```
|
||||
|
||||
If inspection finds an error, delete the unpublished local tag, correct the
|
||||
candidate, and repeat the procedure. Once the tag is pushed, it is immutable.
|
||||
|
||||
## Publish And Verify The Release
|
||||
|
||||
Push only the selected tag ref. Do not use `git push --tags`:
|
||||
|
||||
```sh
|
||||
git push origin \
|
||||
"refs/tags/$RELEASE_VERSION:refs/tags/$RELEASE_VERSION"
|
||||
```
|
||||
|
||||
The tag event starts the release pipeline. Its validation step rejects a
|
||||
non-stable semantic tag, a missing release note, module or repository hygiene
|
||||
violations, and any failing test, race test, vet, build, module-tidiness,
|
||||
formatting, or whitespace check. Its build step also verifies that the host
|
||||
binary reports `weatherreporter $RELEASE_VERSION`.
|
||||
|
||||
Wait for the pipeline to succeed, then confirm that the Gitea release:
|
||||
|
||||
- targets `RELEASE_COMMIT` through `RELEASE_VERSION`;
|
||||
- is titled `Weatherreporter $RELEASE_VERSION`;
|
||||
- uses `RELEASE_NOTE` from the tagged commit as its body;
|
||||
- contains `SHA256SUMS`; and
|
||||
- contains Linux, macOS, and Windows binaries for both `amd64` and `arm64`,
|
||||
named `weatherreporter-$RELEASE_VERSION-<os>-<arch>` with `.exe` on Windows.
|
||||
|
||||
Compare the remote tag with the guarded commit:
|
||||
|
||||
```sh
|
||||
remote_commit=$(
|
||||
git ls-remote --tags origin "refs/tags/$RELEASE_VERSION" |
|
||||
awk 'NR == 1 { print $1 }'
|
||||
)
|
||||
test "$remote_commit" = "$RELEASE_COMMIT"
|
||||
```
|
||||
|
||||
Download `SHA256SUMS` and every release binary into a new temporary directory,
|
||||
run `sha256sum --check SHA256SUMS`, and execute the binary for the maintainer's
|
||||
host platform with `--version`. It must print exactly:
|
||||
|
||||
```text
|
||||
weatherreporter vMAJOR.MINOR.PATCH
|
||||
```
|
||||
|
||||
## Failed Publication And Corrections
|
||||
|
||||
If the tag pipeline fails after publication, preserve the tag and diagnose the
|
||||
failure from the pipeline logs. Fix the cause on `main`, select a new patch
|
||||
version, prepare a new release note, and repeat the complete procedure. Do not
|
||||
move or recreate the failed published tag.
|
||||
|
||||
Do not manually edit an automatically generated Gitea release or republish its
|
||||
assets. A wording-only correction may be committed to the historical document
|
||||
on `main`, with an explicit correction note, but it does not alter the file at
|
||||
the tag or the generated release. Publish a new patch release when the error is
|
||||
material to installation, compatibility, security, or operation.
|
||||
140
docs/releases/v0.10.0.md
Normal file
140
docs/releases/v0.10.0.md
Normal file
@@ -0,0 +1,140 @@
|
||||
# Weatherreporter v0.10.0
|
||||
|
||||
Weatherreporter `v0.10.0` makes report execution stateless, adds stable
|
||||
weather-specific Promptkit profiles, and turns every successful generation
|
||||
into one atomic operator-owned Markdown output.
|
||||
|
||||
## Summary
|
||||
|
||||
- Ordinary generation no longer creates or depends on a managed workspace,
|
||||
historical run artifacts, metadata, receipts, or prior snapshots.
|
||||
- `generate` and `run` now publish directly to operator-selected paths, with
|
||||
useful current-directory defaults when output flags are omitted.
|
||||
- Local Recent Changes comparison and the historical `inspect` command family
|
||||
have been removed.
|
||||
- Promptkit `v0.5.0` and three embedded logical profiles provide a stable model
|
||||
ladder with complete file- or directory-based overrides.
|
||||
- Prompt input and generated-text contracts have been tightened, and output,
|
||||
cancellation, batch preflight, notification, and partial-failure behavior
|
||||
have focused offline coverage.
|
||||
|
||||
## Compatibility
|
||||
|
||||
This pre-`v1` minor release intentionally breaks CLI, configuration,
|
||||
prompt-input, action-summary, and workspace contracts from `v0.9.0`.
|
||||
|
||||
- The `workspace:` and `recent_change:` configuration sections are no longer
|
||||
supported. Strict configuration loading rejects them.
|
||||
- The `inspect reports`, `inspect metadata`, `inspect modules`,
|
||||
`inspect data-package`, `inspect prior`, and `inspect sources` commands have
|
||||
been removed. Weatherreporter no longer reads V1 or V2 run metadata or other
|
||||
historical workspace artifacts.
|
||||
- Every successful `generate` writes exactly one Markdown file. Without
|
||||
`--out`, Daily writes `daily-YYYY-MM-DD.md` and Today, Tomorrow, and Hourly
|
||||
write `today.md`, `tomorrow.md`, and `hourly.md` in the invocation's current
|
||||
directory. `--out` selects that file rather than creating an extra copy of a
|
||||
separately managed report.
|
||||
- `run` writes selected outputs beneath the current directory unless
|
||||
`--out-dir` selects another directory. Successful items remain available
|
||||
when another batch item fails.
|
||||
- Action summaries no longer expose managed report, metadata, snapshot, data
|
||||
package, prompt preparation, prompt execution, generated-text, render-context,
|
||||
or notification-receipt paths. They retain the final `outputPath`, optional
|
||||
`llmDebugPath`, safe effective profile/backend/model details, validation,
|
||||
warnings, notification status, and safe errors.
|
||||
- Batch report items no longer contain per-report notification fields. Batch
|
||||
notification is represented once at the top level. The `total`, `succeeded`,
|
||||
and `failed` counters describe reports only, so notification failure can
|
||||
produce a failed action while `failed` remains `0`.
|
||||
- The prompt data package advances from `weatherreporter.data_package.v3` to
|
||||
`weatherreporter.data_package.v4` and removes `recent_changes`. All four
|
||||
embedded prompts advance from `1.1.0` to `2.0.0`.
|
||||
- Generated-text schemas now require string-valued `precipitation_timing`; the
|
||||
model returns an empty string when there is no timing text. The unused
|
||||
`confidence` field has been removed and is rejected as an unknown field.
|
||||
|
||||
Existing operator-owned Markdown files remain valid. Existing workspace trees
|
||||
are ignored rather than migrated or deleted. Distributor continues to receive
|
||||
the completed Markdown report, but its source is now the selected operator
|
||||
output rather than a managed report copy.
|
||||
|
||||
## Upgrade
|
||||
|
||||
Before replacing `v0.9.0`:
|
||||
|
||||
1. Remove `workspace:` and `recent_change:` from configuration files.
|
||||
2. Give scheduled commands a predictable working directory or explicit
|
||||
`--out` or `--out-dir` destination. Confirm that these selected files may be
|
||||
atomically replaced on later successful runs.
|
||||
3. Remove historical `inspect` invocations and update action-summary consumers
|
||||
to use `outputPath` and the remaining active-workflow fields.
|
||||
4. Decide whether old workspace contents have any external retention value.
|
||||
Weatherreporter no longer reads them; after review, they may be removed
|
||||
manually using the narrowly scoped procedure in the operations guide.
|
||||
5. Review Promptkit profile selection and credentials. Hourly defaults to
|
||||
`weather-light`; Daily, Today, and Tomorrow default to `weather-balanced`.
|
||||
A configured `promptkit.profile` still overrides every report in one action.
|
||||
|
||||
The embedded logical profiles are:
|
||||
|
||||
| Profile | OpenRouter model | Default use |
|
||||
| --- | --- | --- |
|
||||
| `weather-light` | `deepseek/deepseek-v4-flash` | Hourly |
|
||||
| `weather-balanced` | `~google/gemini-flash-latest` | Daily, Today, Tomorrow |
|
||||
| `weather-deep` | `~anthropic/claude-sonnet-latest` | Explicit selection |
|
||||
|
||||
Override a complete same-ID definition through `promptkit.profile_file` or
|
||||
`promptkit.profile_dir` to use different models or a local OpenAI-compatible
|
||||
endpoint. Definitions are replaced rather than field-merged, and a malformed
|
||||
matching override fails instead of silently falling back.
|
||||
|
||||
See the [CLI reference](../cli.md), [configuration
|
||||
reference](../config.md), [operations guide](../operations.md), and [Promptkit
|
||||
integration](../integrations/promptkit.md) for the exact current contracts.
|
||||
|
||||
## Changes
|
||||
|
||||
### Stateless Execution And Operator-Owned Outputs
|
||||
|
||||
- Removed local forecast-change comparison, prior-snapshot selection, durable
|
||||
module and prompt artifacts, managed reports, metadata compatibility, run
|
||||
discovery, notification receipts, and the complete `internal/state`
|
||||
subsystem.
|
||||
- Added an Accepted architecture decision recording the stateless
|
||||
transformation pipeline and operator-owned output boundary.
|
||||
- Kept weather, facts, modules, prompt input, generated text, and render context
|
||||
in memory during ordinary execution.
|
||||
- Made output publication atomic and ensured cancellation or deadline expiry
|
||||
observed before publication leaves an existing destination unchanged.
|
||||
- Added complete batch-destination preflight before the first report prompt,
|
||||
so a structural collision cannot leave an unreported partial batch.
|
||||
- Preserved successful outputs after report or Distributor failure. Batch
|
||||
notification runs only after every selected report succeeds.
|
||||
|
||||
### Promptkit Profiles And Prompt Contracts
|
||||
|
||||
- Upgraded Promptkit from `v0.4.0` to `v0.5.0`.
|
||||
- Added embedded `weather-light`, `weather-balanced`, and `weather-deep`
|
||||
profiles and mapped each exact prompt to its logical default.
|
||||
- Added embedded-profile fallback after configured `profile_file` or
|
||||
`profile_dir` lookup, allowing operators to replace a logical profile without
|
||||
changing report definitions.
|
||||
- Added a maintained local-endpoint example for replacing `weather-light`.
|
||||
- Advanced the four prompt definitions to `2.0.0` and the curated data package
|
||||
to v4 after removing Recent Changes.
|
||||
- Required `precipitation_timing`, normalized whitespace-only timing to an
|
||||
empty string, and removed the unused confidence value.
|
||||
|
||||
### CLI, Reliability, Documentation, And Testing
|
||||
|
||||
- Simplified action summaries to active workflow identity, output, model,
|
||||
validation, warning, debug, notification, and safe error information.
|
||||
- Made batch counters report-only while retaining failed action status and
|
||||
non-zero exit behavior for batch notification failure.
|
||||
- Kept prompt and profile inspection ahead of weather collection and validated
|
||||
every batch candidate before collecting once.
|
||||
- Replaced state-oriented workflow fixtures with focused generation, batch,
|
||||
output, cancellation, profile-resolution, Distributor, and CLI coverage.
|
||||
- Reconciled user, operator, integration, internal, policy, and ADR
|
||||
documentation around the implemented stateless architecture and removed
|
||||
completed temporary roadmaps.
|
||||
33
docs/releases/v0.10.1.md
Normal file
33
docs/releases/v0.10.1.md
Normal file
@@ -0,0 +1,33 @@
|
||||
# Weatherreporter v0.10.1
|
||||
|
||||
This release repairs release validation after the `v0.10.0` pipeline failed in
|
||||
its privileged build container. Application behavior is unchanged from
|
||||
`v0.10.0`.
|
||||
|
||||
## Summary
|
||||
|
||||
The unreadable-secret configuration test now verifies that its process is
|
||||
actually subject to file permission bits before asserting that a mode-`000`
|
||||
file cannot be read. This keeps the test meaningful for ordinary users while
|
||||
allowing the release suite to run correctly in privileged containers.
|
||||
|
||||
## Compatibility
|
||||
|
||||
This patch release makes no changes to Weatherreporter's CLI, configuration,
|
||||
report output, integrations, prompts, profiles, or operating behavior. It is
|
||||
fully compatible with `v0.10.0`.
|
||||
|
||||
## Upgrade
|
||||
|
||||
No special operator action is required. Use `v0.10.1` in place of `v0.10.0`;
|
||||
the `v0.10.0` tag remains immutable, but its failed pipeline did not publish
|
||||
release binaries.
|
||||
|
||||
## Changes
|
||||
|
||||
- Made the unreadable-secret test capability-aware when the test process can
|
||||
bypass filesystem permission bits.
|
||||
- Preserved the production contract that genuinely unreadable secret files
|
||||
fail configuration loading.
|
||||
- Restored portable release validation in Woodpecker's privileged Go
|
||||
container.
|
||||
37
docs/releases/v0.11.0.md
Normal file
37
docs/releases/v0.11.0.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# Weatherreporter v0.11.0
|
||||
|
||||
This release adds a configurable default publication directory for generated
|
||||
weather reports.
|
||||
|
||||
## Summary
|
||||
|
||||
Operators can now set `output.directory` once for both individual reports and
|
||||
scheduled batches. Explicit `--out` and `--out-dir` destinations continue to
|
||||
take precedence, while installations that omit the setting retain the existing
|
||||
current-directory behavior.
|
||||
|
||||
## Compatibility
|
||||
|
||||
This release is additive and compatible with `v0.10.1`. Existing configuration
|
||||
files, commands, report filenames, Promptkit behavior, and Distributor
|
||||
notification behavior remain valid and unchanged.
|
||||
|
||||
## Upgrade
|
||||
|
||||
No special action is required. To use the new default destination, configure
|
||||
`output.directory` as described in the [configuration
|
||||
reference](../config.md). Existing deployments may continue using the current
|
||||
working directory or explicit CLI output flags.
|
||||
|
||||
## Changes
|
||||
|
||||
- Added strict configuration loading and validation for the optional
|
||||
`output.directory` field.
|
||||
- Applied the configured directory consistently to `generate` and `run`, with
|
||||
explicit CLI destinations retaining highest precedence.
|
||||
- Preserved relative-path handling, absolute result paths, atomic publication,
|
||||
cancellation safety, and Distributor notification ordering.
|
||||
- Strengthened output preflight so existing non-directory paths, uninspectable
|
||||
paths, and dangling symlink components fail before expensive report work.
|
||||
- Updated the [CLI reference](../cli.md) and [operations
|
||||
guide](../operations.md) for the new destination-selection behavior.
|
||||
66
docs/releases/v0.12.0.md
Normal file
66
docs/releases/v0.12.0.md
Normal file
@@ -0,0 +1,66 @@
|
||||
# Weatherreporter v0.12.0
|
||||
|
||||
This release completes a repository-wide correctness, security, efficiency,
|
||||
test-durability, and documentation audit.
|
||||
|
||||
## Summary
|
||||
|
||||
Weatherreporter now applies stricter validation and bounded diagnostics across
|
||||
its configuration, weather collection, Promptkit, rendering, publication,
|
||||
comparison, and Distributor boundaries. Report preparation and execution carry
|
||||
one reconciled identity, independent weather sources are collected
|
||||
concurrently, and cancellation preserves completed report and comparison
|
||||
outcomes.
|
||||
|
||||
The release also removes obsolete compatibility surfaces and consolidates
|
||||
duplicated implementation and test policy without changing ordinary report
|
||||
commands or output identities.
|
||||
|
||||
## Compatibility
|
||||
|
||||
This release is compatible with `v0.11.0` for ordinary `generate`, `run`, and
|
||||
`compare` commands, configuration files, report filenames, comparison bundles,
|
||||
and Distributor integration.
|
||||
|
||||
Sensitive prompt-debug capture through `--llm-debug-dir` is now supported only
|
||||
on Unix hosts. Non-Unix hosts reject an explicit capture request before prompt
|
||||
inspection, weather collection, or provider execution because the required
|
||||
handle-relative, no-follow filesystem guarantees are unavailable there.
|
||||
|
||||
Several unused internal compatibility exports were removed. They were not part
|
||||
of the documented CLI, configuration, artifact, or integration contracts.
|
||||
|
||||
## Upgrade
|
||||
|
||||
No special action is required for ordinary installations. Operators who use
|
||||
`--llm-debug-dir` on Windows must run that diagnostic workflow on a Unix host.
|
||||
Review any automation that depended on undocumented internal Go APIs removed by
|
||||
this release.
|
||||
|
||||
## Changes
|
||||
|
||||
- Hardened configuration loading, source validation, secrets rollback,
|
||||
endpoint validation, HTTP diagnostics, generated-text limits, prompt-debug
|
||||
redaction, output publication, comparison replacement, and Distributor
|
||||
failure reporting.
|
||||
- Reconciled inspected, prepared, callback, and completed Promptkit identity
|
||||
and provenance before accepting generated content.
|
||||
- Preserved metric values, civil-day and daypart identity, overnight alerts,
|
||||
precipitation semantics, and Markdown structure across deterministic report
|
||||
preparation and rendering.
|
||||
- Collected independent Weather API sources concurrently and reused readiness
|
||||
data while retaining deterministic normalized results.
|
||||
- Preserved completed report and comparison failures independently from shared
|
||||
cancellation, stopped unfinished work, and skipped batch notification after
|
||||
cancellation or partial report failure.
|
||||
- Made secure prompt-debug traversal descriptor-relative on Unix and fail
|
||||
closed elsewhere. See the [operations
|
||||
guide](../operations.md#optional-prompt-debug-capture).
|
||||
- Strengthened default test portability and determinism, including
|
||||
capability-aware symbolic-link fixtures and platform-appropriate process
|
||||
signal coverage.
|
||||
- Removed obsolete compatibility helpers, duplicated test ownership, dormant
|
||||
persistence code, and completed audit and implementation roadmaps.
|
||||
- Updated the [architecture policy](../policy/architecture.md), [testing
|
||||
policy](../policy/testing.md), and focused internal guides to describe the
|
||||
implemented final state.
|
||||
134
docs/releases/v0.9.0.md
Normal file
134
docs/releases/v0.9.0.md
Normal file
@@ -0,0 +1,134 @@
|
||||
# Weatherreporter v0.9.0
|
||||
|
||||
Weatherreporter `v0.9.0` replaces its external Scriptorium execution path with
|
||||
an in-process Promptkit integration and makes prompt preparation, execution,
|
||||
validation, and failure artifacts first-class parts of each report run.
|
||||
|
||||
## Summary
|
||||
|
||||
- Promptkit `v0.4.0` now executes all generated text for Daily, Today,
|
||||
Tomorrow, and Hourly reports.
|
||||
- The four exact-version prompts and their JSON Schemas are embedded in the
|
||||
Weatherreporter binary.
|
||||
- Prompt preparation and execution have separate durable, redacted provenance
|
||||
records, while sensitive prompt debugging is explicit and stored outside the
|
||||
managed workspace.
|
||||
- Weather API collection now performs a warmup request and retries transient
|
||||
transport, read, and selected HTTP failures.
|
||||
- Release binaries now report their embedded version and are published with
|
||||
checksums through a guarded Woodpecker pipeline.
|
||||
|
||||
## Compatibility
|
||||
|
||||
This pre-`v1` minor release contains intentional configuration, CLI, and
|
||||
artifact changes that require review when upgrading from `v0.8.0`.
|
||||
|
||||
- The `scriptorium:` configuration section is no longer supported. A file that
|
||||
contains it fails with a migration error instead of silently ignoring it.
|
||||
Use `promptkit:` configuration instead.
|
||||
- The previously exposed but unfinished three-day, weekend, and storm report
|
||||
surfaces have been removed. Supported report IDs and `generate` commands are
|
||||
`daily`, `today`, `tomorrow`, and `hourly`. The retired `storm_id`
|
||||
Distributor template variable is also no longer accepted.
|
||||
- Generate and batch result items now expose `preparationPath` and
|
||||
`executionPath` instead of the Scriptorium-oriented `preflightPath` and
|
||||
`generatedTextResultPath`. An opt-in prompt capture may also add
|
||||
`llmDebugPath`.
|
||||
- New runs write `weatherreporter.metadata.v2`, which records Promptkit
|
||||
preparation and execution paths. Inspection and prior-run lookup continue to
|
||||
read existing `weatherreporter.metadata.v1` records.
|
||||
- The built-in `weather_api.precision` default changed from `1` to `0`.
|
||||
Configurations that explicitly set a value retain that value.
|
||||
- Report prose may differ because the embedded prompt corpus, structured
|
||||
output path, alert presentation, and SPC background context have changed.
|
||||
|
||||
The documented Go version remains 1.26. Distributor integration remains at
|
||||
`v0.5.0`. Existing managed workspaces do not require conversion.
|
||||
|
||||
## Upgrade
|
||||
|
||||
Replace the old Scriptorium block in the Weatherreporter configuration. The
|
||||
smallest equivalent Promptkit block is:
|
||||
|
||||
```yaml
|
||||
promptkit:
|
||||
timeout: 2m
|
||||
```
|
||||
|
||||
The embedded prompts default to the Promptkit `gemini-flash-latest` profile.
|
||||
Ensure that the selected profile's credential environment variable is present,
|
||||
or configure `promptkit.profile`, an external `profile_file` or `profile_dir`,
|
||||
or the optional `promptkit.local` backend. Direct per-request API keys are not
|
||||
supported by Weatherreporter.
|
||||
|
||||
Before upgrading automation or downstream processing:
|
||||
|
||||
1. remove any `three-day`, `weekend`, or `storm` command, report override, and
|
||||
`storm_id` template usage;
|
||||
2. update consumers of action-summary JSON to use the new preparation and
|
||||
execution path fields;
|
||||
3. decide whether to retain the new precision default or explicitly configure
|
||||
the previous value; and
|
||||
4. preserve the existing workspace if historical V1 runs must remain
|
||||
inspectable.
|
||||
|
||||
Scriptorium, its executable configuration, and its external prompt corpus are
|
||||
no longer needed by Weatherreporter. See the
|
||||
[configuration reference](../config.md), [CLI reference](../cli.md), and
|
||||
[Promptkit integration](../integrations/promptkit.md) for the current
|
||||
contracts.
|
||||
|
||||
## Changes
|
||||
|
||||
### Prompt Execution And Artifacts
|
||||
|
||||
- Added a project-owned Promptkit adapter with exact prompt and profile
|
||||
inspection, prepare-once execution, error classification, and bounded
|
||||
execution timeouts.
|
||||
- Embedded version `1.0.0` of the Daily, Today, Tomorrow, and Hourly prompts and
|
||||
their private generated-text schemas.
|
||||
- Added durable preparation and execution receipts with prompt, profile,
|
||||
backend, model, hashes, timings, validation status, classified failures, and
|
||||
paths to every artifact reached during the run. Credentials, endpoints,
|
||||
rendered messages, request parameters, and generated content are excluded
|
||||
from these managed records.
|
||||
- Added `--llm-debug-dir` for explicitly requested content-rich diagnostics.
|
||||
Debug output must use an absolute path outside the managed workspace and is
|
||||
written with restrictive filesystem permissions.
|
||||
- Preflight now validates each exact prompt and selected profile before weather
|
||||
collection. Batch execution validates every candidate first, collects once,
|
||||
and retains independent report progress and failure artifacts.
|
||||
|
||||
See the [operations guide](../operations.md) for artifact layout, inspection,
|
||||
debug handling, and recovery.
|
||||
|
||||
### Weather Collection And Report Content
|
||||
|
||||
- Added a `/conditions/current` warmup before source collection and automatic
|
||||
retry for transient transport and response-read failures and HTTP `408`,
|
||||
`429`, `500`, `502`, `503`, and `504` responses.
|
||||
- Changed the default upstream precision query value to `0`.
|
||||
- Added embedded background definitions for recognized SPC categorical,
|
||||
tornado, wind, and hail outlook products.
|
||||
- Made the Alert Digest more concise: alert descriptions are omitted, and an
|
||||
SPC-only digest is rendered only for Enhanced, Moderate, or High categorical
|
||||
risk.
|
||||
- Removed duplicated alert detail from the prompt-facing metadata module; the
|
||||
alert digest remains its single prompt-facing owner.
|
||||
|
||||
See the [Weather API integration](../integrations/weatherapi.md) for the request,
|
||||
retry, and response contract.
|
||||
|
||||
### CLI, Documentation, Testing, And Releases
|
||||
|
||||
- Added `weatherreporter --version`; tagged binaries report `v0.9.0`, while
|
||||
ordinary local builds report `development`.
|
||||
- Reworked CLI summaries and inspection coverage around the Promptkit artifact
|
||||
lifecycle and retained partial-result behavior.
|
||||
- Reorganized contributor, policy, user, operator, integration, template, and
|
||||
internal documentation around explicit canonical owners.
|
||||
- Added focused single-report, batch, CLI, Promptkit adapter, durable-state,
|
||||
and artifact-path coverage while simplifying orchestration internals.
|
||||
- Added guarded tag validation and reproducible release builds for Linux,
|
||||
macOS, and Windows on `amd64` and `arm64`, with SHA-256 checksums and
|
||||
changelog-backed Gitea releases.
|
||||
188
docs/roadmap/future.md
Normal file
188
docs/roadmap/future.md
Normal file
@@ -0,0 +1,188 @@
|
||||
# Future Roadmap
|
||||
|
||||
This roadmap contains future work only. Each section identifies its planning
|
||||
status; current behavior is documented outside `docs/roadmap/`.
|
||||
|
||||
## Upstream Forecast Change Product
|
||||
|
||||
Status: Proposed upstream feature request; unimplemented.
|
||||
|
||||
Weatherreporter's local Recent Changes feature was removed by the accepted
|
||||
[stateless execution decision](../adr/0001-stateless-execution.md). Forecast
|
||||
version history and comparison are better owned by the Weather API, where the
|
||||
underlying forecast issuances can be retained and compared consistently for
|
||||
all consumers.
|
||||
|
||||
A future Weather API feature should expose a structured change product with:
|
||||
|
||||
- explicit current and baseline forecast issuance timestamps or identifiers;
|
||||
- documented baseline selection, such as a requested comparison timestamp,
|
||||
preceding issuance, or fixed rolling period;
|
||||
- location, timezone, and half-open valid-period identity;
|
||||
- typed changed values with previous and current values and units;
|
||||
- stable change categories for temperature, precipitation probability and
|
||||
timing, wind gusts, alerts, and aggregate hazards;
|
||||
- an API-owned significance classification or enough structured information
|
||||
for a stateless consumer to apply a documented presentation threshold; and
|
||||
- deterministic ordering, missing-baseline behavior, and source metadata.
|
||||
|
||||
The API should compare forecast versions, not track a Weatherreporter client's
|
||||
"previous run." It should not require consumer identity, mutable cursors, or
|
||||
Weatherreporter-managed history. A missing baseline should be a normal empty
|
||||
result rather than an error.
|
||||
|
||||
Once a stable upstream contract exists, a separate Weatherreporter roadmap may
|
||||
reintroduce change commentary by collecting that product and mapping it into a
|
||||
curated prompt-facing module. There must be no local snapshot fallback. The
|
||||
ordinary Weatherreporter process must remain stateless, and the upstream
|
||||
feature should have deterministic fixtures before adoption.
|
||||
|
||||
## Automatic Storm Monitoring
|
||||
|
||||
Status: Proposed and unimplemented.
|
||||
|
||||
Storm reporting, whether manual or automatic, is unimplemented.
|
||||
|
||||
Possible direction:
|
||||
|
||||
1. Detect candidate storm events from alerts, forecast discussion, weather
|
||||
story context, hourly thresholds, and material forecast changes.
|
||||
2. Evaluate candidates through Promptkit or another narrow evaluator adapter.
|
||||
3. Keep any required storm lifecycle state in the upstream service or another
|
||||
explicitly designed external owner rather than silently reintroducing a
|
||||
Weatherreporter workspace.
|
||||
4. Generate or update a storm report only when a meaningful event is present.
|
||||
5. Suppress ordinary low-impact thunder or rain chances.
|
||||
|
||||
Possible lifecycle states:
|
||||
|
||||
- `none`
|
||||
- `monitoring`
|
||||
- `active_report`
|
||||
- `escalated`
|
||||
- `deescalating`
|
||||
- `resolved`
|
||||
|
||||
Before implementation, the design must preserve scheduled report behavior,
|
||||
inspectable evaluator failures, and fixture coverage for deterministic
|
||||
candidate detection.
|
||||
|
||||
## Future Report Types
|
||||
|
||||
Status: Proposed and unimplemented.
|
||||
|
||||
Possible future report types:
|
||||
|
||||
- a short-fuse planning report distinct from the implemented Hourly Report, if
|
||||
a separate product is needed
|
||||
- event-specific reports with stable event IDs
|
||||
- storm review or yesterday-style reports using historical observations
|
||||
- archive-focused report variants if generated report history becomes a
|
||||
first-class product
|
||||
|
||||
New reports should preserve the boundaries documented in the [report registry
|
||||
internals](../internal/report-registry.md).
|
||||
|
||||
## Future Modules
|
||||
|
||||
Status: Proposed and unimplemented.
|
||||
|
||||
Possible future modules:
|
||||
|
||||
- `hourly_table` for compact valid-period hourly facts
|
||||
- `forecast_delta` after an upstream forecast-change product exists
|
||||
- `weekend_planning` if weekend-specific planning guidance needs a dedicated
|
||||
deterministic stanza
|
||||
- `storm_window_summary` if manual or automatic storm reports need a dedicated
|
||||
prompt-facing storm-window module
|
||||
- separate AFD section aliases, such as `afd_key_messages`,
|
||||
`afd_short_term_text`, and `afd_long_term_text`, if separate stanzas prove
|
||||
more useful than `area_forecast_discussion.options.sections`
|
||||
- SPC, radar, QPF, snow/rain total, or historical-observation modules once
|
||||
upstream sources and report requirements exist
|
||||
|
||||
QPF fields such as `measurable_qpf_total_in` and `max_hourly_qpf_in` should
|
||||
remain omitted until a real upstream quantitative precipitation source is
|
||||
represented in `CollectedFacts`.
|
||||
|
||||
Future module work should preserve the boundaries documented in [fact
|
||||
contracts](../internal/facts.md), [module internals](../internal/module.md), and
|
||||
[briefing internals](../internal/briefing.md):
|
||||
|
||||
- keep upstream collection in app orchestration
|
||||
- keep upstream collection out of modules
|
||||
- keep broad reusable calculations in `DerivedFacts`
|
||||
- keep prompt-facing field shape inside module builders
|
||||
- use typed options for configurable module behavior
|
||||
- keep module output structured and deterministic
|
||||
|
||||
## Distributor Notification Enhancements
|
||||
|
||||
Status: Proposed and unimplemented.
|
||||
|
||||
Single-report and batch Distributor notification are implemented. Current
|
||||
behavior is documented in the [Distributor adapter guide](../internal/distributor-adapter.md),
|
||||
[Distributor integration guides](../integrations/distributor/), and
|
||||
[operations guide](../operations.md). The following enhancements remain
|
||||
unimplemented:
|
||||
|
||||
- `failure_policy: warn`
|
||||
- durable upload retry queues
|
||||
- distributor-specific CLI flags
|
||||
- destination routing, Markdown-to-HTML transformation, public URLs, or nginx
|
||||
layout inside weatherreporter
|
||||
|
||||
Any distributor enhancement should preserve the adapter boundary:
|
||||
weatherreporter selects explicit generated files and submits source bundles,
|
||||
while distributor owns destination routing and publication behavior.
|
||||
|
||||
## Comparison Profile Diagnostics
|
||||
|
||||
Status: Proposed and unimplemented.
|
||||
|
||||
Comparison preflight failures could identify the profile being inspected and
|
||||
preserve a safe, actionable Promptkit cause, such as a duplicate profile ID,
|
||||
instead of reporting only a generic `profile_load` failure. Any improvement
|
||||
must continue to omit credentials, endpoints, and other sensitive profile
|
||||
values. Regression coverage should include a comparison that mixes built-in
|
||||
and configured-directory profiles and a directory containing duplicate IDs.
|
||||
|
||||
## Alternate Runtime Integrations
|
||||
|
||||
Status: Proposed and unimplemented.
|
||||
|
||||
These ideas remain unimplemented:
|
||||
|
||||
- native LLM client inside `weatherreporter`
|
||||
- database-backed state
|
||||
- public HTTP API
|
||||
- multi-location selection
|
||||
- daemon mode
|
||||
- multi-user authorization
|
||||
- plugin system
|
||||
- dynamic module loading
|
||||
- user-defined module code
|
||||
- YAML-defined module schemas
|
||||
- module-owned Weather API fetching
|
||||
|
||||
Each item needs its own design note before implementation. Non-roadmap docs
|
||||
must not describe these as available behavior.
|
||||
|
||||
## Deferred Refactors
|
||||
|
||||
Status: Deferred.
|
||||
|
||||
These refactors should remain deferred until new requirements or recurring
|
||||
maintenance costs make the added abstraction worthwhile:
|
||||
|
||||
- broad briefing weather-signal consolidation
|
||||
- generic workflow engine
|
||||
- Cobra migration
|
||||
- manifest, resume, or progress system
|
||||
- global test helper package
|
||||
- logging subsystem
|
||||
|
||||
Any future implementation should preserve the public CLI, report-output
|
||||
contract, report identities, module boundaries, and adapter boundaries in
|
||||
effect when that work begins unless a separate roadmap explicitly changes
|
||||
them.
|
||||
File diff suppressed because it is too large
Load Diff
184
docs/templates.md
Normal file
184
docs/templates.md
Normal file
@@ -0,0 +1,184 @@
|
||||
# Report Templates
|
||||
|
||||
This guide is for maintainers editing Weatherreporter's embedded Markdown
|
||||
templates. Templates format already validated report inputs; they do not select
|
||||
sources, derive weather facts, or validate generated prose. For those details,
|
||||
see [Generated Text internals](internal/generatedtext.md) and [Report Template
|
||||
internals](internal/reporttemplate.md).
|
||||
|
||||
## Template Assets
|
||||
|
||||
Only the generated-text reports use repository-native Markdown templates.
|
||||
Each report has one matching template ID, generated-text schema ID, and prompt
|
||||
source:
|
||||
|
||||
| Report | Template | Schema | Prompt ID and source |
|
||||
| --- | --- | --- | --- |
|
||||
| Daily | `templates/daily.md.tmpl` (`daily`) | `daily` | `weather.daily_generated_text`; `internal/promptassets/assets/prompts/daily/` |
|
||||
| Today | `templates/today.md.tmpl` (`today`) | `today` | `weather.today_generated_text`; `internal/promptassets/assets/prompts/today/` |
|
||||
| Tomorrow | `templates/tomorrow.md.tmpl` (`tomorrow`) | `tomorrow` | `weather.tomorrow_generated_text`; `internal/promptassets/assets/prompts/tomorrow/` |
|
||||
| Hourly | `templates/hourly.md.tmpl` (`hourly`) | `hourly` | `weather.hourly_generated_text`; `internal/promptassets/assets/prompts/hourly/` |
|
||||
|
||||
The matching schemas and Promptkit definitions are embedded by
|
||||
`internal/promptassets`. The generated-text catalog requires each report's
|
||||
exact schema/template pair; keep the matching prompt definition aligned with
|
||||
that report-specific triple.
|
||||
|
||||
Shared partials are under `internal/reporttemplate/templates/partials/`:
|
||||
|
||||
| Partial | Used by |
|
||||
| --- | --- |
|
||||
| `alert_digest.md.tmpl` | Daily, Today, Tomorrow, and Hourly |
|
||||
| `precipitation_timing.md.tmpl` | Daily, Today, Tomorrow, and Hourly |
|
||||
| `daypart_forecast.md.tmpl` | Daily and Tomorrow |
|
||||
| `today_daypart_forecast.md.tmpl` | Today |
|
||||
|
||||
All shared partials are parsed whenever any top-level template is rendered. A
|
||||
syntax error in a partial can therefore prevent every generated-text report
|
||||
from rendering.
|
||||
|
||||
## Editing Rules
|
||||
|
||||
- Use Go `text/template` syntax and keep changes to Markdown structure,
|
||||
ordering, and display conditions.
|
||||
- Templates use `missingkey=error`; reference only documented fields and guard
|
||||
optional module pointers with `with` or `if`.
|
||||
- Prefer `.Modules` for deterministic display values. Do not add weather
|
||||
calculations, source selection, or prompt-input shaping to a template.
|
||||
- Keep generated prose in `.GeneratedText`; do not restate deterministic facts
|
||||
in generated prose merely to compensate for a template change.
|
||||
- Render every `.GeneratedText` value through `plainText`. It preserves prose
|
||||
and paragraph breaks while escaping Markdown and HTML syntax, removing code
|
||||
indentation, and replacing control characters. Never interpolate generated
|
||||
prose directly: repository templates alone own headings, lists, links, and
|
||||
other Markdown structure.
|
||||
- When changing the generated-prose contract, update the matching prompt,
|
||||
schema, validator, render context, and template together. The validation and
|
||||
catalog rules are owned by [Generated Text internals](internal/generatedtext.md).
|
||||
- Use `.Modules.Dayparts` for ordered daypart output. Do not range over
|
||||
`.Modules.DerivedDaypartSummaries`, which is a map. The Today partial uses
|
||||
`.Modules.HasDaypartDetails` to ensure its heading has either rows or the
|
||||
explicit no-details fallback.
|
||||
|
||||
Minimal optional-value pattern:
|
||||
|
||||
```gotemplate
|
||||
{{ with .Modules.CurrentConditions }}
|
||||
Currently, it is {{ with .TemperatureF }}{{ . }}°F{{ end }}.
|
||||
{{ else }}
|
||||
Current conditions are unavailable.
|
||||
{{ end }}
|
||||
```
|
||||
|
||||
Minimal list pattern:
|
||||
|
||||
```gotemplate
|
||||
{{ range .GeneratedText.ForecastDiscussion }}
|
||||
{{ plainText . }}
|
||||
{{ end }}
|
||||
```
|
||||
|
||||
## Registered Functions
|
||||
|
||||
Templates have these helpers in addition to Go template built-ins:
|
||||
|
||||
| Function | Accepts | Returns true when |
|
||||
| --- | --- | --- |
|
||||
| `hasRelevantAlerts` | an alert-digest value or pointer | its `Relevant` slice is nonempty |
|
||||
| `hasEnhancedOrHigherSPCRisk` | an SPC outlook value or pointer | its `RiskDigest` contains an Enhanced, Moderate, or High Risk entry |
|
||||
| `isEnhancedOrHigherSPCRisk` | one SPC risk-digest entry | its `LabelText`, or fallback `RiskLabel`, is Enhanced, Moderate, or High Risk |
|
||||
| `plainText` | a generated prose string | a readable plain-text rendering that preserves paragraph breaks without allowing dynamic Markdown or HTML structure |
|
||||
|
||||
For example, the alert partial uses the first two functions to decide whether
|
||||
to render the section:
|
||||
|
||||
```gotemplate
|
||||
{{ if hasRelevantAlerts .Modules.AlertDigest }}
|
||||
## Alert Digest
|
||||
{{ end }}
|
||||
```
|
||||
|
||||
## Render Context
|
||||
|
||||
Every rendered template receives one typed context with these three top-level
|
||||
fields:
|
||||
|
||||
| Field | Purpose |
|
||||
| --- | --- |
|
||||
| `.Report` | Display labels and canonical report timing metadata. |
|
||||
| `.GeneratedText` | Validated prose supplied by Promptkit. |
|
||||
| `.Modules` | Deterministic, typed values prepared for Markdown rendering. |
|
||||
|
||||
### Report Metadata
|
||||
|
||||
All contexts provide `.Report.Title`, `.Report.GeneratedAt`,
|
||||
`.Report.GeneratedAtLabel`, `.Report.ValidPeriod`, and `.Report.Timezone`.
|
||||
|
||||
Hourly additionally provides `.Report.LocationName` and
|
||||
`.Report.ValidPeriodLabel`.
|
||||
|
||||
Daily, Today, and Tomorrow additionally provide `.Report.ForecastDate`,
|
||||
`.Report.ForecastDateLabel`, and `.Report.ForecastDayName`. Their valid-period
|
||||
field remains canonical timing data; use the supplied display labels instead
|
||||
of formatting timestamps in a template.
|
||||
|
||||
### Validated GeneratedText Prose
|
||||
|
||||
GeneratedText is prose returned by Promptkit and validated before rendering.
|
||||
It is not a source for deterministic weather facts.
|
||||
|
||||
| Field | Hourly type | Daily, Today, and Tomorrow type | Notes |
|
||||
| --- | --- | --- | --- |
|
||||
| `.GeneratedText.Summary` | `string` | `string` | Required; at most 4,000 characters. |
|
||||
| `.GeneratedText.ForecastDiscussion` | `string` | `[]string` | Required; Hourly permits 12,000 characters. Day-style values permit up to 12 paragraphs of 4,000 characters each. |
|
||||
| `.GeneratedText.PrecipitationTiming` | `string` | `string` | Required field, at most 4,000 characters; an empty string represents no supported prose. The precipitation partial uses nonempty prose only when deterministic windows exist. |
|
||||
|
||||
The JSON schema rejects unknown properties and defines the required fields, but
|
||||
the schema body and validation behavior are documented in [Generated Text
|
||||
internals](internal/generatedtext.md). All validated generated prose together
|
||||
is limited to 20,000 characters, so template edits can rely on a bounded prose
|
||||
surface.
|
||||
|
||||
### Deterministic Module Values
|
||||
|
||||
Module values are deterministic outputs built from collected and derived facts.
|
||||
Module pointers can be nil when their source or policy permits omission.
|
||||
|
||||
| Module field | Available in |
|
||||
| --- | --- |
|
||||
| `.Modules.CurrentConditions`, `.Modules.HourlyForecast`, `.Modules.PrecipTiming`, `.Modules.AlertDigest`, `.Modules.SPCConvectiveOutlooks`, `.Modules.AreaForecastDiscussion`, `.Modules.SPCConvectiveDiscussion`, `.Modules.WeatherStory` | All four contexts |
|
||||
| `.Modules.DerivedDailySummary`, `.Modules.DerivedDaypartSummaries`, `.Modules.Dayparts` | Daily, Today, Tomorrow |
|
||||
| `.Modules.HasDaypartDetails` | Today |
|
||||
| `.Modules.OutdoorWindows`, `.Modules.DailyPlanning` | Daily |
|
||||
| `.Modules.TodayPlanning` | Today |
|
||||
| `.Modules.TomorrowPlanning` | Tomorrow |
|
||||
|
||||
The repository templates currently use the following nested display values.
|
||||
They are the preferred surface for comparable edits:
|
||||
|
||||
| Area | Values |
|
||||
| --- | --- |
|
||||
| Current conditions | `.TemperatureF`, `.ConditionText`, `.ConditionTextLower`, `.ApparentTemperatureF`, `.RelativeHumidityPercent`, `.WindDirectionText`, `.WindSpeedMph` |
|
||||
| Hourly periods | `.Periods`, `.HourLabel`, `.Name`, `.TemperatureF`, `.TextDescription`, `.TextDescriptionLower`, `.MentionPrecipitation`, `.ProbabilityOfPrecipitationPercent` |
|
||||
| Dayparts | `.Dayparts[].Key` and `.Dayparts[].Summary` fields `DisplayName`, `DominantCondition`, `DominantConditionDisplay`, `TemperatureTrend`, `TemperatureStartPhraseF`, `TemperatureEndPhraseF`, `TemperaturePeakPhraseF`, `TemperatureSteadyPhraseF`, `TemperaturePhraseF`, `MentionPrecipitation`, and `MaxPopPercent` |
|
||||
| Precipitation timing | `.PrecipitationWindows`, plus each window's `PeriodBegins`, `PeriodBeginsHourLabel`, `PeriodEnds`, `PeriodEndsHourLabel`, `ExpectationPhrase`, `MaxPopPercent`, `MaxPopTime`, and `MaxPopHourLabel` |
|
||||
| Alert digest | `.AlertDigest.Relevant` entries' `Event`, `Headline`, `PeriodBegins`, and `PeriodEnds` |
|
||||
| SPC risk digest | `.SPCConvectiveOutlooks.RiskDigest` entries' `LabelText`, `RiskLabel`, `PeriodBegins`, and `PeriodEnds` |
|
||||
|
||||
Other fields on these typed modules remain available when a template has a
|
||||
well-defined display need. Their module contracts and weather derivation belong
|
||||
to [Module contract internals](internal/module.md), [Module builder
|
||||
internals](internal/briefing.md), and [Forecast derivation
|
||||
internals](internal/forecast-derivation.md).
|
||||
|
||||
## Validate Changes
|
||||
|
||||
Run the focused checks after editing templates, partials, prompts, or schemas:
|
||||
|
||||
```sh
|
||||
go test ./internal/reporttemplate ./internal/generatedtext ./internal/app
|
||||
git diff --check
|
||||
```
|
||||
|
||||
The render-context and template tests cover Daily, Today, Tomorrow, and Hourly
|
||||
contexts. Run the repository-wide test suite before merging a broader change.
|
||||
123
examples/config.yml
Normal file
123
examples/config.yml
Normal file
@@ -0,0 +1,123 @@
|
||||
weather_api:
|
||||
base_url: https://weather.api.example.com/
|
||||
timeout: 15s
|
||||
precision: 0
|
||||
units: us
|
||||
timezone: "America/Chicago"
|
||||
format: json
|
||||
|
||||
location:
|
||||
id: home
|
||||
name: Brentwood
|
||||
region: St. Louis Metro
|
||||
|
||||
secrets:
|
||||
directory: ""
|
||||
|
||||
output:
|
||||
directory: /var/lib/weatherreporter/reports
|
||||
|
||||
notify:
|
||||
distributor:
|
||||
enabled: false
|
||||
endpoint: https://distributor.example.com
|
||||
token_env: DISTRIBUTOR_UPLOAD_TOKEN
|
||||
timeout: 30s
|
||||
failure_policy: error
|
||||
pipeline_id_template: "weatherreporter.{report_id}"
|
||||
bundle_id_template: "weatherreporter.{location_id}.{report_id}"
|
||||
idempotency_key_template: "{bundle_id}.{run_id}"
|
||||
batch:
|
||||
enabled: true
|
||||
pipeline_id_template: "weatherreporter"
|
||||
bundle_id_template: "weatherreporter.{location_id}.{batch}"
|
||||
idempotency_key_template: "{bundle_id}.{batch_run_id}"
|
||||
|
||||
missing_source:
|
||||
default: warn
|
||||
sources:
|
||||
alerts: none
|
||||
|
||||
promptkit:
|
||||
timeout: 2m
|
||||
local:
|
||||
concurrency_limit: 1
|
||||
|
||||
dayparts:
|
||||
- name: overnight
|
||||
start: "00:00"
|
||||
end: "06:00"
|
||||
- name: morning
|
||||
start: "06:00"
|
||||
end: "10:00"
|
||||
- name: midday
|
||||
start: "10:00"
|
||||
end: "15:00"
|
||||
- name: afternoon
|
||||
start: "15:00"
|
||||
end: "17:00"
|
||||
- name: evening
|
||||
start: "17:00"
|
||||
end: "24:00"
|
||||
|
||||
reports:
|
||||
daily:
|
||||
distributor:
|
||||
path_templates:
|
||||
- "daily/{valid_start_date}/{run_id}.md"
|
||||
- "daily/{valid_start_date}/index.md"
|
||||
deterministic_modules:
|
||||
- metadata
|
||||
- current_conditions
|
||||
- narrative_forecast
|
||||
- derived_daily_summary
|
||||
- derived_daypart_summaries
|
||||
- precip_timing
|
||||
- alert_digest
|
||||
- spc_convective_outlooks
|
||||
- id: area_forecast_discussion
|
||||
options:
|
||||
sections:
|
||||
- long_term
|
||||
- spc_convective_discussion
|
||||
- weather_story
|
||||
- outdoor_windows
|
||||
- daily_planning
|
||||
- hourly_forecast
|
||||
today:
|
||||
deterministic_modules:
|
||||
- metadata
|
||||
- current_conditions
|
||||
- narrative_forecast
|
||||
- derived_daily_summary
|
||||
- derived_daypart_summaries
|
||||
- precip_timing
|
||||
- alert_digest
|
||||
- spc_convective_outlooks
|
||||
- id: area_forecast_discussion
|
||||
options:
|
||||
sections:
|
||||
- product
|
||||
- key_messages
|
||||
- short_term
|
||||
- long_term
|
||||
- spc_convective_discussion
|
||||
- weather_story
|
||||
- outdoor_windows
|
||||
- hourly_forecast
|
||||
- today_planning
|
||||
hourly:
|
||||
deterministic_modules:
|
||||
- metadata
|
||||
- current_conditions
|
||||
- hourly_forecast
|
||||
- precip_timing
|
||||
- alert_digest
|
||||
- spc_convective_outlooks
|
||||
- id: area_forecast_discussion
|
||||
options:
|
||||
sections:
|
||||
- key_messages
|
||||
- short_term
|
||||
- spc_convective_discussion
|
||||
- weather_story
|
||||
2
examples/minimal-config.yml
Normal file
2
examples/minimal-config.yml
Normal file
@@ -0,0 +1,2 @@
|
||||
weather_api:
|
||||
base_url: https://weather.api.example.com/
|
||||
4
examples/weather-light-local-profile.yml
Normal file
4
examples/weather-light-local-profile.yml
Normal file
@@ -0,0 +1,4 @@
|
||||
id: weather-light
|
||||
endpoint: http://127.0.0.1:11434/v1
|
||||
model: weather-local
|
||||
timeout_seconds: 180
|
||||
14
go.mod
Normal file
14
go.mod
Normal file
@@ -0,0 +1,14 @@
|
||||
module gitea.maximumdirect.net/eric/weatherreporter
|
||||
|
||||
go 1.26
|
||||
|
||||
require gopkg.in/yaml.v3 v3.0.1
|
||||
|
||||
require (
|
||||
gitea.maximumdirect.net/eric/distributor v0.5.0
|
||||
gitea.maximumdirect.net/eric/promptkit v0.5.0
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2
|
||||
golang.org/x/sys v0.45.0
|
||||
)
|
||||
|
||||
require golang.org/x/text v0.14.0 // indirect
|
||||
60
go.sum
Normal file
60
go.sum
Normal file
@@ -0,0 +1,60 @@
|
||||
gitea.maximumdirect.net/eric/distributor v0.5.0 h1:+al7Bw+kMv6V35a3Sm5rUtCTQhwOn5b9x3RsclPMKJk=
|
||||
gitea.maximumdirect.net/eric/distributor v0.5.0/go.mod h1:G03FCFZPHpsUKC6SeMgTdbfNRpPQBdyTtDUj04e1Tu8=
|
||||
gitea.maximumdirect.net/eric/promptkit v0.5.0 h1:jnpazLyyNhWrB2xzwwtUkNUfktkTdkENTwuSPnKiYrc=
|
||||
gitea.maximumdirect.net/eric/promptkit v0.5.0/go.mod h1:R95NM6fbMDGDC0/UomgnSBP6ui2ns+8SZb8bESNvrDQ=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.9 h1:/rYeyO2+HrMztAmxAq9++XJtFMqSIpSsNA0yDGALYq4=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.9/go.mod h1:+HsoOEX80qAVUitj1A2DhCNTjmb3edVyuDypb6LNEeo=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 h1:h5+3VT69KUBK24grGuuA5saDJTj2IIjLb9au668Fo5I=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11/go.mod h1:dnakxebH6UwFvcvujL0LVggYQ8nEvBGjU4G/V79Nv94=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.20 h1:8VMDnWc/kEzxsI/1ngGM9mG81a8IGmIHD8KLcYGwagc=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.20/go.mod h1:PuwEpciweIXGULWeOeSTXtSbH4CW9mWdWrhdCKQI1sM=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.19 h1:yuFzSV1U0aRNYCQGVaTY2zW2M/L93pYHnXnrJUphYhU=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.19/go.mod h1:7y63L1kGzeoDlJaQ3Z578KrnmfBut96JjvJUzGwR+YE=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.25 h1:0w6dCiO8iez+YKwRhRBlL1CH/E3GTfdkuzrwj1by8vo=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.25/go.mod h1:9FDWUothyr5RCRAHc45XOiVCzUR8n/IhCYX+uVqw6vk=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.25 h1:Uii3frf9ztec/ABM2/FSH9/z7PLzxfpG8h4RpkUFflQ=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.25/go.mod h1:G6kntsA2GorAxDPbap6xgB2F+amSLUF8GJTi7PUoX44=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.25 h1:r1+/l6m+WaUJF9HISEsNOLHSNj5EXYQxK8VX6Cz9NlA=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.25/go.mod h1:cKf+D+NMDK1LndD7BowHbBZPgR9V0/5HubH0PFWvA+c=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.26 h1:A1PmWU2zfkIm9EyFlJncFXL4W4phML+h8KjltUsCvNQ=
|
||||
github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.26/go.mod h1:dY4MRzXEizrD4hqtpKvWVGPX7QleSGGVY+EBolo1RmM=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10 h1:d5/908OJ4bXg8lyjeMPvXetEKqoDoLi5Owy1zNue3yg=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.10/go.mod h1:a57l7Hwh+FWI+we50g5NPJHYUKeJKfXbc4w8SyXu8Ig=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18 h1:W/EyPFl9A5rXrtoilfwHYEvzHER+K4SpBPtMXi24Mos=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.18/go.mod h1:UG50K+pvd/uy6xExbobg0rjqFBFZe6I3l75EPDZw4tg=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.25 h1:dD3dhHNglpd98gs72my22Ndqi1hqQGllFFg1F+twfxg=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.25/go.mod h1:0yAbjPfd64gG7mj85RW+fMEYdfBgCRZw8g/oWcL1pjc=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25 h1:2pQEbwf+/6EDbiit/GcBE2K4IUpMZymaA0kOz3xK978=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.25/go.mod h1:KvT6NCcQ0EZ+ZkVRrlBMt04Po3ok23YELEp7WimhLhM=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2 h1:ie4ElCmUKS26pzrZcIk/lmt4yWjAqLLcawstyQCh298=
|
||||
github.com/aws/aws-sdk-go-v2/service/s3 v1.102.2/go.mod h1:zjsomFeX5duj+4PlMB+o4JoWTIx+G0XMyzjYrUbQkN0=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.1.1 h1:1VwbP3qMNfxUDEXWki4rCE5iA+44VA1lokTz9HasGzw=
|
||||
github.com/aws/aws-sdk-go-v2/service/signin v1.1.1/go.mod h1:vUtyoSj0OPji3kjIVSc/GlKuWEiL33f/WFxl6dmpy/A=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.19 h1:N6pIsdFOW1Kd9S4KyFKXdGRBojPPxkP32+uHFWLv4Hc=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.19/go.mod h1:3gt5WJArFooNmyLONS+h/R4J+o86II8du38IgCwj9dE=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.2 h1:hc+lBYiiTr8Zk4MTzIsQ92MeDWCIDvWGmzKUWOaBcOg=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.36.2/go.mod h1:hU6fqB3OJA6/ePheD47LQnxvjYk6br6PtQxs+Q9ojvk=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.42.3 h1:ErklX/7uhSbkAAeyQD/Y1OoQ9hO3SJXQNEgksORW3Js=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.42.3/go.mod h1:ULe4HCzfKPiR6R3HEurE3b1upEkuk8AkMrOKtaOxKO8=
|
||||
github.com/aws/smithy-go v1.26.0 h1:9ouqbi+NyKP7fV3Te7UElCwdAb6Y8uk7LGwPE5tVe/s=
|
||||
github.com/aws/smithy-go v1.26.0/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/dlclark/regexp2 v1.11.0 h1:G/nrcoOa7ZXlpoa/91N3X7mM3r8eIlMBBJZvsz/mxKI=
|
||||
github.com/dlclark/regexp2 v1.11.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
|
||||
github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8=
|
||||
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
|
||||
github.com/pkg/sftp v1.13.10 h1:+5FbKNTe5Z9aspU88DPIKJ9z2KZoaGCu6Sr6kKR/5mU=
|
||||
github.com/pkg/sftp v1.13.10/go.mod h1:bJ1a7uDhrX/4OII+agvy28lzRvQrmIQuaHrcI1HbeGA=
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ=
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
|
||||
github.com/yuin/goldmark v1.8.2 h1:kEGpgqJXdgbkhcOgBxkC0X0PmoPG1ZyoZ117rDVp4zE=
|
||||
github.com/yuin/goldmark v1.8.2/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
|
||||
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
|
||||
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
|
||||
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
|
||||
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
|
||||
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
458
internal/adapters/distributor/client.go
Normal file
458
internal/adapters/distributor/client.go
Normal file
@@ -0,0 +1,458 @@
|
||||
// Package distributor adapts weatherreporter report artifacts to distributor uploads.
|
||||
package distributor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
distributorbundle "gitea.maximumdirect.net/eric/distributor/pkg/bundle"
|
||||
distributorupload "gitea.maximumdirect.net/eric/distributor/pkg/upload"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/config"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
Endpoint string
|
||||
TokenEnv string
|
||||
Timeout time.Duration
|
||||
newUploadClient uploadClientFactory
|
||||
pollWait func(context.Context, time.Duration) error
|
||||
}
|
||||
|
||||
type UploadRequest struct {
|
||||
PipelineID string
|
||||
BundleID string
|
||||
IdempotencyKey string
|
||||
Files []UploadFile
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type UploadFile struct {
|
||||
SourcePath string
|
||||
BundlePath string
|
||||
}
|
||||
|
||||
type UploadResult struct {
|
||||
RunID string
|
||||
Status string
|
||||
UploadStatus string
|
||||
StatusError string
|
||||
RunStatus *RunStatus
|
||||
}
|
||||
|
||||
type RunStatus struct {
|
||||
RunID string
|
||||
PipelineID string
|
||||
Status string
|
||||
AcceptedAt time.Time
|
||||
StartedAt *time.Time
|
||||
FinishedAt *time.Time
|
||||
Report json.RawMessage
|
||||
Error string
|
||||
}
|
||||
|
||||
type IdempotencyConflictError struct {
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *IdempotencyConflictError) Error() string {
|
||||
if e == nil || e.Err == nil {
|
||||
return "distributor idempotency conflict"
|
||||
}
|
||||
return e.Err.Error()
|
||||
}
|
||||
|
||||
func (e *IdempotencyConflictError) Unwrap() error {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return e.Err
|
||||
}
|
||||
|
||||
type uploadClientFactory func(endpoint, token string, timeout time.Duration) (uploadClient, error)
|
||||
|
||||
type uploadClient interface {
|
||||
UploadFiles(ctx context.Context, opts uploadFilesOptions) (uploadFilesResult, error)
|
||||
Status(ctx context.Context, runID string) (runStatus, error)
|
||||
}
|
||||
|
||||
type uploadFilesOptions struct {
|
||||
PipelineID string
|
||||
BundleID string
|
||||
IdempotencyKey string
|
||||
Files []UploadFile
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type uploadFilesResult struct {
|
||||
RunID string
|
||||
Status string
|
||||
}
|
||||
|
||||
type runStatus struct {
|
||||
RunID string
|
||||
PipelineID string
|
||||
Status string
|
||||
AcceptedAt time.Time
|
||||
StartedAt *time.Time
|
||||
FinishedAt *time.Time
|
||||
Report json.RawMessage
|
||||
Error string
|
||||
}
|
||||
|
||||
const statusPollInterval = 250 * time.Millisecond
|
||||
|
||||
const maxDistributorResponseBytes int64 = 1 << 20
|
||||
|
||||
var errDistributorResponseTooLarge = fmt.Errorf("distributor response exceeds the %d-byte limit", maxDistributorResponseBytes)
|
||||
|
||||
func New(cfg config.DistributorNotifyConfig) *Client {
|
||||
return newClient(cfg, newDistributorUploadClient)
|
||||
}
|
||||
|
||||
func newClient(cfg config.DistributorNotifyConfig, factory uploadClientFactory) *Client {
|
||||
if factory == nil {
|
||||
factory = newDistributorUploadClient
|
||||
}
|
||||
return &Client{
|
||||
Endpoint: cfg.Endpoint,
|
||||
TokenEnv: cfg.TokenEnv,
|
||||
Timeout: cfg.Timeout,
|
||||
newUploadClient: factory,
|
||||
pollWait: waitForPoll,
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) Upload(ctx context.Context, req UploadRequest) (UploadResult, error) {
|
||||
if c == nil {
|
||||
return UploadResult{}, fmt.Errorf("distributor client is nil")
|
||||
}
|
||||
if c.Endpoint == "" {
|
||||
return UploadResult{}, fmt.Errorf("distributor endpoint is required")
|
||||
}
|
||||
if c.TokenEnv == "" {
|
||||
return UploadResult{}, fmt.Errorf("distributor token environment variable is required")
|
||||
}
|
||||
if req.PipelineID == "" {
|
||||
return UploadResult{}, fmt.Errorf("distributor pipeline id is required")
|
||||
}
|
||||
if req.BundleID == "" {
|
||||
return UploadResult{}, fmt.Errorf("distributor bundle id is required")
|
||||
}
|
||||
if req.IdempotencyKey == "" {
|
||||
return UploadResult{}, fmt.Errorf("distributor idempotency key is required for bundle %q", req.BundleID)
|
||||
}
|
||||
if len(req.Files) == 0 {
|
||||
return UploadResult{}, fmt.Errorf("distributor upload files are required for bundle %q", req.BundleID)
|
||||
}
|
||||
for i, file := range req.Files {
|
||||
if file.SourcePath == "" {
|
||||
return UploadResult{}, fmt.Errorf("distributor source path is required for bundle %q file %d", req.BundleID, i)
|
||||
}
|
||||
if file.BundlePath == "" {
|
||||
return UploadResult{}, fmt.Errorf("distributor bundle path is required for bundle %q file %d", req.BundleID, i)
|
||||
}
|
||||
}
|
||||
if c.newUploadClient == nil {
|
||||
return UploadResult{}, fmt.Errorf("distributor upload client factory is required for endpoint %q", c.Endpoint)
|
||||
}
|
||||
|
||||
token := os.Getenv(c.TokenEnv)
|
||||
if token == "" {
|
||||
return UploadResult{}, fmt.Errorf("distributor token environment variable %q is not set", c.TokenEnv)
|
||||
}
|
||||
|
||||
uploadClient, err := c.newUploadClient(c.Endpoint, token, c.Timeout)
|
||||
if err != nil {
|
||||
return UploadResult{}, fmt.Errorf("create distributor upload client for endpoint %q: %w", c.Endpoint, redactToken(err, token))
|
||||
}
|
||||
|
||||
runCtx := ctx
|
||||
if runCtx == nil {
|
||||
runCtx = context.Background()
|
||||
}
|
||||
cancel := func() {}
|
||||
if c.Timeout > 0 {
|
||||
runCtx, cancel = context.WithTimeout(runCtx, c.Timeout)
|
||||
}
|
||||
defer cancel()
|
||||
|
||||
result, err := uploadClient.UploadFiles(runCtx, uploadFilesOptions{
|
||||
PipelineID: req.PipelineID,
|
||||
BundleID: req.BundleID,
|
||||
IdempotencyKey: req.IdempotencyKey,
|
||||
Files: append([]UploadFile(nil), req.Files...),
|
||||
CreatedAt: req.CreatedAt,
|
||||
})
|
||||
if err != nil {
|
||||
return UploadResult{}, wrapUploadError(err, uploadErrorContext{
|
||||
Endpoint: c.Endpoint,
|
||||
PipelineID: req.PipelineID,
|
||||
BundleID: req.BundleID,
|
||||
IdempotencyKey: req.IdempotencyKey,
|
||||
SourcePaths: uploadSourcePaths(req.Files),
|
||||
BundlePaths: uploadBundlePaths(req.Files),
|
||||
Token: token,
|
||||
})
|
||||
}
|
||||
|
||||
uploadResult := UploadResult{
|
||||
RunID: result.RunID,
|
||||
Status: result.Status,
|
||||
UploadStatus: result.Status,
|
||||
}
|
||||
pollWait := c.pollWait
|
||||
if pollWait == nil {
|
||||
pollWait = waitForPoll
|
||||
}
|
||||
status, statusErr := waitForRunStatus(runCtx, uploadClient, result.RunID, c.Timeout > 0, pollWait)
|
||||
status = sanitizeRunStatus(status)
|
||||
if status.RunID != "" || status.Status != "" {
|
||||
uploadResult.RunStatus = &RunStatus{
|
||||
RunID: status.RunID,
|
||||
PipelineID: status.PipelineID,
|
||||
Status: status.Status,
|
||||
AcceptedAt: status.AcceptedAt,
|
||||
StartedAt: status.StartedAt,
|
||||
FinishedAt: status.FinishedAt,
|
||||
Report: append(json.RawMessage(nil), status.Report...),
|
||||
Error: redactTokenString(status.Error, token),
|
||||
}
|
||||
if status.Status != "" {
|
||||
uploadResult.Status = status.Status
|
||||
}
|
||||
}
|
||||
if statusErr != nil {
|
||||
uploadResult.StatusError = safeDistributorDiagnostic(statusErr, token).Error()
|
||||
return uploadResult, nil
|
||||
}
|
||||
if status.Status == "failed" {
|
||||
return uploadResult, fmt.Errorf("distributor run %q failed: %s", status.RunID, uploadResult.RunStatus.Error)
|
||||
}
|
||||
return uploadResult, nil
|
||||
}
|
||||
|
||||
func waitForRunStatus(ctx context.Context, client uploadClient, runID string, poll bool, wait func(context.Context, time.Duration) error) (runStatus, error) {
|
||||
status, err := client.Status(ctx, runID)
|
||||
if err != nil || terminalRunStatus(status.Status) || !poll {
|
||||
return status, err
|
||||
}
|
||||
|
||||
for {
|
||||
if err := wait(ctx, statusPollInterval); err != nil {
|
||||
return status, fmt.Errorf("distributor run %q did not reach terminal status before timeout: %w", runID, err)
|
||||
}
|
||||
|
||||
next, err := client.Status(ctx, runID)
|
||||
if err != nil {
|
||||
return status, err
|
||||
}
|
||||
status = next
|
||||
if terminalRunStatus(status.Status) {
|
||||
return status, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func waitForPoll(ctx context.Context, interval time.Duration) error {
|
||||
timer := time.NewTimer(interval)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func terminalRunStatus(status string) bool {
|
||||
return status == "succeeded" || status == "failed"
|
||||
}
|
||||
|
||||
type distributorUploadClient struct {
|
||||
client *distributorupload.Client
|
||||
}
|
||||
|
||||
type boundedResponseTransport struct {
|
||||
base http.RoundTripper
|
||||
limit int64
|
||||
}
|
||||
|
||||
func (t boundedResponseTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
base := t.base
|
||||
if base == nil {
|
||||
base = http.DefaultTransport
|
||||
}
|
||||
response, err := base.RoundTrip(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, t.limit+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if int64(len(data)) > t.limit {
|
||||
return nil, errDistributorResponseTooLarge
|
||||
}
|
||||
response.Body = io.NopCloser(bytes.NewReader(data))
|
||||
response.ContentLength = int64(len(data))
|
||||
return response, nil
|
||||
}
|
||||
|
||||
type RemoteResponseError struct {
|
||||
StatusCode int
|
||||
Retryable bool
|
||||
}
|
||||
|
||||
func (e *RemoteResponseError) Error() string {
|
||||
if e == nil || e.StatusCode == 0 {
|
||||
return "distributor request failed"
|
||||
}
|
||||
return fmt.Sprintf("distributor request failed with HTTP status %d", e.StatusCode)
|
||||
}
|
||||
|
||||
func newDistributorUploadClient(endpoint, token string, timeout time.Duration) (uploadClient, error) {
|
||||
httpClient := &http.Client{
|
||||
Transport: boundedResponseTransport{base: http.DefaultTransport, limit: maxDistributorResponseBytes},
|
||||
}
|
||||
if timeout > 0 {
|
||||
httpClient.Timeout = timeout
|
||||
}
|
||||
client, err := distributorupload.NewClient(distributorupload.ClientOptions{
|
||||
Endpoint: endpoint,
|
||||
Token: token,
|
||||
HTTPClient: httpClient,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return distributorUploadClient{client: client}, nil
|
||||
}
|
||||
|
||||
func (c distributorUploadClient) UploadFiles(ctx context.Context, opts uploadFilesOptions) (uploadFilesResult, error) {
|
||||
files := make([]distributorbundle.BundleFile, 0, len(opts.Files))
|
||||
for _, file := range opts.Files {
|
||||
files = append(files, distributorbundle.BundleFile{
|
||||
SourcePath: file.SourcePath,
|
||||
Path: file.BundlePath,
|
||||
})
|
||||
}
|
||||
result, err := c.client.UploadFiles(ctx, distributorupload.UploadFilesOptions{
|
||||
PipelineID: opts.PipelineID,
|
||||
ID: opts.BundleID,
|
||||
Created: opts.CreatedAt,
|
||||
IdempotencyKey: opts.IdempotencyKey,
|
||||
Files: files,
|
||||
})
|
||||
if err != nil {
|
||||
return uploadFilesResult{}, err
|
||||
}
|
||||
return uploadFilesResult{
|
||||
RunID: result.RunID,
|
||||
Status: result.Status,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (c distributorUploadClient) Status(ctx context.Context, runID string) (runStatus, error) {
|
||||
status, err := c.client.Status(ctx, runID)
|
||||
if err != nil {
|
||||
return runStatus{}, err
|
||||
}
|
||||
return sanitizeRunStatus(runStatus{
|
||||
RunID: status.RunID,
|
||||
PipelineID: status.PipelineID,
|
||||
Status: status.Status,
|
||||
AcceptedAt: status.AcceptedAt,
|
||||
StartedAt: status.StartedAt,
|
||||
FinishedAt: status.FinishedAt,
|
||||
Report: append(json.RawMessage(nil), status.Report...),
|
||||
Error: status.Error,
|
||||
}), nil
|
||||
}
|
||||
|
||||
type uploadErrorContext struct {
|
||||
Endpoint string
|
||||
PipelineID string
|
||||
BundleID string
|
||||
IdempotencyKey string
|
||||
SourcePaths []string
|
||||
BundlePaths []string
|
||||
Token string
|
||||
}
|
||||
|
||||
func wrapUploadError(err error, ctx uploadErrorContext) error {
|
||||
var conflict *distributorupload.IdempotencyConflictError
|
||||
isConflict := errors.As(err, &conflict)
|
||||
err = safeDistributorDiagnostic(err, ctx.Token)
|
||||
if isConflict {
|
||||
return &IdempotencyConflictError{
|
||||
Err: fmt.Errorf("upload distributor bundle %q to pipeline %q at endpoint %q with idempotency key %q from sources %q as bundle paths %q: idempotency conflict: %w", ctx.BundleID, ctx.PipelineID, ctx.Endpoint, ctx.IdempotencyKey, ctx.SourcePaths, ctx.BundlePaths, err),
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("upload distributor bundle %q to pipeline %q at endpoint %q with idempotency key %q from sources %q as bundle paths %q: %w", ctx.BundleID, ctx.PipelineID, ctx.Endpoint, ctx.IdempotencyKey, ctx.SourcePaths, ctx.BundlePaths, err)
|
||||
}
|
||||
|
||||
func safeDistributorDiagnostic(err error, token string) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, errDistributorResponseTooLarge) {
|
||||
return errDistributorResponseTooLarge
|
||||
}
|
||||
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
|
||||
return redactToken(err, token)
|
||||
}
|
||||
var httpErr *distributorupload.HTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
return &RemoteResponseError{StatusCode: httpErr.StatusCode, Retryable: httpErr.Retryable}
|
||||
}
|
||||
return errors.New("distributor request failed")
|
||||
}
|
||||
|
||||
func sanitizeRunStatus(status runStatus) runStatus {
|
||||
status.Report = nil
|
||||
if status.Error != "" {
|
||||
status.Error = "distributor reported a failed run"
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
func uploadSourcePaths(files []UploadFile) []string {
|
||||
paths := make([]string, 0, len(files))
|
||||
for _, file := range files {
|
||||
paths = append(paths, file.SourcePath)
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
func uploadBundlePaths(files []UploadFile) []string {
|
||||
paths := make([]string, 0, len(files))
|
||||
for _, file := range files {
|
||||
paths = append(paths, file.BundlePath)
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
func redactToken(err error, token string) error {
|
||||
if err == nil || token == "" {
|
||||
return err
|
||||
}
|
||||
return errors.New(redactTokenString(err.Error(), token))
|
||||
}
|
||||
|
||||
func redactTokenString(value, token string) string {
|
||||
if token == "" {
|
||||
return value
|
||||
}
|
||||
return strings.ReplaceAll(value, token, "[redacted]")
|
||||
}
|
||||
310
internal/adapters/distributor/client_http_test.go
Normal file
310
internal/adapters/distributor/client_http_test.go
Normal file
@@ -0,0 +1,310 @@
|
||||
package distributor
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"compress/gzip"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/config"
|
||||
)
|
||||
|
||||
const oversizedRemoteDiagnostic = "REMOTE-DIAGNOSTIC"
|
||||
|
||||
func TestUploadUsesProductionHTTPBoundary(t *testing.T) {
|
||||
const token = "test-upload-token"
|
||||
var uploadCalls, statusCalls int
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case r.Method == http.MethodPost && r.URL.Path == "/prefix/v1/pipelines/weather/upload":
|
||||
uploadCalls++
|
||||
if got := r.Header.Get("Authorization"); got != "Bearer "+token {
|
||||
t.Fatalf("authorization = %q", got)
|
||||
}
|
||||
if got := r.Header.Get("Idempotency-Key"); got != "bundle-key" {
|
||||
t.Fatalf("idempotency key = %q", got)
|
||||
}
|
||||
if got := r.Header.Get("Content-Type"); got != "application/gzip" {
|
||||
t.Fatalf("content type = %q", got)
|
||||
}
|
||||
verifyUploadedArchive(t, r.Body, "daily/report.md", "report body")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
_, _ = io.WriteString(w, `{"run_id":"run-123","status":"accepted"}`)
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/prefix/runs/run-123":
|
||||
statusCalls++
|
||||
if got := r.Header.Get("Authorization"); got != "Bearer "+token {
|
||||
t.Fatalf("authorization = %q", got)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(w, `{"run_id":"run-123","pipeline_id":"weather","status":"succeeded","report":{"detail":"REMOTE-DETAIL"}}`)
|
||||
default:
|
||||
t.Fatalf("unexpected request %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client := productionClient(t, server.URL+"/prefix", token)
|
||||
result, err := client.Upload(context.Background(), productionUploadRequest(t))
|
||||
if err != nil || uploadCalls != 1 || statusCalls != 1 || result.RunID != "run-123" || result.Status != "succeeded" || result.UploadStatus != "accepted" || result.RunStatus == nil || result.RunStatus.PipelineID != "weather" || len(result.RunStatus.Report) != 0 {
|
||||
t.Fatalf("result/error/calls = %#v/%v/%d/%d", result, err, uploadCalls, statusCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadClassifiesRemoteHTTPDiagnostics(t *testing.T) {
|
||||
const token = "test-upload-token"
|
||||
const remote = oversizedRemoteDiagnostic
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
handle func(http.ResponseWriter, *http.Request)
|
||||
check func(t *testing.T, result UploadResult, err error)
|
||||
}{
|
||||
{
|
||||
name: "upload failure",
|
||||
handle: func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
t.Fatalf("method = %s", r.Method)
|
||||
}
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = io.WriteString(w, `{"error":"REMOTE-DIAGNOSTIC","retryable":true}`)
|
||||
},
|
||||
check: func(t *testing.T, _ UploadResult, err error) {
|
||||
t.Helper()
|
||||
var remoteErr *RemoteResponseError
|
||||
if err == nil || !errors.As(err, &remoteErr) || remoteErr.StatusCode != http.StatusBadRequest || !remoteErr.Retryable {
|
||||
t.Fatalf("error = %T %v", err, err)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "status failure",
|
||||
handle: func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodPost {
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
_, _ = io.WriteString(w, `{"run_id":"run-123","status":"accepted"}`)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
_, _ = io.WriteString(w, remote)
|
||||
},
|
||||
check: func(t *testing.T, result UploadResult, err error) {
|
||||
t.Helper()
|
||||
if err != nil || result.Status != "accepted" || result.StatusError != "distributor request failed with HTTP status 500" {
|
||||
t.Fatalf("result/error = %#v/%v", result, err)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "failed run",
|
||||
handle: func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodPost {
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
_, _ = io.WriteString(w, `{"run_id":"run-123","status":"accepted"}`)
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(w, `{"run_id":"run-123","status":"failed","error":"REMOTE-DIAGNOSTIC","report":{"detail":"REMOTE-DIAGNOSTIC"}}`)
|
||||
},
|
||||
check: func(t *testing.T, result UploadResult, err error) {
|
||||
t.Helper()
|
||||
if err == nil || result.Status != "failed" || result.RunStatus == nil || result.RunStatus.Error != "distributor reported a failed run" || len(result.RunStatus.Report) != 0 {
|
||||
t.Fatalf("result/error = %#v/%v", result, err)
|
||||
}
|
||||
},
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(tt.handle))
|
||||
defer server.Close()
|
||||
result, err := productionClient(t, server.URL, token).Upload(context.Background(), productionUploadRequest(t))
|
||||
tt.check(t, result, err)
|
||||
for _, value := range []string{fmt.Sprint(result), fmt.Sprint(err)} {
|
||||
if strings.Contains(value, remote) || strings.Contains(value, token) {
|
||||
t.Fatalf("normal diagnostic leaked remote value: %q", value)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadBoundsHTTPResponses(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
response func(size int) string
|
||||
statusCode int
|
||||
statusBody func(size int) string
|
||||
check func(t *testing.T, result UploadResult, err error, overflow bool)
|
||||
}{
|
||||
{
|
||||
name: "accepted response",
|
||||
response: func(size int) string {
|
||||
return paddedJSON(t, `{"run_id":"run-123","status":"accepted","detail":"REMOTE-DIAGNOSTIC"}`, size)
|
||||
},
|
||||
statusBody: func(_ int) string {
|
||||
return `{"run_id":"run-123","status":"succeeded"}`
|
||||
},
|
||||
check: func(t *testing.T, result UploadResult, err error, overflow bool) {
|
||||
t.Helper()
|
||||
if overflow {
|
||||
if !errors.Is(err, errDistributorResponseTooLarge) || result.RunID != "" {
|
||||
t.Fatalf("overflow result/error = %#v/%v", result, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || result.Status != "succeeded" {
|
||||
t.Fatalf("bounded result/error = %#v/%v", result, err)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "status report",
|
||||
response: func(_ int) string {
|
||||
return `{"run_id":"run-123","status":"accepted"}`
|
||||
},
|
||||
statusBody: func(size int) string { return statusReportBody(t, size) },
|
||||
check: func(t *testing.T, result UploadResult, err error, overflow bool) {
|
||||
t.Helper()
|
||||
if overflow {
|
||||
if err != nil || result.Status != "accepted" || result.StatusError != errDistributorResponseTooLarge.Error() {
|
||||
t.Fatalf("overflow result/error = %#v/%v", result, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || result.Status != "succeeded" || result.RunStatus == nil || len(result.RunStatus.Report) != 0 {
|
||||
t.Fatalf("bounded result/error = %#v/%v", result, err)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "error response",
|
||||
response: func(size int) string { return repeatedToLength(oversizedRemoteDiagnostic, size) },
|
||||
statusCode: http.StatusBadRequest,
|
||||
check: func(t *testing.T, result UploadResult, err error, overflow bool) {
|
||||
t.Helper()
|
||||
if overflow {
|
||||
if !errors.Is(err, errDistributorResponseTooLarge) || result.RunID != "" {
|
||||
t.Fatalf("overflow result/error = %#v/%v", result, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
var remoteErr *RemoteResponseError
|
||||
if !errors.As(err, &remoteErr) || remoteErr.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("bounded result/error = %#v/%v", result, err)
|
||||
}
|
||||
},
|
||||
},
|
||||
} {
|
||||
for _, overflow := range []bool{false, true} {
|
||||
t.Run(tt.name+"/"+map[bool]string{false: "limit", true: "over-limit"}[overflow], func(t *testing.T) {
|
||||
size := int(maxDistributorResponseBytes)
|
||||
if overflow {
|
||||
size++
|
||||
}
|
||||
var uploadCalls int
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == http.MethodPost {
|
||||
uploadCalls++
|
||||
statusCode := tt.statusCode
|
||||
if statusCode == 0 {
|
||||
statusCode = http.StatusAccepted
|
||||
}
|
||||
w.WriteHeader(statusCode)
|
||||
_, _ = io.WriteString(w, tt.response(size))
|
||||
return
|
||||
}
|
||||
_, _ = io.WriteString(w, tt.statusBody(size))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
result, err := productionClient(t, server.URL, "test-upload-token").Upload(context.Background(), productionUploadRequest(t))
|
||||
tt.check(t, result, err, overflow)
|
||||
if strings.Contains(fmt.Sprint(result), oversizedRemoteDiagnostic) || strings.Contains(fmt.Sprint(err), oversizedRemoteDiagnostic) {
|
||||
t.Fatalf("result/error leaked oversized response detail: %#v/%v", result, err)
|
||||
}
|
||||
if uploadCalls != 1 {
|
||||
t.Fatalf("upload calls = %d, want one", uploadCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func productionClient(t *testing.T, endpoint, token string) *Client {
|
||||
t.Helper()
|
||||
cfg := config.Defaults().Notify.Distributor
|
||||
cfg.Endpoint = endpoint
|
||||
cfg.Timeout = 0
|
||||
t.Setenv(cfg.TokenEnv, token)
|
||||
return New(cfg)
|
||||
}
|
||||
|
||||
func productionUploadRequest(t *testing.T) UploadRequest {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "report.md")
|
||||
if err := os.WriteFile(path, []byte("report body"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return UploadRequest{
|
||||
PipelineID: "weather", BundleID: "bundle", IdempotencyKey: "bundle-key",
|
||||
Files: []UploadFile{{SourcePath: path, BundlePath: "daily/report.md"}},
|
||||
CreatedAt: time.Date(2026, 6, 7, 12, 0, 0, 0, time.UTC),
|
||||
}
|
||||
}
|
||||
|
||||
func verifyUploadedArchive(t *testing.T, body io.Reader, wantPath, wantContents string) {
|
||||
t.Helper()
|
||||
reader, err := gzip.NewReader(body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer reader.Close()
|
||||
archive := tar.NewReader(reader)
|
||||
for {
|
||||
header, err := archive.Next()
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if header.Name != wantPath {
|
||||
continue
|
||||
}
|
||||
contents, err := io.ReadAll(archive)
|
||||
if err != nil || string(contents) != wantContents {
|
||||
t.Fatalf("archive file contents/error = %q/%v", contents, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
t.Fatalf("archive did not contain %q", wantPath)
|
||||
}
|
||||
|
||||
func paddedJSON(t *testing.T, value string, size int) string {
|
||||
t.Helper()
|
||||
if len(value) > size {
|
||||
t.Fatalf("JSON length = %d, exceeds requested size %d", len(value), size)
|
||||
}
|
||||
return value + strings.Repeat(" ", size-len(value))
|
||||
}
|
||||
|
||||
func statusReportBody(t *testing.T, size int) string {
|
||||
t.Helper()
|
||||
const prefix = `{"run_id":"run-123","pipeline_id":"weather","status":"succeeded","report":"`
|
||||
const suffix = `"}`
|
||||
if len(prefix)+len(suffix) > size {
|
||||
t.Fatalf("status response exceeds requested size %d", size)
|
||||
}
|
||||
return prefix + repeatedToLength(oversizedRemoteDiagnostic, size-len(prefix)-len(suffix)) + suffix
|
||||
}
|
||||
|
||||
func repeatedToLength(value string, size int) string {
|
||||
return strings.Repeat(value, size/len(value)+1)[:size]
|
||||
}
|
||||
407
internal/adapters/distributor/client_test.go
Normal file
407
internal/adapters/distributor/client_test.go
Normal file
@@ -0,0 +1,407 @@
|
||||
package distributor
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
distributorupload "gitea.maximumdirect.net/eric/distributor/pkg/upload"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/config"
|
||||
)
|
||||
|
||||
func TestUploadUsesConfiguredClientAndFiles(t *testing.T) {
|
||||
cfg := config.Defaults().Notify.Distributor
|
||||
cfg.Endpoint = "https://distributor.example.test"
|
||||
cfg.TokenEnv = "DISTRIBUTOR_UPLOAD_TOKEN"
|
||||
cfg.Timeout = 15 * time.Second
|
||||
t.Setenv(cfg.TokenEnv, "secret-token")
|
||||
|
||||
factory := &fakeUploadFactory{
|
||||
client: &fakeUploadClient{
|
||||
result: uploadFilesResult{RunID: "run-123", Status: "accepted"},
|
||||
status: runStatus{RunID: "run-123", PipelineID: "reports", Status: "succeeded", Report: json.RawMessage(`{"actions":[{"action":"replace_older"}]}`)},
|
||||
},
|
||||
}
|
||||
client := newClient(cfg, factory.newClient)
|
||||
|
||||
result, err := client.Upload(context.Background(), UploadRequest{
|
||||
PipelineID: "weatherreporter.daily",
|
||||
BundleID: "weatherreporter.home.daily.run",
|
||||
IdempotencyKey: "weatherreporter.home.daily.run",
|
||||
Files: []UploadFile{
|
||||
{SourcePath: "/tmp/report.md", BundlePath: "2026-06-07/daily/report.md"},
|
||||
{SourcePath: "/tmp/report.md", BundlePath: "2026-06-07/daily/latest.md"},
|
||||
},
|
||||
CreatedAt: time.Date(2026, 6, 7, 12, 0, 0, 123, time.UTC),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Upload() error = %v", err)
|
||||
}
|
||||
if result.RunID != "run-123" || result.Status != "succeeded" || result.UploadStatus != "accepted" {
|
||||
t.Fatalf("result = %#v, want accepted run", result)
|
||||
}
|
||||
if result.RunStatus == nil || result.RunStatus.PipelineID != "reports" || len(result.RunStatus.Report) != 0 {
|
||||
t.Fatalf("RunStatus = %#v, want safe status details", result.RunStatus)
|
||||
}
|
||||
if factory.endpoint != cfg.Endpoint {
|
||||
t.Fatalf("factory endpoint = %q, want %q", factory.endpoint, cfg.Endpoint)
|
||||
}
|
||||
if factory.token != "secret-token" {
|
||||
t.Fatalf("factory token = %q, want secret-token", factory.token)
|
||||
}
|
||||
if factory.timeout != 15*time.Second {
|
||||
t.Fatalf("factory timeout = %s, want 15s", factory.timeout)
|
||||
}
|
||||
got := factory.client.opts
|
||||
if got.PipelineID != "weatherreporter.daily" {
|
||||
t.Fatalf("PipelineID = %q, want weatherreporter.daily", got.PipelineID)
|
||||
}
|
||||
if got.BundleID != "weatherreporter.home.daily.run" {
|
||||
t.Fatalf("BundleID = %q, want weatherreporter.home.daily.run", got.BundleID)
|
||||
}
|
||||
if got.IdempotencyKey != "weatherreporter.home.daily.run" {
|
||||
t.Fatalf("IdempotencyKey = %q, want weatherreporter.home.daily.run", got.IdempotencyKey)
|
||||
}
|
||||
if len(got.Files) != 2 {
|
||||
t.Fatalf("files = %#v, want two mappings", got.Files)
|
||||
}
|
||||
if got.Files[0].SourcePath != "/tmp/report.md" || got.Files[0].BundlePath != "2026-06-07/daily/report.md" {
|
||||
t.Fatalf("first file = %#v, want archive mapping", got.Files[0])
|
||||
}
|
||||
if got.Files[1].SourcePath != "/tmp/report.md" || got.Files[1].BundlePath != "2026-06-07/daily/latest.md" {
|
||||
t.Fatalf("second file = %#v, want latest mapping", got.Files[1])
|
||||
}
|
||||
if got.CreatedAt.IsZero() {
|
||||
t.Fatal("CreatedAt is zero, want generated report timestamp")
|
||||
}
|
||||
if factory.client.statusRunID != "run-123" {
|
||||
t.Fatalf("Status runID = %q, want run-123", factory.client.statusRunID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadRejectsMissingInputs(t *testing.T) {
|
||||
cfg := config.Defaults().Notify.Distributor
|
||||
t.Setenv(cfg.TokenEnv, "secret-token")
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*Client, *UploadRequest)
|
||||
wantErr string
|
||||
}{
|
||||
{
|
||||
name: "Token",
|
||||
mutate: func(c *Client, req *UploadRequest) {
|
||||
t.Setenv(c.TokenEnv, "")
|
||||
},
|
||||
wantErr: "token environment variable",
|
||||
},
|
||||
{
|
||||
name: "PipelineID",
|
||||
mutate: func(c *Client, req *UploadRequest) {
|
||||
req.PipelineID = ""
|
||||
},
|
||||
wantErr: "pipeline id is required",
|
||||
},
|
||||
{
|
||||
name: "Files",
|
||||
mutate: func(c *Client, req *UploadRequest) {
|
||||
req.Files = nil
|
||||
},
|
||||
wantErr: "upload files are required",
|
||||
},
|
||||
{
|
||||
name: "SourcePath",
|
||||
mutate: func(c *Client, req *UploadRequest) {
|
||||
req.Files[0].SourcePath = ""
|
||||
},
|
||||
wantErr: "source path is required",
|
||||
},
|
||||
{
|
||||
name: "BundlePath",
|
||||
mutate: func(c *Client, req *UploadRequest) {
|
||||
req.Files[0].BundlePath = ""
|
||||
},
|
||||
wantErr: "bundle path is required",
|
||||
},
|
||||
{
|
||||
name: "UploadClientFactory",
|
||||
mutate: func(c *Client, req *UploadRequest) {
|
||||
c.newUploadClient = nil
|
||||
},
|
||||
wantErr: "upload client factory is required",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
t.Setenv(cfg.TokenEnv, "secret-token")
|
||||
client := newClient(cfg, (&fakeUploadFactory{client: &fakeUploadClient{}}).newClient)
|
||||
req := validUploadRequest()
|
||||
tt.mutate(client, &req)
|
||||
|
||||
_, err := client.Upload(context.Background(), req)
|
||||
if err == nil {
|
||||
t.Fatal("Upload() error = nil, want error")
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Fatalf("error = %q, want %q", err.Error(), tt.wantErr)
|
||||
}
|
||||
if strings.Contains(err.Error(), "secret-token") {
|
||||
t.Fatalf("error = %q, want no token value", err.Error())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadWrapsFactoryErrorWithoutToken(t *testing.T) {
|
||||
cfg := config.Defaults().Notify.Distributor
|
||||
cfg.Endpoint = "https://distributor.example.test"
|
||||
t.Setenv(cfg.TokenEnv, "secret-token")
|
||||
factory := &fakeUploadFactory{
|
||||
err: fmt.Errorf("factory failed with secret-token"),
|
||||
}
|
||||
client := newClient(cfg, factory.newClient)
|
||||
|
||||
_, err := client.Upload(context.Background(), validUploadRequest())
|
||||
if err == nil {
|
||||
t.Fatal("Upload() error = nil, want error")
|
||||
}
|
||||
if strings.Contains(err.Error(), "secret-token") {
|
||||
t.Fatalf("error = %q, want no token value", err.Error())
|
||||
}
|
||||
if !strings.Contains(err.Error(), cfg.Endpoint) {
|
||||
t.Fatalf("error = %q, want endpoint context", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadWrapsUploadFailureWithContextWithoutToken(t *testing.T) {
|
||||
cfg := config.Defaults().Notify.Distributor
|
||||
cfg.Endpoint = "https://distributor.example.test"
|
||||
t.Setenv(cfg.TokenEnv, "secret-token")
|
||||
factory := &fakeUploadFactory{
|
||||
client: &fakeUploadClient{err: fmt.Errorf("server rejected secret-token")},
|
||||
}
|
||||
client := newClient(cfg, factory.newClient)
|
||||
req := validUploadRequest()
|
||||
|
||||
_, err := client.Upload(context.Background(), req)
|
||||
if err == nil {
|
||||
t.Fatal("Upload() error = nil, want error")
|
||||
}
|
||||
for _, want := range []string{cfg.Endpoint, req.PipelineID, req.BundleID, req.IdempotencyKey, req.Files[0].SourcePath, req.Files[0].BundlePath, req.Files[1].BundlePath} {
|
||||
if !strings.Contains(err.Error(), want) {
|
||||
t.Fatalf("error = %q, want context %q", err.Error(), want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(err.Error(), "secret-token") {
|
||||
t.Fatalf("error = %q, want no token value", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadReturnsAcceptedWhenStatusLookupFails(t *testing.T) {
|
||||
cfg := config.Defaults().Notify.Distributor
|
||||
cfg.Endpoint = "https://distributor.example.test"
|
||||
t.Setenv(cfg.TokenEnv, "secret-token")
|
||||
factory := &fakeUploadFactory{
|
||||
client: &fakeUploadClient{
|
||||
result: uploadFilesResult{RunID: "run-123", Status: "accepted"},
|
||||
statusErr: fmt.Errorf("status rejected secret-token"),
|
||||
},
|
||||
}
|
||||
client := newClient(cfg, factory.newClient)
|
||||
|
||||
result, err := client.Upload(context.Background(), validUploadRequest())
|
||||
if err != nil {
|
||||
t.Fatalf("Upload() error = %v, want accepted upload despite status lookup failure", err)
|
||||
}
|
||||
if result.Status != "accepted" || result.StatusError == "" {
|
||||
t.Fatalf("result = %#v, want accepted status with status error", result)
|
||||
}
|
||||
if strings.Contains(result.StatusError, "secret-token") {
|
||||
t.Fatalf("StatusError = %q, want token redacted", result.StatusError)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadPollsUntilTerminalStatus(t *testing.T) {
|
||||
cfg := config.Defaults().Notify.Distributor
|
||||
cfg.Endpoint = "https://distributor.example.test"
|
||||
cfg.Timeout = 2 * time.Second
|
||||
t.Setenv(cfg.TokenEnv, "secret-token")
|
||||
factory := &fakeUploadFactory{
|
||||
client: &fakeUploadClient{
|
||||
result: uploadFilesResult{RunID: "run-123", Status: "accepted"},
|
||||
statuses: []runStatus{
|
||||
{RunID: "run-123", Status: "accepted"},
|
||||
{RunID: "run-123", Status: "succeeded", Report: json.RawMessage(`{"actions":[{"action":"replace_older"}]}`)},
|
||||
},
|
||||
},
|
||||
}
|
||||
client := newClient(cfg, factory.newClient)
|
||||
client.pollWait = func(context.Context, time.Duration) error { return nil }
|
||||
|
||||
result, err := client.Upload(context.Background(), validUploadRequest())
|
||||
if err != nil {
|
||||
t.Fatalf("Upload() error = %v", err)
|
||||
}
|
||||
if result.Status != "succeeded" || result.RunStatus == nil || len(result.RunStatus.Report) != 0 {
|
||||
t.Fatalf("result = %#v, want terminal succeeded status without remote report", result)
|
||||
}
|
||||
if factory.client.statusCalls != 2 {
|
||||
t.Fatalf("status calls = %d, want 2", factory.client.statusCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadReturnsLatestStatusWhenPollingTimesOut(t *testing.T) {
|
||||
cfg := config.Defaults().Notify.Distributor
|
||||
cfg.Endpoint = "https://distributor.example.test"
|
||||
cfg.Timeout = time.Millisecond
|
||||
t.Setenv(cfg.TokenEnv, "secret-token")
|
||||
factory := &fakeUploadFactory{
|
||||
client: &fakeUploadClient{
|
||||
result: uploadFilesResult{RunID: "run-123", Status: "accepted"},
|
||||
status: runStatus{RunID: "run-123", Status: "running"},
|
||||
},
|
||||
}
|
||||
client := newClient(cfg, factory.newClient)
|
||||
|
||||
result, err := client.Upload(context.Background(), validUploadRequest())
|
||||
if err != nil {
|
||||
t.Fatalf("Upload() error = %v, want accepted upload with status timeout recorded", err)
|
||||
}
|
||||
if result.Status != "running" || result.StatusError == "" {
|
||||
t.Fatalf("result = %#v, want latest status and status timeout", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadFailsWhenDistributorRunFailed(t *testing.T) {
|
||||
cfg := config.Defaults().Notify.Distributor
|
||||
cfg.Endpoint = "https://distributor.example.test"
|
||||
t.Setenv(cfg.TokenEnv, "secret-token")
|
||||
factory := &fakeUploadFactory{
|
||||
client: &fakeUploadClient{
|
||||
result: uploadFilesResult{RunID: "run-123", Status: "accepted"},
|
||||
status: runStatus{
|
||||
RunID: "run-123",
|
||||
Status: "failed",
|
||||
Error: "destination rejected secret-token",
|
||||
Report: json.RawMessage(`{"actions":[{"action":"failed"}]}`),
|
||||
},
|
||||
},
|
||||
}
|
||||
client := newClient(cfg, factory.newClient)
|
||||
|
||||
result, err := client.Upload(context.Background(), validUploadRequest())
|
||||
if err == nil {
|
||||
t.Fatal("Upload() error = nil, want failed distributor run error")
|
||||
}
|
||||
if result.RunStatus == nil || result.RunStatus.Status != "failed" || len(result.RunStatus.Report) != 0 || result.RunStatus.Error != "distributor reported a failed run" {
|
||||
t.Fatalf("result = %#v, want safe failed run status", result)
|
||||
}
|
||||
if strings.Contains(err.Error(), "secret-token") || strings.Contains(result.RunStatus.Error, "secret-token") {
|
||||
t.Fatalf("error/result leaked token: err=%q result=%#v", err.Error(), result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadPreservesIdempotencyConflictDiagnosis(t *testing.T) {
|
||||
cfg := config.Defaults().Notify.Distributor
|
||||
cfg.Endpoint = "https://distributor.example.test"
|
||||
t.Setenv(cfg.TokenEnv, "secret-token")
|
||||
factory := &fakeUploadFactory{
|
||||
client: &fakeUploadClient{
|
||||
err: &distributorupload.IdempotencyConflictError{
|
||||
HTTPError: distributorupload.HTTPError{
|
||||
StatusCode: 409,
|
||||
Status: "409 Conflict",
|
||||
Message: "conflicting upload for secret-token",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
client := newClient(cfg, factory.newClient)
|
||||
|
||||
_, err := client.Upload(context.Background(), validUploadRequest())
|
||||
if err == nil {
|
||||
t.Fatal("Upload() error = nil, want error")
|
||||
}
|
||||
var conflict *IdempotencyConflictError
|
||||
if !errors.As(err, &conflict) {
|
||||
t.Fatalf("Upload() error = %T %v, want IdempotencyConflictError", err, err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "idempotency conflict") {
|
||||
t.Fatalf("error = %q, want idempotency conflict diagnosis", err.Error())
|
||||
}
|
||||
if strings.Contains(err.Error(), "secret-token") {
|
||||
t.Fatalf("error = %q, want no token value", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func validUploadRequest() UploadRequest {
|
||||
return UploadRequest{
|
||||
PipelineID: "weatherreporter.daily",
|
||||
BundleID: "weatherreporter.home.daily.run",
|
||||
IdempotencyKey: "weatherreporter.home.daily.run",
|
||||
Files: []UploadFile{
|
||||
{SourcePath: "/tmp/report.md", BundlePath: "2026-06-07/daily/report.md"},
|
||||
{SourcePath: "/tmp/report.md", BundlePath: "2026-06-07/daily/latest.md"},
|
||||
},
|
||||
CreatedAt: time.Date(2026, 6, 7, 12, 0, 0, 123, time.UTC),
|
||||
}
|
||||
}
|
||||
|
||||
type fakeUploadFactory struct {
|
||||
endpoint string
|
||||
token string
|
||||
timeout time.Duration
|
||||
client *fakeUploadClient
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeUploadFactory) newClient(endpoint, token string, timeout time.Duration) (uploadClient, error) {
|
||||
f.endpoint = endpoint
|
||||
f.token = token
|
||||
f.timeout = timeout
|
||||
if f.err != nil {
|
||||
return nil, f.err
|
||||
}
|
||||
return f.client, nil
|
||||
}
|
||||
|
||||
type fakeUploadClient struct {
|
||||
opts uploadFilesOptions
|
||||
statusRunID string
|
||||
statusCalls int
|
||||
result uploadFilesResult
|
||||
status runStatus
|
||||
statuses []runStatus
|
||||
err error
|
||||
statusErr error
|
||||
}
|
||||
|
||||
func (c *fakeUploadClient) UploadFiles(ctx context.Context, opts uploadFilesOptions) (uploadFilesResult, error) {
|
||||
c.opts = opts
|
||||
if c.err != nil {
|
||||
return uploadFilesResult{}, c.err
|
||||
}
|
||||
return c.result, nil
|
||||
}
|
||||
|
||||
func (c *fakeUploadClient) Status(ctx context.Context, runID string) (runStatus, error) {
|
||||
c.statusRunID = runID
|
||||
c.statusCalls++
|
||||
if c.statusErr != nil {
|
||||
return runStatus{}, c.statusErr
|
||||
}
|
||||
if len(c.statuses) > 0 {
|
||||
index := c.statusCalls - 1
|
||||
if index >= len(c.statuses) {
|
||||
index = len(c.statuses) - 1
|
||||
}
|
||||
return c.statuses[index], nil
|
||||
}
|
||||
return c.status, nil
|
||||
}
|
||||
330
internal/adapters/promptkit/adapter.go
Normal file
330
internal/adapters/promptkit/adapter.go
Normal file
@@ -0,0 +1,330 @@
|
||||
// Package promptkitadapter implements promptexec with Promptkit.
|
||||
package promptkitadapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
promptkit "gitea.maximumdirect.net/eric/promptkit"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/generatedtext"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptassets"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptexec"
|
||||
)
|
||||
|
||||
// Config selects the Promptkit sources and optional local backend for one engine.
|
||||
type Config struct {
|
||||
ProfileDirectory string
|
||||
ProfileFile string
|
||||
LocalEndpoint string
|
||||
LocalConcurrencyLimit int
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Adapter owns one Promptkit engine and its opaque prepared execution handles.
|
||||
// It supports concurrent Execute calls on the shared executor.
|
||||
type Adapter struct {
|
||||
engine *promptkit.Engine
|
||||
}
|
||||
|
||||
var _ promptexec.Executor = (*Adapter)(nil)
|
||||
|
||||
// New constructs a Promptkit-backed executor from Weatherreporter-owned settings.
|
||||
func New(config Config) (*Adapter, error) {
|
||||
return newAdapter(config)
|
||||
}
|
||||
|
||||
func newAdapter(config Config, additionalOptions ...promptkit.Option) (*Adapter, error) {
|
||||
if config.ProfileDirectory != "" && config.ProfileFile != "" {
|
||||
return nil, promptexec.NewError(promptexec.InvalidConfiguration, "profile directory and profile file cannot both be configured", nil)
|
||||
}
|
||||
if config.LocalEndpoint == "" && config.LocalConcurrencyLimit != 0 {
|
||||
return nil, promptexec.NewError(promptexec.InvalidConfiguration, "local concurrency requires a local endpoint", nil)
|
||||
}
|
||||
|
||||
options := []promptkit.Option{
|
||||
promptkit.WithPromptFS(promptassets.PromptFS(), "."),
|
||||
promptkit.WithSchemaFS(promptassets.SchemaFS(), "."),
|
||||
promptkit.WithFallbackProfileFS(promptassets.ProfileFS(), "."),
|
||||
}
|
||||
if config.ProfileFile != "" {
|
||||
options = append(options, promptkit.WithProfileFile(config.ProfileFile))
|
||||
}
|
||||
if config.LocalEndpoint != "" {
|
||||
options = append(options, promptkit.WithBackend(promptkit.LocalBackend(config.LocalEndpoint, config.LocalConcurrencyLimit)))
|
||||
}
|
||||
options = append(options, additionalOptions...)
|
||||
engine, err := promptkit.NewEngine(promptkit.Config{
|
||||
ProfileDir: config.ProfileDirectory,
|
||||
Timeout: config.Timeout,
|
||||
}, options...)
|
||||
if err != nil {
|
||||
return nil, classifyConfigurationError(err)
|
||||
}
|
||||
return &Adapter{engine: engine}, nil
|
||||
}
|
||||
|
||||
func newAdapterForTest(config Config, client promptkit.LLMClient) (*Adapter, error) {
|
||||
return newAdapter(config, promptkit.WithLLMClient(client))
|
||||
}
|
||||
|
||||
// InspectPrompt maps an exact Promptkit prompt inspection into project-owned values.
|
||||
func (adapter *Adapter) InspectPrompt(ctx context.Context, promptID string, promptVersion string) (promptexec.PromptInspection, error) {
|
||||
if adapter == nil || adapter.engine == nil {
|
||||
return promptexec.PromptInspection{}, promptexec.NewError(promptexec.InvalidConfiguration, "prompt executor is not configured", nil)
|
||||
}
|
||||
inspection, err := adapter.engine.InspectPrompt(ctx, promptID, promptVersion)
|
||||
if err != nil {
|
||||
return promptexec.PromptInspection{}, classifyError(err)
|
||||
}
|
||||
inputs := make([]promptexec.InputDefinition, len(inspection.Inputs))
|
||||
for index, input := range inspection.Inputs {
|
||||
inputs[index] = promptexec.InputDefinition{
|
||||
Name: input.Name,
|
||||
Required: input.Required,
|
||||
ContentType: input.ContentType,
|
||||
Description: input.Description,
|
||||
}
|
||||
}
|
||||
return promptexec.PromptInspection{
|
||||
PromptID: inspection.PromptID,
|
||||
PromptVersion: inspection.PromptVersion,
|
||||
PromptHash: inspection.PromptHash,
|
||||
DefaultProfileID: inspection.DefaultProfileID,
|
||||
Inputs: inputs,
|
||||
Output: outputContract(inspection.OutputContract),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// InspectProfile maps one explicit Promptkit profile inspection into safe values.
|
||||
func (adapter *Adapter) InspectProfile(ctx context.Context, profileID string) (promptexec.ProfileInspection, error) {
|
||||
if adapter == nil || adapter.engine == nil {
|
||||
return promptexec.ProfileInspection{}, promptexec.NewError(promptexec.InvalidConfiguration, "prompt executor is not configured", nil)
|
||||
}
|
||||
inspection, err := adapter.engine.InspectProfile(ctx, profileID)
|
||||
if err != nil {
|
||||
return promptexec.ProfileInspection{}, classifyError(err)
|
||||
}
|
||||
return promptexec.ProfileInspection{
|
||||
ProfileID: inspection.ProfileID,
|
||||
BackendID: inspection.EffectiveModelParams.BackendID,
|
||||
ModelName: inspection.EffectiveModelParams.Model,
|
||||
CredentialRequired: inspection.APIKeyRequired,
|
||||
APIKeyEnv: inspection.EffectiveModelParams.APIKeyEnv,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Execute prepares one exact inline data package, invokes prepared after a
|
||||
// successful preparation, and then runs the same opaque prepared handle.
|
||||
func (adapter *Adapter) Execute(ctx context.Context, request promptexec.ExecuteRequest, preparedCallback promptexec.PreparationCallback) (*promptexec.Execution, error) {
|
||||
if adapter == nil || adapter.engine == nil {
|
||||
return nil, promptexec.NewError(promptexec.InvalidConfiguration, "prompt executor is not configured", nil)
|
||||
}
|
||||
prepared, err := adapter.engine.PrepareExecution(ctx, promptkit.RunRequest{
|
||||
PromptID: request.PromptID,
|
||||
PromptVersion: request.PromptVersion,
|
||||
ProfileID: request.ProfileID,
|
||||
Inputs: map[string]promptkit.ArtifactRef{"data_package": promptkit.Inline(string(append([]byte(nil), request.DataPackage...)))},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, classifyError(err)
|
||||
}
|
||||
defer prepared.Discard()
|
||||
|
||||
details := prepared.Details()
|
||||
preparation, debug := preparationValues(details, request.CaptureDebug)
|
||||
if preparedCallback != nil {
|
||||
if err := preparedCallback(preparation, debug); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
result, err := adapter.engine.RunPrepared(ctx, prepared)
|
||||
if err != nil {
|
||||
return nil, classifyError(err)
|
||||
}
|
||||
return executionValue(result, request.CaptureDebug), nil
|
||||
}
|
||||
|
||||
func outputContract(value promptkit.OutputContract) promptexec.OutputContract {
|
||||
return promptexec.OutputContract{
|
||||
Format: string(value.Format),
|
||||
ValidationMode: string(value.ValidationMode),
|
||||
SchemaPath: value.SchemaPath,
|
||||
}
|
||||
}
|
||||
|
||||
func preparationValues(value promptkit.PreparedRun, captureDebug bool) (promptexec.Preparation, *promptexec.PreparationDebug) {
|
||||
preparation := promptexec.Preparation{
|
||||
PromptID: value.PromptID,
|
||||
PromptVersion: value.PromptVersion,
|
||||
PromptHash: value.PromptHash,
|
||||
RenderedPromptHash: value.RenderedPromptHash,
|
||||
InputHashes: copyInputHashes(value.InputHashes),
|
||||
ProfileID: value.SelectedProfileID,
|
||||
BackendID: value.SelectedBackendID,
|
||||
ModelName: value.EffectiveModelParams.Model,
|
||||
Output: outputContract(value.OutputContract),
|
||||
StartedAt: value.StartTime,
|
||||
EndedAt: value.EndTime,
|
||||
Duration: time.Duration(value.DurationMS) * time.Millisecond,
|
||||
}
|
||||
if !captureDebug {
|
||||
return preparation, nil
|
||||
}
|
||||
debug := &promptexec.PreparationDebug{
|
||||
RenderedMessages: renderedMessages(value.Messages),
|
||||
Endpoint: value.EffectiveModelParams.Endpoint,
|
||||
ParametersJSON: marshalDebugParameters(value.EffectiveModelParams),
|
||||
}
|
||||
if value.StructuredOutput != nil && value.StructuredOutput.JSONSchema != nil {
|
||||
debug.StructuredSchema, _ = json.Marshal(value.StructuredOutput.JSONSchema.Schema)
|
||||
}
|
||||
return preparation, debug
|
||||
}
|
||||
|
||||
func executionValue(value *promptkit.RunResult, captureDebug bool) *promptexec.Execution {
|
||||
if value == nil {
|
||||
return nil
|
||||
}
|
||||
validation := promptexec.NewValidation(
|
||||
promptexec.ValidationStatus(value.Validation.Status),
|
||||
string(value.Validation.Mode),
|
||||
value.Validation.SchemaPath,
|
||||
value.Validation.Errors,
|
||||
)
|
||||
rawOutput := []byte(nil)
|
||||
if len(value.RawOutput) <= generatedtext.MaxGeneratedTextBytes {
|
||||
rawOutput = []byte(value.RawOutput)
|
||||
} else {
|
||||
validation = promptexec.NewValidation(
|
||||
promptexec.ValidationFailed,
|
||||
string(value.Validation.Mode),
|
||||
value.Validation.SchemaPath,
|
||||
[]string{"generated output exceeds the configured size limit"},
|
||||
)
|
||||
}
|
||||
execution := &promptexec.Execution{
|
||||
RunID: value.RunID,
|
||||
PromptID: value.PromptID,
|
||||
PromptVersion: value.PromptVersion,
|
||||
PromptHash: value.PromptHash,
|
||||
RenderedPromptHash: value.RenderedPromptHash,
|
||||
InputHashes: copyInputHashes(value.InputHashes),
|
||||
ProfileID: value.SelectedProfileID,
|
||||
BackendID: value.SelectedBackendID,
|
||||
ModelName: value.ModelName,
|
||||
GeneratedHash: value.Artifact.Hash,
|
||||
Usage: promptexec.TokenUsage{
|
||||
PromptTokens: value.Usage.PromptTokens,
|
||||
CompletionTokens: value.Usage.CompletionTokens,
|
||||
TotalTokens: value.Usage.TotalTokens,
|
||||
CachedTokens: value.Usage.CachedTokens,
|
||||
CacheWriteTokens: value.Usage.CacheWriteTokens,
|
||||
},
|
||||
StartedAt: value.StartTime,
|
||||
EndedAt: value.EndTime,
|
||||
Duration: value.Duration,
|
||||
Validation: validation,
|
||||
RawOutput: rawOutput,
|
||||
}
|
||||
if captureDebug {
|
||||
execution.Debug = &promptexec.ExecutionDebug{
|
||||
RawOutput: append([]byte(nil), rawOutput...),
|
||||
ValidationDiagnostics: append([]string(nil), validation.Diagnostics...),
|
||||
}
|
||||
}
|
||||
return execution
|
||||
}
|
||||
|
||||
func renderedMessages(values []promptkit.RenderedMessage) []promptexec.RenderedMessage {
|
||||
messages := make([]promptexec.RenderedMessage, len(values))
|
||||
for index, value := range values {
|
||||
messages[index] = promptexec.RenderedMessage{Role: value.Role, Content: value.Content}
|
||||
}
|
||||
return messages
|
||||
}
|
||||
|
||||
func copyInputHashes(values map[string]string) map[string]string {
|
||||
if values == nil {
|
||||
return nil
|
||||
}
|
||||
copy := make(map[string]string, len(values))
|
||||
for key, value := range values {
|
||||
copy[key] = value
|
||||
}
|
||||
return copy
|
||||
}
|
||||
|
||||
func marshalDebugParameters(value promptkit.ExecutionTarget) []byte {
|
||||
parameters := struct {
|
||||
Temperature float64 `json:"temperature"`
|
||||
MaxTokens int `json:"max_tokens"`
|
||||
TopP float64 `json:"top_p"`
|
||||
TimeoutSeconds int `json:"timeout_seconds"`
|
||||
ServiceTier string `json:"service_tier"`
|
||||
ReasoningEffort string `json:"reasoning_effort"`
|
||||
}{
|
||||
Temperature: value.Temperature,
|
||||
MaxTokens: value.MaxTokens,
|
||||
TopP: value.TopP,
|
||||
TimeoutSeconds: value.TimeoutSeconds,
|
||||
ServiceTier: value.ServiceTier,
|
||||
ReasoningEffort: value.ReasoningEffort,
|
||||
}
|
||||
data, _ := json.Marshal(parameters)
|
||||
return data
|
||||
}
|
||||
|
||||
func classifyConfigurationError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return promptexec.NewError(promptexec.InvalidConfiguration, "prompt executor configuration is invalid", err)
|
||||
}
|
||||
|
||||
func classifyError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return promptexec.NewError(promptexec.Canceled, "prompt operation was canceled", err)
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return promptexec.NewError(promptexec.DeadlineExceeded, "prompt operation exceeded its deadline", err)
|
||||
}
|
||||
var capacityError *promptkit.CapacityError
|
||||
if errors.As(err, &capacityError) {
|
||||
return promptexec.NewCapacityError(capacityError.BackendID, "prompt backend capacity is unavailable", err)
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, promptkit.ErrInvalidConfig):
|
||||
return promptexec.NewError(promptexec.InvalidConfiguration, "prompt executor configuration is invalid", err)
|
||||
case errors.Is(err, promptkit.ErrPromptNotFound):
|
||||
return promptexec.NewError(promptexec.PromptNotFound, "prompt definition was not found", err)
|
||||
case errors.Is(err, promptkit.ErrPromptLoad):
|
||||
return promptexec.NewError(promptexec.PromptLoad, "prompt definition could not be loaded", err)
|
||||
case errors.Is(err, promptkit.ErrProfileNotFound):
|
||||
return promptexec.NewError(promptexec.ProfileNotFound, "execution profile was not found", err)
|
||||
case errors.Is(err, promptkit.ErrProfileLoad):
|
||||
return promptexec.NewError(promptexec.ProfileLoad, "execution profile could not be loaded", err)
|
||||
case errors.Is(err, promptkit.ErrAPIKeyEnvMissing):
|
||||
return promptexec.NewError(promptexec.MissingCredential, "execution credential is unavailable", err)
|
||||
case errors.Is(err, promptkit.ErrArtifactLoad):
|
||||
return promptexec.NewError(promptexec.ArtifactLoad, "prompt input could not be loaded", err)
|
||||
case errors.Is(err, promptkit.ErrPromptRender):
|
||||
return promptexec.NewError(promptexec.PromptRender, "prompt could not be rendered", err)
|
||||
case errors.Is(err, promptkit.ErrCapacityExceeded):
|
||||
return promptexec.NewCapacityError("", "prompt backend capacity is unavailable", err)
|
||||
case errors.Is(err, promptkit.ErrLLMGenerate):
|
||||
return promptexec.NewError(promptexec.Generation, "prompt generation failed", err)
|
||||
case errors.Is(err, promptkit.ErrValidation):
|
||||
return promptexec.NewError(promptexec.OperationalValidation, "prompt output validation could not be completed", err)
|
||||
case errors.Is(err, promptkit.ErrInvalidRequest), errors.Is(err, promptkit.ErrProfileRequired):
|
||||
return promptexec.NewError(promptexec.InvalidRequest, "prompt execution request is invalid", err)
|
||||
default:
|
||||
return promptexec.NewError(promptexec.Generation, "prompt operation failed", fmt.Errorf("%w", err))
|
||||
}
|
||||
}
|
||||
626
internal/adapters/promptkit/adapter_test.go
Normal file
626
internal/adapters/promptkit/adapter_test.go
Normal file
@@ -0,0 +1,626 @@
|
||||
package promptkitadapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
promptkit "gitea.maximumdirect.net/eric/promptkit"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/generatedtext"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptexec"
|
||||
)
|
||||
|
||||
type fakeClient struct {
|
||||
mu sync.Mutex
|
||||
response *promptkit.GenerateResponse
|
||||
err error
|
||||
calls int
|
||||
requests []promptkit.GenerateRequest
|
||||
block bool
|
||||
started chan struct{}
|
||||
}
|
||||
|
||||
type recordingReader struct {
|
||||
ref promptkit.ArtifactRef
|
||||
}
|
||||
|
||||
func (reader *recordingReader) Read(_ context.Context, ref promptkit.ArtifactRef) (*promptkit.Artifact, error) {
|
||||
reader.ref = ref
|
||||
return &promptkit.Artifact{
|
||||
Name: "data_package",
|
||||
ContentType: "application/yaml",
|
||||
Body: []byte(ref.Body),
|
||||
URI: ref.URI,
|
||||
Hash: "input-hash",
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (client *fakeClient) Generate(ctx context.Context, request promptkit.GenerateRequest) (*promptkit.GenerateResponse, error) {
|
||||
client.mu.Lock()
|
||||
client.calls++
|
||||
client.requests = append(client.requests, request)
|
||||
block := client.block
|
||||
started := client.started
|
||||
response := client.response
|
||||
err := client.err
|
||||
client.mu.Unlock()
|
||||
if started != nil {
|
||||
started <- struct{}{}
|
||||
}
|
||||
if block {
|
||||
<-ctx.Done()
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return response, err
|
||||
}
|
||||
|
||||
func TestExecuteSupportsConcurrentCalls(t *testing.T) {
|
||||
client := &fakeClient{response: validResponse(), block: true, started: make(chan struct{}, 2)}
|
||||
adapter := newTestAdapter(t, client)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
executionErrors := make(chan error, 2)
|
||||
for range 2 {
|
||||
go func() {
|
||||
_, err := adapter.Execute(ctx, testExecuteRequest(), nil)
|
||||
executionErrors <- err
|
||||
}()
|
||||
}
|
||||
for range 2 {
|
||||
select {
|
||||
case <-client.started:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out waiting for concurrent Promptkit calls")
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
for range 2 {
|
||||
if err := <-executionErrors; promptexec.CategoryOf(err) != promptexec.Canceled {
|
||||
t.Fatalf("Execute() error/category = %v/%q", err, promptexec.CategoryOf(err))
|
||||
}
|
||||
}
|
||||
if client.callCount() != 2 {
|
||||
t.Fatalf("provider calls = %d, want 2", client.callCount())
|
||||
}
|
||||
}
|
||||
|
||||
func (client *fakeClient) callCount() int {
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
return client.calls
|
||||
}
|
||||
|
||||
func (client *fakeClient) request() promptkit.GenerateRequest {
|
||||
client.mu.Lock()
|
||||
defer client.mu.Unlock()
|
||||
return client.requests[0]
|
||||
}
|
||||
|
||||
func TestInspectPromptAndProfile(t *testing.T) {
|
||||
adapter := newTestAdapter(t, &fakeClient{})
|
||||
inspection, err := adapter.InspectPrompt(context.Background(), "weather.daily_generated_text", "2.0.0")
|
||||
if err != nil {
|
||||
t.Fatalf("InspectPrompt() error = %v", err)
|
||||
}
|
||||
if inspection.PromptID != "weather.daily_generated_text" || inspection.PromptVersion != "2.0.0" || inspection.DefaultProfileID != "weather-balanced" {
|
||||
t.Fatalf("inspection = %#v", inspection)
|
||||
}
|
||||
if len(inspection.Inputs) != 1 || inspection.Inputs[0].Name != "data_package" || !inspection.Inputs[0].Required || inspection.Inputs[0].ContentType != "application/yaml" {
|
||||
t.Fatalf("inputs = %#v", inspection.Inputs)
|
||||
}
|
||||
if inspection.Output.Format != "json" || inspection.Output.ValidationMode != "json_schema" || inspection.Output.SchemaPath != "daily.generated_text.schema.json" {
|
||||
t.Fatalf("output = %#v", inspection.Output)
|
||||
}
|
||||
|
||||
profile, err := adapter.InspectProfile(context.Background(), "test-profile")
|
||||
if err != nil {
|
||||
t.Fatalf("InspectProfile() error = %v", err)
|
||||
}
|
||||
if profile.ProfileID != "test-profile" || profile.BackendID != "" || profile.ModelName != "test-model" || profile.CredentialRequired {
|
||||
t.Fatalf("profile = %#v", profile)
|
||||
}
|
||||
if strings.Contains(fmt.Sprintf("%#v", profile), "https://profile.example") {
|
||||
t.Fatalf("profile leaks endpoint: %#v", profile)
|
||||
}
|
||||
|
||||
builtin, err := adapter.InspectProfile(context.Background(), "gemini-flash-latest")
|
||||
if err != nil {
|
||||
t.Fatalf("InspectProfile(builtin) error = %v", err)
|
||||
}
|
||||
if builtin.ProfileID != "gemini-flash-latest" || builtin.ModelName == "" {
|
||||
t.Fatalf("builtin profile = %#v", builtin)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmbeddedProfilesAreAvailableToProductionAndTestAdapters(t *testing.T) {
|
||||
adapter, err := New(Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("New() error = %v", err)
|
||||
}
|
||||
for _, want := range []struct {
|
||||
id string
|
||||
backend string
|
||||
model string
|
||||
}{
|
||||
{"weather-light", "openrouter", "deepseek/deepseek-v4-flash"},
|
||||
{"weather-balanced", "openrouter", "~google/gemini-flash-latest"},
|
||||
{"weather-deep", "openrouter", "~anthropic/claude-sonnet-latest"},
|
||||
} {
|
||||
t.Run(want.id, func(t *testing.T) {
|
||||
assertProfile(t, adapter, want.id, want.backend, want.model)
|
||||
})
|
||||
}
|
||||
|
||||
testAdapter, err := newAdapterForTest(Config{}, &fakeClient{})
|
||||
if err != nil {
|
||||
t.Fatalf("newAdapterForTest() error = %v", err)
|
||||
}
|
||||
assertProfile(t, testAdapter, "weather-light", "openrouter", "deepseek/deepseek-v4-flash")
|
||||
}
|
||||
|
||||
func TestConfiguredProfilesOverrideEmbeddedFallbacks(t *testing.T) {
|
||||
file := writeProfileFile(t, `id: weather-light
|
||||
endpoint: https://local-file.example/v1
|
||||
model: file-light
|
||||
`)
|
||||
fileAdapter, err := New(Config{ProfileFile: file})
|
||||
if err != nil {
|
||||
t.Fatalf("New(profile file) error = %v", err)
|
||||
}
|
||||
assertProfile(t, fileAdapter, "weather-light", "", "file-light")
|
||||
|
||||
directory := testProfileDirectory(t, `id: weather-light
|
||||
backend: local
|
||||
model: directory-light
|
||||
`)
|
||||
directoryAdapter, err := New(Config{ProfileDirectory: directory, LocalEndpoint: "https://local-directory.example/v1"})
|
||||
if err != nil {
|
||||
t.Fatalf("New(profile directory) error = %v", err)
|
||||
}
|
||||
assertProfile(t, directoryAdapter, "weather-light", promptkit.BackendLocal, "directory-light")
|
||||
}
|
||||
|
||||
func TestMaintainedWeatherLightLocalProfileExampleInspectsOffline(t *testing.T) {
|
||||
adapter, err := New(Config{ProfileFile: filepath.Join("..", "..", "..", "examples", "weather-light-local-profile.yml")})
|
||||
if err != nil {
|
||||
t.Fatalf("New() error = %v", err)
|
||||
}
|
||||
assertProfile(t, adapter, "weather-light", "", "weather-local")
|
||||
}
|
||||
|
||||
func TestProfileResolutionFallsThroughOnlyWhenTheConfiguredIDIsAbsent(t *testing.T) {
|
||||
absentAdapter, err := New(Config{ProfileDirectory: testProfileDirectory(t, `id: other-profile
|
||||
backend: openrouter
|
||||
model: other-model
|
||||
`)})
|
||||
if err != nil {
|
||||
t.Fatalf("New(absent profile) error = %v", err)
|
||||
}
|
||||
assertProfile(t, absentAdapter, "weather-light", "openrouter", "deepseek/deepseek-v4-flash")
|
||||
|
||||
malformedAdapter, err := New(Config{ProfileDirectory: testProfileDirectory(t, `id: weather-light
|
||||
backend: openrouter
|
||||
`)})
|
||||
if err != nil {
|
||||
t.Fatalf("New(malformed profile) error = %v", err)
|
||||
}
|
||||
if _, err := malformedAdapter.InspectProfile(context.Background(), "weather-light"); err == nil {
|
||||
t.Fatal("InspectProfile() error = nil, want malformed configured profile error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProfileResolutionPreservesBuiltInAndExplicitPrecedence(t *testing.T) {
|
||||
adapter, err := New(Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("New() error = %v", err)
|
||||
}
|
||||
builtin, err := adapter.InspectProfile(context.Background(), "gemini-flash-latest")
|
||||
if err != nil {
|
||||
t.Fatalf("InspectProfile(builtin) error = %v", err)
|
||||
}
|
||||
if builtin.ProfileID != "gemini-flash-latest" || builtin.BackendID != "openrouter" || builtin.ModelName == "" {
|
||||
t.Fatalf("builtin profile = %#v", builtin)
|
||||
}
|
||||
|
||||
explicit, err := newAdapter(Config{}, promptkit.WithProfiles(promptkit.Profile{
|
||||
ID: "weather-light",
|
||||
Endpoint: "https://explicit.example/v1",
|
||||
Model: "explicit-light",
|
||||
}))
|
||||
if err != nil {
|
||||
t.Fatalf("newAdapter(explicit profile) error = %v", err)
|
||||
}
|
||||
assertProfile(t, explicit, "weather-light", "", "explicit-light")
|
||||
}
|
||||
|
||||
func TestExecuteUsesPreparedInlineDataPackage(t *testing.T) {
|
||||
client := &fakeClient{response: validResponse()}
|
||||
adapter := newTestAdapter(t, client)
|
||||
request := testExecuteRequest()
|
||||
callbackCalls := 0
|
||||
result, err := adapter.Execute(context.Background(), request, func(preparation promptexec.Preparation, debug *promptexec.PreparationDebug) error {
|
||||
callbackCalls++
|
||||
if preparation.PromptID != request.PromptID || preparation.PromptVersion != request.PromptVersion || preparation.ModelName != "test-model" {
|
||||
t.Fatalf("preparation = %#v", preparation)
|
||||
}
|
||||
if debug != nil {
|
||||
t.Fatalf("debug = %#v, want nil", debug)
|
||||
}
|
||||
if client.callCount() != 0 {
|
||||
t.Fatal("provider called before preparation callback")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Execute() error = %v", err)
|
||||
}
|
||||
if callbackCalls != 1 || client.callCount() != 1 {
|
||||
t.Fatalf("callback/provider calls = %d/%d, want 1/1", callbackCalls, client.callCount())
|
||||
}
|
||||
if result == nil || result.Validation.Status != promptexec.ValidationPassed || string(result.RawOutput) != client.response.Content {
|
||||
t.Fatalf("result = %#v", result)
|
||||
}
|
||||
if result.Debug != nil {
|
||||
t.Fatalf("debug = %#v, want nil", result.Debug)
|
||||
}
|
||||
providerRequest := client.request()
|
||||
if providerRequest.Target.Model != "test-model" || providerRequest.Target.Endpoint != "https://profile.example/v1" {
|
||||
t.Fatalf("provider target = %#v", providerRequest.Target)
|
||||
}
|
||||
if len(providerRequest.Prompt.Messages) == 0 || !strings.Contains(providerRequest.Prompt.Messages[2].Content, string(request.DataPackage)) {
|
||||
t.Fatalf("rendered messages do not contain exact data package: %#v", providerRequest.Prompt.Messages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteEmbeddedHourlyProfileThroughPreparedPath(t *testing.T) {
|
||||
t.Setenv("OPENROUTER_API_KEY", "test-openrouter-key")
|
||||
client := &fakeClient{response: hourlyValidResponse()}
|
||||
adapter, err := newAdapter(Config{}, promptkit.WithLLMClient(client))
|
||||
if err != nil {
|
||||
t.Fatalf("newAdapter() error = %v", err)
|
||||
}
|
||||
request := promptexec.ExecuteRequest{
|
||||
PromptID: "weather.hourly_generated_text",
|
||||
PromptVersion: "2.0.0",
|
||||
ProfileID: "weather-light",
|
||||
DataPackage: []byte("report:\n id: hourly\nbriefing: {}\n"),
|
||||
}
|
||||
var preparation promptexec.Preparation
|
||||
prepared := false
|
||||
result, err := adapter.Execute(context.Background(), request, func(value promptexec.Preparation, _ *promptexec.PreparationDebug) error {
|
||||
if client.callCount() != 0 {
|
||||
t.Fatal("provider was called before preparation completed")
|
||||
}
|
||||
preparation = value
|
||||
prepared = true
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Execute() error = %v", err)
|
||||
}
|
||||
if !prepared || preparation.ProfileID != "weather-light" || preparation.BackendID != "openrouter" || preparation.ModelName != "deepseek/deepseek-v4-flash" {
|
||||
t.Fatalf("preparation = %#v", preparation)
|
||||
}
|
||||
if result == nil || result.ProfileID != "weather-light" || result.BackendID != "openrouter" || result.ModelName != "deepseek/deepseek-v4-flash" || result.Validation.Status != promptexec.ValidationPassed {
|
||||
t.Fatalf("execution = %#v", result)
|
||||
}
|
||||
if client.callCount() != 1 || client.request().Target.Model != "deepseek/deepseek-v4-flash" {
|
||||
t.Fatalf("provider calls/request = %d/%#v", client.callCount(), client.request())
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteUsesExactInlineDataPackageProvenance(t *testing.T) {
|
||||
client := &fakeClient{response: validResponse()}
|
||||
reader := &recordingReader{}
|
||||
adapter := newTestAdapterWithOptions(t, client, promptkit.WithArtifactReader(reader))
|
||||
request := testExecuteRequest()
|
||||
if _, err := adapter.Execute(context.Background(), request, nil); err != nil {
|
||||
t.Fatalf("Execute() error = %v", err)
|
||||
}
|
||||
if reader.ref.Type != promptkit.ArtifactRefInline || reader.ref.URI != "" || reader.ref.Body != string(request.DataPackage) {
|
||||
t.Fatalf("artifact ref = %#v, want exact inline data package provenance", reader.ref)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteCapturesSensitiveDebugOnlyWhenRequested(t *testing.T) {
|
||||
client := &fakeClient{response: validResponse()}
|
||||
adapter := newTestAdapter(t, client)
|
||||
request := testExecuteRequest()
|
||||
request.CaptureDebug = true
|
||||
var preparationDebug *promptexec.PreparationDebug
|
||||
result, err := adapter.Execute(context.Background(), request, func(preparation promptexec.Preparation, debug *promptexec.PreparationDebug) error {
|
||||
preparationDebug = debug
|
||||
if strings.Contains(fmt.Sprintf("%#v", preparation), "https://profile.example") || strings.Contains(fmt.Sprintf("%#v", preparation), string(request.DataPackage)) {
|
||||
t.Fatalf("safe preparation leaks sensitive content: %#v", preparation)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Execute() error = %v", err)
|
||||
}
|
||||
if preparationDebug == nil || preparationDebug.Endpoint != "https://profile.example/v1" || len(preparationDebug.RenderedMessages) == 0 || len(preparationDebug.StructuredSchema) == 0 || len(preparationDebug.ParametersJSON) == 0 {
|
||||
t.Fatalf("preparation debug = %#v", preparationDebug)
|
||||
}
|
||||
if result.Debug == nil || string(result.Debug.RawOutput) != client.response.Content {
|
||||
t.Fatalf("execution debug = %#v", result.Debug)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMarshalDebugParametersOmitsProviderExtras(t *testing.T) {
|
||||
const marker = "private-debug-marker"
|
||||
parameters := string(marshalDebugParameters(promptkit.ExecutionTarget{
|
||||
Temperature: 0.2,
|
||||
MaxTokens: 400,
|
||||
TopP: 0.9,
|
||||
TimeoutSeconds: 30,
|
||||
ServiceTier: "flex",
|
||||
ReasoningEffort: "high",
|
||||
ExtraParams: map[string]any{
|
||||
"access-key": marker,
|
||||
"signature": marker,
|
||||
},
|
||||
}))
|
||||
if strings.Contains(parameters, marker) || strings.Contains(parameters, "extra_params") {
|
||||
t.Fatalf("debug parameters leaked provider extras: %s", parameters)
|
||||
}
|
||||
for _, want := range []string{`"temperature":0.2`, `"max_tokens":400`, `"top_p":0.9`, `"timeout_seconds":30`, `"service_tier":"flex"`, `"reasoning_effort":"high"`} {
|
||||
if !strings.Contains(parameters, want) {
|
||||
t.Fatalf("debug parameters missing safe value %q: %s", want, parameters)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteCallbackFailurePreventsGeneration(t *testing.T) {
|
||||
client := &fakeClient{response: validResponse()}
|
||||
adapter := newTestAdapter(t, client)
|
||||
callbackError := errors.New("save preparation")
|
||||
result, err := adapter.Execute(context.Background(), testExecuteRequest(), func(promptexec.Preparation, *promptexec.PreparationDebug) error {
|
||||
return callbackError
|
||||
})
|
||||
if result != nil || !errors.Is(err, callbackError) || client.callCount() != 0 {
|
||||
t.Fatalf("result/error/provider calls = %#v/%v/%d", result, err, client.callCount())
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteReturnsCompletedValidationRejection(t *testing.T) {
|
||||
client := &fakeClient{response: &promptkit.GenerateResponse{Content: `{"summary":42}`, Usage: promptkit.TokenUsage{TotalTokens: 5}}}
|
||||
adapter := newTestAdapter(t, client)
|
||||
result, err := adapter.Execute(context.Background(), testExecuteRequest(), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Execute() error = %v", err)
|
||||
}
|
||||
if result == nil || result.Validation.Status != promptexec.ValidationFailed || len(result.Validation.Diagnostics) == 0 || string(result.RawOutput) != client.response.Content {
|
||||
t.Fatalf("result = %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteDropsOversizedGeneratedOutput(t *testing.T) {
|
||||
client := &fakeClient{response: &promptkit.GenerateResponse{Content: strings.Repeat("x", generatedtext.MaxGeneratedTextBytes+1)}}
|
||||
adapter := newTestAdapter(t, client)
|
||||
request := testExecuteRequest()
|
||||
request.CaptureDebug = true
|
||||
result, err := adapter.Execute(context.Background(), request, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("Execute() error = %v", err)
|
||||
}
|
||||
if result == nil || result.Validation.Status != promptexec.ValidationFailed || len(result.RawOutput) != 0 || result.Debug == nil || len(result.Debug.RawOutput) != 0 {
|
||||
t.Fatalf("execution = %#v", result)
|
||||
}
|
||||
if len(result.Validation.Diagnostics) != 1 || result.Validation.Diagnostics[0] != "generated output exceeds the configured size limit" {
|
||||
t.Fatalf("diagnostics = %#v", result.Validation.Diagnostics)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteClassifiesOperationalFailures(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
client *fakeClient
|
||||
context func() (context.Context, context.CancelFunc)
|
||||
category promptexec.ErrorCategory
|
||||
}{
|
||||
{
|
||||
name: "generation",
|
||||
client: &fakeClient{err: errors.New("provider response body")},
|
||||
context: func() (context.Context, context.CancelFunc) {
|
||||
return context.WithCancel(context.Background())
|
||||
},
|
||||
category: promptexec.Generation,
|
||||
},
|
||||
{
|
||||
name: "canceled",
|
||||
client: &fakeClient{block: true},
|
||||
context: func() (context.Context, context.CancelFunc) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
return ctx, func() {}
|
||||
},
|
||||
category: promptexec.Canceled,
|
||||
},
|
||||
{
|
||||
name: "deadline",
|
||||
client: &fakeClient{block: true},
|
||||
context: func() (context.Context, context.CancelFunc) {
|
||||
return context.WithTimeout(context.Background(), time.Nanosecond)
|
||||
},
|
||||
category: promptexec.DeadlineExceeded,
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
adapter := newTestAdapter(t, test.client)
|
||||
ctx, cancel := test.context()
|
||||
defer cancel()
|
||||
result, err := adapter.Execute(ctx, testExecuteRequest(), nil)
|
||||
if result != nil || err == nil || promptexec.CategoryOf(err) != test.category {
|
||||
t.Fatalf("result/error/category = %#v/%v/%q, want %q", result, err, promptexec.CategoryOf(err), test.category)
|
||||
}
|
||||
if strings.Contains(err.Error(), "provider response body") {
|
||||
t.Fatalf("error leaks provider detail: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyPromptkitErrors(t *testing.T) {
|
||||
tests := []struct {
|
||||
err error
|
||||
category promptexec.ErrorCategory
|
||||
}{
|
||||
{promptkit.ErrInvalidConfig, promptexec.InvalidConfiguration},
|
||||
{promptkit.ErrInvalidRequest, promptexec.InvalidRequest},
|
||||
{promptkit.ErrPromptNotFound, promptexec.PromptNotFound},
|
||||
{promptkit.ErrPromptLoad, promptexec.PromptLoad},
|
||||
{promptkit.ErrProfileNotFound, promptexec.ProfileNotFound},
|
||||
{promptkit.ErrProfileLoad, promptexec.ProfileLoad},
|
||||
{promptkit.ErrAPIKeyEnvMissing, promptexec.MissingCredential},
|
||||
{promptkit.ErrArtifactLoad, promptexec.ArtifactLoad},
|
||||
{promptkit.ErrPromptRender, promptexec.PromptRender},
|
||||
{promptkit.ErrLLMGenerate, promptexec.Generation},
|
||||
{promptkit.ErrValidation, promptexec.OperationalValidation},
|
||||
{&promptkit.CapacityError{BackendID: "local"}, promptexec.Capacity},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(string(test.category), func(t *testing.T) {
|
||||
got := classifyError(test.err)
|
||||
if promptexec.CategoryOf(got) != test.category {
|
||||
t.Fatalf("category = %q, want %q", promptexec.CategoryOf(got), test.category)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewValidatesConfiguration(t *testing.T) {
|
||||
if _, err := New(Config{ProfileDirectory: "profiles", ProfileFile: "profile.yml"}); promptexec.CategoryOf(err) != promptexec.InvalidConfiguration {
|
||||
t.Fatalf("profile source error = %v", err)
|
||||
}
|
||||
if _, err := New(Config{LocalConcurrencyLimit: 1}); promptexec.CategoryOf(err) != promptexec.InvalidConfiguration {
|
||||
t.Fatalf("local concurrency error = %v", err)
|
||||
}
|
||||
if _, err := New(Config{LocalEndpoint: "not a URL"}); promptexec.CategoryOf(err) != promptexec.InvalidConfiguration {
|
||||
t.Fatalf("local endpoint error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalBackendAndMissingCredentialBehavior(t *testing.T) {
|
||||
t.Setenv("WEATHERREPORTER_TEST_MISSING_KEY", "")
|
||||
profiles := testProfileDirectory(t, `id: local-profile
|
||||
backend: local
|
||||
model: local-model
|
||||
`)
|
||||
adapter, err := newAdapterForTest(Config{
|
||||
ProfileDirectory: profiles,
|
||||
LocalEndpoint: "https://local.example/v1",
|
||||
LocalConcurrencyLimit: 1,
|
||||
}, &fakeClient{})
|
||||
if err != nil {
|
||||
t.Fatalf("newAdapterForTest(local) error = %v", err)
|
||||
}
|
||||
profile, err := adapter.InspectProfile(context.Background(), "local-profile")
|
||||
if err != nil || profile.BackendID != promptkit.BackendLocal || profile.ModelName != "local-model" {
|
||||
t.Fatalf("local profile/error = %#v/%v", profile, err)
|
||||
}
|
||||
if got := classifyError(&promptkit.CapacityError{BackendID: promptkit.BackendLocal}); promptexec.CategoryOf(got) != promptexec.Capacity {
|
||||
t.Fatalf("capacity classification = %v", got)
|
||||
}
|
||||
|
||||
credentialProfiles := testProfileDirectory(t, `id: credential-profile
|
||||
endpoint: https://profile.example/v1
|
||||
model: test-model
|
||||
api_key_env: WEATHERREPORTER_TEST_MISSING_KEY
|
||||
`)
|
||||
client := &fakeClient{response: validResponse()}
|
||||
credentialAdapter, err := newAdapterForTest(Config{ProfileDirectory: credentialProfiles}, client)
|
||||
if err != nil {
|
||||
t.Fatalf("newAdapterForTest(credential) error = %v", err)
|
||||
}
|
||||
credentialProfile, err := credentialAdapter.InspectProfile(context.Background(), "credential-profile")
|
||||
if err != nil || credentialProfile.CredentialRequired || credentialProfile.APIKeyEnv != "WEATHERREPORTER_TEST_MISSING_KEY" {
|
||||
t.Fatalf("credential profile/error = %#v/%v", credentialProfile, err)
|
||||
}
|
||||
request := testExecuteRequest()
|
||||
request.ProfileID = "credential-profile"
|
||||
result, err := credentialAdapter.Execute(context.Background(), request, nil)
|
||||
if result != nil || promptexec.CategoryOf(err) != promptexec.MissingCredential || client.callCount() != 0 {
|
||||
t.Fatalf("credential result/category/calls = %#v/%q/%d", result, promptexec.CategoryOf(err), client.callCount())
|
||||
}
|
||||
}
|
||||
|
||||
func newTestAdapter(t *testing.T, client promptkit.LLMClient) *Adapter {
|
||||
return newTestAdapterWithOptions(t, client)
|
||||
}
|
||||
|
||||
func assertProfile(t *testing.T, adapter *Adapter, id string, backend string, model string) {
|
||||
t.Helper()
|
||||
profile, err := adapter.InspectProfile(context.Background(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("InspectProfile(%q) error = %v", id, err)
|
||||
}
|
||||
if profile.ProfileID != id || profile.BackendID != backend || profile.ModelName != model {
|
||||
t.Fatalf("profile = %#v, want %q with backend/model %q/%q", profile, id, backend, model)
|
||||
}
|
||||
}
|
||||
|
||||
func newTestAdapterWithOptions(t *testing.T, client promptkit.LLMClient, options ...promptkit.Option) *Adapter {
|
||||
t.Helper()
|
||||
profiles := testProfileDirectory(t, `id: test-profile
|
||||
endpoint: https://profile.example/v1
|
||||
model: test-model
|
||||
temperature: 0.2
|
||||
max_tokens: 300
|
||||
top_p: 1
|
||||
timeout_seconds: 30
|
||||
`)
|
||||
options = append(options, promptkit.WithLLMClient(client))
|
||||
adapter, err := newAdapter(Config{ProfileDirectory: profiles, Timeout: time.Second}, options...)
|
||||
if err != nil {
|
||||
t.Fatalf("newAdapter() error = %v", err)
|
||||
}
|
||||
return adapter
|
||||
}
|
||||
|
||||
func testProfileDirectory(t *testing.T, profile string) string {
|
||||
t.Helper()
|
||||
profiles := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(profiles, "profile.yml"), []byte(profile), 0o600); err != nil {
|
||||
t.Fatalf("write profile: %v", err)
|
||||
}
|
||||
return profiles
|
||||
}
|
||||
|
||||
func writeProfileFile(t *testing.T, profile string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "profile.yml")
|
||||
if err := os.WriteFile(path, []byte(profile), 0o600); err != nil {
|
||||
t.Fatalf("write profile: %v", err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func testExecuteRequest() promptexec.ExecuteRequest {
|
||||
return promptexec.ExecuteRequest{
|
||||
PromptID: "weather.daily_generated_text",
|
||||
PromptVersion: "2.0.0",
|
||||
ProfileID: "test-profile",
|
||||
DataPackage: []byte("report:\n id: daily\nbriefing: {}\n"),
|
||||
}
|
||||
}
|
||||
|
||||
func validResponse() *promptkit.GenerateResponse {
|
||||
return &promptkit.GenerateResponse{
|
||||
Content: `{"summary":"A quiet day is expected.","forecast_discussion":["High pressure keeps conditions settled."],"precipitation_timing":""}`,
|
||||
Usage: promptkit.TokenUsage{PromptTokens: 12, CompletionTokens: 8, TotalTokens: 20},
|
||||
}
|
||||
}
|
||||
|
||||
func hourlyValidResponse() *promptkit.GenerateResponse {
|
||||
return &promptkit.GenerateResponse{
|
||||
Content: `{"summary":"A quiet hour is expected.","forecast_discussion":"Conditions remain settled.","precipitation_timing":""}`,
|
||||
Usage: promptkit.TokenUsage{PromptTokens: 12, CompletionTokens: 8, TotalTokens: 20},
|
||||
}
|
||||
}
|
||||
718
internal/adapters/weatherapi/client.go
Normal file
718
internal/adapters/weatherapi/client.go
Normal file
@@ -0,0 +1,718 @@
|
||||
// Package weatherapi adapts the internal weather API to weather data bundles.
|
||||
package weatherapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/config"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/weatherdata"
|
||||
)
|
||||
|
||||
const (
|
||||
convectiveOutlooksEndpoint = "/outlooks/convective"
|
||||
currentConditionsEndpoint = "/conditions/current"
|
||||
sourceSPCConvectiveOutlooks = config.MissingSourceSPCConvectiveOutlooks
|
||||
|
||||
defaultWarmupEndpoint = currentConditionsEndpoint
|
||||
defaultWarmupAttempts = 3
|
||||
defaultWarmupDelay = time.Second
|
||||
defaultFetchAttempts = 2
|
||||
defaultFetchRetryDelay = time.Second
|
||||
maxResponseBodyBytes = 10 << 20
|
||||
)
|
||||
|
||||
var errResponseBodyTooLarge = errors.New("response exceeds 10 MiB limit")
|
||||
|
||||
type Client struct {
|
||||
baseURL *url.URL
|
||||
httpClient *http.Client
|
||||
units string
|
||||
format string
|
||||
timezone string
|
||||
precision int
|
||||
missingSource config.MissingSourceConfig
|
||||
now func() time.Time
|
||||
|
||||
warmupEndpoint string
|
||||
warmupAttempts int
|
||||
warmupDelay time.Duration
|
||||
fetchAttempts int
|
||||
fetchRetryDelay time.Duration
|
||||
}
|
||||
|
||||
type Option func(*Client)
|
||||
|
||||
func WithHTTPClient(httpClient *http.Client) Option {
|
||||
return func(c *Client) {
|
||||
if httpClient != nil {
|
||||
c.httpClient = httpClient
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func WithClock(now func() time.Time) Option {
|
||||
return func(c *Client) {
|
||||
if now != nil {
|
||||
c.now = now
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func New(cfg config.Config, opts ...Option) (*Client, error) {
|
||||
if strings.TrimSpace(cfg.WeatherAPI.BaseURL) == "" {
|
||||
return nil, fmt.Errorf("weather_api.base_url is required")
|
||||
}
|
||||
baseURL, err := url.Parse(cfg.WeatherAPI.BaseURL)
|
||||
if err != nil || baseURL.Scheme == "" || baseURL.Host == "" {
|
||||
return nil, fmt.Errorf("weather_api.base_url must be an absolute URL")
|
||||
}
|
||||
if !strings.EqualFold(baseURL.Scheme, "http") && !strings.EqualFold(baseURL.Scheme, "https") {
|
||||
return nil, fmt.Errorf("weather_api.base_url must use http or https")
|
||||
}
|
||||
|
||||
timeout := cfg.WeatherAPI.Timeout
|
||||
if timeout <= 0 {
|
||||
timeout = 10 * time.Second
|
||||
}
|
||||
|
||||
client := &Client{
|
||||
baseURL: baseURL,
|
||||
httpClient: &http.Client{Timeout: timeout},
|
||||
units: cfg.WeatherAPI.Units,
|
||||
format: cfg.WeatherAPI.Format,
|
||||
timezone: cfg.WeatherAPI.Timezone,
|
||||
precision: cfg.WeatherAPI.Precision,
|
||||
missingSource: config.MissingSourceConfig{
|
||||
Default: cfg.MissingSource.Default,
|
||||
Sources: cfg.MissingSource.Sources,
|
||||
},
|
||||
now: time.Now,
|
||||
warmupEndpoint: defaultWarmupEndpoint,
|
||||
warmupAttempts: defaultWarmupAttempts,
|
||||
warmupDelay: defaultWarmupDelay,
|
||||
fetchAttempts: defaultFetchAttempts,
|
||||
fetchRetryDelay: defaultFetchRetryDelay,
|
||||
}
|
||||
for _, opt := range opts {
|
||||
opt(client)
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (c *Client) FetchBundle(ctx context.Context) (*weatherdata.Bundle, error) {
|
||||
warmup, err := c.warmup(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fetchedAt := c.now()
|
||||
builder := bundleBuilder{
|
||||
client: c,
|
||||
bundle: &weatherdata.Bundle{FetchedAt: fetchedAt},
|
||||
}
|
||||
|
||||
for _, acquired := range builder.acquireSources(ctx, warmup) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, fmt.Errorf("fetch weather API sources: %w", err)
|
||||
}
|
||||
if err := builder.mergeSource(acquired); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return builder.bundle, nil
|
||||
}
|
||||
|
||||
type bundleBuilder struct {
|
||||
client *Client
|
||||
bundle *weatherdata.Bundle
|
||||
}
|
||||
|
||||
type sourceRequest struct {
|
||||
name string
|
||||
endpoint string
|
||||
query queryOptions
|
||||
missingMessage string
|
||||
required bool
|
||||
decodeLabel string
|
||||
}
|
||||
|
||||
type fetchedSource struct {
|
||||
raw json.RawMessage
|
||||
source weatherdata.Source
|
||||
}
|
||||
|
||||
type warmupResponse struct {
|
||||
endpoint string
|
||||
requestURL *url.URL
|
||||
body []byte
|
||||
fetchedAt time.Time
|
||||
}
|
||||
|
||||
type sourceAcquisition struct {
|
||||
request sourceRequest
|
||||
fetched fetchedSource
|
||||
err error
|
||||
warmup warmupResponse
|
||||
usesWarmup bool
|
||||
}
|
||||
|
||||
func (b *bundleBuilder) acquireSources(ctx context.Context, warmup warmupResponse) []sourceAcquisition {
|
||||
sources := []sourceAcquisition{
|
||||
{request: sourceRequest{name: config.MissingSourceObservations, endpoint: "/observations", query: queryOptions{precision: true}, missingMessage: "observation data is missing"}},
|
||||
{request: currentConditionsRequest()},
|
||||
{request: sourceRequest{name: "hourly", endpoint: "/forecast/hourly", query: queryOptions{precision: true, timezone: true}, missingMessage: "hourly forecast data is missing", required: true, decodeLabel: "hourly forecast"}},
|
||||
{request: sourceRequest{name: config.MissingSourceNarrative, endpoint: "/forecast/narrative", query: queryOptions{precision: true, timezone: true}, missingMessage: "narrative forecast data is missing"}},
|
||||
{request: sourceRequest{name: config.MissingSourceAlerts, endpoint: "/alerts/active", query: queryOptions{allowNull: true}, missingMessage: "active alerts data is missing"}},
|
||||
{request: sourceRequest{name: config.MissingSourceDiscussion, endpoint: "/discussion", query: queryOptions{timezone: true}, missingMessage: "forecast discussion data is missing"}},
|
||||
{request: sourceRequest{name: config.MissingSourceWeatherStory, endpoint: "/weatherstories/latest", query: queryOptions{omitUnits: true}, missingMessage: "NWS weather story data is missing"}},
|
||||
{request: sourceRequest{name: sourceSPCConvectiveOutlooks, endpoint: convectiveOutlooksEndpoint, query: queryOptions{timezone: true, omitUnits: true}, missingMessage: "SPC convective outlook data is missing"}},
|
||||
}
|
||||
if warmup.endpoint == currentConditionsEndpoint {
|
||||
sources[1].warmup = warmup
|
||||
sources[1].usesWarmup = true
|
||||
}
|
||||
|
||||
var group sync.WaitGroup
|
||||
for i := range sources {
|
||||
if sources[i].usesWarmup {
|
||||
continue
|
||||
}
|
||||
group.Add(1)
|
||||
go func(index int) {
|
||||
defer group.Done()
|
||||
request := sources[index].request
|
||||
raw, source, err := b.client.fetch(ctx, request.name, request.endpoint, request.query)
|
||||
sources[index].fetched = fetchedSource{raw: raw, source: source}
|
||||
sources[index].err = err
|
||||
}(i)
|
||||
}
|
||||
group.Wait()
|
||||
return sources
|
||||
}
|
||||
|
||||
func (b *bundleBuilder) mergeSource(acquired sourceAcquisition) error {
|
||||
switch acquired.request.name {
|
||||
case config.MissingSourceObservations:
|
||||
return b.fetchObservation(acquired)
|
||||
case config.MissingSourceCurrent:
|
||||
return b.fetchCurrent(acquired)
|
||||
case "hourly":
|
||||
return b.fetchHourly(acquired)
|
||||
case config.MissingSourceNarrative:
|
||||
return b.fetchNarrative(acquired)
|
||||
case config.MissingSourceAlerts:
|
||||
return b.fetchAlerts(acquired)
|
||||
case config.MissingSourceDiscussion:
|
||||
return b.fetchDiscussion(acquired)
|
||||
case config.MissingSourceWeatherStory:
|
||||
return b.fetchWeatherStory(acquired)
|
||||
case sourceSPCConvectiveOutlooks:
|
||||
return b.fetchSPCConvectiveOutlooks(acquired)
|
||||
default:
|
||||
return fmt.Errorf("merge unknown weather source %q", acquired.request.name)
|
||||
}
|
||||
}
|
||||
|
||||
func (b *bundleBuilder) fetchObservation(acquired sourceAcquisition) error {
|
||||
var observation weatherdata.Observation
|
||||
fetched, ok, err := b.fetchDecodedSource(acquired, &observation)
|
||||
if err != nil || !ok {
|
||||
return err
|
||||
}
|
||||
source := fetched.source
|
||||
source.IssuedAt = &observation.Timestamp
|
||||
b.bundle.Observation = &observation
|
||||
b.addSource(source)
|
||||
return nil
|
||||
}
|
||||
|
||||
func currentConditionsRequest() sourceRequest {
|
||||
return sourceRequest{
|
||||
name: config.MissingSourceCurrent,
|
||||
endpoint: currentConditionsEndpoint,
|
||||
query: queryOptions{precision: true},
|
||||
missingMessage: "current conditions data is missing",
|
||||
}
|
||||
}
|
||||
|
||||
func (b *bundleBuilder) fetchCurrent(acquired sourceAcquisition) error {
|
||||
var current weatherdata.Current
|
||||
fetched, ok, err := b.fetchDecodedSource(acquired, ¤t)
|
||||
if err != nil || !ok {
|
||||
return err
|
||||
}
|
||||
source := fetched.source
|
||||
b.bundle.Current = ¤t
|
||||
b.addSource(source)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *bundleBuilder) fetchHourly(acquired sourceAcquisition) error {
|
||||
var hourly weatherdata.ForecastRun
|
||||
fetched, ok, err := b.fetchDecodedSource(acquired, &hourly)
|
||||
if err != nil || !ok {
|
||||
return err
|
||||
}
|
||||
source := fetched.source
|
||||
if len(hourly.Periods) == 0 {
|
||||
return fmt.Errorf("hourly forecast from %s contains no periods", source.Endpoint)
|
||||
}
|
||||
for i, period := range hourly.Periods {
|
||||
if !period.HasUsableTimeBounds() {
|
||||
return fmt.Errorf("hourly forecast from %s has unusable time bounds for period %d", source.Endpoint, i+1)
|
||||
}
|
||||
if !period.HasValidPrecipitationProbability() {
|
||||
return fmt.Errorf("hourly forecast from %s has invalid precipitation probability for period %d", source.Endpoint, i+1)
|
||||
}
|
||||
}
|
||||
source.IssuedAt = &hourly.IssuedAt
|
||||
source.UpdatedAt = hourly.UpdatedAt
|
||||
b.bundle.Hourly = &hourly
|
||||
b.addSource(source)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *bundleBuilder) fetchNarrative(acquired sourceAcquisition) error {
|
||||
var narrative weatherdata.ForecastRun
|
||||
fetched, ok, err := b.fetchDecodedSource(acquired, &narrative)
|
||||
if err != nil || !ok {
|
||||
return err
|
||||
}
|
||||
source := fetched.source
|
||||
source.IssuedAt = &narrative.IssuedAt
|
||||
source.UpdatedAt = narrative.UpdatedAt
|
||||
b.bundle.Narrative = &narrative
|
||||
b.addSource(source)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *bundleBuilder) fetchAlerts(acquired sourceAcquisition) error {
|
||||
fetched, ok, err := b.fetchSource(acquired)
|
||||
if err != nil || !ok {
|
||||
return err
|
||||
}
|
||||
raw, source := fetched.raw, fetched.source
|
||||
if isJSONNull(raw) {
|
||||
b.bundle.Alerts = &weatherdata.AlertRun{}
|
||||
b.addSource(source)
|
||||
return nil
|
||||
}
|
||||
var alerts weatherdata.AlertRun
|
||||
if err := decodeSource(raw, &alerts); err != nil {
|
||||
return b.handleMalformed(&source, err, acquired.request)
|
||||
}
|
||||
if alerts.AsOf != nil {
|
||||
source.IssuedAt = alerts.AsOf
|
||||
}
|
||||
b.bundle.Alerts = &alerts
|
||||
b.addSource(source)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *bundleBuilder) fetchDiscussion(acquired sourceAcquisition) error {
|
||||
var discussion weatherdata.Discussion
|
||||
fetched, ok, err := b.fetchDecodedSource(acquired, &discussion)
|
||||
if err != nil || !ok {
|
||||
return err
|
||||
}
|
||||
source := fetched.source
|
||||
source.IssuedAt = &discussion.IssuedAt
|
||||
source.UpdatedAt = discussion.UpdatedAt
|
||||
b.bundle.Discussion = &discussion
|
||||
b.addSource(source)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *bundleBuilder) fetchWeatherStory(acquired sourceAcquisition) error {
|
||||
var story weatherdata.WeatherStory
|
||||
fetched, ok, err := b.fetchDecodedSource(acquired, &story)
|
||||
if err != nil || !ok {
|
||||
return err
|
||||
}
|
||||
source := fetched.source
|
||||
if !story.HasUsableContent() {
|
||||
return b.handleMalformed(&source, fmt.Errorf("weather story has no usable content"), acquired.request)
|
||||
}
|
||||
if !story.StartTime.IsZero() {
|
||||
source.IssuedAt = &story.StartTime
|
||||
}
|
||||
source.UpdatedAt = story.UpdatedAt
|
||||
b.bundle.WeatherStory = &story
|
||||
b.addSource(source)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *bundleBuilder) fetchSPCConvectiveOutlooks(acquired sourceAcquisition) error {
|
||||
var run weatherdata.ConvectiveOutlookRun
|
||||
fetched, ok, err := b.fetchDecodedSource(acquired, &run)
|
||||
if err != nil || !ok {
|
||||
return err
|
||||
}
|
||||
source := fetched.source
|
||||
if run.IssuedAt != nil {
|
||||
source.IssuedAt = run.IssuedAt
|
||||
} else {
|
||||
source.IssuedAt = run.AsOf
|
||||
}
|
||||
source.UpdatedAt = run.UpdatedAt
|
||||
b.bundle.SPCConvectiveOutlooks = &run
|
||||
b.addSource(source)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *bundleBuilder) fetchDecodedSource(acquired sourceAcquisition, target any) (fetchedSource, bool, error) {
|
||||
fetched, ok, err := b.fetchSource(acquired)
|
||||
if err != nil || !ok {
|
||||
return fetchedSource{}, false, err
|
||||
}
|
||||
return b.decodeFetchedSource(fetched, acquired.request, target)
|
||||
}
|
||||
|
||||
func (b *bundleBuilder) decodeFetchedSource(fetched fetchedSource, request sourceRequest, target any) (fetchedSource, bool, error) {
|
||||
if err := decodeSource(fetched.raw, target); err != nil {
|
||||
return fetchedSource{}, false, b.handleMalformed(&fetched.source, err, request)
|
||||
}
|
||||
return fetched, true, nil
|
||||
}
|
||||
|
||||
func (b *bundleBuilder) fetchSource(acquired sourceAcquisition) (fetchedSource, bool, error) {
|
||||
if acquired.usesWarmup {
|
||||
raw, source, err := b.client.decodeSourceResponse(acquired.request.name, acquired.request.endpoint, acquired.request.query, acquired.warmup.requestURL, acquired.warmup.body, acquired.warmup.fetchedAt)
|
||||
if err != nil {
|
||||
return fetchedSource{}, false, err
|
||||
}
|
||||
acquired.fetched = fetchedSource{raw: raw, source: source}
|
||||
} else if acquired.err != nil {
|
||||
return fetchedSource{}, false, acquired.err
|
||||
}
|
||||
if acquired.fetched.raw == nil {
|
||||
return fetchedSource{}, false, b.handleMissing(&acquired.fetched.source, acquired.request.missingMessage, acquired.request.required)
|
||||
}
|
||||
return acquired.fetched, true, nil
|
||||
}
|
||||
|
||||
func (b *bundleBuilder) handleMissing(source *weatherdata.Source, message string, required bool) error {
|
||||
source.Missing = true
|
||||
if required {
|
||||
return fmt.Errorf("%s from %s is required", message, source.Endpoint)
|
||||
}
|
||||
return b.applyMissingPolicy(source, "missing_source", message)
|
||||
}
|
||||
|
||||
func (b *bundleBuilder) handleMalformed(source *weatherdata.Source, err error, request sourceRequest) error {
|
||||
if request.required {
|
||||
label := request.name
|
||||
if request.decodeLabel != "" {
|
||||
label = request.decodeLabel
|
||||
}
|
||||
return fmt.Errorf("decode %s from %s: %w", label, source.Endpoint, err)
|
||||
}
|
||||
source.Missing = true
|
||||
return b.applyMissingPolicy(source, "malformed_source", fmt.Sprintf("malformed %s data: %v", source.Name, err))
|
||||
}
|
||||
|
||||
func (b *bundleBuilder) applyMissingPolicy(source *weatherdata.Source, code string, message string) error {
|
||||
policy := b.client.policyFor(source.Name)
|
||||
if policy == config.MissingSourceError {
|
||||
return fmt.Errorf("%s: %s", source.Name, message)
|
||||
}
|
||||
if policy == config.MissingSourceWarn {
|
||||
warning := weatherdata.SourceWarning{
|
||||
Source: source.Name,
|
||||
Code: code,
|
||||
Severity: "warning",
|
||||
Message: message,
|
||||
Endpoint: source.Endpoint,
|
||||
CompletenessImpact: "source omitted from bundle",
|
||||
}
|
||||
source.Warnings = append(source.Warnings, warning)
|
||||
b.bundle.Warnings = append(b.bundle.Warnings, warning)
|
||||
}
|
||||
b.addSource(*source)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b *bundleBuilder) addSource(source weatherdata.Source) {
|
||||
b.bundle.Sources = append(b.bundle.Sources, source)
|
||||
}
|
||||
|
||||
func (c *Client) policyFor(source string) config.MissingSourcePolicy {
|
||||
if policy, ok := c.missingSource.Sources[source]; ok {
|
||||
return policy
|
||||
}
|
||||
return c.missingSource.Default
|
||||
}
|
||||
|
||||
type queryOptions struct {
|
||||
precision bool
|
||||
timezone bool
|
||||
allowNull bool
|
||||
omitUnits bool
|
||||
}
|
||||
|
||||
type envelope struct {
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
|
||||
func (c *Client) fetch(ctx context.Context, sourceName string, endpoint string, opts queryOptions) (json.RawMessage, weatherdata.Source, error) {
|
||||
reqURL, body, err := c.fetchHTTP(ctx, endpoint, opts)
|
||||
if err != nil {
|
||||
return nil, weatherdata.Source{}, err
|
||||
}
|
||||
return c.decodeSourceResponse(sourceName, endpoint, opts, reqURL, body, c.now())
|
||||
}
|
||||
|
||||
func (c *Client) decodeSourceResponse(sourceName string, endpoint string, opts queryOptions, reqURL *url.URL, body []byte, fetchedAt time.Time) (json.RawMessage, weatherdata.Source, error) {
|
||||
var env envelope
|
||||
if err := json.Unmarshal(body, &env); err != nil {
|
||||
return nil, weatherdata.Source{}, fmt.Errorf("decode %s envelope: %w", endpoint, err)
|
||||
}
|
||||
|
||||
source := weatherdata.Source{
|
||||
Name: sourceName,
|
||||
Endpoint: endpoint,
|
||||
Query: queryMap(reqURL.Query()),
|
||||
FetchedAt: fetchedAt,
|
||||
}
|
||||
if len(env.Data) == 0 || (isJSONNull(env.Data) && !opts.allowNull) {
|
||||
source.Missing = true
|
||||
return nil, source, nil
|
||||
}
|
||||
hash, err := sourceHash(env.Data)
|
||||
if err != nil {
|
||||
return env.Data, source, nil
|
||||
}
|
||||
source.DataSHA256 = hash
|
||||
return env.Data, source, nil
|
||||
}
|
||||
|
||||
func (c *Client) warmup(ctx context.Context) (warmupResponse, error) {
|
||||
endpoint := c.warmupEndpoint
|
||||
if strings.TrimSpace(endpoint) == "" {
|
||||
endpoint = defaultWarmupEndpoint
|
||||
}
|
||||
attempts := positiveAttemptCount(c.warmupAttempts)
|
||||
var lastErr error
|
||||
var lastRetryable bool
|
||||
for attempt := 1; attempt <= attempts; attempt++ {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return warmupResponse{}, fmt.Errorf("warm up weather API via %s: %w", endpoint, err)
|
||||
}
|
||||
reqURL, body, err := c.warmupOnce(ctx, endpoint)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
lastRetryable = isRetryableRequestError(err)
|
||||
} else {
|
||||
return warmupResponse{endpoint: endpoint, requestURL: reqURL, body: body, fetchedAt: c.now()}, nil
|
||||
}
|
||||
if !lastRetryable || attempt == attempts {
|
||||
break
|
||||
}
|
||||
if err := waitForRetry(ctx, c.warmupDelay); err != nil {
|
||||
return warmupResponse{}, fmt.Errorf("warm up weather API via %s after %d attempt(s): %w", endpoint, attempt, err)
|
||||
}
|
||||
}
|
||||
if !lastRetryable {
|
||||
return warmupResponse{}, lastErr
|
||||
}
|
||||
return warmupResponse{}, fmt.Errorf("warm up weather API via %s failed after %d attempts: %w", endpoint, attempts, lastErr)
|
||||
}
|
||||
|
||||
func (c *Client) warmupOnce(ctx context.Context, endpoint string) (*url.URL, []byte, error) {
|
||||
return c.fetchHTTPOnce(ctx, endpoint, queryOptions{precision: true})
|
||||
}
|
||||
|
||||
func (c *Client) fetchHTTP(ctx context.Context, endpoint string, opts queryOptions) (*url.URL, []byte, error) {
|
||||
attempts := positiveAttemptCount(c.fetchAttempts)
|
||||
var lastErr error
|
||||
var lastRetryable bool
|
||||
for attempt := 1; attempt <= attempts; attempt++ {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, nil, fmt.Errorf("fetch %s: %w", endpoint, err)
|
||||
}
|
||||
reqURL, body, err := c.fetchHTTPOnce(ctx, endpoint, opts)
|
||||
if err == nil {
|
||||
return reqURL, body, nil
|
||||
}
|
||||
lastErr = err
|
||||
lastRetryable = isRetryableRequestError(err)
|
||||
if !lastRetryable || attempt == attempts {
|
||||
break
|
||||
}
|
||||
if err := waitForRetry(ctx, c.fetchRetryDelay); err != nil {
|
||||
return nil, nil, fmt.Errorf("fetch %s retry delay after attempt %d: %w", endpoint, attempt, err)
|
||||
}
|
||||
}
|
||||
if lastRetryable {
|
||||
return nil, nil, fmt.Errorf("fetch %s failed after %d attempts: %w", endpoint, attempts, lastErr)
|
||||
}
|
||||
return nil, nil, lastErr
|
||||
}
|
||||
|
||||
func (c *Client) fetchHTTPOnce(ctx context.Context, endpoint string, opts queryOptions) (*url.URL, []byte, error) {
|
||||
reqURL := c.endpointURL(endpoint, opts)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL.String(), nil)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("create request for %s: %w", endpoint, err)
|
||||
}
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("fetch %s: %w", endpoint, err)
|
||||
if ctx.Err() != nil {
|
||||
return reqURL, nil, err
|
||||
}
|
||||
return reqURL, nil, retryableRequestError{err: err}
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := readResponseBody(resp.Body)
|
||||
if err != nil {
|
||||
return reqURL, nil, responseReadError(ctx, endpoint, err)
|
||||
}
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
err := fmt.Errorf("fetch %s: unexpected HTTP status %d", endpoint, resp.StatusCode)
|
||||
if isRetryableHTTPStatus(resp.StatusCode) {
|
||||
return reqURL, nil, retryableRequestError{err: err}
|
||||
}
|
||||
return reqURL, nil, err
|
||||
}
|
||||
return reqURL, body, nil
|
||||
}
|
||||
|
||||
func readResponseBody(body io.Reader) ([]byte, error) {
|
||||
data, err := io.ReadAll(io.LimitReader(body, maxResponseBodyBytes+1))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if int64(len(data)) > maxResponseBodyBytes {
|
||||
return nil, errResponseBodyTooLarge
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func responseReadError(ctx context.Context, endpoint string, err error) error {
|
||||
err = fmt.Errorf("read %s response: %w", endpoint, err)
|
||||
if errors.Is(err, errResponseBodyTooLarge) || ctx.Err() != nil {
|
||||
return err
|
||||
}
|
||||
return retryableRequestError{err: err}
|
||||
}
|
||||
|
||||
type retryableRequestError struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (e retryableRequestError) Error() string {
|
||||
return e.err.Error()
|
||||
}
|
||||
|
||||
func (e retryableRequestError) Unwrap() error {
|
||||
return e.err
|
||||
}
|
||||
|
||||
func isRetryableRequestError(err error) bool {
|
||||
_, ok := err.(retryableRequestError)
|
||||
return ok
|
||||
}
|
||||
|
||||
func isRetryableHTTPStatus(status int) bool {
|
||||
switch status {
|
||||
case http.StatusRequestTimeout,
|
||||
http.StatusTooManyRequests,
|
||||
http.StatusInternalServerError,
|
||||
http.StatusBadGateway,
|
||||
http.StatusServiceUnavailable,
|
||||
http.StatusGatewayTimeout:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func waitForRetry(ctx context.Context, delay time.Duration) error {
|
||||
if delay <= 0 {
|
||||
return ctx.Err()
|
||||
}
|
||||
timer := time.NewTimer(delay)
|
||||
defer timer.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func positiveAttemptCount(attempts int) int {
|
||||
if attempts < 1 {
|
||||
return 1
|
||||
}
|
||||
return attempts
|
||||
}
|
||||
|
||||
func isJSONNull(raw json.RawMessage) bool {
|
||||
return bytes.Equal(bytes.TrimSpace(raw), []byte("null"))
|
||||
}
|
||||
|
||||
func (c *Client) endpointURL(endpoint string, opts queryOptions) *url.URL {
|
||||
reqURL := *c.baseURL
|
||||
reqURL.Path = path.Join(c.baseURL.Path, endpoint)
|
||||
query := reqURL.Query()
|
||||
query.Set("format", c.format)
|
||||
if !opts.omitUnits {
|
||||
query.Set("units", c.units)
|
||||
}
|
||||
if opts.precision {
|
||||
query.Set("precision", strconv.Itoa(c.precision))
|
||||
}
|
||||
if opts.timezone {
|
||||
query.Set("tz", c.timezone)
|
||||
}
|
||||
reqURL.RawQuery = query.Encode()
|
||||
return &reqURL
|
||||
}
|
||||
|
||||
func queryMap(values url.Values) map[string]string {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
out := make(map[string]string, len(values))
|
||||
for key, value := range values {
|
||||
if len(value) > 0 {
|
||||
out[key] = value[0]
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func decodeSource(raw json.RawMessage, target any) error {
|
||||
if err := json.Unmarshal(raw, target); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func sourceHash(raw json.RawMessage) (string, error) {
|
||||
var compact bytes.Buffer
|
||||
if err := json.Compact(&compact, raw); err != nil {
|
||||
return "", err
|
||||
}
|
||||
sum := sha256.Sum256(compact.Bytes())
|
||||
return hex.EncodeToString(sum[:]), nil
|
||||
}
|
||||
1188
internal/adapters/weatherapi/client_test.go
Normal file
1188
internal/adapters/weatherapi/client_test.go
Normal file
File diff suppressed because it is too large
Load Diff
6
internal/adapters/weatherapi/testdata/alerts.json
vendored
Normal file
6
internal/adapters/weatherapi/testdata/alerts.json
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"data": {
|
||||
"asOf": "2026-05-29T14:00:00Z",
|
||||
"alerts": []
|
||||
}
|
||||
}
|
||||
50
internal/adapters/weatherapi/testdata/convective_outlooks.json
vendored
Normal file
50
internal/adapters/weatherapi/testdata/convective_outlooks.json
vendored
Normal file
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"data": {
|
||||
"locationId": "nws-lsx-grid-90-74",
|
||||
"locationName": "St. Louis, MO",
|
||||
"asOf": "2026-05-29T16:00:00Z",
|
||||
"issuedAt": "2026-05-29T15:45:00Z",
|
||||
"updatedAt": "2026-05-29T16:05:00Z",
|
||||
"product": "convective_outlook",
|
||||
"outlooks": [
|
||||
{
|
||||
"id": "day1-categorical-slight",
|
||||
"provider": "spc",
|
||||
"product": "convective_outlook",
|
||||
"day": 1,
|
||||
"outlookType": "categorical",
|
||||
"label": "SLGT",
|
||||
"labelText": "Slight Risk",
|
||||
"forecaster": "Smith",
|
||||
"severityRank": 3,
|
||||
"validFrom": "2026-05-29T13:00:00-05:00",
|
||||
"validTo": "2026-05-30T07:00:00-05:00",
|
||||
"issuedAt": "2026-05-29T15:45:00Z",
|
||||
"expiresAt": "2026-05-30T07:00:00-05:00",
|
||||
"sourceUrl": "https://www.spc.noaa.gov/products/outlook/day1otlk.html",
|
||||
"imageUrl": "https://www.spc.noaa.gov/products/outlook/day1probotlk_2000_torn.gif",
|
||||
"containsLocation": true,
|
||||
"geometry": {
|
||||
"type": "Polygon",
|
||||
"coordinates": [
|
||||
[
|
||||
[-91.0, 38.0],
|
||||
[-90.0, 38.5],
|
||||
[-89.5, 37.8],
|
||||
[-91.0, 38.0]
|
||||
]
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"discussions": [
|
||||
{
|
||||
"day": 1,
|
||||
"headline": "Severe storms possible",
|
||||
"summary": "Scattered severe storms are possible.",
|
||||
"discussion": "A few storms may become severe during the afternoon.",
|
||||
"updatedAt": "2026-05-29T16:05:00Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
10
internal/adapters/weatherapi/testdata/current.json
vendored
Normal file
10
internal/adapters/weatherapi/testdata/current.json
vendored
Normal file
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"data": {
|
||||
"conditionText": "Partly cloudy",
|
||||
"isDay": true,
|
||||
"temperatureF": 75.9,
|
||||
"apparentTemperatureF": 76.1,
|
||||
"windSpeedMph": 10.7,
|
||||
"relativeHumidityPercent": 56
|
||||
}
|
||||
}
|
||||
20
internal/adapters/weatherapi/testdata/discussion.json
vendored
Normal file
20
internal/adapters/weatherapi/testdata/discussion.json
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"data": {
|
||||
"officeId": "LSX",
|
||||
"officeName": "St. Louis",
|
||||
"product": "discussion",
|
||||
"issuedAt": "2026-05-29T09:25:00-05:00",
|
||||
"keyMessages": [
|
||||
"Scattered showers possible this evening.",
|
||||
"Warmer temperatures this weekend."
|
||||
],
|
||||
"shortTerm": {
|
||||
"qualifier": "(Through This Evening)",
|
||||
"text": "A weak boundary may trigger isolated showers."
|
||||
},
|
||||
"longTerm": {
|
||||
"qualifier": "(This Weekend)",
|
||||
"text": "Warmer temperatures and periodic rain chances continue into the weekend."
|
||||
}
|
||||
}
|
||||
}
|
||||
25
internal/adapters/weatherapi/testdata/hourly.json
vendored
Normal file
25
internal/adapters/weatherapi/testdata/hourly.json
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"data": {
|
||||
"locationId": "nws-lsx-grid-90-74",
|
||||
"locationName": "St. Louis, MO",
|
||||
"issuedAt": "2026-05-29T10:30:00-05:00",
|
||||
"updatedAt": "2026-05-29T10:45:00-05:00",
|
||||
"product": "hourly",
|
||||
"latitude": 38.63,
|
||||
"longitude": -90.2,
|
||||
"elevationFeet": 466,
|
||||
"periods": [
|
||||
{
|
||||
"startTime": "2026-05-29T13:00:00-05:00",
|
||||
"endTime": "2026-05-29T14:00:00-05:00",
|
||||
"isDay": true,
|
||||
"conditionCode": 3,
|
||||
"textDescription": "Partly sunny",
|
||||
"temperatureF": 81,
|
||||
"windSpeedMph": 12,
|
||||
"windGustMph": 20,
|
||||
"probabilityOfPrecipitationPercent": 10
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
20
internal/adapters/weatherapi/testdata/narrative.json
vendored
Normal file
20
internal/adapters/weatherapi/testdata/narrative.json
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"data": {
|
||||
"locationId": "nws-lsx-grid-90-74",
|
||||
"locationName": "St. Louis, MO",
|
||||
"issuedAt": "2026-05-29T10:30:00-05:00",
|
||||
"product": "narrative",
|
||||
"periods": [
|
||||
{
|
||||
"startTime": "2026-05-29T13:00:00-05:00",
|
||||
"endTime": "2026-05-29T19:00:00-05:00",
|
||||
"name": "Today",
|
||||
"isDay": true,
|
||||
"textDescription": "Partly sunny, with a high near 81.",
|
||||
"temperatureF": 81,
|
||||
"windSpeedMph": 12,
|
||||
"probabilityOfPrecipitationPercent": 10
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
13
internal/adapters/weatherapi/testdata/observations.json
vendored
Normal file
13
internal/adapters/weatherapi/testdata/observations.json
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"data": {
|
||||
"stationId": "KSTL",
|
||||
"stationName": "St. Louis",
|
||||
"timestamp": "2026-05-29T14:00:00Z",
|
||||
"conditionCode": 3,
|
||||
"isDay": true,
|
||||
"textDescription": "Partly cloudy",
|
||||
"temperatureF": 75.9,
|
||||
"windSpeedMph": 10.7,
|
||||
"relativeHumidityPercent": 56
|
||||
}
|
||||
}
|
||||
14
internal/adapters/weatherapi/testdata/weather_story.json
vendored
Normal file
14
internal/adapters/weatherapi/testdata/weather_story.json
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"data": {
|
||||
"officeId": "LSX",
|
||||
"startTime": "2026-05-30T08:46:00Z",
|
||||
"endTime": "2026-05-31T11:00:00Z",
|
||||
"updatedAt": "2026-05-30T09:00:34Z",
|
||||
"title": "Several Chances for Rain Through Monday",
|
||||
"description": "A stagnant weather pattern with low pressure over the Great Plains and high pressure over the Great Lakes will continue to produce scattered showers and thunderstorms, for areas mainly along and west of the Mississippi River today and Sunday.",
|
||||
"altText": "This slide shows the forecast for today through Tuesday with icons for showers and thunderstorms and a picture of a cumulonimbus cloud on the right side.",
|
||||
"priority": false,
|
||||
"order": 1,
|
||||
"downloadUrl": "https://api.weather.gov/offices/LSX/weatherstories/download/3228e499-2aae-45a8-9ff9-1c060311026f"
|
||||
}
|
||||
}
|
||||
893
internal/app/app.go
Normal file
893
internal/app/app.go
Normal file
@@ -0,0 +1,893 @@
|
||||
// Package app owns application orchestration and top-level use cases.
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
distributoradapter "gitea.maximumdirect.net/eric/weatherreporter/internal/adapters/distributor"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/briefing"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/collect"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/config"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/facts"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/forecast"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/module"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptdebug"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptexec"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptinput"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/report"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/timeutil"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/weatherdata"
|
||||
)
|
||||
|
||||
type ReportKind string
|
||||
|
||||
const (
|
||||
ReportDaily ReportKind = ReportKind(report.CommandNameDaily)
|
||||
ReportToday ReportKind = ReportKind(report.CommandNameToday)
|
||||
ReportTomorrow ReportKind = ReportKind(report.CommandNameTomorrow)
|
||||
ReportHourly ReportKind = ReportKind(report.CommandNameHourly)
|
||||
)
|
||||
|
||||
type BatchKind string
|
||||
|
||||
const (
|
||||
BatchMorning BatchKind = BatchKind(report.BatchNameMorning)
|
||||
BatchEvening BatchKind = BatchKind(report.BatchNameEvening)
|
||||
)
|
||||
|
||||
type GenerateRequest struct {
|
||||
Config config.Config
|
||||
Report ReportKind
|
||||
WorkingDir string
|
||||
OutputPath string
|
||||
LLMDebugDir string
|
||||
Now time.Time
|
||||
Date time.Time
|
||||
Collector Collector
|
||||
Notifier Notifier
|
||||
Executor promptexec.Executor
|
||||
}
|
||||
|
||||
type BatchRequest struct {
|
||||
Config config.Config
|
||||
Batch BatchKind
|
||||
Now time.Time
|
||||
WorkingDir string
|
||||
OutputDir string
|
||||
LLMDebugDir string
|
||||
Collector Collector
|
||||
Executor promptexec.Executor
|
||||
Notifier Notifier
|
||||
}
|
||||
|
||||
type ModuleSnapshotRequest struct {
|
||||
Config config.Config
|
||||
Resolved report.Resolved
|
||||
Identity briefing.PreparedIdentity
|
||||
}
|
||||
|
||||
type ReportFacts struct {
|
||||
Collected facts.CollectedFacts
|
||||
Derived facts.DerivedFacts
|
||||
}
|
||||
|
||||
type ReportResult struct {
|
||||
ReportID report.ID
|
||||
ReportName string
|
||||
PromptID string
|
||||
PromptVersion string
|
||||
RunID string
|
||||
GeneratedAt time.Time
|
||||
Timezone string
|
||||
ValidPeriod timeutil.Period
|
||||
ProfileID string
|
||||
BackendID string
|
||||
ModelName string
|
||||
SourceWarnings []weatherdata.SourceWarning
|
||||
ValidationStatus promptexec.ValidationStatus
|
||||
LLMDebugPath string
|
||||
OutputPath string
|
||||
Notification *NotificationResult
|
||||
}
|
||||
|
||||
type BatchResult struct {
|
||||
Batch BatchKind `json:"batch"`
|
||||
StartedAt time.Time `json:"startedAt"`
|
||||
FinishedAt time.Time `json:"finishedAt"`
|
||||
Total int `json:"total"`
|
||||
Succeeded int `json:"succeeded"`
|
||||
Failed int `json:"failed"`
|
||||
Canceled int `json:"canceled,omitempty"`
|
||||
Notification *BatchNotificationResult `json:"notification,omitempty"`
|
||||
Reports []BatchReportResult `json:"reports"`
|
||||
}
|
||||
|
||||
type BatchNotificationResult struct {
|
||||
Status string `json:"status"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
RunID string `json:"runId,omitempty"`
|
||||
PipelineID string `json:"pipelineId,omitempty"`
|
||||
BundleID string `json:"bundleId,omitempty"`
|
||||
IdempotencyKey string `json:"idempotencyKey,omitempty"`
|
||||
IncludedReports []BatchNotificationReport `json:"includedReports,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type BatchNotificationReport struct {
|
||||
ReportID report.ID `json:"reportId"`
|
||||
RunID string `json:"runId"`
|
||||
SourcePath string `json:"sourcePath"`
|
||||
BundlePaths []string `json:"bundlePaths"`
|
||||
}
|
||||
|
||||
type BatchReportResult struct {
|
||||
ReportID report.ID `json:"reportId"`
|
||||
ReportName string `json:"reportName"`
|
||||
PromptID string `json:"promptId"`
|
||||
RunID string `json:"runId"`
|
||||
Status string `json:"status"`
|
||||
Error string `json:"error,omitempty"`
|
||||
GeneratedAt time.Time `json:"generatedAt"`
|
||||
ValidPeriod timeutil.Period `json:"validPeriod"`
|
||||
Timezone string `json:"timezone"`
|
||||
ProfileID string `json:"profileId,omitempty"`
|
||||
BackendID string `json:"backendId,omitempty"`
|
||||
ModelName string `json:"modelName,omitempty"`
|
||||
SourceWarnings []weatherdata.SourceWarning `json:"sourceWarnings,omitempty"`
|
||||
ValidationStatus promptexec.ValidationStatus `json:"validationStatus,omitempty"`
|
||||
LLMDebugPath string `json:"llmDebugPath,omitempty"`
|
||||
OutputPath string `json:"outputPath,omitempty"`
|
||||
}
|
||||
|
||||
type BatchError struct {
|
||||
Result *BatchResult
|
||||
Cause error
|
||||
}
|
||||
|
||||
func (e BatchError) Error() string {
|
||||
if e.Result == nil {
|
||||
return "batch failed"
|
||||
}
|
||||
if errors.Is(e.Cause, context.DeadlineExceeded) {
|
||||
return fmt.Sprintf("batch %s deadline exceeded", e.Result.Batch)
|
||||
}
|
||||
if errors.Is(e.Cause, context.Canceled) || e.Result.Canceled > 0 {
|
||||
return fmt.Sprintf("batch %s canceled", e.Result.Batch)
|
||||
}
|
||||
failedReports := batchReportFailures(e.Result)
|
||||
if batchNotificationFailed(e.Result) && failedReports == 0 {
|
||||
if e.Result.Notification.Error != "" {
|
||||
return fmt.Sprintf("batch %s notification failed: %s", e.Result.Batch, e.Result.Notification.Error)
|
||||
}
|
||||
return fmt.Sprintf("batch %s notification failed", e.Result.Batch)
|
||||
}
|
||||
return fmt.Sprintf("batch %s failed: %d of %d reports failed", e.Result.Batch, failedReports, len(e.Result.Reports))
|
||||
}
|
||||
|
||||
func (e BatchError) Unwrap() error {
|
||||
return e.Cause
|
||||
}
|
||||
|
||||
func batchNotificationFailed(result *BatchResult) bool {
|
||||
return result != nil && result.Notification != nil && result.Notification.Status == "failed"
|
||||
}
|
||||
|
||||
func batchReportFailures(result *BatchResult) int {
|
||||
if result == nil {
|
||||
return 0
|
||||
}
|
||||
failures := 0
|
||||
for _, item := range result.Reports {
|
||||
if item.Status == "failed" {
|
||||
failures++
|
||||
}
|
||||
}
|
||||
return failures
|
||||
}
|
||||
|
||||
type Collector interface {
|
||||
Run(context.Context, collect.Request) (*collect.Result, error)
|
||||
}
|
||||
|
||||
type defaultCollector struct{}
|
||||
|
||||
func (defaultCollector) Run(ctx context.Context, req collect.Request) (*collect.Result, error) {
|
||||
return collect.Run(ctx, req)
|
||||
}
|
||||
|
||||
type Notifier interface {
|
||||
Notify(context.Context, NotificationRequest) (*NotificationResult, error)
|
||||
}
|
||||
|
||||
type NotificationRequest struct {
|
||||
ReportID report.ID
|
||||
RunID string
|
||||
PipelineID string
|
||||
BundleID string
|
||||
IdempotencyKey string
|
||||
ReportPath string
|
||||
BundlePaths []string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type NotificationResult struct {
|
||||
BundleID string
|
||||
IdempotencyKey string
|
||||
RunID string
|
||||
Status string
|
||||
UploadStatus string
|
||||
StatusError string
|
||||
PipelineID string
|
||||
AcceptedAt time.Time
|
||||
StartedAt *time.Time
|
||||
FinishedAt *time.Time
|
||||
Report []byte
|
||||
Error string
|
||||
}
|
||||
|
||||
type NotificationError struct {
|
||||
Request NotificationRequest
|
||||
Err error
|
||||
}
|
||||
|
||||
func (e *NotificationError) Error() string {
|
||||
if e == nil || e.Err == nil {
|
||||
return "notification failed"
|
||||
}
|
||||
return e.Err.Error()
|
||||
}
|
||||
|
||||
func (e *NotificationError) Unwrap() error {
|
||||
if e == nil {
|
||||
return nil
|
||||
}
|
||||
return e.Err
|
||||
}
|
||||
|
||||
func Generate(ctx context.Context, req GenerateRequest) error {
|
||||
_, err := GenerateDetailed(ctx, req)
|
||||
return err
|
||||
}
|
||||
|
||||
func GenerateDetailed(ctx context.Context, req GenerateRequest) (*ReportResult, error) {
|
||||
now := req.Now
|
||||
if now.IsZero() {
|
||||
now = time.Now()
|
||||
}
|
||||
resolved, err := ResolveGenerate(req, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := initialReportResult(req, resolved, PromptInspectionResult{})
|
||||
if err := preflightDistributorNotification(req.Config); err != nil {
|
||||
return result, err
|
||||
}
|
||||
outputPath, err := resolveReportOutputPath(req.WorkingDir, req.OutputPath, req.Config.Output.Directory, resolved)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
req.OutputPath = outputPath
|
||||
debugWriter, err := promptdebug.NewPromptDebugWriter(req.LLMDebugDir)
|
||||
if err != nil {
|
||||
return result, promptexec.NewError(promptexec.InvalidConfiguration, "initialize prompt debug", err)
|
||||
}
|
||||
defer func() { _ = debugWriter.Close() }()
|
||||
inspection, err := InspectPromptExecution(ctx, PromptInspectionRequest{
|
||||
Resolved: resolved,
|
||||
Executor: req.Executor,
|
||||
Promptkit: req.Config.Promptkit,
|
||||
})
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.ProfileID, result.BackendID, result.ModelName = inspection.ProfileID, inspection.BackendID, inspection.ModelName
|
||||
collection, err := collectWeather(ctx, req.Config, req.Collector)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
return generatePromptReport(ctx, promptReportRequest{
|
||||
GenerateRequest: req,
|
||||
Resolved: resolved,
|
||||
Collection: *collection,
|
||||
Inspection: inspection,
|
||||
DebugWriter: debugWriter,
|
||||
Result: result,
|
||||
})
|
||||
}
|
||||
|
||||
func RunBatch(ctx context.Context, req BatchRequest) error {
|
||||
result, err := RunBatchDetailed(ctx, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if result.Failed > 0 || batchNotificationFailed(result) {
|
||||
return BatchError{Result: result}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func RunBatchDetailed(ctx context.Context, req BatchRequest) (*BatchResult, error) {
|
||||
now := req.Now
|
||||
if now.IsZero() {
|
||||
now = time.Now()
|
||||
}
|
||||
if _, err := report.BatchForCommandName(string(req.Batch)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := preflightDistributorNotification(req.Config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
outputDir, err := resolveOutputDirWithConfigured(req.WorkingDir, req.OutputDir, req.Config.Output.Directory)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.OutputDir = outputDir
|
||||
debugWriter, err := promptdebug.NewPromptDebugWriter(req.LLMDebugDir)
|
||||
if err != nil {
|
||||
return nil, promptexec.NewError(promptexec.InvalidConfiguration, "initialize prompt debug", err)
|
||||
}
|
||||
defer func() { _ = debugWriter.Close() }()
|
||||
candidates, err := batchInspectionCandidates(req, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
inspections, err := InspectPromptExecutions(ctx, PromptExecutionsInspectionRequest{
|
||||
Resolved: candidates,
|
||||
Executor: req.Executor,
|
||||
Promptkit: req.Config.Promptkit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
collection, err := collectWeather(ctx, req.Config, req.Collector)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
plannedReports, err := planBatchRun(req, now, *collection)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := prepareBatchOutputs(req.OutputDir, plannedReports); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if req.Batch == BatchEvening || req.Batch == BatchMorning {
|
||||
startedAt := now
|
||||
result := &BatchResult{Batch: req.Batch, StartedAt: startedAt}
|
||||
var cancellation error
|
||||
for index, planned := range plannedReports {
|
||||
if cancellation = batchContextCancellationCause(ctx); cancellation != nil {
|
||||
appendCanceledBatchReports(result, plannedReports[index:])
|
||||
break
|
||||
}
|
||||
resolved := planned.Resolved
|
||||
item := batchReportResult(planned)
|
||||
reportResult, err := generatePromptReport(ctx, promptReportRequest{
|
||||
GenerateRequest: GenerateRequest{
|
||||
Config: req.Config,
|
||||
OutputPath: planned.OutputPath,
|
||||
Notifier: req.Notifier,
|
||||
Executor: req.Executor,
|
||||
},
|
||||
Resolved: resolved,
|
||||
Collection: *collection,
|
||||
Inspection: inspections[resolved.Definition.ID],
|
||||
DebugWriter: debugWriter,
|
||||
noNotify: true,
|
||||
})
|
||||
if reportResult != nil {
|
||||
copyBatchReportDetails(&item, reportResult)
|
||||
}
|
||||
if err != nil {
|
||||
if reportCancellation := batchReportCancellationCause(err); reportCancellation != nil {
|
||||
cancellation = reportCancellation
|
||||
item.Status = "canceled"
|
||||
result.Canceled++
|
||||
} else {
|
||||
item.Status = "failed"
|
||||
item.Error = err.Error()
|
||||
result.Failed++
|
||||
}
|
||||
} else {
|
||||
item.Status = "succeeded"
|
||||
result.Succeeded++
|
||||
}
|
||||
result.Reports = append(result.Reports, item)
|
||||
if cancellation == nil {
|
||||
cancellation = batchContextCancellationCause(ctx)
|
||||
}
|
||||
if cancellation != nil {
|
||||
appendCanceledBatchReports(result, plannedReports[index+1:])
|
||||
break
|
||||
}
|
||||
}
|
||||
result.Total = len(result.Reports)
|
||||
batchNotification := notifyBatch(batchNotificationInput{
|
||||
ctx: ctx, cancellation: cancellation, cfg: req.Config, batch: req.Batch,
|
||||
runID: batchRunID(startedAt, req.Batch), startedAt: startedAt,
|
||||
result: result, planned: plannedReports, notifier: req.Notifier,
|
||||
})
|
||||
if batchNotification != nil {
|
||||
result.Notification = batchNotification
|
||||
}
|
||||
result.FinishedAt = time.Now()
|
||||
return result, cancellation
|
||||
}
|
||||
return nil, fmt.Errorf("run is not implemented")
|
||||
}
|
||||
|
||||
func batchReportCancellationCause(err error) error {
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return context.Canceled
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return context.DeadlineExceeded
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func batchContextCancellationCause(ctx context.Context) error {
|
||||
if ctx == nil {
|
||||
return nil
|
||||
}
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
func appendCanceledBatchReports(result *BatchResult, plannedReports []plannedBatchReport) {
|
||||
if result == nil {
|
||||
return
|
||||
}
|
||||
for _, planned := range plannedReports {
|
||||
item := batchReportResult(planned)
|
||||
item.Status = "canceled"
|
||||
result.Reports = append(result.Reports, item)
|
||||
result.Canceled++
|
||||
}
|
||||
}
|
||||
|
||||
func copyBatchReportDetails(item *BatchReportResult, result *ReportResult) {
|
||||
item.LLMDebugPath = result.LLMDebugPath
|
||||
item.OutputPath = result.OutputPath
|
||||
item.ProfileID = result.ProfileID
|
||||
item.BackendID = result.BackendID
|
||||
item.ModelName = result.ModelName
|
||||
item.Timezone = result.Timezone
|
||||
item.SourceWarnings = append([]weatherdata.SourceWarning(nil), result.SourceWarnings...)
|
||||
item.ValidationStatus = result.ValidationStatus
|
||||
}
|
||||
|
||||
func batchInspectionCandidates(req BatchRequest, now time.Time) ([]report.Resolved, error) {
|
||||
location, err := timeutil.LoadLocation(req.Config.WeatherAPI.Timezone)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
registry, err := reportRegistry(req.Config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := []report.ID{report.Tomorrow, report.Daily}
|
||||
if req.Batch == BatchMorning {
|
||||
ids = []report.ID{report.Today, report.Tomorrow, report.Daily}
|
||||
}
|
||||
date := timeutil.LocalDate(now, location).AddDate(0, 0, 2)
|
||||
candidates := make([]report.Resolved, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
resolveReq := report.ResolveRequest{Now: now, Location: location}
|
||||
if id == report.Daily {
|
||||
resolveReq.Date = date
|
||||
}
|
||||
resolved, err := registry.Resolve(id, resolveReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
candidates = append(candidates, resolved)
|
||||
}
|
||||
return candidates, nil
|
||||
}
|
||||
|
||||
func batchReportResult(planned plannedBatchReport) BatchReportResult {
|
||||
resolved := planned.Resolved
|
||||
metadata := resolved.Metadata()
|
||||
return BatchReportResult{
|
||||
ReportID: resolved.Definition.ID,
|
||||
ReportName: resolved.Definition.Name,
|
||||
PromptID: resolved.Definition.PromptID,
|
||||
RunID: metadata.RunID,
|
||||
GeneratedAt: metadata.GeneratedAt,
|
||||
ValidPeriod: metadata.ValidPeriod,
|
||||
Timezone: "",
|
||||
}
|
||||
}
|
||||
|
||||
func ResolveGenerate(req GenerateRequest, now time.Time) (report.Resolved, error) {
|
||||
location, err := timeutil.LoadLocation(req.Config.WeatherAPI.Timezone)
|
||||
if err != nil {
|
||||
return report.Resolved{}, err
|
||||
}
|
||||
id, err := report.IDForCommandName(string(req.Report))
|
||||
if err != nil {
|
||||
return report.Resolved{}, err
|
||||
}
|
||||
registry, err := reportRegistry(req.Config)
|
||||
if err != nil {
|
||||
return report.Resolved{}, err
|
||||
}
|
||||
return registry.Resolve(id, report.ResolveRequest{
|
||||
Now: now,
|
||||
Location: location,
|
||||
Date: req.Date,
|
||||
})
|
||||
}
|
||||
|
||||
func reportRegistry(cfg config.Config) (report.Registry, error) {
|
||||
overrides, err := cfg.ReportModuleOverrides()
|
||||
if err != nil {
|
||||
return report.Registry{}, err
|
||||
}
|
||||
registry, err := report.DefaultRegistry().WithModuleOverrides(overrides)
|
||||
if err != nil {
|
||||
return report.Registry{}, err
|
||||
}
|
||||
return registry, nil
|
||||
}
|
||||
|
||||
func collectWeather(ctx context.Context, cfg config.Config, collector Collector) (*collect.Result, error) {
|
||||
if collector == nil {
|
||||
collector = defaultCollector{}
|
||||
}
|
||||
result, err := collector.Run(ctx, collect.Request{Config: cfg})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if result == nil {
|
||||
return nil, fmt.Errorf("collect weather bundle: collector returned nil result")
|
||||
}
|
||||
if result.Bundle == nil {
|
||||
return nil, fmt.Errorf("collect weather bundle: collector returned nil bundle")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func notifyReport(ctx context.Context, cfg config.Config, resolved report.Resolved, outputPath, runID string, generatedAt time.Time, notifier Notifier) (*NotificationResult, error) {
|
||||
notifier, enabled := reportNotifier(cfg, notifier)
|
||||
if !enabled {
|
||||
return nil, nil
|
||||
}
|
||||
notificationRequest, err := buildNotificationRequest(cfg, resolved, outputPath, runID, generatedAt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := notifier.Notify(ctx, notificationRequest)
|
||||
if err != nil {
|
||||
return result, &NotificationError{
|
||||
Request: notificationRequest,
|
||||
Err: fmt.Errorf("notify report %q run %q from output %q: %w", resolved.Definition.ID, runID, outputPath, err),
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func reportNotifier(cfg config.Config, notifier Notifier) (Notifier, bool) {
|
||||
if !cfg.Notify.Distributor.Enabled {
|
||||
return noopNotifier{}, false
|
||||
}
|
||||
if notifier != nil {
|
||||
return notifier, true
|
||||
}
|
||||
return distributorNotifier{
|
||||
client: distributoradapter.New(cfg.Notify.Distributor),
|
||||
}, true
|
||||
}
|
||||
|
||||
func preflightDistributorNotification(cfg config.Config) error {
|
||||
if !cfg.Notify.Distributor.Enabled {
|
||||
return nil
|
||||
}
|
||||
if err := config.ValidateDistributorEndpoint(cfg.Notify.Distributor.Endpoint); err != nil {
|
||||
return fmt.Errorf("validate notify.distributor.endpoint: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func buildNotificationRequest(cfg config.Config, resolved report.Resolved, outputPath, runID string, generatedAt time.Time) (NotificationRequest, error) {
|
||||
values, err := distributorTemplateValuesForReport(cfg, resolved, runID, filepath.Base(outputPath))
|
||||
if err != nil {
|
||||
return NotificationRequest{}, err
|
||||
}
|
||||
bundleID, err := config.RenderDistributorBundleID(cfg.Notify.Distributor.BundleIDTemplate, values)
|
||||
if err != nil {
|
||||
return NotificationRequest{}, err
|
||||
}
|
||||
values.BundleID = bundleID
|
||||
pipelineID, err := config.RenderDistributorPipelineID(cfg.Notify.Distributor.PipelineIDTemplate, values)
|
||||
if err != nil {
|
||||
return NotificationRequest{}, err
|
||||
}
|
||||
idempotencyKey, err := config.RenderDistributorIdempotencyKey(cfg.Notify.Distributor.IdempotencyKeyTemplate, values)
|
||||
if err != nil {
|
||||
return NotificationRequest{}, err
|
||||
}
|
||||
bundlePaths, err := renderDistributorReportBundlePaths(cfg, resolved, runID, outputPath, values)
|
||||
if err != nil {
|
||||
return NotificationRequest{}, err
|
||||
}
|
||||
return NotificationRequest{
|
||||
ReportID: resolved.Definition.ID,
|
||||
RunID: runID,
|
||||
PipelineID: pipelineID,
|
||||
BundleID: bundleID,
|
||||
IdempotencyKey: idempotencyKey,
|
||||
ReportPath: outputPath,
|
||||
BundlePaths: bundlePaths,
|
||||
CreatedAt: generatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func distributorTemplateValuesForReport(cfg config.Config, resolved report.Resolved, runID string, outputName string) (config.DistributorTemplateValues, error) {
|
||||
values := config.DistributorTemplateValues{
|
||||
LocationID: cfg.Location.ID,
|
||||
ReportID: string(resolved.Definition.ID),
|
||||
RunID: runID,
|
||||
ArtifactGroup: resolved.Definition.ArtifactGroup,
|
||||
BatchOutputName: outputName,
|
||||
}
|
||||
if values.BatchOutputName == "" {
|
||||
var err error
|
||||
values.BatchOutputName, err = resolved.OutputName()
|
||||
if err != nil {
|
||||
return config.DistributorTemplateValues{}, err
|
||||
}
|
||||
}
|
||||
if err := addDistributorValidPeriodValues(&values, resolved.ValidPeriod, cfg.WeatherAPI.Timezone); err != nil {
|
||||
return config.DistributorTemplateValues{}, err
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
func renderDistributorReportBundlePaths(cfg config.Config, resolved report.Resolved, runID string, sourcePath string, values config.DistributorTemplateValues) ([]string, error) {
|
||||
templates, name, err := distributorPathTemplatesForReport(cfg, resolved.Definition)
|
||||
if err != nil {
|
||||
return nil, distributorReportPathError(resolved.Definition.ID, runID, sourcePath, err)
|
||||
}
|
||||
paths, err := config.RenderDistributorReportPaths(name, templates, values)
|
||||
if err != nil {
|
||||
return nil, distributorReportPathError(resolved.Definition.ID, runID, sourcePath, err)
|
||||
}
|
||||
return paths, nil
|
||||
}
|
||||
|
||||
func distributorPathTemplatesForReport(cfg config.Config, definition report.Definition) ([]string, string, error) {
|
||||
overrides, err := cfg.ReportDistributorPathOverrides()
|
||||
if err != nil {
|
||||
return nil, "", err
|
||||
}
|
||||
if templates, ok := overrides[definition.ID]; ok {
|
||||
return append([]string(nil), templates...), fmt.Sprintf("reports.%s.distributor.path_templates", definition.ID), nil
|
||||
}
|
||||
if len(definition.DistributorPathTemplates) > 0 {
|
||||
return append([]string(nil), definition.DistributorPathTemplates...), fmt.Sprintf("report.%s.distributor_path_templates", definition.ID), nil
|
||||
}
|
||||
return nil, "", fmt.Errorf("no distributor path templates configured")
|
||||
}
|
||||
|
||||
func distributorReportPathError(id report.ID, runID string, sourcePath string, err error) error {
|
||||
if sourcePath != "" {
|
||||
return fmt.Errorf("report %q run %q source path %q: %w", id, runID, sourcePath, err)
|
||||
}
|
||||
return fmt.Errorf("report %q run %q: %w", id, runID, err)
|
||||
}
|
||||
|
||||
func addDistributorValidPeriodValues(values *config.DistributorTemplateValues, period timeutil.Period, timezone string) error {
|
||||
location, err := timeutil.LoadLocation(timezone)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
start := period.Start.In(location)
|
||||
end := period.End.In(location)
|
||||
values.ValidStartDate = start.Format(timeutil.DateLayout)
|
||||
values.ValidEndDate = end.Format(timeutil.DateLayout)
|
||||
values.ValidStartTime = start.Format("1504")
|
||||
values.ValidEndTime = end.Format("1504")
|
||||
values.ValidStartStamp = start.Format("2006-01-02T1504")
|
||||
values.ValidEndStamp = end.Format("2006-01-02T1504")
|
||||
return nil
|
||||
}
|
||||
|
||||
type noopNotifier struct{}
|
||||
|
||||
func (noopNotifier) Notify(context.Context, NotificationRequest) (*NotificationResult, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
type distributorNotifier struct {
|
||||
client *distributoradapter.Client
|
||||
}
|
||||
|
||||
func (n distributorNotifier) Notify(ctx context.Context, req NotificationRequest) (*NotificationResult, error) {
|
||||
result, err := n.client.Upload(ctx, distributoradapter.UploadRequest{
|
||||
PipelineID: req.PipelineID,
|
||||
BundleID: req.BundleID,
|
||||
IdempotencyKey: req.IdempotencyKey,
|
||||
Files: distributorUploadFiles(req.ReportPath, req.BundlePaths),
|
||||
CreatedAt: req.CreatedAt,
|
||||
})
|
||||
notification := notificationResultFromUpload(req.PipelineID, req.BundleID, req.IdempotencyKey, result)
|
||||
if err != nil {
|
||||
return notification, err
|
||||
}
|
||||
return notification, nil
|
||||
}
|
||||
|
||||
func (n distributorNotifier) NotifyBatch(ctx context.Context, req batchNotificationRequest) (*NotificationResult, error) {
|
||||
result, err := n.client.Upload(ctx, batchDistributorUploadRequest(req))
|
||||
notification := notificationResultFromUpload(req.PipelineID, req.BundleID, req.IdempotencyKey, result)
|
||||
if err != nil {
|
||||
return notification, err
|
||||
}
|
||||
return notification, nil
|
||||
}
|
||||
|
||||
func notificationResultFromUpload(pipelineID string, bundleID string, idempotencyKey string, result distributoradapter.UploadResult) *NotificationResult {
|
||||
notification := &NotificationResult{
|
||||
PipelineID: pipelineID,
|
||||
BundleID: bundleID,
|
||||
IdempotencyKey: idempotencyKey,
|
||||
RunID: result.RunID,
|
||||
Status: result.Status,
|
||||
UploadStatus: result.UploadStatus,
|
||||
StatusError: safeDistributorStatusError(result.StatusError),
|
||||
}
|
||||
if result.RunStatus != nil {
|
||||
if result.RunStatus.PipelineID != "" {
|
||||
notification.PipelineID = result.RunStatus.PipelineID
|
||||
}
|
||||
notification.AcceptedAt = result.RunStatus.AcceptedAt
|
||||
notification.StartedAt = result.RunStatus.StartedAt
|
||||
notification.FinishedAt = result.RunStatus.FinishedAt
|
||||
notification.Error = safeDistributorRunError(result.RunStatus.Error)
|
||||
}
|
||||
return notification
|
||||
}
|
||||
|
||||
func safeDistributorStatusError(value string) string {
|
||||
if value == "" {
|
||||
return ""
|
||||
}
|
||||
return "distributor status could not be confirmed"
|
||||
}
|
||||
|
||||
func safeDistributorRunError(value string) string {
|
||||
if value == "" {
|
||||
return ""
|
||||
}
|
||||
return "distributor reported a failed run"
|
||||
}
|
||||
|
||||
func distributorUploadFiles(sourcePath string, bundlePaths []string) []distributoradapter.UploadFile {
|
||||
files := make([]distributoradapter.UploadFile, 0, len(bundlePaths))
|
||||
for _, bundlePath := range bundlePaths {
|
||||
files = append(files, distributoradapter.UploadFile{
|
||||
SourcePath: sourcePath,
|
||||
BundlePath: bundlePath,
|
||||
})
|
||||
}
|
||||
return files
|
||||
}
|
||||
|
||||
func BuildModuleSnapshot(req ModuleSnapshotRequest, bundle *weatherdata.Bundle) (module.Snapshot, error) {
|
||||
reportFacts, err := BuildReportFacts(req, bundle)
|
||||
if err != nil {
|
||||
return module.Snapshot{}, err
|
||||
}
|
||||
return BuildModuleSnapshotFromFacts(req, reportFacts)
|
||||
}
|
||||
|
||||
func BuildReportFacts(req ModuleSnapshotRequest, bundle *weatherdata.Bundle) (ReportFacts, error) {
|
||||
collected := facts.BuildCollected(bundle)
|
||||
derived, err := buildDerivedFacts(req.Config, req.Resolved, collected)
|
||||
if err != nil {
|
||||
return ReportFacts{}, err
|
||||
}
|
||||
return ReportFacts{
|
||||
Collected: collected,
|
||||
Derived: derived,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func BuildModuleSnapshotFromFacts(req ModuleSnapshotRequest, reportFacts ReportFacts) (module.Snapshot, error) {
|
||||
if !req.Resolved.ValidPeriod.IsValid() {
|
||||
return module.Snapshot{}, fmt.Errorf("resolved valid period is required")
|
||||
}
|
||||
registry, err := briefing.DefaultModuleRegistry()
|
||||
if err != nil {
|
||||
return module.Snapshot{}, err
|
||||
}
|
||||
identity := req.Identity
|
||||
if identity.ReportID == "" {
|
||||
identity = briefing.BuildPreparedIdentity(briefingBuildContext(req.Config, req.Resolved, reportFacts.Collected))
|
||||
}
|
||||
moduleContext := briefing.ModuleContext{
|
||||
Identity: identity,
|
||||
Resolved: req.Resolved,
|
||||
Collected: reportFacts.Collected,
|
||||
Derived: reportFacts.Derived,
|
||||
Units: req.Config.WeatherAPI.Units,
|
||||
Timezone: req.Config.WeatherAPI.Timezone,
|
||||
Location: briefingLocation(req.Config),
|
||||
}
|
||||
var outputs []module.Output
|
||||
for _, item := range req.Resolved.Definition.Modules {
|
||||
output, err := registry.BuildModule(moduleContext, item)
|
||||
if err != nil {
|
||||
return module.Snapshot{}, err
|
||||
}
|
||||
if output == nil {
|
||||
continue
|
||||
}
|
||||
outputs = append(outputs, *output)
|
||||
}
|
||||
return module.NewSnapshot(outputs)
|
||||
}
|
||||
|
||||
func briefingBuildContext(cfg config.Config, resolved report.Resolved, collected facts.CollectedFacts) briefing.BuildContext {
|
||||
return briefing.BuildContext{
|
||||
Resolved: resolved,
|
||||
Bundle: collected.Bundle(),
|
||||
Units: cfg.WeatherAPI.Units,
|
||||
Timezone: cfg.WeatherAPI.Timezone,
|
||||
Location: briefingLocation(cfg),
|
||||
}
|
||||
}
|
||||
|
||||
func promptMetadata(identity briefing.PreparedIdentity) promptinput.Metadata {
|
||||
return promptinput.Metadata{
|
||||
RunID: identity.RunID,
|
||||
ReportID: identity.ReportID,
|
||||
Variant: identity.Variant,
|
||||
PromptID: identity.PromptID,
|
||||
GeneratedAt: identity.GeneratedAt,
|
||||
Timezone: identity.Timezone,
|
||||
ValidPeriod: identity.ValidPeriod,
|
||||
SourceWarnings: identity.SourceWarnings,
|
||||
}
|
||||
}
|
||||
|
||||
func buildDerivedFacts(cfg config.Config, resolved report.Resolved, collected facts.CollectedFacts) (facts.DerivedFacts, error) {
|
||||
dayparts := make([]forecast.DaypartDefinition, 0, len(cfg.Dayparts))
|
||||
for _, daypart := range cfg.Dayparts {
|
||||
dayparts = append(dayparts, forecast.DaypartDefinition{
|
||||
Name: daypart.Name,
|
||||
Start: daypart.Start,
|
||||
End: daypart.End,
|
||||
})
|
||||
}
|
||||
return facts.BuildDerived(facts.BuildDerivedRequest{
|
||||
Resolved: resolved,
|
||||
Timezone: cfg.WeatherAPI.Timezone,
|
||||
Dayparts: dayparts,
|
||||
Collected: collected,
|
||||
})
|
||||
}
|
||||
|
||||
func briefingLocation(cfg config.Config) *briefing.LocationContext {
|
||||
location := briefing.LocationContext{
|
||||
ID: cfg.Location.ID,
|
||||
Name: cfg.Location.Name,
|
||||
Region: cfg.Location.Region,
|
||||
Timezone: cfg.WeatherAPI.Timezone,
|
||||
}
|
||||
if location.ID == "" && location.Name == "" && location.Region == "" && location.Timezone == "" {
|
||||
return nil
|
||||
}
|
||||
return &location
|
||||
}
|
||||
|
||||
func generatedReportError(resolved report.Resolved, runID string, operation string, err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("generate report %q run %q: %s: %w", resolved.Definition.ID, runID, operation, err)
|
||||
}
|
||||
361
internal/app/batch_generation_test.go
Normal file
361
internal/app/batch_generation_test.go
Normal file
@@ -0,0 +1,361 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/config"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptexec"
|
||||
)
|
||||
|
||||
func TestRunBatchDetailedKeepsSuccessfulOutputAndSkipsNotificationAfterPartialFailure(t *testing.T) {
|
||||
bundle := generationBundle(t)
|
||||
bundle.Hourly.Periods = bundle.Hourly.Periods[:1]
|
||||
notifier := &generationNotifier{}
|
||||
executor := &generationExecutor{failedPrompt: generationDefinitionForPrompt("weather.tomorrow_generated_text").PromptID}
|
||||
result, err := RunBatchDetailed(context.Background(), BatchRequest{
|
||||
Config: generationDistributorConfig(), Batch: BatchMorning,
|
||||
Now: generationTime("2026-05-29T08:30:00-05:00"), WorkingDir: t.TempDir(), OutputDir: t.TempDir(),
|
||||
Collector: &generationCollector{bundle: &bundle}, Executor: executor, Notifier: notifier,
|
||||
})
|
||||
if err != nil || result == nil || result.Total != 2 || result.Succeeded != 1 || result.Failed != 1 || result.Canceled != 0 || result.Notification == nil || result.Notification.Status != "skipped" || notifier.batchCalls != 0 {
|
||||
t.Fatalf("RunBatchDetailed() result/error/notifier = %#v/%v/%#v", result, err, notifier)
|
||||
}
|
||||
if result.Reports[0].Status != "succeeded" || result.Reports[0].OutputPath == "" || result.Reports[1].Status != "failed" || result.Reports[1].OutputPath != "" {
|
||||
t.Fatalf("report results = %#v", result.Reports)
|
||||
}
|
||||
if data, readErr := os.ReadFile(result.Reports[0].OutputPath); readErr != nil || len(data) == 0 {
|
||||
t.Fatalf("successful output = %q, error = %v", data, readErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunBatchDetailedStopsAfterReportCancellation(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
bundle := generationBundle(t)
|
||||
bundle.Hourly.Periods = bundle.Hourly.Periods[:1]
|
||||
notifier := &generationNotifier{}
|
||||
executor := &generationExecutor{cancelBeforeReturn: cancel}
|
||||
|
||||
result, err := RunBatchDetailed(ctx, BatchRequest{
|
||||
Config: generationDistributorConfig(), Batch: BatchMorning,
|
||||
Now: generationTime("2026-05-29T08:30:00-05:00"), WorkingDir: t.TempDir(), OutputDir: t.TempDir(),
|
||||
Collector: &generationCollector{bundle: &bundle}, Executor: executor, Notifier: notifier,
|
||||
})
|
||||
if !errors.Is(err, context.Canceled) || result == nil || result.Total != 2 || result.Succeeded != 0 || result.Failed != 0 || result.Canceled != 2 || executor.executeCalls != 1 || notifier.batchCalls != 0 || result.Notification == nil || result.Notification.Status != "skipped" || result.Notification.Reason != "batch canceled" {
|
||||
t.Fatalf("RunBatchDetailed() result/error/executor/notifier = %#v/%v/%#v/%#v", result, err, executor, notifier)
|
||||
}
|
||||
for _, item := range result.Reports {
|
||||
if item.Status != "canceled" || item.OutputPath != "" {
|
||||
t.Fatalf("canceled report = %#v", item)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunBatchDetailedPreservesIndependentFailureDuringCancellation(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
bundle := generationBundle(t)
|
||||
bundle.Hourly.Periods = bundle.Hourly.Periods[:1]
|
||||
notifier := &generationNotifier{}
|
||||
executor := &generationExecutor{
|
||||
executeErr: errors.New("independent report failure"),
|
||||
beforeExecute: func(promptexec.ExecuteRequest) {
|
||||
cancel()
|
||||
},
|
||||
}
|
||||
|
||||
result, err := RunBatchDetailed(ctx, BatchRequest{
|
||||
Config: generationDistributorConfig(), Batch: BatchMorning,
|
||||
Now: generationTime("2026-05-29T08:30:00-05:00"), WorkingDir: t.TempDir(), OutputDir: t.TempDir(),
|
||||
Collector: &generationCollector{bundle: &bundle}, Executor: executor, Notifier: notifier,
|
||||
})
|
||||
if !errors.Is(err, context.Canceled) || result == nil || result.Total != 2 || result.Succeeded != 0 || result.Failed != 1 || result.Canceled != 1 || notifier.batchCalls != 0 || result.Notification == nil || result.Notification.Status != "skipped" || result.Notification.Reason != "batch canceled" {
|
||||
t.Fatalf("RunBatchDetailed() result/error/notifier = %#v/%v/%#v", result, err, notifier)
|
||||
}
|
||||
if result.Reports[0].Status != "failed" || result.Reports[0].Error == "" || result.Reports[1].Status != "canceled" {
|
||||
t.Fatalf("report results = %#v", result.Reports)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNotifyBatchSkipsCancellationObservedAfterReportsComplete(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
notifier := &generationNotifier{}
|
||||
|
||||
result := notifyBatch(batchNotificationInput{
|
||||
ctx: ctx, cfg: generationDistributorConfig(), batch: BatchMorning,
|
||||
runID: "run-id", startedAt: generationTime("2026-05-29T08:30:00-05:00"),
|
||||
result: &BatchResult{Total: 1, Succeeded: 1, Reports: []BatchReportResult{{Status: "succeeded"}}},
|
||||
notifier: notifier,
|
||||
})
|
||||
|
||||
if result == nil || result.Status != "skipped" || result.Reason != "batch canceled" || notifier.batchCalls != 0 {
|
||||
t.Fatalf("notifyBatch() result/notifier = %#v/%#v", result, notifier)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunBatchDetailedRetainsPublishedReportBeforeCancellation(t *testing.T) {
|
||||
for _, cause := range []error{context.Canceled, context.DeadlineExceeded} {
|
||||
t.Run(cause.Error(), func(t *testing.T) {
|
||||
bundle := generationBundle(t)
|
||||
bundle.Hourly.Periods = bundle.Hourly.Periods[:1]
|
||||
notifier := &generationNotifier{}
|
||||
ctx := &publicationGateContext{Context: context.Background(), err: cause, afterChecks: 4}
|
||||
|
||||
result, err := RunBatchDetailed(ctx, BatchRequest{
|
||||
Config: generationDistributorConfig(), Batch: BatchMorning,
|
||||
Now: generationTime("2026-05-29T08:30:00-05:00"), WorkingDir: t.TempDir(), OutputDir: t.TempDir(),
|
||||
Collector: &generationCollector{bundle: &bundle}, Executor: &generationExecutor{}, Notifier: notifier,
|
||||
})
|
||||
if !errors.Is(err, cause) || result == nil || result.Total != 2 || result.Succeeded != 1 || result.Failed != 0 || result.Canceled != 1 || len(result.Reports) != 2 || result.Reports[0].Status != "succeeded" || result.Reports[0].OutputPath == "" || result.Reports[1].Status != "canceled" || result.Reports[1].OutputPath != "" || notifier.batchCalls != 0 || result.Notification == nil || result.Notification.Status != "skipped" || result.Notification.Reason != "batch canceled" {
|
||||
t.Fatalf("RunBatchDetailed() result/error/notifier = %#v/%v/%#v", result, err, notifier)
|
||||
}
|
||||
if _, statErr := os.Stat(result.Reports[0].OutputPath); statErr != nil {
|
||||
t.Fatalf("published report %q: %v", result.Reports[0].OutputPath, statErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunBatchPreservesCancellationCause(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
bundle := generationBundle(t)
|
||||
bundle.Hourly.Periods = bundle.Hourly.Periods[:1]
|
||||
err := RunBatch(ctx, BatchRequest{
|
||||
Config: generationDistributorConfig(), Batch: BatchMorning,
|
||||
Now: generationTime("2026-05-29T08:30:00-05:00"), WorkingDir: t.TempDir(), OutputDir: t.TempDir(),
|
||||
Collector: &generationCollector{bundle: &bundle}, Executor: &generationExecutor{cancelBeforeReturn: cancel}, Notifier: &generationNotifier{},
|
||||
})
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("RunBatch() error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunBatchDetailedNotifiesOnlyAfterAllOutputsExist(t *testing.T) {
|
||||
bundle := generationBundle(t)
|
||||
bundle.Hourly.Periods = bundle.Hourly.Periods[:1]
|
||||
outputDir := t.TempDir()
|
||||
notifier := &generationNotifier{}
|
||||
result, err := RunBatchDetailed(context.Background(), BatchRequest{
|
||||
Config: generationDistributorConfig(), Batch: BatchMorning,
|
||||
Now: generationTime("2026-05-29T08:30:00-05:00"), WorkingDir: t.TempDir(), OutputDir: outputDir,
|
||||
Collector: &generationCollector{bundle: &bundle}, Executor: &generationExecutor{}, Notifier: notifier,
|
||||
})
|
||||
if err != nil || result == nil || result.Total != 2 || result.Succeeded != 2 || result.Failed != 0 || notifier.batchCalls != 1 || result.Notification == nil || result.Notification.Status != "succeeded" {
|
||||
t.Fatalf("RunBatchDetailed() result/error/notifier = %#v/%v/%#v", result, err, notifier)
|
||||
}
|
||||
if len(notifier.batchRequest.Files) < 2 || len(notifier.batchRequest.IncludedReports) != 2 {
|
||||
t.Fatalf("batch notification = %#v", notifier.batchRequest)
|
||||
}
|
||||
if result.Reports[0].OutputPath == result.Reports[1].OutputPath {
|
||||
t.Fatalf("batch reports share output path %q", result.Reports[0].OutputPath)
|
||||
}
|
||||
for _, file := range notifier.batchRequest.Files {
|
||||
if filepath.Dir(file.SourcePath) != outputDir || file.BundlePath == "" {
|
||||
t.Fatalf("notification file = %#v", file)
|
||||
}
|
||||
if _, statErr := os.Stat(file.SourcePath); statErr != nil {
|
||||
t.Fatalf("notification source %q: %v", file.SourcePath, statErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunBatchDetailedRejectsUnsupportedDistributorEndpointBeforeWork(t *testing.T) {
|
||||
outputDir := t.TempDir()
|
||||
cfg := generationDistributorConfig()
|
||||
cfg.Notify.Distributor.Endpoint = "ftp://distributor.example.test"
|
||||
bundle := generationBundle(t)
|
||||
collector := &generationCollector{bundle: &bundle}
|
||||
executor := &generationExecutor{}
|
||||
notifier := &generationNotifier{}
|
||||
|
||||
result, err := RunBatchDetailed(context.Background(), BatchRequest{
|
||||
Config: cfg, Batch: BatchMorning,
|
||||
Now: generationTime("2026-05-29T08:30:00-05:00"), WorkingDir: t.TempDir(), OutputDir: outputDir,
|
||||
Collector: collector, Executor: executor, Notifier: notifier,
|
||||
})
|
||||
if err == nil || result != nil || collector.called || executor.promptInspections != 0 || executor.called || notifier.calls != 0 || notifier.batchCalls != 0 {
|
||||
t.Fatalf("RunBatchDetailed() result/error/collector/executor/notifier = %#v/%v/%t/%#v/%#v", result, err, collector.called, executor, notifier)
|
||||
}
|
||||
entries, readErr := os.ReadDir(outputDir)
|
||||
if readErr != nil || len(entries) != 0 {
|
||||
t.Fatalf("output directory entries/error = %v/%v", entries, readErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunBatchDetailedUsesDefaultAndConfiguredOutputDirectories(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
directory func(t *testing.T, workingDir string) string
|
||||
wantDir func(t *testing.T, workingDir string, configuredDir string) string
|
||||
}{
|
||||
{
|
||||
name: "working directory default",
|
||||
directory: func(_ *testing.T, _ string) string {
|
||||
return ""
|
||||
},
|
||||
wantDir: func(_ *testing.T, workingDir string, _ string) string {
|
||||
return workingDir
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "absolute directory",
|
||||
directory: func(t *testing.T, _ string) string {
|
||||
return filepath.Join(t.TempDir(), "reports")
|
||||
},
|
||||
wantDir: func(_ *testing.T, _ string, configuredDir string) string {
|
||||
return configuredDir
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "relative directory",
|
||||
directory: func(_ *testing.T, _ string) string {
|
||||
return "configured/../reports"
|
||||
},
|
||||
wantDir: func(_ *testing.T, workingDir string, _ string) string {
|
||||
return filepath.Join(workingDir, "reports")
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
workingDir := t.TempDir()
|
||||
configuredDir := tt.directory(t, workingDir)
|
||||
cfg := generationDistributorConfig()
|
||||
cfg.Output.Directory = configuredDir
|
||||
bundle := generationBundle(t)
|
||||
bundle.Hourly.Periods = bundle.Hourly.Periods[:1]
|
||||
notifier := &generationNotifier{}
|
||||
|
||||
result, err := RunBatchDetailed(context.Background(), BatchRequest{
|
||||
Config: cfg, Batch: BatchMorning,
|
||||
Now: generationTime("2026-05-29T08:30:00-05:00"), WorkingDir: workingDir,
|
||||
Collector: &generationCollector{bundle: &bundle}, Executor: &generationExecutor{}, Notifier: notifier,
|
||||
})
|
||||
wantDir := tt.wantDir(t, workingDir, configuredDir)
|
||||
if err != nil || result == nil || result.Succeeded != len(result.Reports) || notifier.batchCalls != 1 {
|
||||
t.Fatalf("RunBatchDetailed() result/error/notifier = %#v/%v/%#v", result, err, notifier)
|
||||
}
|
||||
for _, item := range result.Reports {
|
||||
if filepath.Dir(item.OutputPath) != wantDir {
|
||||
t.Fatalf("report output %q, want directory %q", item.OutputPath, wantDir)
|
||||
}
|
||||
}
|
||||
for _, file := range notifier.batchRequest.Files {
|
||||
if filepath.Dir(file.SourcePath) != wantDir {
|
||||
t.Fatalf("notification source %q, want directory %q", file.SourcePath, wantDir)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunBatchDetailedExplicitOutputDirectoryIgnoresConfiguredDirectory(t *testing.T) {
|
||||
configuredPath := filepath.Join(t.TempDir(), "not-a-directory")
|
||||
if err := os.WriteFile(configuredPath, []byte("not a directory"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
explicitDir := t.TempDir()
|
||||
cfg := generationDistributorConfig()
|
||||
cfg.Output.Directory = configuredPath
|
||||
bundle := generationBundle(t)
|
||||
bundle.Hourly.Periods = bundle.Hourly.Periods[:1]
|
||||
|
||||
result, err := RunBatchDetailed(context.Background(), BatchRequest{
|
||||
Config: cfg, Batch: BatchMorning,
|
||||
Now: generationTime("2026-05-29T08:30:00-05:00"), WorkingDir: t.TempDir(), OutputDir: explicitDir,
|
||||
Collector: &generationCollector{bundle: &bundle}, Executor: &generationExecutor{}, Notifier: &generationNotifier{},
|
||||
})
|
||||
if err != nil || result == nil || result.Succeeded != len(result.Reports) {
|
||||
t.Fatalf("RunBatchDetailed() result/error = %#v/%v", result, err)
|
||||
}
|
||||
for _, item := range result.Reports {
|
||||
if filepath.Dir(item.OutputPath) != explicitDir {
|
||||
t.Fatalf("report output %q, want directory %q", item.OutputPath, explicitDir)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunBatchDetailedPreflightsAllOutputPaths(t *testing.T) {
|
||||
bundle := generationBundle(t)
|
||||
bundle.Hourly.Periods = bundle.Hourly.Periods[:1]
|
||||
outputDir := t.TempDir()
|
||||
if err := os.Mkdir(filepath.Join(outputDir, "tomorrow.md"), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
todayPath := filepath.Join(outputDir, "today.md")
|
||||
const previousReport = "previous report"
|
||||
if err := os.WriteFile(todayPath, []byte(previousReport), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
executor := &generationExecutor{}
|
||||
promptInspectedBeforeCollection := false
|
||||
collector := &generationCollector{
|
||||
bundle: &bundle,
|
||||
beforeRun: func() {
|
||||
promptInspectedBeforeCollection = executor.promptInspections > 0
|
||||
},
|
||||
}
|
||||
result, err := RunBatchDetailed(context.Background(), BatchRequest{
|
||||
Config: generationDistributorConfig(), Batch: BatchMorning,
|
||||
Now: generationTime("2026-05-29T08:30:00-05:00"), WorkingDir: t.TempDir(), OutputDir: outputDir,
|
||||
Collector: collector, Executor: executor, Notifier: &generationNotifier{},
|
||||
})
|
||||
if err == nil || result != nil || !collector.called || !promptInspectedBeforeCollection || executor.called {
|
||||
t.Fatalf("RunBatchDetailed() result/error/collection/inspection/execution = %#v/%v/%t/%t/%t", result, err, collector.called, promptInspectedBeforeCollection, executor.called)
|
||||
}
|
||||
if data, readErr := os.ReadFile(todayPath); readErr != nil || string(data) != previousReport {
|
||||
t.Fatalf("earlier output = %q, error = %v", data, readErr)
|
||||
}
|
||||
if info, statErr := os.Stat(filepath.Join(outputDir, "tomorrow.md")); statErr != nil || !info.IsDir() {
|
||||
t.Fatalf("blocked output info/error = %#v/%v", info, statErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunBatchDetailedRetainsReportCountsWhenNotificationFails(t *testing.T) {
|
||||
bundle := generationBundle(t)
|
||||
bundle.Hourly.Periods = bundle.Hourly.Periods[:1]
|
||||
outputDir := t.TempDir()
|
||||
notifier := &generationNotifier{batchErr: errors.New("distributor unavailable")}
|
||||
result, err := RunBatchDetailed(context.Background(), BatchRequest{
|
||||
Config: generationDistributorConfig(), Batch: BatchMorning,
|
||||
Now: generationTime("2026-05-29T08:30:00-05:00"), WorkingDir: t.TempDir(), OutputDir: outputDir,
|
||||
Collector: &generationCollector{bundle: &bundle}, Executor: &generationExecutor{}, Notifier: notifier,
|
||||
})
|
||||
if err != nil || result == nil || result.Total != len(result.Reports) || result.Succeeded != len(result.Reports) || result.Failed != 0 || result.Notification == nil || result.Notification.Status != "failed" {
|
||||
t.Fatalf("RunBatchDetailed() result/error = %#v/%v", result, err)
|
||||
}
|
||||
for _, item := range result.Reports {
|
||||
if item.Status != "succeeded" || item.OutputPath == "" {
|
||||
t.Fatalf("report result = %#v", item)
|
||||
}
|
||||
if _, statErr := os.Stat(item.OutputPath); statErr != nil {
|
||||
t.Fatalf("published output %q: %v", item.OutputPath, statErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunBatchReturnsNotificationFailureWithoutReportFailureWording(t *testing.T) {
|
||||
bundle := generationBundle(t)
|
||||
bundle.Hourly.Periods = bundle.Hourly.Periods[:1]
|
||||
err := RunBatch(context.Background(), BatchRequest{
|
||||
Config: generationDistributorConfig(), Batch: BatchMorning,
|
||||
Now: generationTime("2026-05-29T08:30:00-05:00"), WorkingDir: t.TempDir(), OutputDir: t.TempDir(),
|
||||
Collector: &generationCollector{bundle: &bundle}, Executor: &generationExecutor{}, Notifier: &generationNotifier{batchErr: errors.New("distributor unavailable")},
|
||||
})
|
||||
var batchErr BatchError
|
||||
if !errors.As(err, &batchErr) || batchErr.Result == nil || batchErr.Result.Failed != 0 || batchErr.Result.Notification == nil || batchErr.Result.Notification.Status != "failed" || !strings.Contains(err.Error(), "notification failed") || strings.Contains(err.Error(), "reports failed") {
|
||||
t.Fatalf("RunBatch() error/result = %v/%#v", err, batchErr.Result)
|
||||
}
|
||||
}
|
||||
|
||||
func generationDistributorConfig() config.Config {
|
||||
cfg := generationConfig()
|
||||
cfg.Notify.Distributor.Enabled = true
|
||||
cfg.Notify.Distributor.PipelineIDTemplate = "weather"
|
||||
return cfg
|
||||
}
|
||||
318
internal/app/batch_notification.go
Normal file
318
internal/app/batch_notification.go
Normal file
@@ -0,0 +1,318 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
distributoradapter "gitea.maximumdirect.net/eric/weatherreporter/internal/adapters/distributor"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/config"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/report"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/timeutil"
|
||||
)
|
||||
|
||||
const runIDTimestampLayout = "20060102T150405.000000000Z"
|
||||
|
||||
type batchNotificationIdentity struct {
|
||||
PipelineID string
|
||||
BundleID string
|
||||
IdempotencyKey string
|
||||
}
|
||||
|
||||
type batchNotificationRequest struct {
|
||||
Batch BatchKind
|
||||
RunID string
|
||||
PipelineID string
|
||||
BundleID string
|
||||
IdempotencyKey string
|
||||
Files []batchNotificationFile
|
||||
IncludedReports []BatchNotificationReport
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type batchNotificationFile struct {
|
||||
ReportID report.ID
|
||||
RunID string
|
||||
SourcePath string
|
||||
BundlePath string
|
||||
}
|
||||
|
||||
type batchNotifier interface {
|
||||
NotifyBatch(context.Context, batchNotificationRequest) (*NotificationResult, error)
|
||||
}
|
||||
|
||||
type batchNotificationInput struct {
|
||||
ctx context.Context
|
||||
cancellation error
|
||||
cfg config.Config
|
||||
batch BatchKind
|
||||
runID string
|
||||
startedAt time.Time
|
||||
result *BatchResult
|
||||
planned []plannedBatchReport
|
||||
notifier Notifier
|
||||
}
|
||||
|
||||
func batchRunID(startedAt time.Time, batch BatchKind) string {
|
||||
return startedAt.UTC().Format(runIDTimestampLayout) + "_" + string(batch)
|
||||
}
|
||||
|
||||
func notifyBatch(input batchNotificationInput) *BatchNotificationResult {
|
||||
if !input.cfg.Notify.Distributor.Enabled {
|
||||
return nil
|
||||
}
|
||||
if !input.cfg.Notify.Distributor.Batch.Enabled {
|
||||
return nil
|
||||
}
|
||||
if input.result == nil {
|
||||
return failedBatchNotificationResult(batchNotificationRequest{}, fmt.Errorf("batch result is required"))
|
||||
}
|
||||
if input.cancellation != nil || batchContextCancellationCause(input.ctx) != nil || input.result.Canceled > 0 {
|
||||
return &BatchNotificationResult{
|
||||
Status: "skipped",
|
||||
Reason: "batch canceled",
|
||||
}
|
||||
}
|
||||
if input.result.Failed > 0 {
|
||||
return &BatchNotificationResult{
|
||||
Status: "skipped",
|
||||
Reason: "one or more reports failed",
|
||||
}
|
||||
}
|
||||
|
||||
req, err := buildBatchNotificationRequest(input.cfg, input.batch, input.runID, input.startedAt, input.result.Reports, input.planned)
|
||||
if err != nil {
|
||||
return failedBatchNotificationResult(batchNotificationRequest{}, err)
|
||||
}
|
||||
|
||||
batchNotifier, err := resolveBatchNotifier(input.cfg, input.notifier)
|
||||
if err != nil {
|
||||
return failedBatchNotificationResult(req, err)
|
||||
}
|
||||
|
||||
notification, notifyErr := batchNotifier.NotifyBatch(input.ctx, req)
|
||||
wrappedErr := notifyErr
|
||||
if notifyErr != nil {
|
||||
wrappedErr = fmt.Errorf("notify batch %q run %q bundle %q: %w", input.batch, input.runID, req.BundleID, notifyErr)
|
||||
}
|
||||
batchResult := batchNotificationResult(req, notification)
|
||||
if wrappedErr != nil {
|
||||
batchResult.Status = "failed"
|
||||
batchResult.Error = safeDistributorNotificationFailure(wrappedErr)
|
||||
return batchResult
|
||||
}
|
||||
return batchResult
|
||||
}
|
||||
|
||||
func resolveBatchNotifier(cfg config.Config, notifier Notifier) (batchNotifier, error) {
|
||||
if notifier != nil {
|
||||
if batchNotifier, ok := notifier.(batchNotifier); ok {
|
||||
return batchNotifier, nil
|
||||
}
|
||||
return nil, fmt.Errorf("batch distributor notifier is required")
|
||||
}
|
||||
return distributorNotifier{
|
||||
client: distributoradapter.New(cfg.Notify.Distributor),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func buildBatchNotificationRequest(cfg config.Config, batch BatchKind, runID string, startedAt time.Time, reports []BatchReportResult, planned []plannedBatchReport) (batchNotificationRequest, error) {
|
||||
if len(reports) == 0 {
|
||||
return batchNotificationRequest{}, fmt.Errorf("batch notification requires at least one report")
|
||||
}
|
||||
|
||||
identity, err := renderBatchNotificationIdentity(cfg, batch, runID, startedAt)
|
||||
if err != nil {
|
||||
return batchNotificationRequest{}, err
|
||||
}
|
||||
if identity.PipelineID == "" {
|
||||
return batchNotificationRequest{}, fmt.Errorf("batch notification pipeline id is required")
|
||||
}
|
||||
if identity.BundleID == "" {
|
||||
return batchNotificationRequest{}, fmt.Errorf("batch notification bundle id is required")
|
||||
}
|
||||
if identity.IdempotencyKey == "" {
|
||||
return batchNotificationRequest{}, fmt.Errorf("batch notification idempotency key is required for bundle %q", identity.BundleID)
|
||||
}
|
||||
|
||||
plannedByRunID, err := plannedReportsByRunID(planned)
|
||||
if err != nil {
|
||||
return batchNotificationRequest{}, err
|
||||
}
|
||||
|
||||
req := batchNotificationRequest{
|
||||
Batch: batch,
|
||||
RunID: runID,
|
||||
PipelineID: identity.PipelineID,
|
||||
BundleID: identity.BundleID,
|
||||
IdempotencyKey: identity.IdempotencyKey,
|
||||
CreatedAt: startedAt,
|
||||
}
|
||||
seenBundlePaths := map[string]batchNotificationFile{}
|
||||
for _, item := range reports {
|
||||
plannedReport, ok := plannedByRunID[item.RunID]
|
||||
if !ok {
|
||||
return batchNotificationRequest{}, fmt.Errorf("batch notification report %q run %q has no matching planned report", item.ReportID, item.RunID)
|
||||
}
|
||||
if item.ReportID != plannedReport.Resolved.Definition.ID {
|
||||
return batchNotificationRequest{}, fmt.Errorf("batch notification report %q run %q does not match planned report %q", item.ReportID, item.RunID, plannedReport.Resolved.Definition.ID)
|
||||
}
|
||||
if item.OutputPath == "" {
|
||||
return batchNotificationRequest{}, fmt.Errorf("batch notification report %q run %q is missing output path", item.ReportID, item.RunID)
|
||||
}
|
||||
|
||||
values, err := distributorTemplateValuesForReport(cfg, plannedReport.Resolved, item.RunID, filepath.Base(item.OutputPath))
|
||||
if err != nil {
|
||||
return batchNotificationRequest{}, fmt.Errorf("batch notification report %q run %q source path %q: %w", item.ReportID, item.RunID, item.OutputPath, err)
|
||||
}
|
||||
bundlePaths, err := renderDistributorReportBundlePaths(cfg, plannedReport.Resolved, item.RunID, item.OutputPath, values)
|
||||
if err != nil {
|
||||
return batchNotificationRequest{}, err
|
||||
}
|
||||
|
||||
included := BatchNotificationReport{
|
||||
ReportID: item.ReportID,
|
||||
RunID: item.RunID,
|
||||
SourcePath: item.OutputPath,
|
||||
BundlePaths: append([]string(nil), bundlePaths...),
|
||||
}
|
||||
for _, bundlePath := range bundlePaths {
|
||||
file := batchNotificationFile{
|
||||
ReportID: item.ReportID,
|
||||
RunID: item.RunID,
|
||||
SourcePath: item.OutputPath,
|
||||
BundlePath: bundlePath,
|
||||
}
|
||||
if previous, ok := seenBundlePaths[bundlePath]; ok {
|
||||
return batchNotificationRequest{}, fmt.Errorf("batch notification duplicate bundle path %q for report %q run %q source path %q; already used by report %q run %q source path %q", bundlePath, item.ReportID, item.RunID, item.OutputPath, previous.ReportID, previous.RunID, previous.SourcePath)
|
||||
}
|
||||
seenBundlePaths[bundlePath] = file
|
||||
req.Files = append(req.Files, file)
|
||||
}
|
||||
req.IncludedReports = append(req.IncludedReports, included)
|
||||
}
|
||||
if len(req.Files) == 0 {
|
||||
return batchNotificationRequest{}, fmt.Errorf("batch notification requires at least one file mapping")
|
||||
}
|
||||
return req, nil
|
||||
}
|
||||
|
||||
func plannedReportsByRunID(planned []plannedBatchReport) (map[string]plannedBatchReport, error) {
|
||||
byRunID := make(map[string]plannedBatchReport, len(planned))
|
||||
for _, item := range planned {
|
||||
runID := item.Resolved.Metadata().RunID
|
||||
if runID == "" {
|
||||
return nil, fmt.Errorf("planned report %q has empty run id", item.Resolved.Definition.ID)
|
||||
}
|
||||
if previous, ok := byRunID[runID]; ok {
|
||||
return nil, fmt.Errorf("planned reports %q and %q share run id %q", previous.Resolved.Definition.ID, item.Resolved.Definition.ID, runID)
|
||||
}
|
||||
byRunID[runID] = item
|
||||
}
|
||||
return byRunID, nil
|
||||
}
|
||||
|
||||
func batchDistributorUploadRequest(req batchNotificationRequest) distributoradapter.UploadRequest {
|
||||
files := make([]distributoradapter.UploadFile, 0, len(req.Files))
|
||||
for _, file := range req.Files {
|
||||
files = append(files, distributoradapter.UploadFile{
|
||||
SourcePath: file.SourcePath,
|
||||
BundlePath: file.BundlePath,
|
||||
})
|
||||
}
|
||||
return distributoradapter.UploadRequest{
|
||||
PipelineID: req.PipelineID,
|
||||
BundleID: req.BundleID,
|
||||
IdempotencyKey: req.IdempotencyKey,
|
||||
Files: files,
|
||||
CreatedAt: req.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func batchNotificationResult(req batchNotificationRequest, result *NotificationResult) *BatchNotificationResult {
|
||||
notification := &BatchNotificationResult{
|
||||
Status: "unknown",
|
||||
PipelineID: req.PipelineID,
|
||||
BundleID: req.BundleID,
|
||||
IdempotencyKey: req.IdempotencyKey,
|
||||
IncludedReports: append([]BatchNotificationReport(nil), req.IncludedReports...),
|
||||
}
|
||||
if result != nil {
|
||||
notification.Status = result.Status
|
||||
notification.RunID = result.RunID
|
||||
if result.PipelineID != "" {
|
||||
notification.PipelineID = result.PipelineID
|
||||
}
|
||||
if result.BundleID != "" {
|
||||
notification.BundleID = result.BundleID
|
||||
}
|
||||
if result.IdempotencyKey != "" {
|
||||
notification.IdempotencyKey = result.IdempotencyKey
|
||||
}
|
||||
if result.Error != "" {
|
||||
notification.Error = safeDistributorRunError(result.Error)
|
||||
}
|
||||
}
|
||||
if notification.Status == "" {
|
||||
notification.Status = "unknown"
|
||||
}
|
||||
return notification
|
||||
}
|
||||
|
||||
func failedBatchNotificationResult(req batchNotificationRequest, err error) *BatchNotificationResult {
|
||||
notification := batchNotificationResult(req, nil)
|
||||
notification.Status = "failed"
|
||||
if err != nil {
|
||||
notification.Error = safeDistributorNotificationFailure(err)
|
||||
}
|
||||
return notification
|
||||
}
|
||||
|
||||
func safeDistributorNotificationFailure(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
return "distributor notification failed"
|
||||
}
|
||||
|
||||
func renderBatchNotificationIdentity(cfg config.Config, batch BatchKind, runID string, startedAt time.Time) (batchNotificationIdentity, error) {
|
||||
values, err := batchNotificationTemplateValues(cfg, batch, runID, startedAt)
|
||||
if err != nil {
|
||||
return batchNotificationIdentity{}, err
|
||||
}
|
||||
|
||||
bundleID, err := config.RenderDistributorBatchBundleID(cfg.Notify.Distributor.Batch.BundleIDTemplate, values)
|
||||
if err != nil {
|
||||
return batchNotificationIdentity{}, err
|
||||
}
|
||||
values.BundleID = bundleID
|
||||
|
||||
pipelineID, err := config.RenderDistributorBatchPipelineID(cfg.Notify.Distributor.Batch.PipelineIDTemplate, values)
|
||||
if err != nil {
|
||||
return batchNotificationIdentity{}, err
|
||||
}
|
||||
idempotencyKey, err := config.RenderDistributorBatchIdempotencyKey(cfg.Notify.Distributor.Batch.IdempotencyKeyTemplate, values)
|
||||
if err != nil {
|
||||
return batchNotificationIdentity{}, err
|
||||
}
|
||||
|
||||
return batchNotificationIdentity{
|
||||
PipelineID: pipelineID,
|
||||
BundleID: bundleID,
|
||||
IdempotencyKey: idempotencyKey,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func batchNotificationTemplateValues(cfg config.Config, batch BatchKind, runID string, startedAt time.Time) (config.DistributorBatchTemplateValues, error) {
|
||||
location, err := timeutil.LoadLocation(cfg.WeatherAPI.Timezone)
|
||||
if err != nil {
|
||||
return config.DistributorBatchTemplateValues{}, fmt.Errorf("load batch notification timezone: %w", err)
|
||||
}
|
||||
return config.DistributorBatchTemplateValues{
|
||||
LocationID: cfg.Location.ID,
|
||||
Batch: string(batch),
|
||||
BatchRunID: runID,
|
||||
BatchStartedDate: startedAt.In(location).Format(timeutil.DateLayout),
|
||||
}, nil
|
||||
}
|
||||
135
internal/app/batch_plan.go
Normal file
135
internal/app/batch_plan.go
Normal file
@@ -0,0 +1,135 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/collect"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/report"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/timeutil"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/weatherdata"
|
||||
)
|
||||
|
||||
type plannedBatchReport struct {
|
||||
Resolved report.Resolved
|
||||
OutputPath string
|
||||
}
|
||||
|
||||
func planBatchRun(req BatchRequest, now time.Time, collection collect.Result) ([]plannedBatchReport, error) {
|
||||
location, err := timeutil.LoadLocation(req.Config.WeatherAPI.Timezone)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
batch, err := report.BatchForCommandName(string(req.Batch))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
registry, err := reportRegistry(req.Config)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resolveReq := report.ResolveRequest{
|
||||
Now: now,
|
||||
Location: location,
|
||||
}
|
||||
var planned []plannedBatchReport
|
||||
switch batch {
|
||||
case report.Morning:
|
||||
planned, err = appendPlannedReport(planned, registry, report.Today, resolveReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
planned, err = appendPlannedReport(planned, registry, report.Tomorrow, resolveReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case report.Evening:
|
||||
planned, err = appendPlannedReport(planned, registry, report.Tomorrow, resolveReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown batch %q", batch)
|
||||
}
|
||||
|
||||
var hourly *weatherdata.ForecastRun
|
||||
if collection.Bundle != nil {
|
||||
hourly = collection.Bundle.Hourly
|
||||
}
|
||||
for _, date := range eligibleDailyDates(hourly, now, location) {
|
||||
dailyReq := resolveReq
|
||||
dailyReq.Date = date
|
||||
planned, err = appendPlannedReport(planned, registry, report.Daily, dailyReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return planned, nil
|
||||
}
|
||||
|
||||
func appendPlannedReport(planned []plannedBatchReport, registry report.Registry, id report.ID, req report.ResolveRequest) ([]plannedBatchReport, error) {
|
||||
resolved, err := registry.Resolve(id, req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return append(planned, plannedBatchReport{Resolved: resolved}), nil
|
||||
}
|
||||
|
||||
func eligibleDailyDates(hourly *weatherdata.ForecastRun, now time.Time, location *time.Location) []time.Time {
|
||||
if hourly == nil || location == nil || hourly.Product != "hourly" || len(hourly.Periods) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
hourlyStarts := make(map[time.Time]struct{}, len(hourly.Periods))
|
||||
var maxLocalDate time.Time
|
||||
for _, period := range hourly.Periods {
|
||||
if !isHourlyPeriod(period) {
|
||||
continue
|
||||
}
|
||||
start := period.StartTime
|
||||
hourlyStarts[instantKey(start)] = struct{}{}
|
||||
localDate := localDateStart(start, location)
|
||||
if maxLocalDate.IsZero() || localDate.After(maxLocalDate) {
|
||||
maxLocalDate = localDate
|
||||
}
|
||||
}
|
||||
if len(hourlyStarts) == 0 || maxLocalDate.IsZero() {
|
||||
return nil
|
||||
}
|
||||
|
||||
startDate := localDateStart(now.In(location).AddDate(0, 0, 2), location)
|
||||
var dates []time.Time
|
||||
for candidate := startDate; !candidate.After(maxLocalDate); candidate = candidate.AddDate(0, 0, 1) {
|
||||
if hasFullHourlyCoverage(candidate, location, hourlyStarts) {
|
||||
dates = append(dates, candidate)
|
||||
}
|
||||
}
|
||||
return dates
|
||||
}
|
||||
|
||||
func isHourlyPeriod(period weatherdata.ForecastPeriod) bool {
|
||||
if period.StartTime.IsZero() || period.EndTime.IsZero() {
|
||||
return false
|
||||
}
|
||||
return period.EndTime.Equal(period.StartTime.Add(time.Hour))
|
||||
}
|
||||
|
||||
func hasFullHourlyCoverage(date time.Time, location *time.Location, hourlyStarts map[time.Time]struct{}) bool {
|
||||
day := timeutil.CivilDay(date, location)
|
||||
for required := day.Start; required.Before(day.End); required = required.Add(time.Hour) {
|
||||
if _, ok := hourlyStarts[instantKey(required)]; !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func instantKey(value time.Time) time.Time {
|
||||
return value.UTC()
|
||||
}
|
||||
|
||||
func localDateStart(value time.Time, location *time.Location) time.Time {
|
||||
local := value.In(location)
|
||||
return time.Date(local.Year(), local.Month(), local.Day(), 0, 0, 0, 0, location)
|
||||
}
|
||||
347
internal/app/batch_plan_test.go
Normal file
347
internal/app/batch_plan_test.go
Normal file
@@ -0,0 +1,347 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/collect"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/config"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/report"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/timeutil"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/weatherdata"
|
||||
)
|
||||
|
||||
func TestPlanBatchRunMorningOrder(t *testing.T) {
|
||||
location := mustLoadTestLocation(t, "America/Chicago")
|
||||
hourly := hourlyRun(fullDayPeriods(t, "2026-05-31", location)...)
|
||||
|
||||
planned, err := planBatchRun(BatchRequest{Config: planningConfig(), Batch: BatchMorning}, mustParse("2026-05-29T08:00:00-05:00"), collectionWithHourly(hourly))
|
||||
if err != nil {
|
||||
t.Fatalf("planBatchRun() error = %v", err)
|
||||
}
|
||||
|
||||
assertPlannedReportIDs(t, planned, report.Today, report.Tomorrow, report.Daily)
|
||||
}
|
||||
|
||||
func TestPlanBatchRunEveningOrder(t *testing.T) {
|
||||
location := mustLoadTestLocation(t, "America/Chicago")
|
||||
hourly := hourlyRun(fullDayPeriods(t, "2026-05-31", location)...)
|
||||
|
||||
planned, err := planBatchRun(BatchRequest{Config: planningConfig(), Batch: BatchEvening}, mustParse("2026-05-29T18:00:00-05:00"), collectionWithHourly(hourly))
|
||||
if err != nil {
|
||||
t.Fatalf("planBatchRun() error = %v", err)
|
||||
}
|
||||
|
||||
assertPlannedReportIDs(t, planned, report.Tomorrow, report.Daily)
|
||||
}
|
||||
|
||||
func TestPlanBatchRunDynamicDailyDatesStartAfterTomorrow(t *testing.T) {
|
||||
location := mustLoadTestLocation(t, "America/Chicago")
|
||||
periods := fullDayPeriods(t, "2026-05-30", location)
|
||||
periods = append(periods, fullDayPeriods(t, "2026-05-31", location)...)
|
||||
periods = append(periods, fullDayPeriods(t, "2026-06-01", location)...)
|
||||
|
||||
planned, err := planBatchRun(BatchRequest{Config: planningConfig(), Batch: BatchMorning}, mustParse("2026-05-29T08:00:00-05:00"), collectionWithHourly(hourlyRun(periods...)))
|
||||
if err != nil {
|
||||
t.Fatalf("planBatchRun() error = %v", err)
|
||||
}
|
||||
|
||||
daily := plannedDailyReports(planned)
|
||||
if len(daily) != 2 {
|
||||
t.Fatalf("daily reports = %#v, want two future Daily reports", daily)
|
||||
}
|
||||
assertPlanningPeriod(t, daily[0].Resolved.ValidPeriod, "2026-05-31T00:00:00-05:00", "2026-06-01T00:00:00-05:00")
|
||||
assertPlanningPeriod(t, daily[1].Resolved.ValidPeriod, "2026-06-01T00:00:00-05:00", "2026-06-02T00:00:00-05:00")
|
||||
}
|
||||
|
||||
func TestPlanBatchRunUsesResolvedOutputNames(t *testing.T) {
|
||||
location := mustLoadTestLocation(t, "America/Chicago")
|
||||
hourly := hourlyRun(fullDayPeriods(t, "2026-05-31", location)...)
|
||||
|
||||
planned, err := planBatchRun(BatchRequest{Config: planningConfig(), Batch: BatchEvening}, mustParse("2026-05-29T18:00:00-05:00"), collectionWithHourly(hourly))
|
||||
if err != nil {
|
||||
t.Fatalf("planBatchRun() error = %v", err)
|
||||
}
|
||||
|
||||
daily := plannedDailyReports(planned)
|
||||
if len(daily) != 1 {
|
||||
t.Fatalf("daily reports = %#v, want one Daily report", daily)
|
||||
}
|
||||
outputName, err := daily[0].Resolved.OutputName()
|
||||
if err != nil {
|
||||
t.Fatalf("OutputName() error = %v", err)
|
||||
}
|
||||
if outputName != "daily-2026-05-31.md" {
|
||||
t.Fatalf("Daily output name = %q, want date-qualified name", outputName)
|
||||
}
|
||||
outputName, err = planned[0].Resolved.OutputName()
|
||||
if err != nil {
|
||||
t.Fatalf("OutputName() error = %v", err)
|
||||
}
|
||||
if outputName != "tomorrow.md" {
|
||||
t.Fatalf("Tomorrow output name = %q, want tomorrow.md", outputName)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlanBatchRunRejectsUnknownBatch(t *testing.T) {
|
||||
_, err := planBatchRun(BatchRequest{Config: planningConfig(), Batch: BatchKind("hourly")}, mustParse("2026-05-29T08:00:00-05:00"), collect.Result{Bundle: &weatherdata.Bundle{}})
|
||||
if err == nil || !strings.Contains(err.Error(), `unknown batch command "hourly"`) {
|
||||
t.Fatalf("planBatchRun() error = %v, want unknown batch command", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEligibleDailyDatesRequiresFullOrdinaryLocalDay(t *testing.T) {
|
||||
location := mustLoadTestLocation(t, "America/Chicago")
|
||||
hourly := hourlyRun(fullDayPeriods(t, "2026-05-31", location)...)
|
||||
|
||||
got := eligibleDailyDates(hourly, mustParse("2026-05-29T08:00:00-05:00"), location)
|
||||
assertLocalDates(t, got, location, "2026-05-31")
|
||||
}
|
||||
|
||||
func TestEligibleDailyDatesMatchesFixedOffsetStartInstants(t *testing.T) {
|
||||
location := mustLoadTestLocation(t, "America/Chicago")
|
||||
hourly := hourlyRun(fixedOffsetPeriods(t, fullDayPeriods(t, "2026-05-31", location))...)
|
||||
|
||||
got := eligibleDailyDates(hourly, mustParse("2026-05-29T08:00:00-05:00"), location)
|
||||
assertLocalDates(t, got, location, "2026-05-31")
|
||||
}
|
||||
|
||||
func TestEligibleDailyDatesSkipsDayWithMissingRequiredHour(t *testing.T) {
|
||||
location := mustLoadTestLocation(t, "America/Chicago")
|
||||
periods := fullDayPeriods(t, "2026-05-31", location)
|
||||
periods = append(periods[:12], periods[13:]...)
|
||||
hourly := hourlyRun(periods...)
|
||||
|
||||
got := eligibleDailyDates(hourly, mustParse("2026-05-29T08:00:00-05:00"), location)
|
||||
assertLocalDates(t, got, location)
|
||||
}
|
||||
|
||||
func TestEligibleDailyDatesSkipsPartialFinalDay(t *testing.T) {
|
||||
location := mustLoadTestLocation(t, "America/Chicago")
|
||||
periods := fullDayPeriods(t, "2026-05-31", location)
|
||||
periods = append(periods, partialDayPeriods(t, "2026-06-01", location, 12)...)
|
||||
hourly := hourlyRun(periods...)
|
||||
|
||||
got := eligibleDailyDates(hourly, mustParse("2026-05-29T08:00:00-05:00"), location)
|
||||
assertLocalDates(t, got, location, "2026-05-31")
|
||||
}
|
||||
|
||||
func TestEligibleDailyDatesStartsAfterTomorrow(t *testing.T) {
|
||||
location := mustLoadTestLocation(t, "America/Chicago")
|
||||
periods := fullDayPeriods(t, "2026-05-29", location)
|
||||
periods = append(periods, fullDayPeriods(t, "2026-05-30", location)...)
|
||||
periods = append(periods, fullDayPeriods(t, "2026-05-31", location)...)
|
||||
hourly := hourlyRun(periods...)
|
||||
|
||||
got := eligibleDailyDates(hourly, mustParse("2026-05-29T08:00:00-05:00"), location)
|
||||
assertLocalDates(t, got, location, "2026-05-31")
|
||||
}
|
||||
|
||||
func TestEligibleDailyDatesReturnsMultipleFutureDatesInOrder(t *testing.T) {
|
||||
location := mustLoadTestLocation(t, "America/Chicago")
|
||||
periods := fullDayPeriods(t, "2026-05-31", location)
|
||||
periods = append(periods, fullDayPeriods(t, "2026-06-01", location)...)
|
||||
hourly := hourlyRun(periods...)
|
||||
|
||||
got := eligibleDailyDates(hourly, mustParse("2026-05-29T08:00:00-05:00"), location)
|
||||
assertLocalDates(t, got, location, "2026-05-31", "2026-06-01")
|
||||
}
|
||||
|
||||
func TestEligibleDailyDatesIgnoresNonHourlyAndInvalidPeriods(t *testing.T) {
|
||||
location := mustLoadTestLocation(t, "America/Chicago")
|
||||
day := timeutil.CivilDay(mustParseLocalDate(t, "2026-05-31", location), location)
|
||||
periods := []weatherdata.ForecastPeriod{
|
||||
{StartTime: day.Start, EndTime: day.Start.Add(2 * time.Hour)},
|
||||
{StartTime: day.Start.Add(time.Hour), EndTime: day.Start.Add(time.Hour)},
|
||||
{StartTime: time.Time{}, EndTime: day.Start.Add(3 * time.Hour)},
|
||||
}
|
||||
periods = append(periods, fullDayPeriods(t, "2026-06-01", location)...)
|
||||
hourly := hourlyRun(periods...)
|
||||
|
||||
got := eligibleDailyDates(hourly, mustParse("2026-05-29T08:00:00-05:00"), location)
|
||||
assertLocalDates(t, got, location, "2026-06-01")
|
||||
}
|
||||
|
||||
func TestEligibleDailyDatesUsesDSTCivilDayInstants(t *testing.T) {
|
||||
location := mustLoadTestLocation(t, "America/New_York")
|
||||
tests := []struct {
|
||||
name string
|
||||
now string
|
||||
date string
|
||||
}{
|
||||
{
|
||||
name: "spring forward",
|
||||
now: "2026-03-06T08:00:00-05:00",
|
||||
date: "2026-03-08",
|
||||
},
|
||||
{
|
||||
name: "fall back",
|
||||
now: "2026-10-30T08:00:00-04:00",
|
||||
date: "2026-11-01",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
hourly := hourlyRun(fullDayPeriods(t, tt.date, location)...)
|
||||
|
||||
got := eligibleDailyDates(hourly, mustParse(tt.now), location)
|
||||
assertLocalDates(t, got, location, tt.date)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEligibleDailyDatesReturnsNoneWithoutHourlyForecast(t *testing.T) {
|
||||
location := mustLoadTestLocation(t, "America/Chicago")
|
||||
fullDay := fullDayPeriods(t, "2026-05-31", location)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
hourly *weatherdata.ForecastRun
|
||||
}{
|
||||
{name: "nil run"},
|
||||
{name: "empty periods", hourly: hourlyRun()},
|
||||
{name: "non-hourly product", hourly: forecastRun("narrative", fullDay...)},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := eligibleDailyDates(tt.hourly, mustParse("2026-05-29T08:00:00-05:00"), location)
|
||||
assertLocalDates(t, got, location)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func hourlyRun(periods ...weatherdata.ForecastPeriod) *weatherdata.ForecastRun {
|
||||
return forecastRun("hourly", periods...)
|
||||
}
|
||||
|
||||
func forecastRun(product string, periods ...weatherdata.ForecastPeriod) *weatherdata.ForecastRun {
|
||||
return &weatherdata.ForecastRun{
|
||||
Product: product,
|
||||
Periods: periods,
|
||||
}
|
||||
}
|
||||
|
||||
func collectionWithHourly(hourly *weatherdata.ForecastRun) collect.Result {
|
||||
return collect.Result{Bundle: &weatherdata.Bundle{Hourly: hourly}}
|
||||
}
|
||||
|
||||
func planningConfig() config.Config {
|
||||
cfg := config.Defaults()
|
||||
cfg.WeatherAPI.Timezone = "America/Chicago"
|
||||
return cfg
|
||||
}
|
||||
|
||||
func assertPlannedReportIDs(t *testing.T, got []plannedBatchReport, want ...report.ID) {
|
||||
t.Helper()
|
||||
gotIDs := make([]string, 0, len(got))
|
||||
for _, item := range got {
|
||||
gotIDs = append(gotIDs, string(item.Resolved.Definition.ID))
|
||||
}
|
||||
wantIDs := make([]string, 0, len(want))
|
||||
for _, id := range want {
|
||||
wantIDs = append(wantIDs, string(id))
|
||||
}
|
||||
if strings.Join(gotIDs, ",") != strings.Join(wantIDs, ",") {
|
||||
t.Fatalf("planned report IDs = [%s], want [%s]", strings.Join(gotIDs, ","), strings.Join(wantIDs, ","))
|
||||
}
|
||||
}
|
||||
|
||||
func plannedDailyReports(planned []plannedBatchReport) []plannedBatchReport {
|
||||
var daily []plannedBatchReport
|
||||
for _, item := range planned {
|
||||
if item.Resolved.Definition.ID == report.Daily {
|
||||
daily = append(daily, item)
|
||||
}
|
||||
}
|
||||
return daily
|
||||
}
|
||||
|
||||
func fullDayPeriods(t *testing.T, date string, location *time.Location) []weatherdata.ForecastPeriod {
|
||||
t.Helper()
|
||||
day := timeutil.CivilDay(mustParseLocalDate(t, date, location), location)
|
||||
var periods []weatherdata.ForecastPeriod
|
||||
for start := day.Start; start.Before(day.End); start = start.Add(time.Hour) {
|
||||
periods = append(periods, weatherdata.ForecastPeriod{
|
||||
StartTime: start,
|
||||
EndTime: start.Add(time.Hour),
|
||||
})
|
||||
}
|
||||
return periods
|
||||
}
|
||||
|
||||
func partialDayPeriods(t *testing.T, date string, location *time.Location, count int) []weatherdata.ForecastPeriod {
|
||||
t.Helper()
|
||||
periods := fullDayPeriods(t, date, location)
|
||||
if count > len(periods) {
|
||||
count = len(periods)
|
||||
}
|
||||
return periods[:count]
|
||||
}
|
||||
|
||||
func fixedOffsetPeriods(t *testing.T, periods []weatherdata.ForecastPeriod) []weatherdata.ForecastPeriod {
|
||||
t.Helper()
|
||||
out := make([]weatherdata.ForecastPeriod, 0, len(periods))
|
||||
for _, period := range periods {
|
||||
start, err := time.Parse(time.RFC3339, period.StartTime.Format(time.RFC3339))
|
||||
if err != nil {
|
||||
t.Fatalf("parse fixed-offset start: %v", err)
|
||||
}
|
||||
end, err := time.Parse(time.RFC3339, period.EndTime.Format(time.RFC3339))
|
||||
if err != nil {
|
||||
t.Fatalf("parse fixed-offset end: %v", err)
|
||||
}
|
||||
out = append(out, weatherdata.ForecastPeriod{StartTime: start, EndTime: end})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func assertLocalDates(t *testing.T, got []time.Time, location *time.Location, want ...string) {
|
||||
t.Helper()
|
||||
gotDates := make([]string, 0, len(got))
|
||||
for _, date := range got {
|
||||
gotDates = append(gotDates, date.In(location).Format(timeutil.DateLayout))
|
||||
}
|
||||
if strings.Join(gotDates, ",") != strings.Join(want, ",") {
|
||||
t.Fatalf("eligibleDailyDates() = [%s], want [%s]", strings.Join(gotDates, ","), strings.Join(want, ","))
|
||||
}
|
||||
for _, date := range got {
|
||||
day := timeutil.CivilDay(date, location)
|
||||
if !date.Equal(day.Start) {
|
||||
t.Fatalf("eligible date %s is not local civil day start %s", date, day.Start)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func assertPlanningPeriod(t *testing.T, period timeutil.Period, wantStart string, wantEnd string) {
|
||||
t.Helper()
|
||||
if !period.IsValid() {
|
||||
t.Fatalf("period = %#v, want valid", period)
|
||||
}
|
||||
if got := period.Start.Format(time.RFC3339); got != wantStart {
|
||||
t.Fatalf("Start = %s, want %s", got, wantStart)
|
||||
}
|
||||
if got := period.End.Format(time.RFC3339); got != wantEnd {
|
||||
t.Fatalf("End = %s, want %s", got, wantEnd)
|
||||
}
|
||||
}
|
||||
|
||||
func mustLoadTestLocation(t *testing.T, name string) *time.Location {
|
||||
t.Helper()
|
||||
location, err := time.LoadLocation(name)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadLocation(%q) error = %v", name, err)
|
||||
}
|
||||
return location
|
||||
}
|
||||
|
||||
func mustParseLocalDate(t *testing.T, value string, location *time.Location) time.Time {
|
||||
t.Helper()
|
||||
parsed, err := timeutil.ParseLocalDate(value, location)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseLocalDate(%q) error = %v", value, err)
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
237
internal/app/comparison.go
Normal file
237
internal/app/comparison.go
Normal file
@@ -0,0 +1,237 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/comparison"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/config"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptdebug"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptexec"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/report"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/timeutil"
|
||||
)
|
||||
|
||||
// ComparisonRequest describes one explicit, multi-profile report comparison.
|
||||
// It deliberately does not accept a notifier: comparison publication is local.
|
||||
type ComparisonRequest struct {
|
||||
Config config.Config
|
||||
Report ReportKind
|
||||
ProfileIDs []string
|
||||
WorkingDir string
|
||||
OutputDir string
|
||||
Replace bool
|
||||
LLMDebugDir string
|
||||
Date time.Time
|
||||
Clock timeutil.Clock
|
||||
Collector Collector
|
||||
Executor promptexec.Executor
|
||||
}
|
||||
|
||||
// ComparisonResult records the resolved comparison and profile outcomes.
|
||||
type ComparisonResult struct {
|
||||
ComparisonID string
|
||||
ReportID report.ID
|
||||
ReportName string
|
||||
PromptID string
|
||||
PromptVersion string
|
||||
PromptHash string
|
||||
StartedAt time.Time
|
||||
FinishedAt time.Time
|
||||
Timezone string
|
||||
ValidPeriod timeutil.Period
|
||||
OutputDirectory string
|
||||
ManifestPath string
|
||||
DataPackagePath string
|
||||
Total int
|
||||
Succeeded int
|
||||
Failed int
|
||||
Results []ComparisonProfileResult
|
||||
}
|
||||
|
||||
// ComparisonProfileResult records one explicitly selected profile.
|
||||
type ComparisonProfileResult struct {
|
||||
Position int
|
||||
ProfileID string
|
||||
BackendID string
|
||||
ModelName string
|
||||
Status string
|
||||
ValidationStatus promptexec.ValidationStatus
|
||||
ReportPath string
|
||||
LLMDebugPath string
|
||||
Error *comparison.SafeError
|
||||
}
|
||||
|
||||
type comparisonPublisher func(context.Context, comparison.DestinationPlan, comparison.LogicalBundle) (comparison.PublicationResult, error)
|
||||
|
||||
// CompareDetailed assembles, executes, and atomically publishes a comparison
|
||||
// bundle. Profile failures publish a complete partial bundle. Failures before
|
||||
// commit leave the destination untouched; a post-commit cleanup failure leaves
|
||||
// the new bundle installed and returns its artifact paths with an error.
|
||||
func CompareDetailed(ctx context.Context, req ComparisonRequest) (*ComparisonResult, error) {
|
||||
return compareDetailed(ctx, req, comparison.Publish)
|
||||
}
|
||||
|
||||
func compareDetailed(ctx context.Context, req ComparisonRequest, publish comparisonPublisher) (*ComparisonResult, error) {
|
||||
if err := comparison.ValidateProfileIDs(req.ProfileIDs); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
clock := req.Clock
|
||||
if clock == nil {
|
||||
clock = timeutil.SystemClock{}
|
||||
}
|
||||
now := clock.Now()
|
||||
resolved, err := ResolveGenerate(GenerateRequest{Config: req.Config, Report: req.Report, Date: req.Date}, now)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
metadata := resolved.Metadata()
|
||||
comparisonID, err := comparison.BuildComparisonID(metadata.RunID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build comparison identity: %w", err)
|
||||
}
|
||||
result := initialComparisonResult(req, resolved, comparisonID, now.UTC())
|
||||
defer func() {
|
||||
if result.FinishedAt.IsZero() {
|
||||
finalizeComparisonResult(result, clock)
|
||||
}
|
||||
}()
|
||||
|
||||
outputName, err := resolved.OutputName()
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("resolve comparison output name: %w", err)
|
||||
}
|
||||
outputDirectory, err := resolveComparisonOutputDirectory(req.WorkingDir, req.OutputDir, req.Config.Output.Directory, outputName)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.OutputDirectory = outputDirectory
|
||||
publicationPlan, err := comparison.PlanDestination(req.WorkingDir, outputDirectory, req.Replace)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("preflight comparison destination: %w", err)
|
||||
}
|
||||
|
||||
debugWriter, err := promptdebug.NewPromptDebugWriter(req.LLMDebugDir)
|
||||
if err != nil {
|
||||
return result, promptexec.NewError(promptexec.InvalidConfiguration, "initialize prompt debug", err)
|
||||
}
|
||||
defer func() { _ = debugWriter.Close() }()
|
||||
inspection, err := InspectComparisonExecution(ctx, ComparisonInspectionRequest{
|
||||
Resolved: resolved, ProfileIDs: req.ProfileIDs, Executor: req.Executor, LookupEnv: os.LookupEnv,
|
||||
})
|
||||
result.PromptID, result.PromptVersion, result.PromptHash = inspection.PromptID, inspection.PromptVersion, inspection.PromptHash
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
collection, err := collectWeather(ctx, req.Config, req.Collector)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
prepared, err := prepareReport(prepareReportRequest{Config: req.Config, Resolved: resolved, Collection: *collection, handler: inspection.handler})
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("prepare comparison report: %w", err)
|
||||
}
|
||||
|
||||
executed := executeComparisonProfiles(ctx, comparisonExecutionRequest{
|
||||
Prepared: prepared, Inspection: inspection, ComparisonID: comparisonID, DebugWriter: debugWriter, Executor: req.Executor,
|
||||
})
|
||||
finalizeComparisonResult(result, clock)
|
||||
copyComparisonOutcomes(result, executed.Outcomes, false)
|
||||
if executed.Canceled {
|
||||
return result, fmt.Errorf("comparison execution: %w", ctx.Err())
|
||||
}
|
||||
|
||||
bundle := comparisonBundle(result, prepared.dataPackageCopy(), executed.Outcomes)
|
||||
if err := bundle.Validate(); err != nil {
|
||||
return result, fmt.Errorf("build comparison bundle: %w", err)
|
||||
}
|
||||
publication, err := publish(ctx, publicationPlan, bundle)
|
||||
if publication.Committed {
|
||||
result.OutputDirectory = publicationPlan.Target
|
||||
result.ManifestPath = filepath.Join(publicationPlan.Target, comparison.ManifestFilename)
|
||||
result.DataPackagePath = filepath.Join(publicationPlan.Target, comparison.DataPackageFilename)
|
||||
copyComparisonOutcomes(result, executed.Outcomes, true)
|
||||
}
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("publish comparison bundle: %w", err)
|
||||
}
|
||||
|
||||
if result.Failed > 0 {
|
||||
return result, fmt.Errorf("comparison completed with %d failed profiles", result.Failed)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func finalizeComparisonResult(result *ComparisonResult, clock timeutil.Clock) {
|
||||
finishedAt := clock.Now().UTC()
|
||||
if finishedAt.IsZero() {
|
||||
finishedAt = time.Unix(0, 1).UTC()
|
||||
}
|
||||
if finishedAt.Before(result.StartedAt) {
|
||||
finishedAt = result.StartedAt
|
||||
}
|
||||
result.FinishedAt = finishedAt
|
||||
}
|
||||
|
||||
func initialComparisonResult(req ComparisonRequest, resolved report.Resolved, comparisonID string, startedAt time.Time) *ComparisonResult {
|
||||
metadata := resolved.Metadata()
|
||||
return &ComparisonResult{
|
||||
ComparisonID: comparisonID,
|
||||
ReportID: resolved.Definition.ID,
|
||||
ReportName: resolved.Definition.Name,
|
||||
StartedAt: startedAt,
|
||||
Timezone: req.Config.WeatherAPI.Timezone,
|
||||
ValidPeriod: metadata.ValidPeriod,
|
||||
}
|
||||
}
|
||||
|
||||
func copyComparisonOutcomes(result *ComparisonResult, outcomes []comparisonProfileOutcome, published bool) {
|
||||
result.Results = make([]ComparisonProfileResult, len(outcomes))
|
||||
result.Total, result.Succeeded, result.Failed = len(outcomes), 0, 0
|
||||
for index, outcome := range outcomes {
|
||||
profile := ComparisonProfileResult{
|
||||
Position: outcome.Position, ProfileID: outcome.ProfileID, BackendID: outcome.BackendID, ModelName: outcome.ModelName,
|
||||
Status: outcome.Status, ValidationStatus: outcome.ValidationStatus, LLMDebugPath: outcome.LLMDebugPath, Error: outcome.Error,
|
||||
}
|
||||
if published && outcome.Status == comparison.StatusSucceeded {
|
||||
profile.ReportPath = filepath.Join(result.OutputDirectory, outcome.ReportPath)
|
||||
}
|
||||
result.Results[index] = profile
|
||||
if outcome.Status == comparison.StatusSucceeded {
|
||||
result.Succeeded++
|
||||
} else {
|
||||
result.Failed++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func comparisonBundle(result *ComparisonResult, dataPackage []byte, outcomes []comparisonProfileOutcome) comparison.LogicalBundle {
|
||||
manifest := comparison.Manifest{
|
||||
SchemaVersion: comparison.SchemaVersion, ComparisonID: result.ComparisonID,
|
||||
StartedAt: result.StartedAt.UTC(), FinishedAt: result.FinishedAt.UTC(),
|
||||
ReportID: string(result.ReportID), Timezone: result.Timezone,
|
||||
ValidPeriod: comparison.ValidPeriod{Start: result.ValidPeriod.Start, End: result.ValidPeriod.End},
|
||||
PromptID: result.PromptID, PromptVersion: result.PromptVersion, PromptHash: result.PromptHash,
|
||||
DataPackage: comparison.DataPackageReference{Path: comparison.DataPackageFilename, SHA256: comparison.SHA256(dataPackage)},
|
||||
Total: result.Total, Succeeded: result.Succeeded, Failed: result.Failed,
|
||||
Results: make([]comparison.Result, len(outcomes)),
|
||||
}
|
||||
bundle := comparison.LogicalBundle{Manifest: manifest, DataPackage: dataPackage}
|
||||
for index, outcome := range outcomes {
|
||||
manifestResult := comparison.Result{
|
||||
Position: outcome.Position, ProfileID: outcome.ProfileID, BackendID: outcome.BackendID, ModelName: outcome.ModelName,
|
||||
Status: outcome.Status, ValidationStatus: string(outcome.ValidationStatus), Error: outcome.Error,
|
||||
}
|
||||
if outcome.Status == comparison.StatusSucceeded {
|
||||
manifestResult.ReportPath = outcome.ReportPath
|
||||
bundle.Reports = append(bundle.Reports, comparison.BundleReport{Position: outcome.Position, Path: outcome.ReportPath, Markdown: outcome.Markdown})
|
||||
}
|
||||
bundle.Manifest.Results[index] = manifestResult
|
||||
}
|
||||
return bundle
|
||||
}
|
||||
177
internal/app/comparison_execution.go
Normal file
177
internal/app/comparison_execution.go
Normal file
@@ -0,0 +1,177 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/comparison"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptdebug"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptexec"
|
||||
)
|
||||
|
||||
type comparisonExecutionRequest struct {
|
||||
Prepared preparedReport
|
||||
Inspection ComparisonInspectionResult
|
||||
ComparisonID string
|
||||
DebugWriter *promptdebug.PromptDebugWriter
|
||||
Executor promptexec.Executor
|
||||
}
|
||||
|
||||
type comparisonExecutionResult struct {
|
||||
Outcomes []comparisonProfileOutcome
|
||||
Canceled bool
|
||||
}
|
||||
|
||||
type comparisonProfileOutcome struct {
|
||||
Position int
|
||||
ProfileID string
|
||||
BackendID string
|
||||
ModelName string
|
||||
Status string
|
||||
ValidationStatus promptexec.ValidationStatus
|
||||
ReportPath string
|
||||
Markdown []byte
|
||||
LLMDebugPath string
|
||||
Error *comparison.SafeError
|
||||
canceled bool
|
||||
}
|
||||
|
||||
type comparisonProfileExecutionState uint8
|
||||
|
||||
const (
|
||||
comparisonProfilePending comparisonProfileExecutionState = iota
|
||||
comparisonProfileRunning
|
||||
comparisonProfileComplete
|
||||
)
|
||||
|
||||
func executeComparisonProfiles(ctx context.Context, req comparisonExecutionRequest) comparisonExecutionResult {
|
||||
profiles := req.Inspection.Profiles
|
||||
result := comparisonExecutionResult{Outcomes: make([]comparisonProfileOutcome, len(profiles))}
|
||||
states := make([]comparisonProfileExecutionState, len(profiles))
|
||||
for index, profile := range profiles {
|
||||
result.Outcomes[index] = comparisonProfileOutcome{
|
||||
Position: index + 1,
|
||||
ProfileID: profile.ProfileID,
|
||||
BackendID: profile.BackendID,
|
||||
ModelName: profile.ModelName,
|
||||
Status: comparison.StatusFailed,
|
||||
}
|
||||
}
|
||||
|
||||
var waitGroup sync.WaitGroup
|
||||
for index, profile := range profiles {
|
||||
if err := ctx.Err(); err != nil {
|
||||
result.Canceled = true
|
||||
break
|
||||
}
|
||||
index, profile := index, profile
|
||||
states[index] = comparisonProfileRunning
|
||||
waitGroup.Add(1)
|
||||
go func() {
|
||||
defer waitGroup.Done()
|
||||
result.Outcomes[index] = executeComparisonProfile(ctx, req, index, profile)
|
||||
states[index] = comparisonProfileComplete
|
||||
}()
|
||||
}
|
||||
waitGroup.Wait()
|
||||
if err := ctx.Err(); err != nil {
|
||||
result.Canceled = true
|
||||
for index := range result.Outcomes {
|
||||
if states[index] != comparisonProfileComplete || result.Outcomes[index].canceled {
|
||||
markCanceledComparisonOutcome(&result.Outcomes[index], err)
|
||||
}
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func executeComparisonProfile(ctx context.Context, req comparisonExecutionRequest, index int, profile ComparisonProfileInspection) comparisonProfileOutcome {
|
||||
position := index + 1
|
||||
outcome := comparisonProfileOutcome{
|
||||
Position: position, ProfileID: profile.ProfileID, BackendID: profile.BackendID, ModelName: profile.ModelName,
|
||||
Status: comparison.StatusFailed,
|
||||
}
|
||||
debugRef := promptdebug.PromptDebugRef{
|
||||
ReportID: req.Prepared.resolved.Definition.ID,
|
||||
ValidDate: req.Prepared.resolved.ValidPeriod.Start.Format("2006-01-02"),
|
||||
RunID: comparisonDebugRunID(req.ComparisonID, position, len(req.Inspection.Profiles), profile.ProfileID),
|
||||
}
|
||||
execution, markdown, err := executePreparedProfile(ctx, profileExecutionRequest{
|
||||
Prepared: req.Prepared,
|
||||
Prompt: PromptInspectionResult{
|
||||
PromptID: req.Inspection.PromptID, PromptVersion: req.Inspection.PromptVersion, PromptHash: req.Inspection.PromptHash,
|
||||
},
|
||||
Profile: promptexec.ProfileInspection{ProfileID: profile.ProfileID, BackendID: profile.BackendID, ModelName: profile.ModelName},
|
||||
Executor: req.Executor, DebugWriter: req.DebugWriter, DebugRef: &debugRef,
|
||||
})
|
||||
outcome.ProfileID, outcome.BackendID, outcome.ModelName = execution.ProfileID, execution.BackendID, execution.ModelName
|
||||
outcome.ValidationStatus = execution.ValidationStatus
|
||||
outcome.LLMDebugPath = execution.LLMDebugPath
|
||||
if err != nil {
|
||||
outcome.canceled = cancellationError(err)
|
||||
safe := comparisonSafeExecutionError(err)
|
||||
outcome.Error = &safe
|
||||
return outcome
|
||||
}
|
||||
reportPath, err := comparison.ReportFilename(position, len(req.Inspection.Profiles), profile.ProfileID)
|
||||
if err != nil {
|
||||
safe := comparison.NewSafeError("application", "derive comparison report filename failed")
|
||||
outcome.Error = &safe
|
||||
return outcome
|
||||
}
|
||||
outcome.Status = comparison.StatusSucceeded
|
||||
outcome.ReportPath = reportPath
|
||||
outcome.Markdown = append([]byte(nil), markdown...)
|
||||
return outcome
|
||||
}
|
||||
|
||||
func comparisonDebugRunID(comparisonID string, position, profileCount int, profileID string) string {
|
||||
return fmt.Sprintf("%s_%0*d-%s", comparisonID, comparison.OrdinalWidth(profileCount), position, comparison.ProfileSlug(profileID))
|
||||
}
|
||||
|
||||
func markCanceledComparisonOutcome(outcome *comparisonProfileOutcome, err error) {
|
||||
outcome.Status = comparison.StatusFailed
|
||||
outcome.ValidationStatus = promptexec.ValidationSkipped
|
||||
outcome.ReportPath = ""
|
||||
outcome.Markdown = nil
|
||||
safe := comparisonSafeExecutionError(err)
|
||||
outcome.Error = &safe
|
||||
}
|
||||
|
||||
func cancellationError(err error) bool {
|
||||
category := promptexec.CategoryOf(err)
|
||||
return errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) ||
|
||||
category == promptexec.Canceled || category == promptexec.DeadlineExceeded
|
||||
}
|
||||
|
||||
func comparisonSafeExecutionError(err error) comparison.SafeError {
|
||||
category := promptexec.CategoryOf(err)
|
||||
if category == "" {
|
||||
switch {
|
||||
case errors.Is(err, context.Canceled):
|
||||
category = promptexec.Canceled
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
category = promptexec.DeadlineExceeded
|
||||
}
|
||||
}
|
||||
if category == "" {
|
||||
return comparison.NewSafeError("application", comparisonExecutionMessage(err))
|
||||
}
|
||||
return comparison.NewSafeError(string(category), comparisonExecutionMessage(err))
|
||||
}
|
||||
|
||||
func comparisonExecutionMessage(err error) string {
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return "profile execution canceled"
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return "profile execution deadline exceeded"
|
||||
}
|
||||
var execution *profileExecutionError
|
||||
if errors.As(err, &execution) {
|
||||
return comparison.TruncateErrorMessage(execution.operation + " failed")
|
||||
}
|
||||
return "profile execution failed"
|
||||
}
|
||||
320
internal/app/comparison_execution_test.go
Normal file
320
internal/app/comparison_execution_test.go
Normal file
@@ -0,0 +1,320 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/comparison"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptdebug"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptexec"
|
||||
)
|
||||
|
||||
func TestExecuteComparisonProfilesRunsOrderedProfilesConcurrently(t *testing.T) {
|
||||
prepared, prompt := preparedDailyProfile(t)
|
||||
profiles := comparisonProfiles(10)
|
||||
executor := newBarrierExecutor(profiles)
|
||||
results := startComparisonExecution(t, context.Background(), comparisonExecutionRequest{
|
||||
Prepared: prepared, Inspection: comparisonInspection(prompt, profiles), ComparisonID: "comparison_daily", Executor: executor,
|
||||
}, executor)
|
||||
waitForProfileStarts(t, executor, profiles, results)
|
||||
if executor.maximumInFlight() < 2 {
|
||||
t.Fatalf("maximum in-flight executions = %d, want overlap", executor.maximumInFlight())
|
||||
}
|
||||
for index := len(profiles) - 1; index >= 0; index-- {
|
||||
executor.release(profiles[index].ProfileID)
|
||||
}
|
||||
result := <-results
|
||||
if result.Canceled || len(result.Outcomes) != len(profiles) {
|
||||
t.Fatalf("result = %#v", result)
|
||||
}
|
||||
for index, profile := range profiles {
|
||||
outcome := result.Outcomes[index]
|
||||
wantPath, err := comparison.ReportFilename(index+1, len(profiles), profile.ProfileID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if outcome.Position != index+1 || outcome.ProfileID != profile.ProfileID || outcome.Status != comparison.StatusSucceeded || outcome.ValidationStatus != promptexec.ValidationPassed || outcome.ReportPath != wantPath || len(outcome.Markdown) == 0 || outcome.Error != nil {
|
||||
t.Fatalf("outcome[%d] = %#v", index, outcome)
|
||||
}
|
||||
request, ok := executor.request(profile.ProfileID)
|
||||
if !ok || request.PromptVersion != prompt.PromptVersion || !bytesEqual(request.DataPackage, prepared.dataPackage) {
|
||||
t.Fatalf("request for %q = %#v, want prompt version %q and shared data package", profile.ProfileID, request, prompt.PromptVersion)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteComparisonProfilesContinuesAfterProfileFailure(t *testing.T) {
|
||||
prepared, prompt := preparedDailyProfile(t)
|
||||
profiles := comparisonProfiles(3)
|
||||
executor := newBarrierExecutor(profiles)
|
||||
executor.setError(profiles[1].ProfileID, errors.New("provider response body must not escape"))
|
||||
results := startComparisonExecution(t, context.Background(), comparisonExecutionRequest{
|
||||
Prepared: prepared, Inspection: comparisonInspection(prompt, profiles), ComparisonID: "comparison_daily", Executor: executor,
|
||||
}, executor)
|
||||
waitForProfileStarts(t, executor, profiles, results)
|
||||
for _, profile := range profiles {
|
||||
executor.release(profile.ProfileID)
|
||||
}
|
||||
result := <-results
|
||||
if result.Canceled || result.Outcomes[0].Status != comparison.StatusSucceeded || result.Outcomes[1].Status != comparison.StatusFailed || result.Outcomes[2].Status != comparison.StatusSucceeded {
|
||||
t.Fatalf("outcomes = %#v", result.Outcomes)
|
||||
}
|
||||
failure := result.Outcomes[1]
|
||||
if failure.Error == nil || failure.Error.Category != string(promptexec.Generation) || failure.Error.Message != "execute prompt failed" || failure.ReportPath != "" || len(failure.Markdown) != 0 {
|
||||
t.Fatalf("failure outcome = %#v", failure)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteComparisonProfilesPropagatesCancellationAndJoins(t *testing.T) {
|
||||
prepared, prompt := preparedDailyProfile(t)
|
||||
profiles := comparisonProfiles(4)
|
||||
executor := newBarrierExecutor(profiles)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
results := startComparisonExecution(t, ctx, comparisonExecutionRequest{
|
||||
Prepared: prepared, Inspection: comparisonInspection(prompt, profiles), ComparisonID: "comparison_daily", Executor: executor,
|
||||
}, executor)
|
||||
waitForProfileStarts(t, executor, profiles, results)
|
||||
cancel()
|
||||
result := <-results
|
||||
if !result.Canceled || executor.inFlightCount() != 0 {
|
||||
t.Fatalf("result/in-flight = %#v/%d", result, executor.inFlightCount())
|
||||
}
|
||||
for _, outcome := range result.Outcomes {
|
||||
if outcome.Status != comparison.StatusFailed || outcome.Error == nil || outcome.Error.Category != string(promptexec.Canceled) || outcome.ValidationStatus != promptexec.ValidationSkipped || outcome.ReportPath != "" || len(outcome.Markdown) != 0 {
|
||||
t.Fatalf("canceled outcome = %#v", outcome)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecuteComparisonProfilesUsesDistinctDeterministicDebugReferences(t *testing.T) {
|
||||
prepared, prompt := preparedDailyProfile(t)
|
||||
profiles := []ComparisonProfileInspection{
|
||||
{ProfileID: "light.one", BackendID: "local", ModelName: "light"},
|
||||
{ProfileID: "deep/two", BackendID: "cloud", ModelName: "deep"},
|
||||
}
|
||||
debugWriter, err := promptdebug.NewPromptDebugWriter(t.TempDir())
|
||||
if errors.Is(err, promptdebug.ErrSecureCaptureUnsupported) {
|
||||
t.Skipf("secure prompt debug capture is unavailable: %v", err)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("NewPromptDebugWriter() error = %v", err)
|
||||
}
|
||||
executor := newBarrierExecutor(profiles)
|
||||
results := startComparisonExecution(t, context.Background(), comparisonExecutionRequest{
|
||||
Prepared: prepared, Inspection: comparisonInspection(prompt, profiles), ComparisonID: "comparison_daily", DebugWriter: debugWriter, Executor: executor,
|
||||
}, executor)
|
||||
waitForProfileStarts(t, executor, profiles, results)
|
||||
for _, profile := range profiles {
|
||||
executor.release(profile.ProfileID)
|
||||
}
|
||||
result := <-results
|
||||
paths := map[string]struct{}{}
|
||||
for index, outcome := range result.Outcomes {
|
||||
wantName := fmt.Sprintf("comparison_daily_%0*d-%s", comparison.OrdinalWidth(len(profiles)), index+1, comparison.ProfileSlug(outcome.ProfileID))
|
||||
if filepath.Base(outcome.LLMDebugPath) != wantName {
|
||||
t.Fatalf("debug path = %q, want base %q", outcome.LLMDebugPath, wantName)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(outcome.LLMDebugPath, "preparation.json")); err != nil {
|
||||
t.Fatalf("preparation artifact %q: %v", outcome.LLMDebugPath, err)
|
||||
}
|
||||
paths[outcome.LLMDebugPath] = struct{}{}
|
||||
}
|
||||
if len(paths) != len(profiles) {
|
||||
t.Fatalf("debug paths = %#v", paths)
|
||||
}
|
||||
}
|
||||
|
||||
type barrierExecutor struct {
|
||||
mu sync.Mutex
|
||||
started chan string
|
||||
callbackFailures chan error
|
||||
releases map[string]chan struct{}
|
||||
requests map[string]promptexec.ExecuteRequest
|
||||
errors map[string]error
|
||||
profiles map[string]ComparisonProfileInspection
|
||||
inFlight int
|
||||
maximum int
|
||||
}
|
||||
|
||||
func newBarrierExecutor(profiles []ComparisonProfileInspection) *barrierExecutor {
|
||||
releases := make(map[string]chan struct{}, len(profiles))
|
||||
identities := make(map[string]ComparisonProfileInspection, len(profiles))
|
||||
for _, profile := range profiles {
|
||||
releases[profile.ProfileID] = make(chan struct{})
|
||||
identities[profile.ProfileID] = profile
|
||||
}
|
||||
return &barrierExecutor{
|
||||
started: make(chan string, len(profiles)), callbackFailures: make(chan error, len(profiles)), releases: releases,
|
||||
requests: make(map[string]promptexec.ExecuteRequest, len(profiles)), errors: map[string]error{}, profiles: identities,
|
||||
}
|
||||
}
|
||||
|
||||
func (e *barrierExecutor) InspectPrompt(context.Context, string, string) (promptexec.PromptInspection, error) {
|
||||
return promptexec.PromptInspection{}, errors.New("unexpected prompt inspection")
|
||||
}
|
||||
|
||||
func (e *barrierExecutor) InspectProfile(context.Context, string) (promptexec.ProfileInspection, error) {
|
||||
return promptexec.ProfileInspection{}, errors.New("unexpected profile inspection")
|
||||
}
|
||||
|
||||
func (e *barrierExecutor) Execute(ctx context.Context, req promptexec.ExecuteRequest, callback promptexec.PreparationCallback) (*promptexec.Execution, error) {
|
||||
stamp := time.Date(2026, 5, 29, 15, 0, 0, 0, time.UTC)
|
||||
e.mu.Lock()
|
||||
profile := e.profiles[req.ProfileID]
|
||||
e.mu.Unlock()
|
||||
if err := callback(promptexec.Preparation{PromptID: req.PromptID, PromptVersion: req.PromptVersion, PromptHash: generationPromptHash, ProfileID: req.ProfileID, BackendID: profile.BackendID, ModelName: profile.ModelName, Output: promptexec.OutputContract{Format: "json", ValidationMode: "json_schema", SchemaPath: generationDefinitionForPrompt(req.PromptID).GeneratedTextSchemaID + ".generated_text.schema.json"}, StartedAt: stamp, EndedAt: stamp}, nil); err != nil {
|
||||
e.callbackFailures <- err
|
||||
return nil, err
|
||||
}
|
||||
e.mu.Lock()
|
||||
e.requests[req.ProfileID] = promptexec.ExecuteRequest{PromptID: req.PromptID, PromptVersion: req.PromptVersion, ProfileID: req.ProfileID, DataPackage: append([]byte(nil), req.DataPackage...), CaptureDebug: req.CaptureDebug}
|
||||
e.inFlight++
|
||||
if e.inFlight > e.maximum {
|
||||
e.maximum = e.inFlight
|
||||
}
|
||||
release := e.releases[req.ProfileID]
|
||||
e.mu.Unlock()
|
||||
e.started <- req.ProfileID
|
||||
select {
|
||||
case <-release:
|
||||
case <-ctx.Done():
|
||||
e.mu.Lock()
|
||||
e.inFlight--
|
||||
e.mu.Unlock()
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
e.mu.Lock()
|
||||
e.inFlight--
|
||||
err := e.errors[req.ProfileID]
|
||||
e.mu.Unlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &promptexec.Execution{
|
||||
PromptID: req.PromptID, PromptVersion: req.PromptVersion, PromptHash: generationPromptHash,
|
||||
ProfileID: req.ProfileID, BackendID: profile.BackendID, ModelName: profile.ModelName,
|
||||
StartedAt: stamp, EndedAt: stamp, RawOutput: comparisonRawOutput(),
|
||||
Validation: promptexec.NewValidation(promptexec.ValidationPassed, "json_schema", generationDefinitionForPrompt(req.PromptID).GeneratedTextSchemaID+".generated_text.schema.json", nil),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (e *barrierExecutor) request(profileID string) (promptexec.ExecuteRequest, bool) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
request, ok := e.requests[profileID]
|
||||
return request, ok
|
||||
}
|
||||
|
||||
func (e *barrierExecutor) setError(profileID string, err error) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.errors[profileID] = err
|
||||
}
|
||||
|
||||
func (e *barrierExecutor) release(profileID string) {
|
||||
close(e.releases[profileID])
|
||||
}
|
||||
|
||||
func (e *barrierExecutor) releaseAll() {
|
||||
for _, release := range e.releases {
|
||||
select {
|
||||
case <-release:
|
||||
default:
|
||||
close(release)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (e *barrierExecutor) maximumInFlight() int {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
return e.maximum
|
||||
}
|
||||
|
||||
func (e *barrierExecutor) inFlightCount() int {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
return e.inFlight
|
||||
}
|
||||
|
||||
const comparisonExecutionTestTimeout = 5 * time.Second
|
||||
|
||||
func startComparisonExecution(t *testing.T, ctx context.Context, request comparisonExecutionRequest, executor *barrierExecutor) <-chan comparisonExecutionResult {
|
||||
t.Helper()
|
||||
results := make(chan comparisonExecutionResult, 1)
|
||||
finished := make(chan struct{})
|
||||
t.Cleanup(func() {
|
||||
executor.releaseAll()
|
||||
timeout := time.NewTimer(comparisonExecutionTestTimeout)
|
||||
defer timeout.Stop()
|
||||
select {
|
||||
case <-finished:
|
||||
case <-timeout.C:
|
||||
t.Error("comparison execution workers did not finish after release")
|
||||
}
|
||||
})
|
||||
go func() {
|
||||
defer close(finished)
|
||||
results <- executeComparisonProfiles(ctx, request)
|
||||
}()
|
||||
return results
|
||||
}
|
||||
|
||||
func waitForProfileStarts(t *testing.T, executor *barrierExecutor, profiles []ComparisonProfileInspection, results <-chan comparisonExecutionResult) {
|
||||
t.Helper()
|
||||
timeout := time.NewTimer(comparisonExecutionTestTimeout)
|
||||
defer timeout.Stop()
|
||||
seen := map[string]struct{}{}
|
||||
for range profiles {
|
||||
var profileID string
|
||||
select {
|
||||
case profileID = <-executor.started:
|
||||
case err := <-executor.callbackFailures:
|
||||
executor.releaseAll()
|
||||
select {
|
||||
case result := <-results:
|
||||
t.Fatalf("comparison profile preparation failed before executor entry: %v; result: %#v", err, result)
|
||||
case <-timeout.C:
|
||||
t.Fatalf("comparison profile preparation failed before executor entry: %v; comparison did not finish", err)
|
||||
}
|
||||
case result := <-results:
|
||||
t.Fatalf("comparison completed before all profiles started: %#v", result)
|
||||
case <-timeout.C:
|
||||
t.Fatal("timed out waiting for comparison profile starts")
|
||||
}
|
||||
if _, duplicate := seen[profileID]; duplicate {
|
||||
t.Fatalf("duplicate execution start for %q", profileID)
|
||||
}
|
||||
seen[profileID] = struct{}{}
|
||||
}
|
||||
}
|
||||
|
||||
func comparisonProfiles(count int) []ComparisonProfileInspection {
|
||||
profiles := make([]ComparisonProfileInspection, 0, count)
|
||||
for index := 1; index <= count; index++ {
|
||||
profiles = append(profiles, ComparisonProfileInspection{ProfileID: fmt.Sprintf("profile.%02d", index), BackendID: "backend", ModelName: "model"})
|
||||
}
|
||||
return profiles
|
||||
}
|
||||
|
||||
func comparisonInspection(prompt PromptInspectionResult, profiles []ComparisonProfileInspection) ComparisonInspectionResult {
|
||||
return ComparisonInspectionResult{PromptID: prompt.PromptID, PromptVersion: prompt.PromptVersion, PromptHash: prompt.PromptHash, Profiles: profiles}
|
||||
}
|
||||
|
||||
func comparisonRawOutput() []byte {
|
||||
return []byte(`{"summary":"Showers are possible during the selected day.","forecast_discussion":["A front will keep rain chances in the forecast."],"precipitation_timing":"Rain is most likely during the afternoon."}`)
|
||||
}
|
||||
|
||||
func bytesEqual(left, right []byte) bool {
|
||||
return reflect.DeepEqual(left, right)
|
||||
}
|
||||
|
||||
var _ promptexec.Executor = (*barrierExecutor)(nil)
|
||||
399
internal/app/comparison_test.go
Normal file
399
internal/app/comparison_test.go
Normal file
@@ -0,0 +1,399 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/comparison"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/config"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptexec"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/timeutil"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/weatherdata"
|
||||
)
|
||||
|
||||
func TestCompareDetailedPublishesOneCoherentBundle(t *testing.T) {
|
||||
cfg := comparisonConfig()
|
||||
bundle := generationBundle(t)
|
||||
workingDir := t.TempDir()
|
||||
executor := &generationExecutor{}
|
||||
inspectedBeforeCollection := false
|
||||
result, err := CompareDetailed(context.Background(), ComparisonRequest{
|
||||
Config: cfg, Report: ReportDaily, ProfileIDs: []string{"weather-light", "weather-deep"},
|
||||
WorkingDir: workingDir, Date: generationTime("2026-05-29T12:00:00-05:00"),
|
||||
Clock: timeutil.FixedClock{Time: generationTime("2026-05-29T08:30:00-05:00")},
|
||||
Collector: &generationCollector{bundle: &bundle, beforeRun: func() {
|
||||
inspectedBeforeCollection = executor.promptInspections == 1 && executor.profileInspections == 2
|
||||
}}, Executor: executor,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("CompareDetailed() error = %v", err)
|
||||
}
|
||||
if result == nil || result.Total != 2 || result.Succeeded != 2 || result.Failed != 0 || executor.promptInspections != 1 || executor.profileInspections != 2 || executor.executeCalls != 2 || !inspectedBeforeCollection || result.ManifestPath == "" || result.DataPackagePath == "" {
|
||||
t.Fatalf("result/executor = %#v/%#v", result, executor)
|
||||
}
|
||||
if result.OutputDirectory != filepath.Dir(result.ManifestPath) || !filepath.IsAbs(result.ManifestPath) || !filepath.IsAbs(result.DataPackagePath) {
|
||||
t.Fatalf("published paths = %#v", result)
|
||||
}
|
||||
for index, profile := range result.Results {
|
||||
if profile.Position != index+1 || profile.Status != comparison.StatusSucceeded || !filepath.IsAbs(profile.ReportPath) || profile.Error != nil {
|
||||
t.Fatalf("profile result = %#v", profile)
|
||||
}
|
||||
}
|
||||
data, readErr := os.ReadFile(result.ManifestPath)
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
var manifest comparison.Manifest
|
||||
if err := json.Unmarshal(data, &manifest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if manifest.ComparisonID != result.ComparisonID || manifest.Total != result.Total || manifest.Succeeded != result.Succeeded || manifest.DataPackage.SHA256 == "" || len(manifest.Results) != 2 {
|
||||
t.Fatalf("manifest = %#v", manifest)
|
||||
}
|
||||
if manifest.Results[0].ReportPath != filepath.Base(result.Results[0].ReportPath) || manifest.Results[1].ReportPath != filepath.Base(result.Results[1].ReportPath) {
|
||||
t.Fatalf("manifest report paths = %#v", manifest.Results)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompareDetailedPublishesPartialBundleAndReturnsAggregateError(t *testing.T) {
|
||||
cfg := comparisonConfig()
|
||||
bundle := generationBundle(t)
|
||||
executor := &generationExecutor{executeErrors: map[string]error{"weather-deep": errors.New("provider detail must not escape")}}
|
||||
result, err := CompareDetailed(context.Background(), ComparisonRequest{
|
||||
Config: cfg, Report: ReportDaily, ProfileIDs: []string{"weather-light", "weather-deep", "weather-fallback"},
|
||||
WorkingDir: t.TempDir(), Date: generationTime("2026-05-29T12:00:00-05:00"),
|
||||
Clock: timeutil.FixedClock{Time: generationTime("2026-05-29T08:30:00-05:00")},
|
||||
Collector: &generationCollector{bundle: &bundle}, Executor: executor,
|
||||
})
|
||||
if err == nil || err.Error() != "comparison completed with 1 failed profiles" || result == nil || result.Total != 3 || result.Succeeded != 2 || result.Failed != 1 {
|
||||
t.Fatalf("CompareDetailed() result/error = %#v/%v", result, err)
|
||||
}
|
||||
failure := result.Results[1]
|
||||
if failure.Status != comparison.StatusFailed || failure.ReportPath != "" || failure.Error == nil || strings.Contains(failure.Error.Message, "provider detail") {
|
||||
t.Fatalf("failure = %#v", failure)
|
||||
}
|
||||
if _, statErr := os.Stat(result.ManifestPath); statErr != nil {
|
||||
t.Fatalf("partial manifest: %v", statErr)
|
||||
}
|
||||
if _, statErr := os.Stat(filepath.Join(result.OutputDirectory, filepath.Base(result.Results[0].ReportPath))); statErr != nil {
|
||||
t.Fatalf("successful partial report: %v", statErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompareDetailedRetainsCommittedPathsWhenBackupCleanupFails(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
state comparison.BackupRecoveryState
|
||||
path bool
|
||||
}{
|
||||
{name: "complete recovery bundle", state: comparison.BackupRecoveryComplete, path: true},
|
||||
{name: "partial remnants", state: comparison.BackupRecoveryPartial, path: true},
|
||||
{name: "absent backup", state: comparison.BackupRecoveryAbsent},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
bundle := generationBundle(t)
|
||||
recoveryPath := ""
|
||||
if test.path {
|
||||
recoveryPath = filepath.Join(t.TempDir(), ".comparison-daily.backup-recovery")
|
||||
}
|
||||
cleanupCause := errors.New("backup cleanup failed")
|
||||
publish := func(context.Context, comparison.DestinationPlan, comparison.LogicalBundle) (comparison.PublicationResult, error) {
|
||||
return comparison.PublicationResult{Committed: true, RecoveryState: test.state, RecoveryPath: recoveryPath}, &comparison.PublicationCleanupError{RecoveryState: test.state, RecoveryPath: recoveryPath, Err: cleanupCause}
|
||||
}
|
||||
|
||||
result, err := compareDetailed(context.Background(), ComparisonRequest{
|
||||
Config: comparisonConfig(), Report: ReportDaily, ProfileIDs: []string{"weather-light", "weather-deep"},
|
||||
WorkingDir: t.TempDir(), Date: generationTime("2026-05-29T12:00:00-05:00"),
|
||||
Clock: timeutil.FixedClock{Time: generationTime("2026-05-29T08:30:00-05:00")},
|
||||
Collector: &generationCollector{bundle: &bundle}, Executor: &generationExecutor{},
|
||||
}, publish)
|
||||
var cleanupErr *comparison.PublicationCleanupError
|
||||
if result == nil || !errors.As(err, &cleanupErr) || !errors.Is(err, cleanupCause) || cleanupErr.RecoveryState != test.state || cleanupErr.RecoveryPath != recoveryPath || !filepath.IsAbs(result.ManifestPath) || !filepath.IsAbs(result.DataPackagePath) {
|
||||
t.Fatalf("CompareDetailed() result/error = %#v/%v", result, err)
|
||||
}
|
||||
for _, profile := range result.Results {
|
||||
if profile.Status == comparison.StatusSucceeded && !filepath.IsAbs(profile.ReportPath) {
|
||||
t.Fatalf("published profile result = %#v", profile)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompareDetailedPreflightsBeforePromptOrCollection(t *testing.T) {
|
||||
invalidDestination := filepath.Join(t.TempDir(), "not-a-directory")
|
||||
if err := os.WriteFile(invalidDestination, []byte("x"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bundle := generationBundle(t)
|
||||
collector := &generationCollector{bundle: &bundle}
|
||||
executor := &generationExecutor{}
|
||||
result, err := CompareDetailed(context.Background(), ComparisonRequest{
|
||||
Config: comparisonConfig(), Report: ReportDaily, ProfileIDs: []string{"weather-light", "weather-deep"},
|
||||
WorkingDir: t.TempDir(), OutputDir: invalidDestination, Date: generationTime("2026-05-29T12:00:00-05:00"),
|
||||
Clock: timeutil.FixedClock{Time: generationTime("2026-05-29T08:30:00-05:00")}, Collector: collector, Executor: executor,
|
||||
})
|
||||
if err == nil || result == nil || collector.called || executor.promptInspections != 0 || executor.executeCalls != 0 || result.ManifestPath != "" {
|
||||
t.Fatalf("result/error/collector/executor = %#v/%v/%#v/%#v", result, err, collector, executor)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompareDetailedFinalizesUnpublishedFailures(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
prepare func(t *testing.T, outputDirectory string)
|
||||
debugDir string
|
||||
executor *generationExecutor
|
||||
collector *generationCollector
|
||||
wantPrompt bool
|
||||
wantCollection bool
|
||||
}{
|
||||
{
|
||||
name: "destination preflight",
|
||||
prepare: func(t *testing.T, outputDirectory string) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(outputDirectory, []byte("not a directory"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
},
|
||||
executor: &generationExecutor{},
|
||||
},
|
||||
{
|
||||
name: "debug initialization",
|
||||
debugDir: "relative-debug-directory",
|
||||
executor: &generationExecutor{},
|
||||
collector: &generationCollector{},
|
||||
},
|
||||
{
|
||||
name: "prompt preflight",
|
||||
executor: &generationExecutor{inspectErr: promptexec.NewError(promptexec.PromptLoad, "unsafe prompt detail", errors.New("unsafe cause"))},
|
||||
collector: &generationCollector{},
|
||||
wantPrompt: false,
|
||||
},
|
||||
{
|
||||
name: "profile preflight",
|
||||
executor: &generationExecutor{profileInspectErrors: map[string]error{
|
||||
"weather-deep": promptexec.NewError(promptexec.MissingCredential, "profile credential is unavailable", errors.New("unsafe cause")),
|
||||
}},
|
||||
collector: &generationCollector{},
|
||||
wantPrompt: true,
|
||||
},
|
||||
{
|
||||
name: "collection",
|
||||
executor: &generationExecutor{},
|
||||
collector: &generationCollector{err: errors.New("collection failed")},
|
||||
wantPrompt: true,
|
||||
wantCollection: true,
|
||||
},
|
||||
{
|
||||
name: "preparation",
|
||||
executor: &generationExecutor{},
|
||||
collector: &generationCollector{bundle: &weatherdata.Bundle{}},
|
||||
wantPrompt: true,
|
||||
wantCollection: true,
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
workingDirectory := t.TempDir()
|
||||
outputDirectory := filepath.Join(workingDirectory, "comparison-output")
|
||||
if test.prepare != nil {
|
||||
test.prepare(t, outputDirectory)
|
||||
}
|
||||
collector := test.collector
|
||||
if collector == nil {
|
||||
bundle := generationBundle(t)
|
||||
collector = &generationCollector{bundle: &bundle}
|
||||
}
|
||||
result, err := CompareDetailed(context.Background(), ComparisonRequest{
|
||||
Config: comparisonConfig(), Report: ReportDaily, ProfileIDs: []string{"weather-light", "weather-deep"},
|
||||
WorkingDir: workingDirectory, OutputDir: outputDirectory, LLMDebugDir: test.debugDir,
|
||||
Date: generationTime("2026-05-29T12:00:00-05:00"), Clock: timeutil.FixedClock{Time: generationTime("2026-05-29T08:30:00-05:00")},
|
||||
Collector: collector, Executor: test.executor,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("CompareDetailed() error = nil")
|
||||
}
|
||||
assertUnpublishedComparisonResult(t, result, outputDirectory)
|
||||
if (result.PromptID != "") != test.wantPrompt || (result.PromptHash != "") != test.wantPrompt {
|
||||
t.Fatalf("prompt identity = %q/%q, want resolved=%t", result.PromptID, result.PromptHash, test.wantPrompt)
|
||||
}
|
||||
if collector.called != test.wantCollection || test.executor.executeCalls != 0 {
|
||||
t.Fatalf("collection/execution = %t/%d, want collection=%t and no execution", collector.called, test.executor.executeCalls, test.wantCollection)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompareDetailedLeavesDestinationWhenCollectionOrPreparationFails(t *testing.T) {
|
||||
collectionErr := errors.New("weather collection failed")
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
collector *generationCollector
|
||||
}{
|
||||
{name: "collection", collector: &generationCollector{err: collectionErr}},
|
||||
{name: "preparation", collector: &generationCollector{bundle: &weatherdata.Bundle{}}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
workingDir := t.TempDir()
|
||||
executor := &generationExecutor{}
|
||||
result, err := CompareDetailed(context.Background(), ComparisonRequest{
|
||||
Config: comparisonConfig(), Report: ReportDaily, ProfileIDs: []string{"weather-light", "weather-deep"},
|
||||
WorkingDir: workingDir, Date: generationTime("2026-05-29T12:00:00-05:00"),
|
||||
Clock: timeutil.FixedClock{Time: generationTime("2026-05-29T08:30:00-05:00")}, Collector: test.collector, Executor: executor,
|
||||
})
|
||||
if err == nil || result == nil || executor.executeCalls != 0 || result.ManifestPath != "" || result.DataPackagePath != "" {
|
||||
t.Fatalf("CompareDetailed() result/error/executor = %#v/%v/%#v", result, err, executor)
|
||||
}
|
||||
if _, statErr := os.Stat(filepath.Join(workingDir, "comparison-daily-2026-05-29")); !os.IsNotExist(statErr) {
|
||||
t.Fatalf("comparison destination stat error = %v", statErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompareDetailedPublishesManifestWhenEveryProfileFails(t *testing.T) {
|
||||
bundle := generationBundle(t)
|
||||
executor := &generationExecutor{executeErrors: map[string]error{
|
||||
"weather-light": errors.New("first provider failure"), "weather-deep": errors.New("second provider failure"),
|
||||
}}
|
||||
result, err := CompareDetailed(context.Background(), ComparisonRequest{
|
||||
Config: comparisonConfig(), Report: ReportDaily, ProfileIDs: []string{"weather-light", "weather-deep"},
|
||||
WorkingDir: t.TempDir(), Date: generationTime("2026-05-29T12:00:00-05:00"),
|
||||
Clock: timeutil.FixedClock{Time: generationTime("2026-05-29T08:30:00-05:00")},
|
||||
Collector: &generationCollector{bundle: &bundle}, Executor: executor,
|
||||
})
|
||||
if err == nil || err.Error() != "comparison completed with 2 failed profiles" || result == nil || result.Succeeded != 0 || result.Failed != 2 || result.ManifestPath == "" {
|
||||
t.Fatalf("CompareDetailed() result/error = %#v/%v", result, err)
|
||||
}
|
||||
for _, profile := range result.Results {
|
||||
if profile.ReportPath != "" || profile.Error == nil {
|
||||
t.Fatalf("failed profile = %#v", profile)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompareDetailedCancellationPreservesPublishedBundle(t *testing.T) {
|
||||
workingDir := t.TempDir()
|
||||
bundle := generationBundle(t)
|
||||
request := ComparisonRequest{
|
||||
Config: comparisonConfig(), Report: ReportDaily, ProfileIDs: []string{"weather-light", "weather-deep"},
|
||||
WorkingDir: workingDir, Date: generationTime("2026-05-29T12:00:00-05:00"),
|
||||
Clock: timeutil.FixedClock{Time: generationTime("2026-05-29T08:30:00-05:00")}, Collector: &generationCollector{bundle: &bundle}, Executor: &generationExecutor{},
|
||||
}
|
||||
previous, err := CompareDetailed(context.Background(), request)
|
||||
if err != nil {
|
||||
t.Fatalf("initial CompareDetailed() error = %v", err)
|
||||
}
|
||||
before, err := os.ReadFile(previous.ManifestPath)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
request.Replace = true
|
||||
request.Executor = &generationExecutor{cancelBeforeReturn: cancel}
|
||||
result, err := CompareDetailed(ctx, request)
|
||||
if !errors.Is(err, context.Canceled) || result == nil || result.ManifestPath != "" || result.DataPackagePath != "" {
|
||||
t.Fatalf("canceled CompareDetailed() result/error = %#v/%v", result, err)
|
||||
}
|
||||
after, readErr := os.ReadFile(previous.ManifestPath)
|
||||
if readErr != nil || string(after) != string(before) {
|
||||
t.Fatalf("published manifest changed = %q, error = %v", after, readErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompareDetailedPreservesCompletedProfileFailureWhenCanceled(t *testing.T) {
|
||||
bundle := generationBundle(t)
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
failureStarted := make(chan struct{})
|
||||
var signalFailure sync.Once
|
||||
executor := &generationExecutor{
|
||||
validations: map[string]promptexec.ValidationStatus{"weather-light": promptexec.ValidationFailed},
|
||||
waitForCancellation: map[string]bool{"weather-deep": true},
|
||||
beforeExecute: func(request promptexec.ExecuteRequest) {
|
||||
if request.ProfileID == "weather-light" {
|
||||
signalFailure.Do(func() { close(failureStarted) })
|
||||
}
|
||||
},
|
||||
}
|
||||
results := make(chan struct {
|
||||
result *ComparisonResult
|
||||
err error
|
||||
}, 1)
|
||||
go func() {
|
||||
result, err := CompareDetailed(ctx, ComparisonRequest{
|
||||
Config: comparisonConfig(), Report: ReportDaily, ProfileIDs: []string{"weather-light", "weather-deep"},
|
||||
WorkingDir: t.TempDir(), Date: generationTime("2026-05-29T12:00:00-05:00"),
|
||||
Clock: timeutil.FixedClock{Time: generationTime("2026-05-29T08:30:00-05:00")},
|
||||
Collector: &generationCollector{bundle: &bundle}, Executor: executor,
|
||||
})
|
||||
results <- struct {
|
||||
result *ComparisonResult
|
||||
err error
|
||||
}{result: result, err: err}
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-failureStarted:
|
||||
cancel()
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("timed out waiting for the completed profile failure")
|
||||
}
|
||||
completed := <-results
|
||||
if !errors.Is(completed.err, context.Canceled) || completed.result == nil || completed.result.ManifestPath != "" || completed.result.DataPackagePath != "" || completed.result.Succeeded != 0 || completed.result.Failed != 2 {
|
||||
t.Fatalf("CompareDetailed() result/error = %#v/%v", completed.result, completed.err)
|
||||
}
|
||||
failed, canceled := completed.result.Results[0], completed.result.Results[1]
|
||||
if failed.Error == nil || failed.Error.Category != string(promptexec.ValidationRejected) || failed.ValidationStatus != promptexec.ValidationFailed || failed.ReportPath != "" {
|
||||
t.Fatalf("completed failure = %#v", failed)
|
||||
}
|
||||
if canceled.Error == nil || canceled.Error.Category != string(promptexec.Canceled) || canceled.ValidationStatus != promptexec.ValidationSkipped || canceled.ReportPath != "" {
|
||||
t.Fatalf("canceled profile = %#v", canceled)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCompareDetailedLeavesExistingBundleWhenPublicationPreflightChanges(t *testing.T) {
|
||||
workingDir := t.TempDir()
|
||||
target := filepath.Join(workingDir, "comparison-output")
|
||||
bundle := generationBundle(t)
|
||||
executor := &generationExecutor{beforeExecute: func(promptexec.ExecuteRequest) {
|
||||
_ = os.WriteFile(target, []byte("changed"), 0o600)
|
||||
}}
|
||||
result, err := CompareDetailed(context.Background(), ComparisonRequest{
|
||||
Config: comparisonConfig(), Report: ReportDaily, ProfileIDs: []string{"weather-light", "weather-deep"},
|
||||
WorkingDir: workingDir, OutputDir: target, Date: generationTime("2026-05-29T12:00:00-05:00"),
|
||||
Clock: timeutil.FixedClock{Time: generationTime("2026-05-29T08:30:00-05:00")}, Collector: &generationCollector{bundle: &bundle}, Executor: executor,
|
||||
})
|
||||
if err == nil || result == nil || result.ManifestPath != "" || result.DataPackagePath != "" || result.Results[0].ReportPath != "" {
|
||||
t.Fatalf("CompareDetailed() result/error = %#v/%v", result, err)
|
||||
}
|
||||
data, readErr := os.ReadFile(target)
|
||||
if readErr != nil || string(data) != "changed" {
|
||||
t.Fatalf("destination = %q, error = %v", data, readErr)
|
||||
}
|
||||
}
|
||||
|
||||
func comparisonConfig() config.Config {
|
||||
cfg := config.Defaults()
|
||||
cfg.WeatherAPI.Timezone, cfg.Location.ID = "America/Chicago", "home"
|
||||
return cfg
|
||||
}
|
||||
|
||||
func assertUnpublishedComparisonResult(t *testing.T, result *ComparisonResult, outputDirectory string) {
|
||||
t.Helper()
|
||||
if result == nil || result.OutputDirectory != outputDirectory || !filepath.IsAbs(result.OutputDirectory) || result.FinishedAt.IsZero() || result.FinishedAt.Location() != time.UTC || result.FinishedAt.Before(result.StartedAt) || result.ManifestPath != "" || result.DataPackagePath != "" {
|
||||
t.Fatalf("unpublished comparison result = %#v", result)
|
||||
}
|
||||
for _, profile := range result.Results {
|
||||
if profile.ReportPath != "" {
|
||||
t.Fatalf("unpublished profile result = %#v", profile)
|
||||
}
|
||||
}
|
||||
}
|
||||
45
internal/app/distributor_notification_test.go
Normal file
45
internal/app/distributor_notification_test.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
distributoradapter "gitea.maximumdirect.net/eric/weatherreporter/internal/adapters/distributor"
|
||||
)
|
||||
|
||||
func TestNotificationResultFromUploadExcludesRemoteResponseDetails(t *testing.T) {
|
||||
const remote = "REMOTE-DIAGNOSTIC"
|
||||
notification := notificationResultFromUpload("weather", "bundle", "key", distributoradapter.UploadResult{
|
||||
RunID: "run-123", Status: "failed", UploadStatus: "accepted", StatusError: remote,
|
||||
RunStatus: &distributoradapter.RunStatus{PipelineID: "weather", Status: "failed", Report: []byte(`{"detail":"REMOTE-DIAGNOSTIC"}`), Error: remote},
|
||||
})
|
||||
if notification == nil || notification.StatusError != "distributor status could not be confirmed" || notification.Error != "distributor reported a failed run" || len(notification.Report) != 0 {
|
||||
t.Fatalf("notification = %#v", notification)
|
||||
}
|
||||
if strings.Contains(notification.StatusError, remote) || strings.Contains(notification.Error, remote) {
|
||||
t.Fatalf("notification includes remote detail: %#v", notification)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchNotificationResultExcludesRemoteResponseDetails(t *testing.T) {
|
||||
const remote = "REMOTE-DIAGNOSTIC"
|
||||
notification := batchNotificationResult(batchNotificationRequest{PipelineID: "weather", BundleID: "bundle", IdempotencyKey: "key"}, &NotificationResult{Status: "failed", Error: remote})
|
||||
if notification == nil || notification.Error != "distributor reported a failed run" {
|
||||
t.Fatalf("notification = %#v", notification)
|
||||
}
|
||||
if strings.Contains(notification.Error, remote) {
|
||||
t.Fatalf("notification includes remote detail: %#v", notification)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedBatchNotificationResultExcludesRemoteResponseDetails(t *testing.T) {
|
||||
const remote = "REMOTE-DIAGNOSTIC"
|
||||
notification := failedBatchNotificationResult(batchNotificationRequest{PipelineID: "weather", BundleID: "bundle", IdempotencyKey: "key"}, errors.New(remote))
|
||||
if notification == nil || notification.Error != "distributor notification failed" {
|
||||
t.Fatalf("notification = %#v", notification)
|
||||
}
|
||||
if strings.Contains(notification.Error, remote) {
|
||||
t.Fatalf("notification includes remote detail: %#v", notification)
|
||||
}
|
||||
}
|
||||
609
internal/app/generation_test.go
Normal file
609
internal/app/generation_test.go
Normal file
@@ -0,0 +1,609 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/collect"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/config"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptdebug"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptexec"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/report"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/testutil"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/weatherdata"
|
||||
)
|
||||
|
||||
type generationCollector struct {
|
||||
bundle *weatherdata.Bundle
|
||||
err error
|
||||
called bool
|
||||
calls int
|
||||
beforeRun func()
|
||||
}
|
||||
|
||||
type publicationGateContext struct {
|
||||
context.Context
|
||||
err error
|
||||
checks int
|
||||
afterChecks int
|
||||
}
|
||||
|
||||
func (c *publicationGateContext) Err() error {
|
||||
c.checks++
|
||||
afterChecks := c.afterChecks
|
||||
if afterChecks == 0 {
|
||||
afterChecks = 2
|
||||
}
|
||||
if c.checks >= afterChecks {
|
||||
return c.err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *generationCollector) Run(context.Context, collect.Request) (*collect.Result, error) {
|
||||
if c.beforeRun != nil {
|
||||
c.beforeRun()
|
||||
}
|
||||
c.called = true
|
||||
c.calls++
|
||||
return &collect.Result{Bundle: c.bundle}, c.err
|
||||
}
|
||||
|
||||
type generationExecutor struct {
|
||||
called bool
|
||||
executeCalls int
|
||||
promptInspections int
|
||||
profileInspections int
|
||||
inspectErr error
|
||||
profileInspectErrors map[string]error
|
||||
executeErr error
|
||||
executeErrors map[string]error
|
||||
beforeExecute func(promptexec.ExecuteRequest)
|
||||
cancelBeforeReturn context.CancelFunc
|
||||
validation promptexec.ValidationStatus
|
||||
validations map[string]promptexec.ValidationStatus
|
||||
rawOutput []byte
|
||||
waitForCancellation map[string]bool
|
||||
failedPrompt string
|
||||
skipPreparation bool
|
||||
preparationCalls int
|
||||
prepare func(*promptexec.Preparation)
|
||||
complete func(*promptexec.Execution)
|
||||
}
|
||||
|
||||
var generationExecutorMu sync.Mutex
|
||||
|
||||
func (e *generationExecutor) InspectPrompt(_ context.Context, id, version string) (promptexec.PromptInspection, error) {
|
||||
generationExecutorMu.Lock()
|
||||
defer generationExecutorMu.Unlock()
|
||||
e.promptInspections++
|
||||
if e.inspectErr != nil {
|
||||
return promptexec.PromptInspection{}, e.inspectErr
|
||||
}
|
||||
definition := generationDefinitionForPrompt(id)
|
||||
return promptexec.PromptInspection{PromptID: id, PromptVersion: version, PromptHash: generationPromptHash, DefaultProfileID: "fixture", Inputs: []promptexec.InputDefinition{{Name: "data_package", Required: true, ContentType: "application/yaml"}}, Output: promptexec.OutputContract{Format: "json", ValidationMode: "json_schema", SchemaPath: definition.GeneratedTextSchemaID + ".generated_text.schema.json"}}, nil
|
||||
}
|
||||
func (e *generationExecutor) InspectProfile(_ context.Context, id string) (promptexec.ProfileInspection, error) {
|
||||
generationExecutorMu.Lock()
|
||||
defer generationExecutorMu.Unlock()
|
||||
e.profileInspections++
|
||||
if err := e.profileInspectErrors[id]; err != nil {
|
||||
return promptexec.ProfileInspection{}, err
|
||||
}
|
||||
return promptexec.ProfileInspection{ProfileID: id, BackendID: "fixture", ModelName: "fixture-model"}, nil
|
||||
}
|
||||
func (e *generationExecutor) Execute(ctx context.Context, req promptexec.ExecuteRequest, callback promptexec.PreparationCallback) (*promptexec.Execution, error) {
|
||||
stamp := time.Date(2026, 5, 29, 15, 0, 0, 0, time.UTC)
|
||||
generationExecutorMu.Lock()
|
||||
skipPreparation := e.skipPreparation
|
||||
prepare := e.prepare
|
||||
preparationCalls := e.preparationCalls
|
||||
generationExecutorMu.Unlock()
|
||||
if !skipPreparation {
|
||||
calls := preparationCalls
|
||||
if calls == 0 {
|
||||
calls = 1
|
||||
}
|
||||
for range calls {
|
||||
preparation := promptexec.Preparation{PromptID: req.PromptID, PromptVersion: req.PromptVersion, PromptHash: generationPromptHash, RenderedPromptHash: "rendered-hash", ProfileID: req.ProfileID, BackendID: "fixture", ModelName: "fixture-model", Output: promptexec.OutputContract{Format: "json", ValidationMode: "json_schema", SchemaPath: generationDefinitionForPrompt(req.PromptID).GeneratedTextSchemaID + ".generated_text.schema.json"}, StartedAt: stamp, EndedAt: stamp}
|
||||
if prepare != nil {
|
||||
prepare(&preparation)
|
||||
}
|
||||
if err := callback(preparation, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
generationExecutorMu.Lock()
|
||||
e.called = true
|
||||
e.executeCalls++
|
||||
beforeExecute := e.beforeExecute
|
||||
profileErr := e.executeErrors[req.ProfileID]
|
||||
executeErr := e.executeErr
|
||||
status := e.validation
|
||||
if profileStatus, ok := e.validations[req.ProfileID]; ok {
|
||||
status = profileStatus
|
||||
}
|
||||
rawOutput := append([]byte(nil), e.rawOutput...)
|
||||
waitForCancellation := e.waitForCancellation[req.ProfileID]
|
||||
failedPrompt := e.failedPrompt
|
||||
cancelBeforeReturn := e.cancelBeforeReturn
|
||||
complete := e.complete
|
||||
generationExecutorMu.Unlock()
|
||||
if beforeExecute != nil {
|
||||
beforeExecute(req)
|
||||
}
|
||||
if waitForCancellation {
|
||||
<-ctx.Done()
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
if profileErr != nil {
|
||||
return nil, profileErr
|
||||
}
|
||||
if executeErr != nil {
|
||||
return nil, executeErr
|
||||
}
|
||||
if status == "" {
|
||||
status = promptexec.ValidationPassed
|
||||
}
|
||||
if failedPrompt == req.PromptID {
|
||||
status = promptexec.ValidationFailed
|
||||
}
|
||||
if rawOutput == nil {
|
||||
rawOutput = []byte(`{"summary":"Showers are possible during the selected day.","forecast_discussion":["A front will keep rain chances in the forecast."],"precipitation_timing":"Rain is most likely during the afternoon."}`)
|
||||
}
|
||||
if cancelBeforeReturn != nil {
|
||||
cancelBeforeReturn()
|
||||
}
|
||||
execution := &promptexec.Execution{RunID: "provider-run", PromptID: req.PromptID, PromptVersion: req.PromptVersion, PromptHash: generationPromptHash, RenderedPromptHash: "rendered-hash", ProfileID: req.ProfileID, BackendID: "fixture", ModelName: "fixture-model", StartedAt: stamp, EndedAt: stamp, RawOutput: rawOutput, Validation: promptexec.NewValidation(status, "json_schema", generationDefinitionForPrompt(req.PromptID).GeneratedTextSchemaID+".generated_text.schema.json", nil)}
|
||||
if complete != nil {
|
||||
complete(execution)
|
||||
}
|
||||
return execution, nil
|
||||
}
|
||||
|
||||
const generationPromptHash = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
|
||||
|
||||
func generationDefinitionForPrompt(promptID string) report.Definition {
|
||||
for _, definition := range report.DefaultRegistry().All() {
|
||||
if definition.PromptID == promptID {
|
||||
return definition
|
||||
}
|
||||
}
|
||||
panic("unknown fixture prompt " + promptID)
|
||||
}
|
||||
|
||||
func TestGenerateDetailedPublishesOnlySelectedOutput(t *testing.T) {
|
||||
cfg := config.Defaults()
|
||||
cfg.WeatherAPI.Timezone, cfg.Location.ID = "America/Chicago", "home"
|
||||
bundle := generationBundle(t)
|
||||
executor := &generationExecutor{}
|
||||
collector := &generationCollector{bundle: &bundle}
|
||||
workingDir := t.TempDir()
|
||||
result, err := GenerateDetailed(context.Background(), GenerateRequest{Config: cfg, Report: ReportDaily, Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"), WorkingDir: workingDir, Collector: collector, Executor: executor})
|
||||
if err != nil {
|
||||
t.Fatalf("GenerateDetailed() error = %v", err)
|
||||
}
|
||||
if !executor.called || executor.executeCalls != 1 || collector.calls != 1 || result.OutputPath != filepath.Join(workingDir, "daily-2026-05-29.md") || result.ValidationStatus != promptexec.ValidationPassed || result.ProfileID == "" || result.BackendID == "" || result.ModelName == "" {
|
||||
t.Fatalf("result = %#v", result)
|
||||
}
|
||||
if result.LLMDebugPath != "" {
|
||||
t.Fatalf("unexpected debug output = %q", result.LLMDebugPath)
|
||||
}
|
||||
if _, err := os.Stat(filepath.Join(workingDir, "workspace")); !os.IsNotExist(err) {
|
||||
t.Fatalf("unexpected default state directory: %v", err)
|
||||
}
|
||||
data, err := os.ReadFile(result.OutputPath)
|
||||
if err != nil || len(data) == 0 {
|
||||
t.Fatalf("output = %q, error = %v", data, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateDetailedUsesConfiguredOutputDirectory(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
directory func(t *testing.T, workingDir string) string
|
||||
wantDir func(t *testing.T, workingDir string, configuredDir string) string
|
||||
}{
|
||||
{
|
||||
name: "absolute directory",
|
||||
directory: func(t *testing.T, _ string) string {
|
||||
return filepath.Join(t.TempDir(), "reports")
|
||||
},
|
||||
wantDir: func(_ *testing.T, _ string, configuredDir string) string {
|
||||
return configuredDir
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "relative directory",
|
||||
directory: func(_ *testing.T, _ string) string {
|
||||
return "configured/../reports"
|
||||
},
|
||||
wantDir: func(_ *testing.T, workingDir string, _ string) string {
|
||||
return filepath.Join(workingDir, "reports")
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
workingDir := t.TempDir()
|
||||
configuredDir := tt.directory(t, workingDir)
|
||||
cfg := generationDistributorConfig()
|
||||
cfg.Output.Directory = configuredDir
|
||||
bundle := generationBundle(t)
|
||||
notifier := &generationNotifier{}
|
||||
|
||||
result, err := GenerateDetailed(context.Background(), GenerateRequest{
|
||||
Config: cfg, Report: ReportDaily,
|
||||
Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"),
|
||||
WorkingDir: workingDir, Collector: &generationCollector{bundle: &bundle}, Executor: &generationExecutor{}, Notifier: notifier,
|
||||
})
|
||||
wantPath := filepath.Join(tt.wantDir(t, workingDir, configuredDir), "daily-2026-05-29.md")
|
||||
if err != nil || result == nil || result.OutputPath != wantPath || notifier.request.ReportPath != wantPath {
|
||||
t.Fatalf("GenerateDetailed() result/error/notification = %#v/%v/%#v", result, err, notifier.request)
|
||||
}
|
||||
if info, statErr := os.Stat(filepath.Dir(wantPath)); statErr != nil || !info.IsDir() {
|
||||
t.Fatalf("configured output directory info/error = %#v/%v", info, statErr)
|
||||
}
|
||||
if _, statErr := os.Stat(wantPath); statErr != nil {
|
||||
t.Fatalf("output %q: %v", wantPath, statErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateDetailedExplicitOutputPathIgnoresConfiguredDirectory(t *testing.T) {
|
||||
configuredPath := filepath.Join(t.TempDir(), "not-a-directory")
|
||||
if err := os.WriteFile(configuredPath, []byte("not a directory"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
explicitPath := filepath.Join(t.TempDir(), "explicit.md")
|
||||
cfg := generationConfig()
|
||||
cfg.Output.Directory = configuredPath
|
||||
bundle := generationBundle(t)
|
||||
|
||||
result, err := GenerateDetailed(context.Background(), GenerateRequest{
|
||||
Config: cfg, Report: ReportDaily,
|
||||
Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"),
|
||||
WorkingDir: t.TempDir(), OutputPath: explicitPath, Collector: &generationCollector{bundle: &bundle}, Executor: &generationExecutor{},
|
||||
})
|
||||
if err != nil || result == nil || result.OutputPath != explicitPath {
|
||||
t.Fatalf("GenerateDetailed() result/error = %#v/%v", result, err)
|
||||
}
|
||||
if _, statErr := os.Stat(explicitPath); statErr != nil {
|
||||
t.Fatalf("explicit output %q: %v", explicitPath, statErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateDetailedRejectsConfiguredNonDirectoryBeforeWork(t *testing.T) {
|
||||
configuredPath := filepath.Join(t.TempDir(), "not-a-directory")
|
||||
if err := os.WriteFile(configuredPath, []byte("not a directory"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg := generationDistributorConfig()
|
||||
cfg.Output.Directory = configuredPath
|
||||
bundle := generationBundle(t)
|
||||
collector := &generationCollector{bundle: &bundle}
|
||||
executor := &generationExecutor{}
|
||||
notifier := &generationNotifier{}
|
||||
|
||||
result, err := GenerateDetailed(context.Background(), GenerateRequest{
|
||||
Config: cfg, Report: ReportDaily,
|
||||
Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"),
|
||||
WorkingDir: t.TempDir(), Collector: collector, Executor: executor, Notifier: notifier,
|
||||
})
|
||||
if err == nil || result == nil || collector.called || executor.promptInspections != 0 || executor.called || notifier.calls != 0 {
|
||||
t.Fatalf("GenerateDetailed() result/error/collector/executor/notifier = %#v/%v/%t/%#v/%#v", result, err, collector.called, executor, notifier)
|
||||
}
|
||||
if data, readErr := os.ReadFile(configuredPath); readErr != nil || string(data) != "not a directory" {
|
||||
t.Fatalf("configured path = %q, error = %v", data, readErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateDetailedRejectsOverlongOutputBeforeWork(t *testing.T) {
|
||||
missingDirectory := filepath.Join(t.TempDir(), "missing")
|
||||
outputPath := filepath.Join(missingDirectory, strings.Repeat("a", 253)+".md")
|
||||
bundle := generationBundle(t)
|
||||
collector := &generationCollector{bundle: &bundle}
|
||||
executor := &generationExecutor{}
|
||||
|
||||
result, err := GenerateDetailed(context.Background(), GenerateRequest{
|
||||
Config: generationConfig(), Report: ReportDaily,
|
||||
Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"),
|
||||
WorkingDir: t.TempDir(), OutputPath: outputPath, Collector: collector, Executor: executor,
|
||||
})
|
||||
if err == nil || result == nil || collector.called || executor.promptInspections != 0 || executor.called {
|
||||
t.Fatalf("GenerateDetailed() result/error/collector/executor = %#v/%v/%t/%#v", result, err, collector.called, executor)
|
||||
}
|
||||
if _, statErr := os.Stat(missingDirectory); !os.IsNotExist(statErr) {
|
||||
t.Fatalf("missing output directory exists after preflight failure: %v", statErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateDetailedRejectsUnsupportedDistributorEndpointBeforeWork(t *testing.T) {
|
||||
outputPath := filepath.Join(t.TempDir(), "daily.md")
|
||||
cfg := generationDistributorConfig()
|
||||
cfg.Notify.Distributor.Endpoint = "ftp://distributor.example.test"
|
||||
bundle := generationBundle(t)
|
||||
collector := &generationCollector{bundle: &bundle}
|
||||
executor := &generationExecutor{}
|
||||
notifier := &generationNotifier{}
|
||||
|
||||
result, err := GenerateDetailed(context.Background(), GenerateRequest{
|
||||
Config: cfg, Report: ReportDaily,
|
||||
Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"),
|
||||
WorkingDir: t.TempDir(), OutputPath: outputPath, Collector: collector, Executor: executor, Notifier: notifier,
|
||||
})
|
||||
if err == nil || result == nil || collector.called || executor.promptInspections != 0 || executor.called || notifier.calls != 0 {
|
||||
t.Fatalf("GenerateDetailed() result/error/collector/executor/notifier = %#v/%v/%t/%#v/%#v", result, err, collector.called, executor, notifier)
|
||||
}
|
||||
if _, statErr := os.Stat(outputPath); !os.IsNotExist(statErr) {
|
||||
t.Fatalf("output exists after endpoint preflight failure: %v", statErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateDetailedReturnsResolvedResultWhenCollectionFails(t *testing.T) {
|
||||
cfg := config.Defaults()
|
||||
cfg.WeatherAPI.Timezone, cfg.Location.ID = "America/Chicago", "home"
|
||||
collectionErr := errors.New("weather source unavailable")
|
||||
result, err := GenerateDetailed(context.Background(), GenerateRequest{
|
||||
Config: cfg, Report: ReportDaily, Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"),
|
||||
WorkingDir: t.TempDir(), Collector: &generationCollector{err: collectionErr}, Executor: &generationExecutor{},
|
||||
})
|
||||
if !errors.Is(err, collectionErr) {
|
||||
t.Fatalf("GenerateDetailed() error = %v, want %v", err, collectionErr)
|
||||
}
|
||||
if result == nil || result.ReportID != report.Daily || result.RunID == "" || result.ProfileID != "fixture" || result.BackendID != "fixture" || result.ModelName != "fixture-model" || result.OutputPath != "" {
|
||||
t.Fatalf("result = %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateDetailedInspectsPromptBeforeCollectingWeather(t *testing.T) {
|
||||
cfg := generationConfig()
|
||||
inspectionErr := errors.New("profile is invalid")
|
||||
collector := &generationCollector{bundle: generationBundlePointer(t)}
|
||||
result, err := GenerateDetailed(context.Background(), GenerateRequest{Config: cfg, Report: ReportDaily, Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"), WorkingDir: t.TempDir(), Collector: collector, Executor: &generationExecutor{inspectErr: inspectionErr}})
|
||||
if !errors.Is(err, inspectionErr) || collector.called || result == nil {
|
||||
t.Fatalf("GenerateDetailed() result/error/collector-called = %#v/%v/%t", result, err, collector.called)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateDetailedPreservesDestinationBeforePublish(t *testing.T) {
|
||||
for _, scenario := range []struct {
|
||||
name string
|
||||
executor generationExecutor
|
||||
}{
|
||||
{name: "generation", executor: generationExecutor{executeErr: errors.New("provider unavailable")}},
|
||||
{name: "render", executor: generationExecutor{rawOutput: []byte(`{"summary":""}`)}},
|
||||
} {
|
||||
t.Run(scenario.name, func(t *testing.T) {
|
||||
outputPath := filepath.Join(t.TempDir(), "daily.md")
|
||||
if err := os.WriteFile(outputPath, []byte("previous report"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bundle := generationBundle(t)
|
||||
result, err := GenerateDetailed(context.Background(), GenerateRequest{Config: generationConfig(), Report: ReportDaily, Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"), WorkingDir: t.TempDir(), OutputPath: outputPath, Collector: &generationCollector{bundle: &bundle}, Executor: &scenario.executor})
|
||||
data, readErr := os.ReadFile(outputPath)
|
||||
if err == nil || result == nil || readErr != nil || string(data) != "previous report" {
|
||||
t.Fatalf("GenerateDetailed() result/error/output = %#v/%v/%q (%v)", result, err, data, readErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateDetailedPreservesDestinationWhenContextCancelsBeforePublication(t *testing.T) {
|
||||
outputPath := filepath.Join(t.TempDir(), "daily.md")
|
||||
const previousReport = "previous report"
|
||||
if err := os.WriteFile(outputPath, []byte(previousReport), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
bundle := generationBundle(t)
|
||||
result, err := GenerateDetailed(ctx, GenerateRequest{
|
||||
Config: generationConfig(), Report: ReportDaily,
|
||||
Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"),
|
||||
WorkingDir: t.TempDir(), OutputPath: outputPath, Collector: &generationCollector{bundle: &bundle}, Executor: &generationExecutor{cancelBeforeReturn: cancel},
|
||||
})
|
||||
data, readErr := os.ReadFile(outputPath)
|
||||
if !errors.Is(err, context.Canceled) || promptexec.CategoryOf(err) != promptexec.Canceled || result == nil || result.OutputPath != "" || readErr != nil || string(data) != previousReport {
|
||||
t.Fatalf("GenerateDetailed() result/error/output = %#v/%v/%q (%v)", result, err, data, readErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateDetailedPreservesDestinationWhenContextDeadlineExpiresBeforePublication(t *testing.T) {
|
||||
outputPath := filepath.Join(t.TempDir(), "daily.md")
|
||||
const previousReport = "previous report"
|
||||
if err := os.WriteFile(outputPath, []byte(previousReport), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithDeadline(context.Background(), time.Unix(0, 0))
|
||||
defer cancel()
|
||||
bundle := generationBundle(t)
|
||||
result, err := GenerateDetailed(ctx, GenerateRequest{
|
||||
Config: generationConfig(), Report: ReportDaily,
|
||||
Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"),
|
||||
WorkingDir: t.TempDir(), OutputPath: outputPath, Collector: &generationCollector{bundle: &bundle}, Executor: &generationExecutor{},
|
||||
})
|
||||
data, readErr := os.ReadFile(outputPath)
|
||||
if !errors.Is(err, context.DeadlineExceeded) || promptexec.CategoryOf(err) != promptexec.DeadlineExceeded || result == nil || result.OutputPath != "" || readErr != nil || string(data) != previousReport {
|
||||
t.Fatalf("GenerateDetailed() result/error/output = %#v/%v/%q (%v)", result, err, data, readErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateDetailedPreservesDestinationWhenContextChangesDuringPublication(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
err error
|
||||
category promptexec.ErrorCategory
|
||||
}{
|
||||
{name: "canceled", err: context.Canceled, category: promptexec.Canceled},
|
||||
{name: "deadline", err: context.DeadlineExceeded, category: promptexec.DeadlineExceeded},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
outputPath := filepath.Join(t.TempDir(), "daily.md")
|
||||
const previousReport = "previous report"
|
||||
if err := os.WriteFile(outputPath, []byte(previousReport), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx := &publicationGateContext{Context: context.Background(), err: tt.err}
|
||||
cfg := generationConfig()
|
||||
cfg.Notify.Distributor.Enabled = true
|
||||
cfg.Notify.Distributor.PipelineIDTemplate = "weather"
|
||||
bundle := generationBundle(t)
|
||||
notifier := &generationNotifier{}
|
||||
result, err := GenerateDetailed(ctx, GenerateRequest{
|
||||
Config: cfg, Report: ReportDaily,
|
||||
Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"),
|
||||
WorkingDir: t.TempDir(), OutputPath: outputPath, Collector: &generationCollector{bundle: &bundle}, Executor: &generationExecutor{}, Notifier: notifier,
|
||||
})
|
||||
data, readErr := os.ReadFile(outputPath)
|
||||
matches, globErr := filepath.Glob(filepath.Join(filepath.Dir(outputPath), ".weatherreporter-*.tmp"))
|
||||
if !errors.Is(err, tt.err) || promptexec.CategoryOf(err) != tt.category || result == nil || result.OutputPath != "" || notifier.calls != 0 || readErr != nil || string(data) != previousReport || globErr != nil || len(matches) != 0 {
|
||||
t.Fatalf("GenerateDetailed() result/error/output/notification/temp = %#v/%v/%q/%#v/%v/%v", result, err, data, notifier, matches, globErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateDetailedRetainsPublishedOutputWhenNotificationFails(t *testing.T) {
|
||||
cfg := generationConfig()
|
||||
cfg.Notify.Distributor.Enabled = true
|
||||
cfg.Notify.Distributor.PipelineIDTemplate = "weather"
|
||||
bundle := generationBundle(t)
|
||||
outputPath := filepath.Join(t.TempDir(), "daily.md")
|
||||
notifier := &generationNotifier{err: errors.New("distributor unavailable")}
|
||||
result, err := GenerateDetailed(context.Background(), GenerateRequest{Config: cfg, Report: ReportDaily, Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"), WorkingDir: t.TempDir(), OutputPath: outputPath, Collector: &generationCollector{bundle: &bundle}, Executor: &generationExecutor{}, Notifier: notifier})
|
||||
if err == nil || result == nil || result.OutputPath != outputPath || notifier.request.ReportPath != outputPath || len(notifier.request.BundlePaths) == 0 {
|
||||
t.Fatalf("GenerateDetailed() result/error/request = %#v/%v/%#v", result, err, notifier.request)
|
||||
}
|
||||
if data, readErr := os.ReadFile(outputPath); readErr != nil || len(data) == 0 {
|
||||
t.Fatalf("published output = %q, error = %v", data, readErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateDetailedDoesNotReplaceDirectoryOutput(t *testing.T) {
|
||||
bundle := generationBundle(t)
|
||||
outputPath := filepath.Join(t.TempDir(), "daily.md")
|
||||
if err := os.Mkdir(outputPath, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
collector := &generationCollector{bundle: &bundle}
|
||||
executor := &generationExecutor{}
|
||||
notifier := &generationNotifier{}
|
||||
result, err := GenerateDetailed(context.Background(), GenerateRequest{Config: generationConfig(), Report: ReportDaily, Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"), WorkingDir: t.TempDir(), OutputPath: outputPath, Collector: collector, Executor: executor, Notifier: notifier})
|
||||
info, statErr := os.Stat(outputPath)
|
||||
if err == nil || result == nil || statErr != nil || !info.IsDir() || collector.called || executor.promptInspections != 0 || executor.called || notifier.calls != 0 {
|
||||
t.Fatalf("GenerateDetailed() result/error/output-info/collector/executor/notifier = %#v/%v/%#v (%v)/%t/%#v/%#v", result, err, info, statErr, collector.called, executor, notifier)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateDetailedDoesNotReplaceSymbolicLinkOutput(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
backing := filepath.Join(dir, "backing.md")
|
||||
if err := os.WriteFile(backing, []byte("previous report"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outputPath := filepath.Join(dir, "daily.md")
|
||||
testutil.RequireSymlink(t, backing, outputPath)
|
||||
bundle := generationBundle(t)
|
||||
collector := &generationCollector{bundle: &bundle}
|
||||
executor := &generationExecutor{}
|
||||
notifier := &generationNotifier{}
|
||||
result, err := GenerateDetailed(context.Background(), GenerateRequest{Config: generationConfig(), Report: ReportDaily, Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"), WorkingDir: t.TempDir(), OutputPath: outputPath, Collector: collector, Executor: executor, Notifier: notifier})
|
||||
info, statErr := os.Lstat(outputPath)
|
||||
data, readErr := os.ReadFile(backing)
|
||||
if err == nil || result == nil || statErr != nil || info.Mode()&os.ModeSymlink == 0 || readErr != nil || string(data) != "previous report" || collector.called || executor.promptInspections != 0 || executor.called || notifier.calls != 0 {
|
||||
t.Fatalf("GenerateDetailed() result/error/output/backing/collector/executor/notifier = %#v/%v/%#v (%v)/%q (%v)/%t/%#v/%#v", result, err, info, statErr, data, readErr, collector.called, executor, notifier)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerateDetailedWritesRequestedPromptDebugArtifacts(t *testing.T) {
|
||||
bundle := generationBundle(t)
|
||||
debugRoot := t.TempDir()
|
||||
result, err := GenerateDetailed(context.Background(), GenerateRequest{
|
||||
Config: generationConfig(), Report: ReportDaily,
|
||||
Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"),
|
||||
WorkingDir: t.TempDir(), LLMDebugDir: debugRoot, Collector: &generationCollector{bundle: &bundle}, Executor: &generationExecutor{},
|
||||
})
|
||||
if errors.Is(err, promptdebug.ErrSecureCaptureUnsupported) {
|
||||
t.Skipf("secure prompt debug capture is unavailable: %v", err)
|
||||
}
|
||||
if err != nil || result == nil || result.LLMDebugPath == "" {
|
||||
t.Fatalf("GenerateDetailed() result/error = %#v/%v", result, err)
|
||||
}
|
||||
for _, name := range []string{"preparation.json", "execution.json"} {
|
||||
if _, statErr := os.Stat(filepath.Join(result.LLMDebugPath, name)); statErr != nil {
|
||||
t.Fatalf("debug artifact %q: %v", name, statErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func generationConfig() config.Config {
|
||||
cfg := config.Defaults()
|
||||
cfg.WeatherAPI.Timezone, cfg.Location.ID = "America/Chicago", "home"
|
||||
return cfg
|
||||
}
|
||||
|
||||
func generationBundlePointer(t *testing.T) *weatherdata.Bundle {
|
||||
bundle := generationBundle(t)
|
||||
return &bundle
|
||||
}
|
||||
|
||||
type generationNotifier struct {
|
||||
err error
|
||||
batchErr error
|
||||
calls int
|
||||
request NotificationRequest
|
||||
batchRequest batchNotificationRequest
|
||||
batchCalls int
|
||||
}
|
||||
|
||||
func (n *generationNotifier) Notify(_ context.Context, request NotificationRequest) (*NotificationResult, error) {
|
||||
n.calls++
|
||||
n.request = request
|
||||
if n.err != nil {
|
||||
return nil, n.err
|
||||
}
|
||||
return &NotificationResult{Status: "succeeded"}, nil
|
||||
}
|
||||
|
||||
func (n *generationNotifier) NotifyBatch(_ context.Context, request batchNotificationRequest) (*NotificationResult, error) {
|
||||
n.batchCalls++
|
||||
n.batchRequest = request
|
||||
for _, file := range request.Files {
|
||||
if _, err := os.Stat(file.SourcePath); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &NotificationResult{Status: "succeeded", PipelineID: request.PipelineID, BundleID: request.BundleID}, n.batchErr
|
||||
}
|
||||
|
||||
func generationBundle(t *testing.T) weatherdata.Bundle {
|
||||
t.Helper()
|
||||
data, err := os.ReadFile(filepath.Join("..", "forecast", "testdata", "daily_bundle.json"))
|
||||
if err != nil {
|
||||
t.Fatalf("read bundle fixture: %v", err)
|
||||
}
|
||||
var bundle weatherdata.Bundle
|
||||
if err := json.Unmarshal(data, &bundle); err != nil {
|
||||
t.Fatalf("decode bundle fixture: %v", err)
|
||||
}
|
||||
return bundle
|
||||
}
|
||||
func generationTime(value string) time.Time {
|
||||
parsed, _ := time.Parse(time.RFC3339, value)
|
||||
return parsed
|
||||
}
|
||||
|
||||
var _ promptexec.Executor = (*generationExecutor)(nil)
|
||||
var _ Collector = (*generationCollector)(nil)
|
||||
var _ Notifier = (*generationNotifier)(nil)
|
||||
var _ = report.Daily
|
||||
192
internal/app/output.go
Normal file
192
internal/app/output.go
Normal file
@@ -0,0 +1,192 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/comparison"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/fileutil"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/report"
|
||||
)
|
||||
|
||||
func plannedBatchOutputPath(outputDir string, planned plannedBatchReport) (string, error) {
|
||||
outputName, err := planned.Resolved.OutputName()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return validateOutputPath(filepath.Join(outputDir, outputName))
|
||||
}
|
||||
|
||||
func prepareBatchOutputs(outputDir string, plannedReports []plannedBatchReport) error {
|
||||
for index := range plannedReports {
|
||||
outputPath, err := plannedBatchOutputPath(outputDir, plannedReports[index])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
plannedReports[index].OutputPath = outputPath
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func resolveReportOutputPath(workingDir, override, configuredDir string, resolved report.Resolved) (string, error) {
|
||||
outputName, err := resolved.OutputName()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if override != "" {
|
||||
return resolveOutputPath(workingDir, override, outputName)
|
||||
}
|
||||
outputDir, err := resolveOutputDir(workingDir, configuredDir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return validateOutputPath(filepath.Join(outputDir, outputName))
|
||||
}
|
||||
|
||||
func resolveOutputDirWithConfigured(workingDir, override, configuredDir string) (string, error) {
|
||||
directory := configuredDir
|
||||
if override != "" {
|
||||
directory = override
|
||||
}
|
||||
return resolveOutputDir(workingDir, directory)
|
||||
}
|
||||
|
||||
func resolveComparisonOutputDirectory(workingDir, override, configuredDir, reportOutputName string) (string, error) {
|
||||
workingDir, err := validateWorkingDir(workingDir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if override != "" {
|
||||
return resolveComparisonDirectoryPath(workingDir, override)
|
||||
}
|
||||
outputDir, err := resolveOutputDir(workingDir, configuredDir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
name, err := comparison.DefaultDirectoryName(reportOutputName)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return filepath.Join(outputDir, name), nil
|
||||
}
|
||||
|
||||
func resolveComparisonDirectoryPath(workingDir, directory string) (string, error) {
|
||||
if strings.TrimSpace(directory) == "" {
|
||||
return "", fmt.Errorf("comparison output directory is required")
|
||||
}
|
||||
if !filepath.IsAbs(directory) {
|
||||
directory = filepath.Join(workingDir, directory)
|
||||
}
|
||||
return filepath.Clean(directory), nil
|
||||
}
|
||||
|
||||
func resolveOutputDir(workingDir, override string) (string, error) {
|
||||
workingDir, err := validateWorkingDir(workingDir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if override == "" {
|
||||
return workingDir, nil
|
||||
}
|
||||
if strings.TrimSpace(override) == "" {
|
||||
return "", fmt.Errorf("output directory is required")
|
||||
}
|
||||
directory := override
|
||||
if !filepath.IsAbs(directory) {
|
||||
directory = filepath.Join(workingDir, directory)
|
||||
}
|
||||
directory = filepath.Clean(directory)
|
||||
if err := preflightOutputDirectory(directory); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return directory, nil
|
||||
}
|
||||
|
||||
func preflightOutputDirectory(directory string) error {
|
||||
info, err := os.Stat(directory)
|
||||
if err == nil {
|
||||
if !info.IsDir() {
|
||||
return fmt.Errorf("output directory %q is not a directory", directory)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !os.IsNotExist(err) {
|
||||
return fmt.Errorf("inspect output directory %q: %w", directory, err)
|
||||
}
|
||||
|
||||
// A missing directory is valid, but os.Stat also reports ErrNotExist for a
|
||||
// dangling symlink. Walk to the first existing component so invalid links
|
||||
// fail preflight instead of being discovered only during publication.
|
||||
for component := directory; ; component = filepath.Dir(component) {
|
||||
componentInfo, componentErr := os.Lstat(component)
|
||||
if componentErr == nil {
|
||||
if componentInfo.Mode()&os.ModeSymlink != 0 {
|
||||
targetInfo, targetErr := os.Stat(component)
|
||||
if targetErr != nil {
|
||||
return fmt.Errorf("inspect output directory %q at %q: %w", directory, component, targetErr)
|
||||
}
|
||||
if !targetInfo.IsDir() {
|
||||
return fmt.Errorf("output directory %q has non-directory path component %q", directory, component)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !componentInfo.IsDir() {
|
||||
return fmt.Errorf("output directory %q has non-directory path component %q", directory, component)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if !os.IsNotExist(componentErr) {
|
||||
return fmt.Errorf("inspect output directory %q at %q: %w", directory, component, componentErr)
|
||||
}
|
||||
if filepath.Dir(component) == component {
|
||||
return fmt.Errorf("inspect output directory %q: no existing directory ancestor", directory)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func resolveOutputPath(workingDir, override, defaultName string) (string, error) {
|
||||
workingDir, err := validateWorkingDir(workingDir)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
path := override
|
||||
if path == "" {
|
||||
path = defaultName
|
||||
}
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return "", fmt.Errorf("final output path is required")
|
||||
}
|
||||
if !filepath.IsAbs(path) {
|
||||
path = filepath.Join(workingDir, path)
|
||||
}
|
||||
return validateOutputPath(path)
|
||||
}
|
||||
|
||||
func validateWorkingDir(workingDir string) (string, error) {
|
||||
if strings.TrimSpace(workingDir) == "" {
|
||||
return "", fmt.Errorf("working directory is required")
|
||||
}
|
||||
if !filepath.IsAbs(workingDir) {
|
||||
return "", fmt.Errorf("working directory %q must be absolute", workingDir)
|
||||
}
|
||||
return filepath.Clean(workingDir), nil
|
||||
}
|
||||
|
||||
func validateOutputPath(path string) (string, error) {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return "", fmt.Errorf("final output path is required")
|
||||
}
|
||||
path = filepath.Clean(path)
|
||||
if !filepath.IsAbs(path) {
|
||||
return "", fmt.Errorf("final output path %q must be absolute", path)
|
||||
}
|
||||
if filepath.Dir(path) == path {
|
||||
return "", fmt.Errorf("final output path %q must not be a filesystem root", path)
|
||||
}
|
||||
if err := fileutil.ValidateAtomicPath(path); err != nil {
|
||||
return "", fmt.Errorf("validate final output path %q: %w", path, err)
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
59
internal/app/output_linux_test.go
Normal file
59
internal/app/output_linux_test.go
Normal file
@@ -0,0 +1,59 @@
|
||||
//go:build linux
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGenerateDetailedRejectsSpecialOutputBeforeWork(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
setup func(t *testing.T, path string)
|
||||
}{
|
||||
{
|
||||
name: "named pipe",
|
||||
setup: func(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
if err := syscall.Mkfifo(path, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "socket",
|
||||
setup: func(t *testing.T, path string) {
|
||||
t.Helper()
|
||||
listener, err := net.ListenUnix("unix", &net.UnixAddr{Name: path, Net: "unix"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = listener.Close() })
|
||||
},
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
outputPath := filepath.Join(t.TempDir(), "daily.md")
|
||||
tt.setup(t, outputPath)
|
||||
bundle := generationBundle(t)
|
||||
collector := &generationCollector{bundle: &bundle}
|
||||
executor := &generationExecutor{}
|
||||
notifier := &generationNotifier{}
|
||||
|
||||
result, err := GenerateDetailed(context.Background(), GenerateRequest{
|
||||
Config: generationConfig(), Report: ReportDaily,
|
||||
Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"),
|
||||
WorkingDir: t.TempDir(), OutputPath: outputPath, Collector: collector, Executor: executor, Notifier: notifier,
|
||||
})
|
||||
info, statErr := os.Lstat(outputPath)
|
||||
if err == nil || result == nil || statErr != nil || info.Mode().IsRegular() || collector.called || executor.promptInspections != 0 || executor.called || notifier.calls != 0 {
|
||||
t.Fatalf("GenerateDetailed() result/error/output/collector/executor/notifier = %#v/%v/%#v (%v)/%t/%#v/%#v", result, err, info, statErr, collector.called, executor, notifier)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
73
internal/app/output_test.go
Normal file
73
internal/app/output_test.go
Normal file
@@ -0,0 +1,73 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/testutil"
|
||||
)
|
||||
|
||||
func TestResolveComparisonOutputDirectory(t *testing.T) {
|
||||
workingDir := t.TempDir()
|
||||
configured := filepath.Join(workingDir, "configured")
|
||||
blocked := filepath.Join(workingDir, "not-a-directory")
|
||||
if err := os.WriteFile(blocked, []byte("blocked"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
override string
|
||||
configuredDir string
|
||||
reportOutputName string
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "working directory default", reportOutputName: "today.md", want: filepath.Join(workingDir, "comparison-today")},
|
||||
{name: "configured relative directory", configuredDir: "configured", reportOutputName: "tomorrow.md", want: filepath.Join(configured, "comparison-tomorrow")},
|
||||
{name: "configured absolute directory", configuredDir: configured, reportOutputName: "hourly.md", want: filepath.Join(configured, "comparison-hourly")},
|
||||
{name: "relative explicit directory", override: "exact", configuredDir: blocked, reportOutputName: "daily-2026-08-24.md", want: filepath.Join(workingDir, "exact")},
|
||||
{name: "absolute explicit directory", override: filepath.Join(workingDir, "absolute"), reportOutputName: "today.md", want: filepath.Join(workingDir, "absolute")},
|
||||
{name: "invalid report suffix", reportOutputName: "today.txt", wantErr: true},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got, err := resolveComparisonOutputDirectory(workingDir, test.override, test.configuredDir, test.reportOutputName)
|
||||
if (err != nil) != test.wantErr {
|
||||
t.Fatalf("resolveComparisonOutputDirectory() error = %v, want error %t", err, test.wantErr)
|
||||
}
|
||||
if !test.wantErr && got != test.want {
|
||||
t.Fatalf("resolveComparisonOutputDirectory() = %q, want %q", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveOutputDirRejectsDanglingSymlinkComponents(t *testing.T) {
|
||||
workingDir := t.TempDir()
|
||||
dangling := filepath.Join(workingDir, "dangling")
|
||||
testutil.RequireSymlink(t, filepath.Join(workingDir, "missing"), dangling)
|
||||
|
||||
for _, directory := range []string{dangling, filepath.Join(dangling, "reports")} {
|
||||
t.Run(filepath.Base(directory), func(t *testing.T) {
|
||||
if _, err := resolveOutputDir(workingDir, directory); err == nil {
|
||||
t.Fatalf("resolveOutputDir(%q) error = nil, want dangling symlink error", directory)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveOutputDirAllowsMissingDirectoryBelowValidSymlink(t *testing.T) {
|
||||
workingDir := t.TempDir()
|
||||
target := t.TempDir()
|
||||
link := filepath.Join(workingDir, "linked")
|
||||
testutil.RequireSymlink(t, target, link)
|
||||
|
||||
directory := filepath.Join(link, "reports")
|
||||
got, err := resolveOutputDir(workingDir, directory)
|
||||
if err != nil || got != directory {
|
||||
t.Fatalf("resolveOutputDir() = %q, %v, want %q, nil", got, err, directory)
|
||||
}
|
||||
}
|
||||
148
internal/app/prepared_report.go
Normal file
148
internal/app/prepared_report.go
Normal file
@@ -0,0 +1,148 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/briefing"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/collect"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/config"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/facts"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/generatedtext"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/module"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptinput"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/report"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/weatherdata"
|
||||
)
|
||||
|
||||
// preparedReport contains the immutable deterministic inputs shared by prompt
|
||||
// executions for one resolved report.
|
||||
type preparedReport struct {
|
||||
resolved report.Resolved
|
||||
derived facts.DerivedFacts
|
||||
moduleSnapshot module.Snapshot
|
||||
identity briefing.PreparedIdentity
|
||||
sourceWarnings []weatherdata.SourceWarning
|
||||
dataPackage []byte
|
||||
handler generatedtext.Handler
|
||||
}
|
||||
|
||||
type prepareReportRequest struct {
|
||||
Config config.Config
|
||||
Resolved report.Resolved
|
||||
Collection collect.Result
|
||||
handler generatedtext.Handler
|
||||
}
|
||||
|
||||
type preparationError struct {
|
||||
operation string
|
||||
err error
|
||||
}
|
||||
|
||||
func (e *preparationError) Error() string {
|
||||
return e.operation + ": " + e.err.Error()
|
||||
}
|
||||
|
||||
func (e *preparationError) Unwrap() error {
|
||||
return e.err
|
||||
}
|
||||
|
||||
func prepareReport(req prepareReportRequest) (preparedReport, error) {
|
||||
if req.Collection.Bundle == nil {
|
||||
return preparedReport{}, &preparationError{operation: "prepare report", err: fmt.Errorf("collected weather bundle is required")}
|
||||
}
|
||||
|
||||
reportFacts, err := BuildReportFacts(ModuleSnapshotRequest{Config: req.Config, Resolved: req.Resolved}, req.Collection.Bundle)
|
||||
if err != nil {
|
||||
return preparedReport{}, &preparationError{operation: "build report facts", err: err}
|
||||
}
|
||||
buildContext := briefingBuildContext(req.Config, req.Resolved, reportFacts.Collected)
|
||||
identity := briefing.BuildPreparedIdentity(buildContext)
|
||||
moduleSnapshot, err := BuildModuleSnapshotFromFacts(ModuleSnapshotRequest{Config: req.Config, Resolved: req.Resolved, Identity: identity}, reportFacts)
|
||||
if err != nil {
|
||||
return preparedReport{}, &preparationError{operation: "build module snapshot", err: err}
|
||||
}
|
||||
dataPackage, err := promptinput.Build(promptinput.BuildRequest{Metadata: promptMetadata(identity), Modules: moduleSnapshot})
|
||||
if err != nil {
|
||||
return preparedReport{}, &preparationError{operation: "build data package", err: err}
|
||||
}
|
||||
serializedDataPackage, err := promptinput.MarshalYAML(dataPackage)
|
||||
if err != nil {
|
||||
return preparedReport{}, &preparationError{operation: "marshal data package", err: err}
|
||||
}
|
||||
clonedDerived, err := clonePreparedValue(reportFacts.Derived)
|
||||
if err != nil {
|
||||
return preparedReport{}, &preparationError{operation: "copy prepared derived facts", err: err}
|
||||
}
|
||||
clonedSnapshot, err := clonePreparedValue(moduleSnapshot)
|
||||
if err != nil {
|
||||
return preparedReport{}, &preparationError{operation: "copy prepared module snapshot", err: err}
|
||||
}
|
||||
clonedIdentity, err := clonePreparedValue(identity)
|
||||
if err != nil {
|
||||
return preparedReport{}, &preparationError{operation: "copy prepared identity", err: err}
|
||||
}
|
||||
prepared := preparedReport{
|
||||
resolved: cloneResolved(req.Resolved),
|
||||
derived: clonedDerived,
|
||||
moduleSnapshot: clonedSnapshot,
|
||||
identity: clonedIdentity,
|
||||
sourceWarnings: append([]weatherdata.SourceWarning(nil), clonedIdentity.SourceWarnings...),
|
||||
dataPackage: append([]byte(nil), serializedDataPackage...),
|
||||
handler: req.handler,
|
||||
}
|
||||
return prepared, nil
|
||||
}
|
||||
|
||||
func cloneResolved(value report.Resolved) report.Resolved {
|
||||
cloned := value
|
||||
cloned.Definition.DistributorPathTemplates = append([]string(nil), value.Definition.DistributorPathTemplates...)
|
||||
cloned.Definition.Modules = make([]module.ConfigItem, len(value.Definition.Modules))
|
||||
for i, item := range value.Definition.Modules {
|
||||
cloned.Definition.Modules[i] = item
|
||||
switch options := item.Options.(type) {
|
||||
case module.AreaForecastDiscussionOptions:
|
||||
options.Sections = append([]string(nil), options.Sections...)
|
||||
cloned.Definition.Modules[i].Options = options
|
||||
}
|
||||
}
|
||||
return cloned
|
||||
}
|
||||
|
||||
func (p preparedReport) dataPackageCopy() []byte {
|
||||
return append([]byte(nil), p.dataPackage...)
|
||||
}
|
||||
|
||||
func (p preparedReport) sourceWarningsCopy() []weatherdata.SourceWarning {
|
||||
return append([]weatherdata.SourceWarning(nil), p.sourceWarnings...)
|
||||
}
|
||||
|
||||
func (p preparedReport) renderInputs() (briefing.PreparedIdentity, module.Snapshot, facts.DerivedFacts, error) {
|
||||
identity, err := clonePreparedValue(p.identity)
|
||||
if err != nil {
|
||||
return briefing.PreparedIdentity{}, module.Snapshot{}, facts.DerivedFacts{}, err
|
||||
}
|
||||
snapshot, err := clonePreparedValue(p.moduleSnapshot)
|
||||
if err != nil {
|
||||
return briefing.PreparedIdentity{}, module.Snapshot{}, facts.DerivedFacts{}, err
|
||||
}
|
||||
derived, err := clonePreparedValue(p.derived)
|
||||
if err != nil {
|
||||
return briefing.PreparedIdentity{}, module.Snapshot{}, facts.DerivedFacts{}, err
|
||||
}
|
||||
return identity, snapshot, derived, nil
|
||||
}
|
||||
|
||||
func clonePreparedValue[T any](value T) (T, error) {
|
||||
encoded, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
var zero T
|
||||
return zero, fmt.Errorf("marshal immutable prepared value: %w", err)
|
||||
}
|
||||
var cloned T
|
||||
if err := json.Unmarshal(encoded, &cloned); err != nil {
|
||||
var zero T
|
||||
return zero, fmt.Errorf("unmarshal immutable prepared value: %w", err)
|
||||
}
|
||||
return cloned, nil
|
||||
}
|
||||
121
internal/app/prepared_report_test.go
Normal file
121
internal/app/prepared_report_test.go
Normal file
@@ -0,0 +1,121 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/briefing"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/collect"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/generatedtext"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/module"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/report"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/weatherdata"
|
||||
)
|
||||
|
||||
func TestPrepareReportBuildsImmutableDeterministicInputs(t *testing.T) {
|
||||
cfg := generationConfig()
|
||||
bundle := generationBundle(t)
|
||||
resolved, err := ResolveGenerate(GenerateRequest{
|
||||
Config: cfg, Report: ReportDaily,
|
||||
Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"),
|
||||
}, generationTime("2026-05-29T08:30:00-05:00"))
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveGenerate() error = %v", err)
|
||||
}
|
||||
|
||||
request := prepareReportRequest{Config: cfg, Resolved: resolved, Collection: collect.Result{Bundle: &bundle}, handler: preparedHandler(t, resolved)}
|
||||
prepared, err := prepareReport(request)
|
||||
if err != nil {
|
||||
t.Fatalf("prepareReport() error = %v", err)
|
||||
}
|
||||
repeated, err := prepareReport(request)
|
||||
if err != nil {
|
||||
t.Fatalf("second prepareReport() error = %v", err)
|
||||
}
|
||||
if len(prepared.dataPackage) == 0 || !bytes.Equal(prepared.dataPackage, repeated.dataPackage) || !reflect.DeepEqual(prepared.identity, repeated.identity) {
|
||||
t.Fatalf("prepared package and identity are not deterministic: %q/%#v", prepared.dataPackage, prepared.identity)
|
||||
}
|
||||
|
||||
originalDataPackage := append([]byte(nil), prepared.dataPackage...)
|
||||
originalIdentity := prepared.identity
|
||||
originalDerived := prepared.derived
|
||||
originalWarnings := append([]weatherdata.SourceWarning(nil), prepared.sourceWarnings...)
|
||||
identity, snapshot, derived, err := prepared.renderInputs()
|
||||
if err != nil {
|
||||
t.Fatalf("renderInputs() error = %v", err)
|
||||
}
|
||||
identity.SourceWarnings = append(identity.SourceWarnings, weatherdata.SourceWarning{Source: "test", Message: "consumer mutation"})
|
||||
snapshot.Outputs = nil
|
||||
derived.PrecipTiming.ThunderMentioned = false
|
||||
bundle.Hourly.Periods[0].TextDescription = "mutated after preparation"
|
||||
bundle.Warnings = append(bundle.Warnings, weatherdata.SourceWarning{Source: "test", Message: "mutated warning"})
|
||||
if len(bundle.Sources) > 0 {
|
||||
if bundle.Sources[0].Query == nil {
|
||||
bundle.Sources[0].Query = map[string]string{}
|
||||
}
|
||||
bundle.Sources[0].Query["mutated"] = "true"
|
||||
}
|
||||
|
||||
if !bytes.Equal(prepared.dataPackage, originalDataPackage) || !reflect.DeepEqual(prepared.identity, originalIdentity) || !reflect.DeepEqual(prepared.derived, originalDerived) || !reflect.DeepEqual(prepared.sourceWarnings, originalWarnings) {
|
||||
t.Fatalf("prepared values changed after caller mutation: %#v", prepared)
|
||||
}
|
||||
if len(prepared.moduleSnapshot.Outputs) == 0 {
|
||||
t.Fatal("prepared report values retain consumer mutation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareReportProjectsPreparedIdentity(t *testing.T) {
|
||||
cfg := generationConfig()
|
||||
bundle := generationBundle(t)
|
||||
resolved, err := ResolveGenerate(GenerateRequest{
|
||||
Config: cfg, Report: ReportDaily,
|
||||
Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"),
|
||||
}, generationTime("2026-05-29T08:30:00-05:00"))
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveGenerate() error = %v", err)
|
||||
}
|
||||
prepared, err := prepareReport(prepareReportRequest{Config: cfg, Resolved: resolved, Collection: collect.Result{Bundle: &bundle}, handler: preparedHandler(t, resolved)})
|
||||
if err != nil {
|
||||
t.Fatalf("prepareReport() error = %v", err)
|
||||
}
|
||||
|
||||
identity := prepared.identity
|
||||
renderIdentity, _, _, err := prepared.renderInputs()
|
||||
if err != nil {
|
||||
t.Fatalf("renderInputs() error = %v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(renderIdentity, identity) {
|
||||
t.Fatalf("render identity = %#v, want %#v", renderIdentity, identity)
|
||||
}
|
||||
prompt := promptMetadata(identity)
|
||||
if prompt.RunID != identity.RunID || prompt.ReportID != identity.ReportID || prompt.Variant != identity.Variant || prompt.PromptID != identity.PromptID || !prompt.GeneratedAt.Equal(identity.GeneratedAt) || prompt.Timezone != identity.Timezone || prompt.ValidPeriod != identity.ValidPeriod || !reflect.DeepEqual(prompt.SourceWarnings, identity.SourceWarnings) {
|
||||
t.Fatalf("prompt metadata does not match prepared identity: %#v/%#v", prompt, identity)
|
||||
}
|
||||
|
||||
moduleMetadata, found, err := module.StanzaValue[briefing.MetadataModule](prepared.moduleSnapshot, "metadata")
|
||||
if err != nil || !found {
|
||||
t.Fatalf("metadata stanza = %#v/%t/%v", moduleMetadata, found, err)
|
||||
}
|
||||
if moduleMetadata.RunID != identity.RunID || moduleMetadata.ReportID != identity.ReportID || moduleMetadata.Variant != identity.Variant || moduleMetadata.PromptID != identity.PromptID || !moduleMetadata.GeneratedAt.Equal(identity.GeneratedAt) || moduleMetadata.Units != identity.Units || moduleMetadata.Timezone != identity.Timezone || moduleMetadata.ValidPeriod != identity.ValidPeriod || !reflect.DeepEqual(moduleMetadata.Location, identity.Location) {
|
||||
t.Fatalf("module metadata does not match prepared identity: %#v/%#v", moduleMetadata, identity)
|
||||
}
|
||||
if len(moduleMetadata.SourceWarnings) != len(identity.SourceWarnings) {
|
||||
t.Fatalf("module source warnings = %#v, want %#v", moduleMetadata.SourceWarnings, identity.SourceWarnings)
|
||||
}
|
||||
for index, warning := range identity.SourceWarnings {
|
||||
summary := moduleMetadata.SourceWarnings[index]
|
||||
if summary.Source != warning.Source || summary.Code != warning.Code || summary.Severity != warning.Severity || summary.Message != warning.Message || summary.CompletenessImpact != warning.CompletenessImpact {
|
||||
t.Fatalf("module source warning %d = %#v, want %#v", index, summary, warning)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func preparedHandler(t *testing.T, resolved report.Resolved) generatedtext.Handler {
|
||||
t.Helper()
|
||||
handler, err := generatedtext.LookupDefinition(resolved.Definition)
|
||||
if err != nil {
|
||||
t.Fatalf("LookupDefinition() error = %v", err)
|
||||
}
|
||||
return handler
|
||||
}
|
||||
200
internal/app/profile_execution.go
Normal file
200
internal/app/profile_execution.go
Normal file
@@ -0,0 +1,200 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/generatedtext"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptdebug"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptexec"
|
||||
)
|
||||
|
||||
type profileExecutionRequest struct {
|
||||
Prepared preparedReport
|
||||
Prompt PromptInspectionResult
|
||||
Profile promptexec.ProfileInspection
|
||||
Executor promptexec.Executor
|
||||
DebugWriter *promptdebug.PromptDebugWriter
|
||||
DebugRef *promptdebug.PromptDebugRef
|
||||
}
|
||||
|
||||
type profileExecutionOutcome struct {
|
||||
ProfileID string
|
||||
BackendID string
|
||||
ModelName string
|
||||
ValidationStatus promptexec.ValidationStatus
|
||||
LLMDebugPath string
|
||||
}
|
||||
|
||||
type profileExecutionError struct {
|
||||
operation string
|
||||
err error
|
||||
callbackFailure bool
|
||||
}
|
||||
|
||||
func (e *profileExecutionError) Error() string {
|
||||
return e.operation + ": " + e.err.Error()
|
||||
}
|
||||
|
||||
func (e *profileExecutionError) Unwrap() error {
|
||||
return e.err
|
||||
}
|
||||
|
||||
func executePreparedProfile(ctx context.Context, req profileExecutionRequest) (profileExecutionOutcome, []byte, error) {
|
||||
outcome := profileExecutionOutcome{
|
||||
ProfileID: req.Profile.ProfileID,
|
||||
BackendID: req.Profile.BackendID,
|
||||
ModelName: req.Profile.ModelName,
|
||||
}
|
||||
if req.Executor == nil {
|
||||
return outcome, nil, &profileExecutionError{operation: "execute prompt", err: promptexec.NewError(promptexec.InvalidConfiguration, "prompt executor is required", nil)}
|
||||
}
|
||||
if err := validatePreparedExecutionRequest(req); err != nil {
|
||||
return outcome, nil, &profileExecutionError{operation: "validate prompt provenance", err: err}
|
||||
}
|
||||
|
||||
callbackFailed := false
|
||||
preparationCount := 0
|
||||
var preparation promptexec.Preparation
|
||||
preparationCallback := func(value promptexec.Preparation, debug *promptexec.PreparationDebug) error {
|
||||
preparationCount++
|
||||
if preparationCount != 1 {
|
||||
return promptProvenanceError()
|
||||
}
|
||||
if err := validatePreparationProvenance(req, value); err != nil {
|
||||
return err
|
||||
}
|
||||
preparation = clonePreparation(value)
|
||||
if req.DebugWriter == nil || !req.DebugWriter.Enabled() {
|
||||
return nil
|
||||
}
|
||||
if req.DebugRef == nil {
|
||||
callbackFailed = true
|
||||
return promptDebugWriteError(fmt.Errorf("prompt debug reference is required"))
|
||||
}
|
||||
path, err := req.DebugWriter.WritePreparation(*req.DebugRef, value, debug)
|
||||
if err != nil {
|
||||
callbackFailed = true
|
||||
return promptDebugWriteError(err)
|
||||
}
|
||||
outcome.LLMDebugPath = path
|
||||
return nil
|
||||
}
|
||||
|
||||
captureDebug := req.DebugWriter != nil && req.DebugWriter.Enabled()
|
||||
execution, err := req.Executor.Execute(ctx, promptexec.ExecuteRequest{
|
||||
PromptID: req.Prompt.PromptID,
|
||||
PromptVersion: req.Prompt.PromptVersion,
|
||||
ProfileID: req.Profile.ProfileID,
|
||||
DataPackage: req.Prepared.dataPackageCopy(),
|
||||
CaptureDebug: captureDebug,
|
||||
}, preparationCallback)
|
||||
if err != nil {
|
||||
if callbackFailed {
|
||||
return outcome, nil, &profileExecutionError{operation: "execute prompt", err: err, callbackFailure: true}
|
||||
}
|
||||
return outcome, nil, &profileExecutionError{operation: "execute prompt", err: classifiedPromptError("prompt execution failed", err)}
|
||||
}
|
||||
if execution == nil {
|
||||
return outcome, nil, &profileExecutionError{operation: "execute prompt", err: promptexec.NewError(promptexec.Generation, "prompt executor returned no execution", nil)}
|
||||
}
|
||||
if preparationCount != 1 {
|
||||
return outcome, nil, &profileExecutionError{operation: "validate prompt provenance", err: promptProvenanceError()}
|
||||
}
|
||||
if err := validateExecutionProvenance(req, preparation, *execution); err != nil {
|
||||
return outcome, nil, &profileExecutionError{operation: "validate prompt provenance", err: err}
|
||||
}
|
||||
outcome.ValidationStatus = execution.Validation.Status
|
||||
if err := generatedtext.ValidateRawOutput(execution.RawOutput); err != nil {
|
||||
return outcome, nil, &profileExecutionError{operation: "validate generated text", err: err}
|
||||
}
|
||||
if req.DebugWriter != nil && req.DebugWriter.Enabled() {
|
||||
if req.DebugRef == nil {
|
||||
return outcome, nil, &profileExecutionError{operation: "write prompt debug", err: promptDebugWriteError(fmt.Errorf("prompt debug reference is required"))}
|
||||
}
|
||||
path, err := req.DebugWriter.WriteExecution(*req.DebugRef, *execution)
|
||||
if err != nil {
|
||||
return outcome, nil, &profileExecutionError{operation: "write prompt debug", err: promptDebugWriteError(err)}
|
||||
}
|
||||
if path != "" {
|
||||
outcome.LLMDebugPath = path
|
||||
}
|
||||
}
|
||||
|
||||
if execution.Validation.Status != promptexec.ValidationPassed && execution.Validation.Status != promptexec.ValidationFailed {
|
||||
return outcome, nil, &profileExecutionError{operation: "validate prompt execution", err: promptexec.NewError(promptexec.OperationalValidation, "prompt execution did not complete validation", nil)}
|
||||
}
|
||||
if execution.Validation.Status == promptexec.ValidationFailed {
|
||||
return outcome, nil, &profileExecutionError{operation: "validate prompt execution", err: promptexec.NewError(promptexec.ValidationRejected, "prompt output did not satisfy its schema", nil)}
|
||||
}
|
||||
|
||||
generatedText, err := req.Prepared.handler.Validate(execution.RawOutput)
|
||||
if err != nil {
|
||||
return outcome, nil, &profileExecutionError{operation: "validate generated text", err: err}
|
||||
}
|
||||
identity, snapshot, derived, err := req.Prepared.renderInputs()
|
||||
if err != nil {
|
||||
return outcome, nil, &profileExecutionError{operation: "copy prepared render inputs", err: err}
|
||||
}
|
||||
renderContext, err := req.Prepared.handler.BuildRenderContext(identity, snapshot, derived, generatedText)
|
||||
if err != nil {
|
||||
return outcome, nil, &profileExecutionError{operation: "build render context", err: err}
|
||||
}
|
||||
rendered, err := req.Prepared.handler.Render(renderContext)
|
||||
if err != nil {
|
||||
return outcome, nil, &profileExecutionError{operation: "render template", err: err}
|
||||
}
|
||||
return outcome, rendered, nil
|
||||
}
|
||||
|
||||
func validatePreparedExecutionRequest(req profileExecutionRequest) error {
|
||||
definition := req.Prepared.resolved.Definition
|
||||
if definition.PromptID != req.Prompt.PromptID || definition.PromptVersion != req.Prompt.PromptVersion ||
|
||||
definition.GeneratedTextSchemaID != req.Prepared.handler.SchemaID() {
|
||||
return promptProvenanceError()
|
||||
}
|
||||
if req.Prompt.ProfileID != "" && (req.Prompt.ProfileID != req.Profile.ProfileID || req.Prompt.BackendID != req.Profile.BackendID || req.Prompt.ModelName != req.Profile.ModelName) {
|
||||
return promptProvenanceError()
|
||||
}
|
||||
if req.Prompt.PromptHash == "" || req.Profile.ProfileID == "" || req.Profile.BackendID == "" || req.Profile.ModelName == "" {
|
||||
return promptProvenanceError()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validatePreparationProvenance(req profileExecutionRequest, preparation promptexec.Preparation) error {
|
||||
definition := req.Prepared.resolved.Definition
|
||||
if preparation.PromptID != req.Prompt.PromptID || preparation.PromptVersion != req.Prompt.PromptVersion || preparation.PromptHash != req.Prompt.PromptHash ||
|
||||
preparation.ProfileID != req.Profile.ProfileID || preparation.BackendID != req.Profile.BackendID || preparation.ModelName != req.Profile.ModelName ||
|
||||
!validPromptOutput(definition, preparation.Output) {
|
||||
return promptProvenanceError()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateExecutionProvenance(req profileExecutionRequest, preparation promptexec.Preparation, execution promptexec.Execution) error {
|
||||
definition := req.Prepared.resolved.Definition
|
||||
if execution.PromptID != preparation.PromptID || execution.PromptVersion != preparation.PromptVersion || execution.PromptHash != preparation.PromptHash ||
|
||||
execution.RenderedPromptHash != preparation.RenderedPromptHash || !reflect.DeepEqual(execution.InputHashes, preparation.InputHashes) ||
|
||||
execution.ProfileID != preparation.ProfileID || execution.BackendID != preparation.BackendID || execution.ModelName != preparation.ModelName ||
|
||||
execution.Validation.Mode != "json_schema" || execution.Validation.SchemaPath != definition.GeneratedTextSchemaID+".generated_text.schema.json" {
|
||||
return promptProvenanceError()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func promptProvenanceError() error {
|
||||
return promptexec.NewError(promptexec.InvalidConfiguration, "prompt execution provenance is inconsistent", nil)
|
||||
}
|
||||
|
||||
func clonePreparation(value promptexec.Preparation) promptexec.Preparation {
|
||||
if value.InputHashes != nil {
|
||||
inputHashes := make(map[string]string, len(value.InputHashes))
|
||||
for name, hash := range value.InputHashes {
|
||||
inputHashes[name] = hash
|
||||
}
|
||||
value.InputHashes = inputHashes
|
||||
}
|
||||
return value
|
||||
}
|
||||
176
internal/app/profile_execution_test.go
Normal file
176
internal/app/profile_execution_test.go
Normal file
@@ -0,0 +1,176 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/collect"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/generatedtext"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptdebug"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptexec"
|
||||
)
|
||||
|
||||
func TestExecutePreparedProfileRendersWithoutPublishing(t *testing.T) {
|
||||
prepared, inspection := preparedDailyProfile(t)
|
||||
executor := &generationExecutor{}
|
||||
outputPath := filepath.Join(t.TempDir(), "report.md")
|
||||
outcome, rendered, err := executePreparedProfile(context.Background(), profileExecutionRequest{
|
||||
Prepared: prepared, Prompt: inspection,
|
||||
Profile: promptexec.ProfileInspection{ProfileID: inspection.ProfileID, BackendID: inspection.BackendID, ModelName: inspection.ModelName},
|
||||
Executor: executor,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("executePreparedProfile() error = %v", err)
|
||||
}
|
||||
if len(rendered) == 0 || outcome.ValidationStatus != promptexec.ValidationPassed || outcome.ProfileID != inspection.ProfileID || executor.executeCalls != 1 {
|
||||
t.Fatalf("outcome/rendered/execution calls = %#v/%q/%d", outcome, rendered, executor.executeCalls)
|
||||
}
|
||||
if _, statErr := os.Stat(outputPath); !os.IsNotExist(statErr) {
|
||||
t.Fatalf("execution unexpectedly published %q: %v", outputPath, statErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutePreparedProfileKeepsDebugCallbackFailureLocal(t *testing.T) {
|
||||
prepared, inspection := preparedDailyProfile(t)
|
||||
debugWriter, err := promptdebug.NewPromptDebugWriter(t.TempDir())
|
||||
if errors.Is(err, promptdebug.ErrSecureCaptureUnsupported) {
|
||||
t.Skipf("secure prompt debug capture is unavailable: %v", err)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("NewPromptDebugWriter() error = %v", err)
|
||||
}
|
||||
executor := &generationExecutor{}
|
||||
outcome, rendered, err := executePreparedProfile(context.Background(), profileExecutionRequest{
|
||||
Prepared: prepared, Prompt: inspection,
|
||||
Profile: promptexec.ProfileInspection{ProfileID: inspection.ProfileID, BackendID: inspection.BackendID, ModelName: inspection.ModelName},
|
||||
Executor: executor, DebugWriter: debugWriter,
|
||||
DebugRef: &promptdebug.PromptDebugRef{ReportID: inspectionResolved(t).Definition.ID, ValidDate: "2026-05-29", RunID: "invalid/path"},
|
||||
})
|
||||
var executionErr *profileExecutionError
|
||||
if err == nil || !errors.As(err, &executionErr) || !executionErr.callbackFailure || promptexec.CategoryOf(err) != promptexec.InvalidConfiguration || len(rendered) != 0 || executor.executeCalls != 0 || outcome.LLMDebugPath != "" {
|
||||
t.Fatalf("outcome/rendered/error/execution calls = %#v/%q/%v/%d", outcome, rendered, err, executor.executeCalls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutePreparedProfileBoundsOversizedExecutorOutput(t *testing.T) {
|
||||
prepared, inspection := preparedDailyProfile(t)
|
||||
marker := "provider-controlled-marker"
|
||||
executor := &generationExecutor{rawOutput: []byte(strings.Repeat("x", generatedtext.MaxGeneratedTextBytes+1) + marker)}
|
||||
_, _, err := executePreparedProfile(context.Background(), profileExecutionRequest{
|
||||
Prepared: prepared, Prompt: inspection,
|
||||
Profile: promptexec.ProfileInspection{ProfileID: inspection.ProfileID, BackendID: inspection.BackendID, ModelName: inspection.ModelName},
|
||||
Executor: executor,
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "65536-byte limit") {
|
||||
t.Fatalf("executePreparedProfile() error = %v, want bounded raw size error", err)
|
||||
}
|
||||
if len(err.Error()) > 160 || strings.Contains(err.Error(), marker) {
|
||||
t.Fatalf("ordinary error leaked provider content: %q", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutePreparedProfileRejectsInconsistentProvenance(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mutate func(*preparedReport, *PromptInspectionResult, *promptexec.ProfileInspection, *generationExecutor)
|
||||
invoked bool
|
||||
}{
|
||||
{
|
||||
name: "prepared definition", mutate: func(prepared *preparedReport, _ *PromptInspectionResult, _ *promptexec.ProfileInspection, _ *generationExecutor) {
|
||||
prepared.resolved.Definition.PromptVersion = "different-version"
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "missing callback", mutate: func(_ *preparedReport, _ *PromptInspectionResult, _ *promptexec.ProfileInspection, executor *generationExecutor) {
|
||||
executor.skipPreparation = true
|
||||
}, invoked: true,
|
||||
},
|
||||
{
|
||||
name: "duplicate callback", mutate: func(_ *preparedReport, _ *PromptInspectionResult, _ *promptexec.ProfileInspection, executor *generationExecutor) {
|
||||
executor.preparationCalls = 2
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "callback prompt hash", mutate: func(_ *preparedReport, _ *PromptInspectionResult, _ *promptexec.ProfileInspection, executor *generationExecutor) {
|
||||
executor.prepare = func(value *promptexec.Preparation) { value.PromptHash = "different-hash" }
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "callback output schema", mutate: func(_ *preparedReport, _ *PromptInspectionResult, _ *promptexec.ProfileInspection, executor *generationExecutor) {
|
||||
executor.prepare = func(value *promptexec.Preparation) { value.Output.SchemaPath = "other.generated_text.schema.json" }
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "completed profile", mutate: func(_ *preparedReport, _ *PromptInspectionResult, _ *promptexec.ProfileInspection, executor *generationExecutor) {
|
||||
executor.complete = func(value *promptexec.Execution) { value.ProfileID = "different-profile" }
|
||||
}, invoked: true,
|
||||
},
|
||||
{
|
||||
name: "completed rendered prompt hash", mutate: func(_ *preparedReport, _ *PromptInspectionResult, _ *promptexec.ProfileInspection, executor *generationExecutor) {
|
||||
executor.complete = func(value *promptexec.Execution) { value.RenderedPromptHash = "different-rendered-hash" }
|
||||
}, invoked: true,
|
||||
},
|
||||
{
|
||||
name: "completed input hashes", mutate: func(_ *preparedReport, _ *PromptInspectionResult, _ *promptexec.ProfileInspection, executor *generationExecutor) {
|
||||
executor.prepare = func(value *promptexec.Preparation) {
|
||||
value.InputHashes = map[string]string{"data_package": "prepared-hash"}
|
||||
}
|
||||
executor.complete = func(value *promptexec.Execution) {
|
||||
value.InputHashes = map[string]string{"data_package": "completed-hash"}
|
||||
}
|
||||
}, invoked: true,
|
||||
},
|
||||
{
|
||||
name: "completed validation mode", mutate: func(_ *preparedReport, _ *PromptInspectionResult, _ *promptexec.ProfileInspection, executor *generationExecutor) {
|
||||
executor.complete = func(value *promptexec.Execution) { value.Validation.Mode = "other" }
|
||||
}, invoked: true,
|
||||
},
|
||||
{
|
||||
name: "completed validation schema", mutate: func(_ *preparedReport, _ *PromptInspectionResult, _ *promptexec.ProfileInspection, executor *generationExecutor) {
|
||||
executor.complete = func(value *promptexec.Execution) { value.Validation.SchemaPath = "other.generated_text.schema.json" }
|
||||
}, invoked: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
prepared, inspection := preparedDailyProfile(t)
|
||||
profile := promptexec.ProfileInspection{ProfileID: inspection.ProfileID, BackendID: inspection.BackendID, ModelName: inspection.ModelName}
|
||||
executor := &generationExecutor{}
|
||||
tt.mutate(&prepared, &inspection, &profile, executor)
|
||||
|
||||
outcome, rendered, err := executePreparedProfile(context.Background(), profileExecutionRequest{Prepared: prepared, Prompt: inspection, Profile: profile, Executor: executor})
|
||||
if err == nil || promptexec.CategoryOf(err) != promptexec.InvalidConfiguration || len(rendered) != 0 {
|
||||
t.Fatalf("outcome/rendered/error = %#v/%q/%v", outcome, rendered, err)
|
||||
}
|
||||
if outcome.ProfileID != profile.ProfileID || outcome.BackendID != profile.BackendID || outcome.ModelName != profile.ModelName || outcome.ValidationStatus != "" {
|
||||
t.Fatalf("outcome retained unverified provenance: %#v", outcome)
|
||||
}
|
||||
if (executor.executeCalls == 1) != tt.invoked {
|
||||
t.Fatalf("executor calls = %d, want invoked=%t", executor.executeCalls, tt.invoked)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func preparedDailyProfile(t *testing.T) (preparedReport, PromptInspectionResult) {
|
||||
t.Helper()
|
||||
cfg := generationConfig()
|
||||
resolved, err := ResolveGenerate(GenerateRequest{
|
||||
Config: cfg, Report: ReportDaily,
|
||||
Date: generationTime("2026-05-29T12:00:00-05:00"), Now: generationTime("2026-05-29T08:30:00-05:00"),
|
||||
}, generationTime("2026-05-29T08:30:00-05:00"))
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveGenerate() error = %v", err)
|
||||
}
|
||||
bundle := generationBundle(t)
|
||||
prepared, err := prepareReport(prepareReportRequest{Config: cfg, Resolved: resolved, Collection: collect.Result{Bundle: &bundle}, handler: preparedHandler(t, resolved)})
|
||||
if err != nil {
|
||||
t.Fatalf("prepareReport() error = %v", err)
|
||||
}
|
||||
return prepared, PromptInspectionResult{PromptID: resolved.Definition.PromptID, PromptVersion: resolved.Definition.PromptVersion, PromptHash: generationPromptHash, ProfileID: "fixture", BackendID: "fixture", ModelName: "fixture-model"}
|
||||
}
|
||||
145
internal/app/prompt_generate.go
Normal file
145
internal/app/prompt_generate.go
Normal file
@@ -0,0 +1,145 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/collect"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/fileutil"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptdebug"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptexec"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/report"
|
||||
)
|
||||
|
||||
type promptReportRequest struct {
|
||||
GenerateRequest
|
||||
Resolved report.Resolved
|
||||
Collection collect.Result
|
||||
Inspection PromptInspectionResult
|
||||
DebugWriter *promptdebug.PromptDebugWriter
|
||||
Result *ReportResult
|
||||
noNotify bool
|
||||
}
|
||||
|
||||
func generatePromptReport(ctx context.Context, req promptReportRequest) (*ReportResult, error) {
|
||||
if req.Collection.Bundle == nil {
|
||||
return nil, fmt.Errorf("collected weather bundle is required")
|
||||
}
|
||||
result := req.Result
|
||||
if result == nil {
|
||||
result = initialReportResult(req.GenerateRequest, req.Resolved, req.Inspection)
|
||||
}
|
||||
prepared, err := prepareReport(prepareReportRequest{Config: req.Config, Resolved: req.Resolved, Collection: req.Collection, handler: req.Inspection.handler})
|
||||
if err != nil {
|
||||
return result, generatedPreparationError(req.Resolved, result.RunID, err)
|
||||
}
|
||||
result.SourceWarnings = prepared.sourceWarningsCopy()
|
||||
debugRef := promptdebug.PromptDebugRef{ReportID: result.ReportID, ValidDate: prepared.resolved.ValidPeriod.Start.Format("2006-01-02"), RunID: result.RunID}
|
||||
outcome, rendered, err := executePreparedProfile(ctx, profileExecutionRequest{
|
||||
Prepared: prepared,
|
||||
Prompt: req.Inspection,
|
||||
Profile: promptexec.ProfileInspection{
|
||||
ProfileID: req.Inspection.ProfileID,
|
||||
BackendID: req.Inspection.BackendID,
|
||||
ModelName: req.Inspection.ModelName,
|
||||
},
|
||||
Executor: req.Executor, DebugWriter: req.DebugWriter, DebugRef: &debugRef,
|
||||
})
|
||||
result.ProfileID, result.BackendID, result.ModelName = outcome.ProfileID, outcome.BackendID, outcome.ModelName
|
||||
result.ValidationStatus = outcome.ValidationStatus
|
||||
result.LLMDebugPath = outcome.LLMDebugPath
|
||||
if err != nil {
|
||||
return result, generatedProfileExecutionError(req.Resolved, result.RunID, err)
|
||||
}
|
||||
return publishPromptReport(ctx, promptPublicationRequest{
|
||||
GenerateRequest: req.GenerateRequest,
|
||||
Resolved: req.Resolved,
|
||||
OutputPath: req.OutputPath,
|
||||
Result: result,
|
||||
Markdown: rendered,
|
||||
suppressNotification: req.noNotify,
|
||||
})
|
||||
}
|
||||
|
||||
func initialReportResult(req GenerateRequest, resolved report.Resolved, inspection PromptInspectionResult) *ReportResult {
|
||||
metadata := resolved.Metadata()
|
||||
return &ReportResult{
|
||||
ReportID: resolved.Definition.ID, ReportName: resolved.Definition.Name,
|
||||
PromptID: resolved.Definition.PromptID, PromptVersion: resolved.Definition.PromptVersion,
|
||||
RunID: metadata.RunID, GeneratedAt: metadata.GeneratedAt, Timezone: req.Config.WeatherAPI.Timezone,
|
||||
ValidPeriod: metadata.ValidPeriod,
|
||||
ProfileID: inspection.ProfileID, BackendID: inspection.BackendID, ModelName: inspection.ModelName,
|
||||
}
|
||||
}
|
||||
|
||||
type promptPublicationRequest struct {
|
||||
GenerateRequest
|
||||
Resolved report.Resolved
|
||||
OutputPath string
|
||||
Result *ReportResult
|
||||
Markdown []byte
|
||||
suppressNotification bool
|
||||
}
|
||||
|
||||
func publishPromptReport(ctx context.Context, req promptPublicationRequest) (*ReportResult, error) {
|
||||
if err := publicationContextError(ctx); err != nil {
|
||||
return req.Result, generatedReportError(req.Resolved, req.Result.RunID, "publish report", err)
|
||||
}
|
||||
if err := fileutil.WriteFileAtomicContext(ctx, req.OutputPath, req.Markdown); err != nil {
|
||||
if contextErr := publicationContextError(ctx); contextErr != nil {
|
||||
return req.Result, generatedReportError(req.Resolved, req.Result.RunID, "publish report", contextErr)
|
||||
}
|
||||
return req.Result, err
|
||||
}
|
||||
req.Result.OutputPath = req.OutputPath
|
||||
if req.suppressNotification {
|
||||
return req.Result, nil
|
||||
}
|
||||
notification, err := notifyReport(ctx, req.Config, req.Resolved, req.Result.OutputPath, req.Result.RunID, req.Result.GeneratedAt, req.Notifier)
|
||||
req.Result.Notification = notification
|
||||
if err != nil {
|
||||
return req.Result, err
|
||||
}
|
||||
return req.Result, nil
|
||||
}
|
||||
|
||||
func generatedPreparationError(resolved report.Resolved, runID string, err error) error {
|
||||
var preparation *preparationError
|
||||
if errors.As(err, &preparation) {
|
||||
return generatedReportError(resolved, runID, preparation.operation, preparation.err)
|
||||
}
|
||||
return generatedReportError(resolved, runID, "prepare report", err)
|
||||
}
|
||||
|
||||
func generatedProfileExecutionError(resolved report.Resolved, runID string, err error) error {
|
||||
var execution *profileExecutionError
|
||||
if errors.As(err, &execution) {
|
||||
if execution.callbackFailure {
|
||||
return execution.err
|
||||
}
|
||||
return generatedReportError(resolved, runID, execution.operation, execution.err)
|
||||
}
|
||||
return generatedReportError(resolved, runID, "execute prompt", err)
|
||||
}
|
||||
|
||||
func classifiedPromptError(operation string, err error) error {
|
||||
if promptexec.CategoryOf(err) != "" {
|
||||
return err
|
||||
}
|
||||
return promptexec.NewError(promptexec.Generation, operation, err)
|
||||
}
|
||||
|
||||
func publicationContextError(ctx context.Context) error {
|
||||
if err := ctx.Err(); err != nil {
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return promptexec.NewError(promptexec.DeadlineExceeded, "context expired before output publication", err)
|
||||
}
|
||||
return promptexec.NewError(promptexec.Canceled, "context canceled before output publication", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func promptDebugWriteError(err error) error {
|
||||
return promptexec.NewError(promptexec.InvalidConfiguration, "write requested prompt debug artifact", err)
|
||||
}
|
||||
240
internal/app/prompt_inspection.go
Normal file
240
internal/app/prompt_inspection.go
Normal file
@@ -0,0 +1,240 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/comparison"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/config"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/generatedtext"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptexec"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/report"
|
||||
)
|
||||
|
||||
// PromptInspectionRequest contains the non-executing inputs required to
|
||||
// validate one report's configured prompt and profile.
|
||||
type PromptInspectionRequest struct {
|
||||
Resolved report.Resolved
|
||||
Executor promptexec.Executor
|
||||
Promptkit config.PromptkitConfig
|
||||
LookupEnv func(string) (string, bool)
|
||||
}
|
||||
|
||||
// PromptInspectionResult contains only safe identity and provenance from a
|
||||
// prompt/profile inspection.
|
||||
type PromptInspectionResult struct {
|
||||
PromptID string
|
||||
PromptVersion string
|
||||
PromptHash string
|
||||
ProfileID string
|
||||
BackendID string
|
||||
ModelName string
|
||||
handler generatedtext.Handler
|
||||
}
|
||||
|
||||
// PromptExecutionsInspectionRequest validates all prompt/profile combinations
|
||||
// needed by a batch before collection begins.
|
||||
type PromptExecutionsInspectionRequest struct {
|
||||
Resolved []report.Resolved
|
||||
Executor promptexec.Executor
|
||||
Promptkit config.PromptkitConfig
|
||||
LookupEnv func(string) (string, bool)
|
||||
}
|
||||
|
||||
// ComparisonInspectionRequest contains the explicit profile selection for one
|
||||
// resolved prompt comparison. It intentionally has no configured profile field.
|
||||
type ComparisonInspectionRequest struct {
|
||||
Resolved report.Resolved
|
||||
ProfileIDs []string
|
||||
Executor promptexec.Executor
|
||||
LookupEnv func(string) (string, bool)
|
||||
}
|
||||
|
||||
// ComparisonInspectionResult contains the safe, shared prompt identity and
|
||||
// ordered effective profile identities for a comparison.
|
||||
type ComparisonInspectionResult struct {
|
||||
PromptID string
|
||||
PromptVersion string
|
||||
PromptHash string
|
||||
Profiles []ComparisonProfileInspection
|
||||
handler generatedtext.Handler
|
||||
}
|
||||
|
||||
// ComparisonProfileInspection contains one requested profile's safe effective
|
||||
// execution identity.
|
||||
type ComparisonProfileInspection struct {
|
||||
ProfileID string
|
||||
BackendID string
|
||||
ModelName string
|
||||
}
|
||||
|
||||
// InspectPromptExecution validates the exact prompt and profile needed for a
|
||||
// report before collection, execution, or durable writes begin.
|
||||
func InspectPromptExecution(ctx context.Context, req PromptInspectionRequest) (PromptInspectionResult, error) {
|
||||
results, err := InspectPromptExecutions(ctx, PromptExecutionsInspectionRequest{
|
||||
Resolved: []report.Resolved{req.Resolved},
|
||||
Executor: req.Executor,
|
||||
Promptkit: req.Promptkit,
|
||||
LookupEnv: req.LookupEnv,
|
||||
})
|
||||
if err != nil {
|
||||
return PromptInspectionResult{}, err
|
||||
}
|
||||
return results[req.Resolved.Definition.ID], nil
|
||||
}
|
||||
|
||||
// InspectPromptExecutions validates exact prompt contracts and their unique
|
||||
// effective profiles. It performs no collection, execution, or durable write.
|
||||
func InspectPromptExecutions(ctx context.Context, req PromptExecutionsInspectionRequest) (map[report.ID]PromptInspectionResult, error) {
|
||||
if req.Executor == nil {
|
||||
return nil, promptexec.NewError(promptexec.InvalidConfiguration, "prompt executor is required", nil)
|
||||
}
|
||||
results := make(map[report.ID]PromptInspectionResult, len(req.Resolved))
|
||||
profiles := map[string]promptexec.ProfileInspection{}
|
||||
for _, resolved := range req.Resolved {
|
||||
definition := resolved.Definition
|
||||
handler, err := generatedtext.LookupDefinition(definition)
|
||||
if err != nil {
|
||||
return nil, promptexec.NewError(promptexec.InvalidConfiguration, "report generated-text catalog is incompatible", err)
|
||||
}
|
||||
inspection, err := inspectPromptContract(ctx, req.Executor, definition)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
profileID := req.Promptkit.Profile
|
||||
if profileID == "" {
|
||||
profileID = inspection.DefaultProfileID
|
||||
}
|
||||
if strings.TrimSpace(profileID) == "" {
|
||||
return nil, promptexec.NewError(promptexec.InvalidConfiguration, "prompt has no execution profile", nil)
|
||||
}
|
||||
profile, ok := profiles[profileID]
|
||||
if !ok {
|
||||
profile, err = inspectPromptProfile(ctx, req.Executor, profileID, req.LookupEnv)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
profiles[profileID] = profile
|
||||
}
|
||||
results[definition.ID] = PromptInspectionResult{
|
||||
PromptID: inspection.PromptID, PromptVersion: inspection.PromptVersion, PromptHash: inspection.PromptHash,
|
||||
ProfileID: profile.ProfileID, BackendID: profile.BackendID, ModelName: profile.ModelName,
|
||||
handler: handler,
|
||||
}
|
||||
}
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// InspectComparisonExecution validates one exact prompt and every explicitly
|
||||
// requested profile before collection or model execution. Profiles are
|
||||
// inspected sequentially in request order. If a profile fails, the returned
|
||||
// partial result retains the prompt identity and successfully inspected prefix.
|
||||
func InspectComparisonExecution(ctx context.Context, req ComparisonInspectionRequest) (ComparisonInspectionResult, error) {
|
||||
if err := comparison.ValidateProfileIDs(req.ProfileIDs); err != nil {
|
||||
return ComparisonInspectionResult{}, promptexec.NewError(promptexec.InvalidRequest, "comparison profile selection is invalid", err)
|
||||
}
|
||||
if req.Executor == nil {
|
||||
return ComparisonInspectionResult{}, promptexec.NewError(promptexec.InvalidConfiguration, "prompt executor is required", nil)
|
||||
}
|
||||
|
||||
handler, err := generatedtext.LookupDefinition(req.Resolved.Definition)
|
||||
if err != nil {
|
||||
return ComparisonInspectionResult{}, comparisonInspectionError("comparison generated-text catalog inspection failed", promptexec.NewError(promptexec.InvalidConfiguration, "report generated-text catalog is incompatible", err))
|
||||
}
|
||||
inspection, err := inspectPromptContract(ctx, req.Executor, req.Resolved.Definition)
|
||||
if err != nil {
|
||||
return ComparisonInspectionResult{}, comparisonInspectionError("comparison prompt inspection failed", err)
|
||||
}
|
||||
result := ComparisonInspectionResult{
|
||||
PromptID: inspection.PromptID,
|
||||
PromptVersion: inspection.PromptVersion,
|
||||
PromptHash: inspection.PromptHash,
|
||||
Profiles: make([]ComparisonProfileInspection, 0, len(req.ProfileIDs)),
|
||||
handler: handler,
|
||||
}
|
||||
for _, profileID := range req.ProfileIDs {
|
||||
profile, err := inspectPromptProfile(ctx, req.Executor, profileID, req.LookupEnv)
|
||||
if err != nil {
|
||||
return result, comparisonInspectionError("comparison profile inspection failed", err)
|
||||
}
|
||||
result.Profiles = append(result.Profiles, ComparisonProfileInspection{
|
||||
ProfileID: profile.ProfileID,
|
||||
BackendID: profile.BackendID,
|
||||
ModelName: profile.ModelName,
|
||||
})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func inspectPromptContract(ctx context.Context, executor promptexec.Executor, definition report.Definition) (promptexec.PromptInspection, error) {
|
||||
if strings.TrimSpace(definition.PromptID) == "" || strings.TrimSpace(definition.PromptVersion) == "" {
|
||||
return promptexec.PromptInspection{}, promptexec.NewError(promptexec.InvalidConfiguration, "report prompt identity is incomplete", nil)
|
||||
}
|
||||
inspection, err := executor.InspectPrompt(ctx, definition.PromptID, definition.PromptVersion)
|
||||
if err != nil {
|
||||
return promptexec.PromptInspection{}, promptInspectionError("prompt inspection failed", err)
|
||||
}
|
||||
if inspection.PromptID != definition.PromptID || inspection.PromptVersion != definition.PromptVersion {
|
||||
return promptexec.PromptInspection{}, promptexec.NewError(promptexec.InvalidConfiguration, "prompt inspection did not return the requested prompt version", nil)
|
||||
}
|
||||
if strings.TrimSpace(inspection.PromptHash) == "" {
|
||||
return promptexec.PromptInspection{}, promptexec.NewError(promptexec.InvalidConfiguration, "prompt inspection did not return a prompt hash", nil)
|
||||
}
|
||||
if !validPromptInput(inspection.Inputs) {
|
||||
return promptexec.PromptInspection{}, promptexec.NewError(promptexec.InvalidConfiguration, "prompt must declare exactly one required application/yaml data_package input", nil)
|
||||
}
|
||||
if !validPromptOutput(definition, inspection.Output) {
|
||||
return promptexec.PromptInspection{}, promptexec.NewError(promptexec.InvalidConfiguration, "prompt must declare the report JSON Schema output contract", nil)
|
||||
}
|
||||
return inspection, nil
|
||||
}
|
||||
|
||||
func inspectPromptProfile(ctx context.Context, executor promptexec.Executor, profileID string, lookupEnv func(string) (string, bool)) (promptexec.ProfileInspection, error) {
|
||||
profile, err := executor.InspectProfile(ctx, profileID)
|
||||
if err != nil {
|
||||
return promptexec.ProfileInspection{}, promptInspectionError("profile inspection failed", err)
|
||||
}
|
||||
if profile.ProfileID != profileID {
|
||||
return promptexec.ProfileInspection{}, promptexec.NewError(promptexec.InvalidConfiguration, "profile inspection did not return the selected profile", nil)
|
||||
}
|
||||
if profile.CredentialRequired {
|
||||
return promptexec.ProfileInspection{}, promptexec.NewError(promptexec.MissingCredential, "selected profile requires an unsupported direct API key", nil)
|
||||
}
|
||||
if strings.TrimSpace(profile.APIKeyEnv) != "" {
|
||||
if lookupEnv == nil {
|
||||
lookupEnv = os.LookupEnv
|
||||
}
|
||||
value, present := lookupEnv(profile.APIKeyEnv)
|
||||
if !present || strings.TrimSpace(value) == "" {
|
||||
return promptexec.ProfileInspection{}, promptexec.NewError(promptexec.MissingCredential, "selected profile credential is unavailable", nil)
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(profile.BackendID) == "" || strings.TrimSpace(profile.ModelName) == "" {
|
||||
return promptexec.ProfileInspection{}, promptexec.NewError(promptexec.InvalidConfiguration, "profile inspection did not return a complete execution identity", nil)
|
||||
}
|
||||
return profile, nil
|
||||
}
|
||||
|
||||
func validPromptInput(inputs []promptexec.InputDefinition) bool {
|
||||
return len(inputs) == 1 && inputs[0].Name == "data_package" && inputs[0].Required && inputs[0].ContentType == "application/yaml"
|
||||
}
|
||||
|
||||
func validPromptOutput(definition report.Definition, output promptexec.OutputContract) bool {
|
||||
return output.Format == "json" && output.ValidationMode == "json_schema" && output.SchemaPath == definition.GeneratedTextSchemaID+".generated_text.schema.json"
|
||||
}
|
||||
|
||||
func promptInspectionError(operation string, err error) error {
|
||||
if promptexec.CategoryOf(err) != "" {
|
||||
return err
|
||||
}
|
||||
return promptexec.NewError(promptexec.InvalidConfiguration, operation, err)
|
||||
}
|
||||
|
||||
func comparisonInspectionError(operation string, err error) error {
|
||||
category := promptexec.CategoryOf(err)
|
||||
if category == "" {
|
||||
category = promptexec.InvalidConfiguration
|
||||
}
|
||||
return promptexec.NewError(category, operation, err)
|
||||
}
|
||||
374
internal/app/prompt_inspection_test.go
Normal file
374
internal/app/prompt_inspection_test.go
Normal file
@@ -0,0 +1,374 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/config"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/promptexec"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/report"
|
||||
)
|
||||
|
||||
func TestInspectPromptExecutionSelectsDefaultAndOverrideProfiles(t *testing.T) {
|
||||
resolved := inspectionResolved(t)
|
||||
executor := &inspectionExecutor{
|
||||
prompt: validPromptInspection(resolved.Definition),
|
||||
profiles: map[string]promptexec.ProfileInspection{
|
||||
"default-profile": {ProfileID: "default-profile", BackendID: "local", ModelName: "default-model"},
|
||||
"override-profile": {ProfileID: "override-profile", BackendID: "cloud", ModelName: "override-model"},
|
||||
},
|
||||
}
|
||||
defaultResult, err := InspectPromptExecution(context.Background(), PromptInspectionRequest{Resolved: resolved, Executor: executor})
|
||||
if err != nil {
|
||||
t.Fatalf("InspectPromptExecution(default) error = %v", err)
|
||||
}
|
||||
if defaultResult.ProfileID != "default-profile" || defaultResult.ModelName != "default-model" {
|
||||
t.Fatalf("default result = %#v", defaultResult)
|
||||
}
|
||||
overrideResult, err := InspectPromptExecution(context.Background(), PromptInspectionRequest{
|
||||
Resolved: resolved, Executor: executor, Promptkit: config.PromptkitConfig{Profile: "override-profile"},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InspectPromptExecution(override) error = %v", err)
|
||||
}
|
||||
if overrideResult.ProfileID != "override-profile" || overrideResult.ModelName != "override-model" {
|
||||
t.Fatalf("override result = %#v", overrideResult)
|
||||
}
|
||||
if len(executor.promptRequests) != 2 || executor.promptRequests[0].version != resolved.Definition.PromptVersion || executor.profileRequests[0] != "default-profile" || executor.profileRequests[1] != "override-profile" {
|
||||
t.Fatalf("inspection requests = prompts %#v profiles %#v", executor.promptRequests, executor.profileRequests)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspectPromptExecutionRejectsInvalidContractsAndCredentials(t *testing.T) {
|
||||
resolved := inspectionResolved(t)
|
||||
basePrompt := validPromptInspection(resolved.Definition)
|
||||
tests := []struct {
|
||||
name string
|
||||
prompt promptexec.PromptInspection
|
||||
profile promptexec.ProfileInspection
|
||||
lookupEnv func(string) (string, bool)
|
||||
wantCategory promptexec.ErrorCategory
|
||||
}{
|
||||
{
|
||||
name: "extra input",
|
||||
prompt: func() promptexec.PromptInspection {
|
||||
value := basePrompt
|
||||
value.Inputs = append(value.Inputs, promptexec.InputDefinition{Name: "unexpected"})
|
||||
return value
|
||||
}(),
|
||||
wantCategory: promptexec.InvalidConfiguration,
|
||||
},
|
||||
{
|
||||
name: "wrong schema",
|
||||
prompt: func() promptexec.PromptInspection {
|
||||
value := basePrompt
|
||||
value.Output.SchemaPath = "unexpected.schema.json"
|
||||
return value
|
||||
}(),
|
||||
wantCategory: promptexec.InvalidConfiguration,
|
||||
},
|
||||
{
|
||||
name: "missing prompt hash",
|
||||
prompt: func() promptexec.PromptInspection {
|
||||
value := basePrompt
|
||||
value.PromptHash = ""
|
||||
return value
|
||||
}(),
|
||||
wantCategory: promptexec.InvalidConfiguration,
|
||||
},
|
||||
{
|
||||
name: "missing profile backend",
|
||||
prompt: basePrompt,
|
||||
profile: promptexec.ProfileInspection{ProfileID: "default-profile", ModelName: "model"},
|
||||
wantCategory: promptexec.InvalidConfiguration,
|
||||
},
|
||||
{
|
||||
name: "direct key",
|
||||
prompt: basePrompt,
|
||||
profile: promptexec.ProfileInspection{ProfileID: "default-profile", CredentialRequired: true},
|
||||
wantCategory: promptexec.MissingCredential,
|
||||
},
|
||||
{
|
||||
name: "missing environment credential",
|
||||
prompt: basePrompt,
|
||||
profile: promptexec.ProfileInspection{ProfileID: "default-profile", APIKeyEnv: "PROMPT_API_KEY"},
|
||||
lookupEnv: func(string) (string, bool) { return "", false },
|
||||
wantCategory: promptexec.MissingCredential,
|
||||
},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
executor := &inspectionExecutor{prompt: test.prompt, profiles: map[string]promptexec.ProfileInspection{"default-profile": test.profile}}
|
||||
_, err := InspectPromptExecution(context.Background(), PromptInspectionRequest{Resolved: resolved, Executor: executor, LookupEnv: test.lookupEnv})
|
||||
if err == nil || promptexec.CategoryOf(err) != test.wantCategory {
|
||||
t.Fatalf("error/category = %v/%q, want %q", err, promptexec.CategoryOf(err), test.wantCategory)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspectPromptExecutionReturnsSafeInspectionError(t *testing.T) {
|
||||
resolved := inspectionResolved(t)
|
||||
executor := &inspectionExecutor{promptErr: errors.New("provider response contains resolved-secret-value")}
|
||||
_, err := InspectPromptExecution(context.Background(), PromptInspectionRequest{Resolved: resolved, Executor: executor})
|
||||
if err == nil || promptexec.CategoryOf(err) != promptexec.InvalidConfiguration {
|
||||
t.Fatalf("error/category = %v/%q", err, promptexec.CategoryOf(err))
|
||||
}
|
||||
if strings.Contains(err.Error(), "resolved-secret-value") {
|
||||
t.Fatalf("inspection error leaks provider value: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspectPromptExecutionsReusesEffectiveProfile(t *testing.T) {
|
||||
first := inspectionResolved(t)
|
||||
second := inspectionResolvedFor(t, report.Today)
|
||||
executor := &inspectionExecutor{
|
||||
prompt: validPromptInspection(first.Definition),
|
||||
profiles: map[string]promptexec.ProfileInspection{
|
||||
"default-profile": {ProfileID: "default-profile", BackendID: "local", ModelName: "model"},
|
||||
},
|
||||
}
|
||||
executor.prompts = map[string]promptexec.PromptInspection{
|
||||
first.Definition.PromptID: validPromptInspection(first.Definition),
|
||||
second.Definition.PromptID: validPromptInspection(second.Definition),
|
||||
}
|
||||
results, err := InspectPromptExecutions(context.Background(), PromptExecutionsInspectionRequest{Resolved: []report.Resolved{first, second}, Executor: executor})
|
||||
if err != nil {
|
||||
t.Fatalf("InspectPromptExecutions() error = %v", err)
|
||||
}
|
||||
if len(results) != 2 || len(executor.profileRequests) != 1 {
|
||||
t.Fatalf("results/profile requests = %#v/%#v, want two results and one profile inspection", results, executor.profileRequests)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPromptInspectionRejectsIncompatibleGeneratedTextCatalogBeforeExecutorWork(t *testing.T) {
|
||||
base := inspectionResolved(t)
|
||||
tests := []struct {
|
||||
name string
|
||||
resolved report.Resolved
|
||||
inspect func(context.Context, report.Resolved, *inspectionExecutor) error
|
||||
}{
|
||||
{
|
||||
name: "single report unknown template",
|
||||
resolved: func() report.Resolved {
|
||||
resolved := base
|
||||
resolved.Definition.TemplateID = "unknown"
|
||||
return resolved
|
||||
}(),
|
||||
inspect: func(ctx context.Context, resolved report.Resolved, executor *inspectionExecutor) error {
|
||||
_, err := InspectPromptExecution(ctx, PromptInspectionRequest{Resolved: resolved, Executor: executor})
|
||||
return err
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "batch known pair for another report",
|
||||
resolved: func() report.Resolved {
|
||||
resolved := base
|
||||
resolved.Definition.GeneratedTextSchemaID = "today"
|
||||
resolved.Definition.TemplateID = "today"
|
||||
return resolved
|
||||
}(),
|
||||
inspect: func(ctx context.Context, resolved report.Resolved, executor *inspectionExecutor) error {
|
||||
_, err := InspectPromptExecutions(ctx, PromptExecutionsInspectionRequest{Resolved: []report.Resolved{resolved}, Executor: executor})
|
||||
return err
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "comparison known pair for another report",
|
||||
resolved: func() report.Resolved {
|
||||
resolved := base
|
||||
resolved.Definition.GeneratedTextSchemaID = "today"
|
||||
resolved.Definition.TemplateID = "today"
|
||||
return resolved
|
||||
}(),
|
||||
inspect: func(ctx context.Context, resolved report.Resolved, executor *inspectionExecutor) error {
|
||||
_, err := InspectComparisonExecution(ctx, ComparisonInspectionRequest{Resolved: resolved, ProfileIDs: []string{"weather-light", "weather-deep"}, Executor: executor})
|
||||
return err
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
executor := &inspectionExecutor{}
|
||||
err := test.inspect(context.Background(), test.resolved, executor)
|
||||
if err == nil || promptexec.CategoryOf(err) != promptexec.InvalidConfiguration {
|
||||
t.Fatalf("inspection error/category = %v/%q, want invalid configuration", err, promptexec.CategoryOf(err))
|
||||
}
|
||||
if len(executor.promptRequests) != 0 || len(executor.profileRequests) != 0 || executor.executeRequests != 0 {
|
||||
t.Fatalf("incompatible catalog performed executor work: prompts %#v profiles %#v executions %d", executor.promptRequests, executor.profileRequests, executor.executeRequests)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspectComparisonExecutionPreservesOrderedExplicitProfiles(t *testing.T) {
|
||||
resolved := inspectionResolved(t)
|
||||
executor := &inspectionExecutor{
|
||||
prompt: validPromptInspection(resolved.Definition),
|
||||
profiles: map[string]promptexec.ProfileInspection{
|
||||
"weather-light": {ProfileID: "weather-light", BackendID: "local", ModelName: "light-model"},
|
||||
"weather-deep": {ProfileID: "weather-deep", BackendID: "cloud", ModelName: "deep-model"},
|
||||
},
|
||||
}
|
||||
profileIDs := []string{"weather-light", "weather-deep"}
|
||||
result, err := InspectComparisonExecution(context.Background(), ComparisonInspectionRequest{
|
||||
Resolved: resolved, ProfileIDs: profileIDs, Executor: executor,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InspectComparisonExecution() error = %v", err)
|
||||
}
|
||||
if result.PromptID != resolved.Definition.PromptID || result.PromptVersion != resolved.Definition.PromptVersion || result.PromptHash != "prompt-hash" {
|
||||
t.Fatalf("prompt result = %#v", result)
|
||||
}
|
||||
if !reflect.DeepEqual(executor.profileRequests, profileIDs) || len(executor.promptRequests) != 1 || executor.executeRequests != 0 {
|
||||
t.Fatalf("prompt/profile/execute requests = %#v/%#v/%d", executor.promptRequests, executor.profileRequests, executor.executeRequests)
|
||||
}
|
||||
wantProfiles := []ComparisonProfileInspection{
|
||||
{ProfileID: "weather-light", BackendID: "local", ModelName: "light-model"},
|
||||
{ProfileID: "weather-deep", BackendID: "cloud", ModelName: "deep-model"},
|
||||
}
|
||||
if !reflect.DeepEqual(result.Profiles, wantProfiles) {
|
||||
t.Fatalf("profiles = %#v, want %#v", result.Profiles, wantProfiles)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspectComparisonExecutionRejectsInvalidProfilesBeforeInspection(t *testing.T) {
|
||||
resolved := inspectionResolved(t)
|
||||
for _, profileIDs := range [][]string{
|
||||
{"weather-light"},
|
||||
{"weather-light", " \t"},
|
||||
{"weather-light", "weather-light"},
|
||||
} {
|
||||
t.Run(strings.Join(profileIDs, ","), func(t *testing.T) {
|
||||
executor := &inspectionExecutor{prompt: validPromptInspection(resolved.Definition)}
|
||||
_, err := InspectComparisonExecution(context.Background(), ComparisonInspectionRequest{
|
||||
Resolved: resolved, ProfileIDs: profileIDs, Executor: executor,
|
||||
})
|
||||
if err == nil || promptexec.CategoryOf(err) != promptexec.InvalidRequest {
|
||||
t.Fatalf("error/category = %v/%q, want invalid request", err, promptexec.CategoryOf(err))
|
||||
}
|
||||
if len(executor.promptRequests) != 0 || len(executor.profileRequests) != 0 || executor.executeRequests != 0 {
|
||||
t.Fatalf("invalid profile selection performed prompt/profile/execution work: %#v/%#v/%d", executor.promptRequests, executor.profileRequests, executor.executeRequests)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspectComparisonExecutionStopsAtFirstProfileFailure(t *testing.T) {
|
||||
resolved := inspectionResolved(t)
|
||||
executor := &inspectionExecutor{
|
||||
prompt: validPromptInspection(resolved.Definition),
|
||||
profiles: map[string]promptexec.ProfileInspection{
|
||||
"weather-light": {ProfileID: "weather-light", BackendID: "local", ModelName: "light-model"},
|
||||
"missing-key": {ProfileID: "missing-key", APIKeyEnv: "PROMPT_API_KEY"},
|
||||
"weather-deep": {ProfileID: "weather-deep", BackendID: "cloud", ModelName: "deep-model"},
|
||||
},
|
||||
}
|
||||
result, err := InspectComparisonExecution(context.Background(), ComparisonInspectionRequest{
|
||||
Resolved: resolved, ProfileIDs: []string{"weather-light", "missing-key", "weather-deep"}, Executor: executor,
|
||||
LookupEnv: func(string) (string, bool) { return "", false },
|
||||
})
|
||||
if err == nil || promptexec.CategoryOf(err) != promptexec.MissingCredential {
|
||||
t.Fatalf("error/category = %v/%q, want missing credential", err, promptexec.CategoryOf(err))
|
||||
}
|
||||
if !reflect.DeepEqual(executor.profileRequests, []string{"weather-light", "missing-key"}) || len(executor.promptRequests) != 1 || executor.executeRequests != 0 {
|
||||
t.Fatalf("prompt/profile/execute requests = %#v/%#v/%d", executor.promptRequests, executor.profileRequests, executor.executeRequests)
|
||||
}
|
||||
if result.PromptID != resolved.Definition.PromptID || result.PromptVersion != resolved.Definition.PromptVersion || result.PromptHash == "" || len(result.Profiles) != 1 || result.Profiles[0].ProfileID != "weather-light" {
|
||||
t.Fatalf("partial inspection result = %#v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInspectComparisonExecutionStopsBeforeProfileInspectionWhenPromptFails(t *testing.T) {
|
||||
resolved := inspectionResolved(t)
|
||||
executor := &inspectionExecutor{promptErr: promptexec.NewError(promptexec.PromptNotFound, "prompt is unavailable", nil)}
|
||||
_, err := InspectComparisonExecution(context.Background(), ComparisonInspectionRequest{
|
||||
Resolved: resolved, ProfileIDs: []string{"weather-light", "weather-deep"}, Executor: executor,
|
||||
})
|
||||
if err == nil || promptexec.CategoryOf(err) != promptexec.PromptNotFound || !strings.Contains(err.Error(), "comparison prompt") {
|
||||
t.Fatalf("error/category = %v/%q, want prompt-context prompt not found", err, promptexec.CategoryOf(err))
|
||||
}
|
||||
if len(executor.promptRequests) != 1 || len(executor.profileRequests) != 0 || executor.executeRequests != 0 {
|
||||
t.Fatalf("prompt/profile/execute requests = %#v/%#v/%d", executor.promptRequests, executor.profileRequests, executor.executeRequests)
|
||||
}
|
||||
}
|
||||
|
||||
type inspectionPromptRequest struct {
|
||||
id string
|
||||
version string
|
||||
}
|
||||
|
||||
type inspectionExecutor struct {
|
||||
prompt promptexec.PromptInspection
|
||||
prompts map[string]promptexec.PromptInspection
|
||||
profiles map[string]promptexec.ProfileInspection
|
||||
promptErr error
|
||||
promptRequests []inspectionPromptRequest
|
||||
profileRequests []string
|
||||
executeRequests int
|
||||
}
|
||||
|
||||
func (e *inspectionExecutor) InspectPrompt(_ context.Context, id string, version string) (promptexec.PromptInspection, error) {
|
||||
e.promptRequests = append(e.promptRequests, inspectionPromptRequest{id: id, version: version})
|
||||
if e.promptErr != nil {
|
||||
return promptexec.PromptInspection{}, e.promptErr
|
||||
}
|
||||
if prompt, ok := e.prompts[id]; ok {
|
||||
return prompt, nil
|
||||
}
|
||||
return e.prompt, nil
|
||||
}
|
||||
|
||||
func (e *inspectionExecutor) InspectProfile(_ context.Context, id string) (promptexec.ProfileInspection, error) {
|
||||
e.profileRequests = append(e.profileRequests, id)
|
||||
value, ok := e.profiles[id]
|
||||
if !ok {
|
||||
return promptexec.ProfileInspection{}, errors.New("profile missing")
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (e *inspectionExecutor) Execute(context.Context, promptexec.ExecuteRequest, promptexec.PreparationCallback) (*promptexec.Execution, error) {
|
||||
e.executeRequests++
|
||||
return nil, errors.New("unexpected execution")
|
||||
}
|
||||
|
||||
func inspectionResolved(t *testing.T) report.Resolved {
|
||||
return inspectionResolvedFor(t, report.Daily)
|
||||
}
|
||||
|
||||
func inspectionResolvedFor(t *testing.T, id report.ID) report.Resolved {
|
||||
t.Helper()
|
||||
request := report.ResolveRequest{Now: time.Date(2026, 5, 29, 12, 0, 0, 0, time.UTC), Location: time.UTC}
|
||||
if id == report.Daily {
|
||||
request.Date = time.Date(2026, 5, 29, 0, 0, 0, 0, time.UTC)
|
||||
}
|
||||
resolved, err := report.DefaultRegistry().Resolve(id, request)
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve() error = %v", err)
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
func validPromptInspection(definition report.Definition) promptexec.PromptInspection {
|
||||
return promptexec.PromptInspection{
|
||||
PromptID: definition.PromptID, PromptVersion: definition.PromptVersion, PromptHash: "prompt-hash", DefaultProfileID: "default-profile",
|
||||
Inputs: []promptexec.InputDefinition{{Name: "data_package", Required: true, ContentType: "application/yaml"}},
|
||||
Output: promptexec.OutputContract{Format: "json", ValidationMode: "json_schema", SchemaPath: definition.GeneratedTextSchemaID + ".generated_text.schema.json"},
|
||||
}
|
||||
}
|
||||
|
||||
func logicalPromptInspection(definition report.Definition) promptexec.PromptInspection {
|
||||
inspection := validPromptInspection(definition)
|
||||
if definition.ID == report.Hourly {
|
||||
inspection.DefaultProfileID = "weather-light"
|
||||
} else {
|
||||
inspection.DefaultProfileID = "weather-balanced"
|
||||
}
|
||||
return inspection
|
||||
}
|
||||
74
internal/app/prompt_profile_integration_test.go
Normal file
74
internal/app/prompt_profile_integration_test.go
Normal file
@@ -0,0 +1,74 @@
|
||||
package app_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
promptkitadapter "gitea.maximumdirect.net/eric/weatherreporter/internal/adapters/promptkit"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/app"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/config"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/report"
|
||||
)
|
||||
|
||||
func TestPromptInspectionResolvesEmbeddedAndOverriddenProfilesOffline(t *testing.T) {
|
||||
lookupEnv := func(string) (string, bool) { return "test-key", true }
|
||||
inspect := func(t *testing.T, adapter *promptkitadapter.Adapter, id report.ID, profile string, wantID string, wantBackend string, wantModel string) {
|
||||
t.Helper()
|
||||
result, err := app.InspectPromptExecution(context.Background(), app.PromptInspectionRequest{
|
||||
Resolved: resolvedPromptProfile(t, id),
|
||||
Executor: adapter,
|
||||
Promptkit: config.PromptkitConfig{Profile: profile},
|
||||
LookupEnv: lookupEnv,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InspectPromptExecution() error = %v", err)
|
||||
}
|
||||
if result.ProfileID != wantID || result.BackendID != wantBackend || result.ModelName != wantModel {
|
||||
t.Fatalf("inspection = %#v, want profile/backend/model %q/%q/%q", result, wantID, wantBackend, wantModel)
|
||||
}
|
||||
}
|
||||
|
||||
embedded, err := promptkitadapter.New(promptkitadapter.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("New(embedded) error = %v", err)
|
||||
}
|
||||
inspect(t, embedded, report.Hourly, "", "weather-light", "openrouter", "deepseek/deepseek-v4-flash")
|
||||
inspect(t, embedded, report.Daily, "", "weather-balanced", "openrouter", "~google/gemini-flash-latest")
|
||||
inspect(t, embedded, report.Daily, "weather-deep", "weather-deep", "openrouter", "~anthropic/claude-sonnet-latest")
|
||||
|
||||
override, err := promptkitadapter.New(promptkitadapter.Config{ProfileFile: writeProfileFile(t, `id: weather-light
|
||||
endpoint: https://local.example/v1
|
||||
backend: openrouter
|
||||
model: local-weather
|
||||
`)})
|
||||
if err != nil {
|
||||
t.Fatalf("New(override) error = %v", err)
|
||||
}
|
||||
inspect(t, override, report.Hourly, "", "weather-light", "openrouter", "local-weather")
|
||||
}
|
||||
|
||||
func resolvedPromptProfile(t *testing.T, id report.ID) report.Resolved {
|
||||
t.Helper()
|
||||
now := time.Date(2026, 5, 29, 12, 0, 0, 0, time.UTC)
|
||||
request := report.ResolveRequest{Now: now, Location: time.UTC}
|
||||
if id == report.Daily {
|
||||
request.Date = now
|
||||
}
|
||||
resolved, err := report.DefaultRegistry().Resolve(id, request)
|
||||
if err != nil {
|
||||
t.Fatalf("Resolve(%q) error = %v", id, err)
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
func writeProfileFile(t *testing.T, profile string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "profile.yml")
|
||||
if err := os.WriteFile(path, []byte(profile), 0o600); err != nil {
|
||||
t.Fatalf("write profile: %v", err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
21
internal/app/test_helpers_test.go
Normal file
21
internal/app/test_helpers_test.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func mustParse(value string) time.Time {
|
||||
parsed, err := time.Parse(time.RFC3339, value)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
func requireNoError(t *testing.T, err error) {
|
||||
t.Helper()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
68
internal/briefing/alert_digest_module.go
Normal file
68
internal/briefing/alert_digest_module.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package briefing
|
||||
|
||||
import (
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/facts"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/forecast"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/module"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/weatherdata"
|
||||
)
|
||||
|
||||
type AlertDigestModule struct {
|
||||
Checked bool `json:"checked"`
|
||||
ActiveCount int `json:"active_count"`
|
||||
RelevantCount int `json:"relevant_count"`
|
||||
Missing bool `json:"missing,omitempty"`
|
||||
Relevant []AlertSummary `json:"relevant,omitempty"`
|
||||
}
|
||||
|
||||
type AlertSummary struct {
|
||||
Event string `json:"event,omitempty"`
|
||||
Headline string `json:"headline,omitempty"`
|
||||
Severity string `json:"severity,omitempty"`
|
||||
PeriodBegins string `json:"period_begins,omitempty"`
|
||||
PeriodEnds string `json:"period_ends,omitempty"`
|
||||
Instruction string `json:"instruction,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
}
|
||||
|
||||
func buildAlertDigestModule(ctx ModuleContext, _ any) (*module.Output, error) {
|
||||
value := alertDigest(ctx.Collected, ctx.Derived.AlertOverlaps, ctx.Timezone)
|
||||
if value == nil {
|
||||
value = &AlertDigestModule{}
|
||||
}
|
||||
return &module.Output{ID: module.AlertDigest, StanzaName: "alert_digest", Value: *value}, nil
|
||||
}
|
||||
|
||||
func alertDigest(collected facts.CollectedFacts, overlaps []forecast.AlertOverlap, timezone string) *AlertDigestModule {
|
||||
missing := sourceMissing(collected.SourceProvenance, "alerts")
|
||||
if collected.Alerts == nil && !missing {
|
||||
return nil
|
||||
}
|
||||
value := &AlertDigestModule{Missing: missing}
|
||||
if collected.Alerts != nil {
|
||||
value.Checked = true
|
||||
value.ActiveCount = len(collected.Alerts.Alerts)
|
||||
}
|
||||
value.RelevantCount = len(overlaps)
|
||||
for _, overlap := range overlaps {
|
||||
value.Relevant = append(value.Relevant, AlertSummary{
|
||||
Event: overlap.Event,
|
||||
Headline: overlap.Headline,
|
||||
Severity: overlap.Severity,
|
||||
PeriodBegins: friendlyMonthDayTimeLabel(overlap.Period.Start, timezone),
|
||||
PeriodEnds: friendlyMonthDayTimeLabel(overlap.Period.End, timezone),
|
||||
Instruction: overlap.Instruction,
|
||||
Description: overlap.Description,
|
||||
})
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func sourceMissing(sources []weatherdata.Source, name string) bool {
|
||||
for _, source := range sources {
|
||||
if source.Name == name && source.Missing {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
67
internal/briefing/area_forecast_discussion_module.go
Normal file
67
internal/briefing/area_forecast_discussion_module.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package briefing
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/module"
|
||||
)
|
||||
|
||||
type AreaForecastDiscussionModule struct {
|
||||
Product string `json:"product,omitempty"`
|
||||
KeyMessages []string `json:"key_messages,omitempty"`
|
||||
ShortTerm string `json:"short_term,omitempty"`
|
||||
LongTerm string `json:"long_term,omitempty"`
|
||||
}
|
||||
|
||||
func buildAreaForecastDiscussionModule(ctx ModuleContext, options any) (*module.Output, error) {
|
||||
discussion := ctx.Collected.Discussion
|
||||
if discussion == nil {
|
||||
return nil, nil
|
||||
}
|
||||
opts, ok := options.(module.AreaForecastDiscussionOptions)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("area forecast discussion options have type %T", options)
|
||||
}
|
||||
sections, err := areaForecastDiscussionSections(opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
value := AreaForecastDiscussionModule{}
|
||||
if sections["product"] {
|
||||
value.Product = discussion.Product
|
||||
}
|
||||
if sections["key_messages"] {
|
||||
value.KeyMessages = append([]string(nil), discussion.KeyMessages...)
|
||||
}
|
||||
if sections["short_term"] && discussion.ShortTerm != nil {
|
||||
value.ShortTerm = discussion.ShortTerm.Text
|
||||
}
|
||||
if sections["long_term"] && discussion.LongTerm != nil {
|
||||
value.LongTerm = discussion.LongTerm.Text
|
||||
}
|
||||
if value.Product == "" && len(value.KeyMessages) == 0 && value.ShortTerm == "" && value.LongTerm == "" {
|
||||
return nil, nil
|
||||
}
|
||||
return &module.Output{ID: module.AreaForecastDiscussion, StanzaName: "area_forecast_discussion", Value: value}, nil
|
||||
}
|
||||
|
||||
func areaForecastDiscussionSections(options module.AreaForecastDiscussionOptions) (map[string]bool, error) {
|
||||
if len(options.Sections) == 0 {
|
||||
return map[string]bool{
|
||||
"product": true,
|
||||
"key_messages": true,
|
||||
"short_term": true,
|
||||
"long_term": true,
|
||||
}, nil
|
||||
}
|
||||
sections := map[string]bool{}
|
||||
for _, section := range options.Sections {
|
||||
switch section {
|
||||
case "product", "key_messages", "short_term", "long_term":
|
||||
sections[section] = true
|
||||
default:
|
||||
return nil, fmt.Errorf("area forecast discussion section %q is not supported", section)
|
||||
}
|
||||
}
|
||||
return sections, nil
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
{
|
||||
"provenance": {
|
||||
"sources": [
|
||||
{
|
||||
"url": "https://www.spc.noaa.gov/about/outlooks/",
|
||||
"updated_on": "2026-03-03",
|
||||
"applies_to": "categorical outlook descriptions"
|
||||
},
|
||||
{
|
||||
"url": "https://www.spc.noaa.gov/exper/conditional-intensity-information",
|
||||
"updated_on": "2026-02-04",
|
||||
"applies_to": "conditional intensity group descriptions"
|
||||
}
|
||||
],
|
||||
"reviewed_on": "2026-08-13",
|
||||
"review_owner": "Weatherreporter maintainers",
|
||||
"review_schedule": "Review annually and whenever SPC updates either referenced page."
|
||||
},
|
||||
"definitions": {
|
||||
"categorical:TSTM": {
|
||||
"plain_language": "General or non-severe thunderstorms.",
|
||||
"official_description": "Encloses a 10% or higher probability of thunderstorms.",
|
||||
"relative_level": "0 of 5"
|
||||
},
|
||||
"categorical:MRGL": {
|
||||
"plain_language": "Isolated severe storms possible.",
|
||||
"official_description": "Includes severe storms of either limited organization and longevity or very low coverage.",
|
||||
"relative_level": "1 of 5"
|
||||
},
|
||||
"categorical:SLGT": {
|
||||
"plain_language": "Scattered severe storms possible.",
|
||||
"official_description": "Implies organized severe thunderstorms are expected, but usually in low coverage with varying levels of intensity.",
|
||||
"relative_level": "2 of 5"
|
||||
},
|
||||
"categorical:ENH": {
|
||||
"plain_language": "Numerous severe storms possible.",
|
||||
"official_description": "Depicts a greater concentration of organized severe thunderstorms with varying levels of intensity.",
|
||||
"relative_level": "3 of 5"
|
||||
},
|
||||
"categorical:MDT": {
|
||||
"plain_language": "Widespread severe storms likely.",
|
||||
"official_description": "Indicates potential for widespread severe weather with several tornadoes and/or numerous severe thunderstorms, some of which may be intense.",
|
||||
"relative_level": "4 of 5"
|
||||
},
|
||||
"categorical:HIGH": {
|
||||
"plain_language": "Major severe outbreak expected.",
|
||||
"official_description": "Suggests a severe weather outbreak is expected from either numerous intense to violent long-track tornadoes or a long-lived derecho system with hurricane-force wind gusts producing widespread damage.",
|
||||
"relative_level": "5 of 5"
|
||||
},
|
||||
"tornado:CIG1": {
|
||||
"plain_language": "Conditional potential for significant tornadoes.",
|
||||
"official_description": "Intensity Level 1: Reasonable Max EF2. Note that this product describes the reasonable maximum intensity of a hazard if that hazard occurs. It does not by itself indicate the probability that the hazard will occur.",
|
||||
"relative_level": "1 of 3"
|
||||
},
|
||||
"tornado:CIG2": {
|
||||
"plain_language": "Conditional potential for strong tornadoes.",
|
||||
"official_description": "Intensity Level 2: Reasonable Max EF3. Note that this product describes the reasonable maximum intensity of a hazard if that hazard occurs. It does not by itself indicate the probability that the hazard will occur.",
|
||||
"relative_level": "2 of 3"
|
||||
},
|
||||
"tornado:CIG3": {
|
||||
"plain_language": "Conditional potential for violent tornadoes.",
|
||||
"official_description": "Intensity Level 3: Reasonable Max EF4 or higher. Note that this product describes the reasonable maximum intensity of a hazard if that hazard occurs. It does not by itself indicate the probability that the hazard will occur.",
|
||||
"relative_level": "3 of 3"
|
||||
},
|
||||
"wind:CIG1": {
|
||||
"plain_language": "Conditional potential for significant severe wind.",
|
||||
"official_description": "Intensity Level 1: Reasonable Max wind gusts around 65 kt / 75 mph or higher. Note that this product describes the reasonable maximum intensity of a hazard if that hazard occurs. It does not by itself indicate the probability that the hazard will occur.",
|
||||
"relative_level": "1 of 3"
|
||||
},
|
||||
"wind:CIG2": {
|
||||
"plain_language": "Conditional potential for intense severe wind.",
|
||||
"official_description": "Intensity Level 2: Reasonable Max wind gusts around 75 kt / 85 mph or higher. Note that this product describes the reasonable maximum intensity of a hazard if that hazard occurs. It does not by itself indicate the probability that the hazard will occur.",
|
||||
"relative_level": "2 of 3"
|
||||
},
|
||||
"wind:CIG3": {
|
||||
"plain_language": "Conditional potential for extreme severe wind.",
|
||||
"official_description": "Intensity Level 3: Reasonable Max wind gusts around 100 kt / 115 mph or higher. Note that this product describes the reasonable maximum intensity of a hazard if that hazard occurs. It does not by itself indicate the probability that the hazard will occur.",
|
||||
"relative_level": "3 of 3"
|
||||
},
|
||||
"hail:CIG1": {
|
||||
"plain_language": "Conditional potential for significant hail.",
|
||||
"official_description": "Intensity Level 1: Reasonable Max hail size around 2.00 to 3.75 inches. Note that this product describes the reasonable maximum intensity of a hazard if that hazard occurs. It does not by itself indicate the probability that the hazard will occur.",
|
||||
"relative_level": "1 of 2"
|
||||
},
|
||||
"hail:CIG2": {
|
||||
"plain_language": "Conditional potential for giant hail.",
|
||||
"official_description": "Intensity Level 2: Reasonable Max hail size greater than 3.75 inches. Note that this product describes the reasonable maximum intensity of a hazard if that hazard occurs. It does not by itself indicate the probability that the hazard will occur.",
|
||||
"relative_level": "2 of 2"
|
||||
}
|
||||
}
|
||||
}
|
||||
782
internal/briefing/base_modules_test.go
Normal file
782
internal/briefing/base_modules_test.go
Normal file
@@ -0,0 +1,782 @@
|
||||
package briefing
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/facts"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/forecast"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/module"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/report"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/timeutil"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/weatherdata"
|
||||
)
|
||||
|
||||
func TestBaseModulesBuildAvailableSourceOutputs(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
|
||||
tests := []struct {
|
||||
id module.ID
|
||||
stanza string
|
||||
}{
|
||||
{id: module.Metadata, stanza: "metadata"},
|
||||
{id: module.CurrentConditions, stanza: "current_conditions"},
|
||||
{id: module.NarrativeForecast, stanza: "narrative_forecast"},
|
||||
{id: module.HourlyForecast, stanza: "hourly_forecast"},
|
||||
{id: module.AlertDigest, stanza: "alert_digest"},
|
||||
{id: module.AreaForecastDiscussion, stanza: "area_forecast_discussion"},
|
||||
{id: module.WeatherStory, stanza: "weather_story"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(string(tt.id), func(t *testing.T) {
|
||||
output, err := registry.BuildModule(ctx, module.ConfigItem{ID: tt.id})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule() error = %v", err)
|
||||
}
|
||||
if output == nil {
|
||||
t.Fatal("BuildModule() output = nil, want stanza")
|
||||
}
|
||||
if output.ID != tt.id || output.StanzaName != tt.stanza {
|
||||
t.Fatalf("output = %#v, want id %q stanza %q", output, tt.id, tt.stanza)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestHourlyForecastModuleUsesValidPeriodHourlyPeriods(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
|
||||
output, err := registry.BuildModule(ctx, module.ConfigItem{ID: module.HourlyForecast})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule() error = %v", err)
|
||||
}
|
||||
value := moduleValue[HourlyForecastModule](t, output)
|
||||
if value.Product != "hourly" || value.SourceLocationID != "test-grid" || len(value.Periods) != 1 {
|
||||
t.Fatalf("HourlyForecast = %#v, want hourly metadata and one valid-period period", value)
|
||||
}
|
||||
period := value.Periods[0]
|
||||
if period.HourLabel != "8:00 AM" || period.TextDescription != "Showers likely." || period.TextDescriptionLower != "showers likely." || period.TemperatureF == nil || *period.TemperatureF != 76 {
|
||||
t.Fatalf("HourlyForecast period = %#v, want hourly period facts", period)
|
||||
}
|
||||
if period.PeriodBegins != "2026-05-29 at 8:00 AM" || period.PeriodEnds != "2026-05-29 at 9:00 AM" {
|
||||
t.Fatalf("HourlyForecast period times = %q/%q, want friendly local time labels", period.PeriodBegins, period.PeriodEnds)
|
||||
}
|
||||
if period.WindDirection != "S" || period.ProbabilityOfPrecipitationPercent == nil || *period.ProbabilityOfPrecipitationPercent != 70 {
|
||||
t.Fatalf("HourlyForecast period = %#v, want compass wind and precip chance", period)
|
||||
}
|
||||
if !period.MentionPrecipitation {
|
||||
t.Fatalf("MentionPrecipitation = false, want true for default threshold")
|
||||
}
|
||||
data, err := json.Marshal(output.Value)
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal hourly forecast: %v", err)
|
||||
}
|
||||
jsonText := string(data)
|
||||
for _, field := range []string{"source_location_id", "hour_label", "period_begins", "period_ends", "text_description", "text_description_lower", "temperature_f", "wind_direction", "probability_of_precipitation_percent", "mention_precipitation", "relative_humidity_percent"} {
|
||||
if !strings.Contains(jsonText, field) {
|
||||
t.Fatalf("hourly json = %s, want field %s", jsonText, field)
|
||||
}
|
||||
}
|
||||
if strings.Contains(jsonText, "wind_direction_degrees") || strings.Contains(jsonText, "Tomorrow") {
|
||||
t.Fatalf("hourly json = %s, want valid-period prompt fields only", jsonText)
|
||||
}
|
||||
if strings.Contains(jsonText, `"start_time"`) || strings.Contains(jsonText, `"end_time"`) {
|
||||
t.Fatalf("hourly json = %s, want period_begins/period_ends instead of start_time/end_time", jsonText)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHourlyForecastPromptExportOmitsTemplateHelpers(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
|
||||
output, err := registry.BuildModule(ctx, module.ConfigItem{ID: module.HourlyForecast})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule() error = %v", err)
|
||||
}
|
||||
richText := mustMarshalModuleJSON(t, output.Value)
|
||||
for _, field := range []string{"hour_label", "text_description_lower", "mention_precipitation"} {
|
||||
if !strings.Contains(richText, field) {
|
||||
t.Fatalf("rich hourly json = %s, want helper field %s", richText, field)
|
||||
}
|
||||
}
|
||||
|
||||
prompt := moduleDataPackageValue[HourlyForecastPromptExport](t, output)
|
||||
if prompt.Product != "hourly" || prompt.SourceLocationID != "test-grid" || len(prompt.Periods) != 1 {
|
||||
t.Fatalf("hourly prompt export = %#v, want hourly metadata and one period", prompt)
|
||||
}
|
||||
period := prompt.Periods[0]
|
||||
if period.PeriodBegins != "2026-05-29 at 8:00 AM" || period.PeriodEnds != "2026-05-29 at 9:00 AM" || period.TextDescription != "Showers likely." {
|
||||
t.Fatalf("hourly prompt period = %#v, want factual period fields", period)
|
||||
}
|
||||
if period.TemperatureF == nil || *period.TemperatureF != 76 || period.WindSpeedMph == nil || *period.WindSpeedMph != 14 || period.ProbabilityOfPrecipitationPercent == nil || *period.ProbabilityOfPrecipitationPercent != 70 {
|
||||
t.Fatalf("hourly prompt period = %#v, want temperature, wind, and precip fields", period)
|
||||
}
|
||||
if period.WindDirection != "S" || period.RelativeHumidityPercent == nil || *period.RelativeHumidityPercent != 66 {
|
||||
t.Fatalf("hourly prompt period = %#v, want wind direction and humidity", period)
|
||||
}
|
||||
promptText := mustMarshalModuleJSON(t, output.DataPackageValue())
|
||||
for _, field := range []string{"period_begins", "period_ends", "text_description", "temperature_f", "wind_direction", "probability_of_precipitation_percent", "relative_humidity_percent"} {
|
||||
if !strings.Contains(promptText, field) {
|
||||
t.Fatalf("hourly prompt json = %s, want field %s", promptText, field)
|
||||
}
|
||||
}
|
||||
for _, field := range []string{"hour_label", "text_description_lower", "mention_precipitation"} {
|
||||
if strings.Contains(promptText, field) {
|
||||
t.Fatalf("hourly prompt json = %s, want omitted helper field %s", promptText, field)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHourlyForecastPrecipMentionThreshold(t *testing.T) {
|
||||
periods := []weatherdata.ForecastPeriod{
|
||||
{StartTime: mustParseModuleTime("2026-05-29T08:00:00-05:00"), ProbabilityOfPrecipitationPercent: floatPtr(19)},
|
||||
{StartTime: mustParseModuleTime("2026-05-29T09:00:00-05:00"), ProbabilityOfPrecipitationPercent: floatPtr(20)},
|
||||
{StartTime: mustParseModuleTime("2026-05-29T10:00:00-05:00")},
|
||||
}
|
||||
value := hourlyForecastPeriodsWithPrecipMentionThreshold(periods, "America/Chicago", 20)
|
||||
if len(value) != 3 {
|
||||
t.Fatalf("periods length = %d, want 3", len(value))
|
||||
}
|
||||
if value[0].MentionPrecipitation {
|
||||
t.Fatalf("19%% MentionPrecipitation = true, want false")
|
||||
}
|
||||
if !value[1].MentionPrecipitation {
|
||||
t.Fatalf("20%% MentionPrecipitation = false, want true")
|
||||
}
|
||||
if value[2].MentionPrecipitation {
|
||||
t.Fatalf("nil MentionPrecipitation = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestHourlyForecastModuleRejectsUnsupportedReports(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
ctx.Resolved.Definition = report.Definition{ID: report.ID("unsupported")}
|
||||
|
||||
_, err := registry.BuildModule(ctx, module.ConfigItem{ID: module.HourlyForecast})
|
||||
if err == nil || !strings.Contains(err.Error(), `module "hourly_forecast" is not compatible with report "unsupported"`) {
|
||||
t.Fatalf("BuildModule() error = %v, want incompatible report", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHourlyForecastModuleBuildsForHourly(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
ctx.Resolved.Definition = report.DefaultRegistry().MustLookup(report.Hourly)
|
||||
|
||||
output, err := registry.BuildModule(ctx, module.ConfigItem{ID: module.HourlyForecast})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule() error = %v", err)
|
||||
}
|
||||
value := moduleValue[HourlyForecastModule](t, output)
|
||||
if len(value.Periods) != 1 || value.Periods[0].TextDescription != "Showers likely." {
|
||||
t.Fatalf("HourlyForecast = %#v, want hourly report period", value)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNarrativeForecastModuleUsesValidPeriodNarrativePeriods(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
|
||||
output, err := registry.BuildModule(ctx, module.ConfigItem{ID: module.NarrativeForecast})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule() error = %v", err)
|
||||
}
|
||||
value := moduleValue[NarrativeForecastModule](t, output)
|
||||
if value.Product != "narrative" || value.SourceLocationID != "test-grid" || len(value.Periods) != 1 {
|
||||
t.Fatalf("NarrativeForecast = %#v, want narrative metadata and one valid-period period", value)
|
||||
}
|
||||
period := value.Periods[0]
|
||||
if period.Name != "Today" || period.TextDescription != "Morning storms, then partly sunny." {
|
||||
t.Fatalf("NarrativeForecast period = %#v, want Today narrative", period)
|
||||
}
|
||||
if period.PeriodBegins != "2026-05-29 at 6:00 AM" || period.PeriodEnds != "2026-05-29 at 6:00 PM" {
|
||||
t.Fatalf("NarrativeForecast period times = %q/%q, want friendly local time labels", period.PeriodBegins, period.PeriodEnds)
|
||||
}
|
||||
if period.IsDay == nil || !*period.IsDay || period.TemperatureF == nil || *period.TemperatureF != 81 || period.ProbabilityOfPrecipitationPercent == nil || *period.ProbabilityOfPrecipitationPercent != 60 {
|
||||
t.Fatalf("NarrativeForecast period = %#v, want day, temperature, and precip values", period)
|
||||
}
|
||||
if period.WindDirection != "NE" {
|
||||
t.Fatalf("NarrativeForecast period wind direction = %q, want NE", period.WindDirection)
|
||||
}
|
||||
data, err := json.Marshal(output.Value)
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal narrative forecast: %v", err)
|
||||
}
|
||||
jsonText := string(data)
|
||||
for _, field := range []string{"source_location_id", "period_begins", "period_ends", "text_description", "temperature_f", "wind_speed_mph", "wind_direction", "probability_of_precipitation_percent"} {
|
||||
if !strings.Contains(jsonText, field) {
|
||||
t.Fatalf("narrative json = %s, want field %s", jsonText, field)
|
||||
}
|
||||
}
|
||||
if strings.Contains(jsonText, "wind_direction_degrees") {
|
||||
t.Fatalf("narrative json = %s, want compass wind_direction without degrees field", jsonText)
|
||||
}
|
||||
if strings.Contains(jsonText, `"start_time"`) || strings.Contains(jsonText, `"end_time"`) {
|
||||
t.Fatalf("narrative json = %s, want period_begins/period_ends instead of start_time/end_time", jsonText)
|
||||
}
|
||||
if strings.Contains(jsonText, "Tomorrow night") {
|
||||
t.Fatalf("narrative json = %s, want only valid-period narrative periods", jsonText)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNarrativeForecastModuleRejectsUnsupportedReports(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
ctx.Resolved.Definition = report.Definition{ID: report.ID("unsupported")}
|
||||
|
||||
_, err := registry.BuildModule(ctx, module.ConfigItem{ID: module.NarrativeForecast})
|
||||
if err == nil || !strings.Contains(err.Error(), `module "narrative_forecast" is not compatible with report "unsupported"`) {
|
||||
t.Fatalf("BuildModule() error = %v, want incompatible report", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMetadataModuleUsesPromptSafeSourceWarningSummary(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
|
||||
output, err := registry.BuildModule(ctx, module.ConfigItem{ID: module.Metadata})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule() error = %v", err)
|
||||
}
|
||||
value := moduleValue[MetadataModule](t, output)
|
||||
if value.RunID == "" || value.ReportID != report.Daily || value.PromptID != "weather.daily_generated_text" {
|
||||
t.Fatalf("metadata = %#v, want report identity", value)
|
||||
}
|
||||
if value.Location == nil || value.Location.Name != "Brentwood" {
|
||||
t.Fatalf("Location = %#v, want configured location", value.Location)
|
||||
}
|
||||
if len(value.SourceWarnings) != 1 || value.SourceWarnings[0].CompletenessImpact != "source omitted" {
|
||||
t.Fatalf("SourceWarnings = %#v, want warning summary", value.SourceWarnings)
|
||||
}
|
||||
data, err := json.Marshal(output.Value)
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal metadata: %v", err)
|
||||
}
|
||||
jsonText := string(data)
|
||||
if !strings.Contains(jsonText, "source_warnings") || strings.Contains(jsonText, "endpoint") || strings.Contains(jsonText, "dataSha256") {
|
||||
t.Fatalf("metadata json = %s, want source warning summary without transport provenance", jsonText)
|
||||
}
|
||||
if strings.Contains(jsonText, `"alerts"`) {
|
||||
t.Fatalf("metadata json = %s, want alert details only in alert_digest", jsonText)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentConditionsModuleUsesSnakeCaseUnitFields(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
|
||||
output, err := registry.BuildModule(ctx, module.ConfigItem{ID: module.CurrentConditions})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule() error = %v", err)
|
||||
}
|
||||
value := moduleValue[CurrentConditionsModule](t, output)
|
||||
if value.ConditionText != "Partly cloudy" || value.ConditionTextLower != "partly cloudy" || value.TemperatureF == nil || *value.TemperatureF != 74 {
|
||||
t.Fatalf("CurrentConditions = %#v, want rounded current condition facts", value)
|
||||
}
|
||||
if value.ApparentTemperatureF == nil || *value.ApparentTemperatureF != 76 || value.RelativeHumidityPercent == nil || *value.RelativeHumidityPercent != 71 || value.WindSpeedMph == nil || *value.WindSpeedMph != 8 {
|
||||
t.Fatalf("CurrentConditions rounded values = %#v, want apparent 76, humidity 71, wind 8", value)
|
||||
}
|
||||
if value.WindDirection != "S" {
|
||||
t.Fatalf("WindDirection = %q, want S", value.WindDirection)
|
||||
}
|
||||
if value.WindDirectionText != "south" {
|
||||
t.Fatalf("WindDirectionText = %q, want south", value.WindDirectionText)
|
||||
}
|
||||
data, err := json.Marshal(output.Value)
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal current conditions: %v", err)
|
||||
}
|
||||
jsonText := string(data)
|
||||
for _, field := range []string{"condition_text", "condition_text_lower", "temperature_f", "apparent_temperature_f", "relative_humidity_percent", "wind_speed_mph", "wind_direction", "wind_direction_text"} {
|
||||
if !strings.Contains(jsonText, field) {
|
||||
t.Fatalf("current json = %s, want field %s", jsonText, field)
|
||||
}
|
||||
}
|
||||
if strings.Contains(jsonText, "wind_direction_degrees") {
|
||||
t.Fatalf("current json = %s, want compass wind_direction without degrees field", jsonText)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentConditionsPromptExportOmitsTemplateHelpers(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
|
||||
output, err := registry.BuildModule(ctx, module.ConfigItem{ID: module.CurrentConditions})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule() error = %v", err)
|
||||
}
|
||||
richText := mustMarshalModuleJSON(t, output.Value)
|
||||
for _, field := range []string{"condition_text_lower", "wind_direction_text"} {
|
||||
if !strings.Contains(richText, field) {
|
||||
t.Fatalf("rich current conditions json = %s, want helper field %s", richText, field)
|
||||
}
|
||||
}
|
||||
|
||||
prompt := moduleDataPackageValue[CurrentConditionsPromptExport](t, output)
|
||||
if prompt.ConditionText != "Partly cloudy" || prompt.TemperatureF == nil || *prompt.TemperatureF != 74 {
|
||||
t.Fatalf("current prompt export = %#v, want condition text and temperature", prompt)
|
||||
}
|
||||
if prompt.ApparentTemperatureF == nil || *prompt.ApparentTemperatureF != 76 || prompt.RelativeHumidityPercent == nil || *prompt.RelativeHumidityPercent != 71 || prompt.WindSpeedMph == nil || *prompt.WindSpeedMph != 8 {
|
||||
t.Fatalf("current prompt export = %#v, want apparent temperature, humidity, and wind speed", prompt)
|
||||
}
|
||||
if prompt.WindDirection != "S" {
|
||||
t.Fatalf("current prompt wind direction = %q, want S", prompt.WindDirection)
|
||||
}
|
||||
promptText := mustMarshalModuleJSON(t, output.DataPackageValue())
|
||||
for _, field := range []string{"condition_text", "temperature_f", "apparent_temperature_f", "relative_humidity_percent", "wind_speed_mph", "wind_direction"} {
|
||||
if !strings.Contains(promptText, field) {
|
||||
t.Fatalf("current prompt json = %s, want field %s", promptText, field)
|
||||
}
|
||||
}
|
||||
for _, field := range []string{"condition_text_lower", "wind_direction_text"} {
|
||||
if strings.Contains(promptText, field) {
|
||||
t.Fatalf("current prompt json = %s, want omitted helper field %s", promptText, field)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlertDigestDistinguishesCheckedEmptyAndMissing(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
ctx.Collected.Alerts = &weatherdata.AlertRun{}
|
||||
ctx.Derived.AlertOverlaps = nil
|
||||
|
||||
output, err := registry.BuildModule(ctx, module.ConfigItem{ID: module.AlertDigest})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule(checked empty) error = %v", err)
|
||||
}
|
||||
checked := moduleValue[AlertDigestModule](t, output)
|
||||
if !checked.Checked || checked.ActiveCount != 0 || checked.RelevantCount != 0 || checked.Missing {
|
||||
t.Fatalf("checked empty alert digest = %#v, want checked/no active", checked)
|
||||
}
|
||||
|
||||
ctx.Collected.Alerts = nil
|
||||
ctx.Collected.SourceProvenance = []weatherdata.Source{{Name: "alerts", Missing: true}}
|
||||
output, err = registry.BuildModule(ctx, module.ConfigItem{ID: module.AlertDigest})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule(missing) error = %v", err)
|
||||
}
|
||||
missing := moduleValue[AlertDigestModule](t, output)
|
||||
if missing.Checked || !missing.Missing {
|
||||
t.Fatalf("missing alert digest = %#v, want missing unchecked source", missing)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlertDigestIncludesPeriodAndGuidance(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
ctx.Collected.Alerts = &weatherdata.AlertRun{Alerts: []json.RawMessage{json.RawMessage(`{"event":"Wind Advisory"}`)}}
|
||||
ctx.Derived.AlertOverlaps = []forecast.AlertOverlap{{
|
||||
Event: "Wind Advisory",
|
||||
Headline: "Wind Advisory until 8 PM",
|
||||
Severity: "Moderate",
|
||||
Period: timeutil.Period{Start: mustParseModuleTime("2026-06-17T18:00:00Z"), End: mustParseModuleTime("2026-06-18T01:00:00Z")},
|
||||
Instruction: "Secure outdoor objects.",
|
||||
Description: "Gusty winds may blow around unsecured objects.",
|
||||
}}
|
||||
|
||||
output, err := registry.BuildModule(ctx, module.ConfigItem{ID: module.AlertDigest})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule(alert digest) error = %v", err)
|
||||
}
|
||||
value := moduleValue[AlertDigestModule](t, output)
|
||||
if len(value.Relevant) != 1 {
|
||||
t.Fatalf("Relevant length = %d, want 1", len(value.Relevant))
|
||||
}
|
||||
alert := value.Relevant[0]
|
||||
if alert.Event != "Wind Advisory" || alert.Headline != "Wind Advisory until 8 PM" || alert.Severity != "Moderate" {
|
||||
t.Fatalf("alert identity = %#v, want preserved event/headline/severity", alert)
|
||||
}
|
||||
if alert.PeriodBegins != "June 17 at 1:00 PM" || alert.PeriodEnds != "June 17 at 8:00 PM" {
|
||||
t.Fatalf("alert period = %q/%q, want friendly local labels", alert.PeriodBegins, alert.PeriodEnds)
|
||||
}
|
||||
if alert.Instruction != "Secure outdoor objects." || alert.Description != "Gusty winds may blow around unsecured objects." {
|
||||
t.Fatalf("alert guidance = %#v, want instruction and description preserved", alert)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseModulesOmitMissingOptionalOutputs(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
ctx.Collected.Current = nil
|
||||
ctx.Collected.Narrative = nil
|
||||
ctx.Collected.Hourly = nil
|
||||
ctx.Derived.ValidPeriodNarrativePeriods = nil
|
||||
ctx.Derived.ValidPeriodHourlyPeriods = nil
|
||||
ctx.Collected.Discussion = nil
|
||||
ctx.Collected.WeatherStory = nil
|
||||
|
||||
for _, id := range []module.ID{module.CurrentConditions, module.NarrativeForecast, module.HourlyForecast, module.AreaForecastDiscussion, module.WeatherStory} {
|
||||
output, err := registry.BuildModule(ctx, module.ConfigItem{ID: id})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule(%s) error = %v", id, err)
|
||||
}
|
||||
if output != nil {
|
||||
t.Fatalf("BuildModule(%s) output = %#v, want omitted", id, output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAreaForecastDiscussionAndWeatherStoryModules(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
|
||||
afdOutput, err := registry.BuildModule(ctx, module.ConfigItem{ID: module.AreaForecastDiscussion})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule(afd) error = %v", err)
|
||||
}
|
||||
afd := moduleValue[AreaForecastDiscussionModule](t, afdOutput)
|
||||
if len(afd.KeyMessages) != 1 || afd.ShortTerm != "Showers increase this afternoon." || afd.LongTerm != "Periodic rain chances continue." {
|
||||
t.Fatalf("AFD = %#v, want discussion sections", afd)
|
||||
}
|
||||
|
||||
storyOutput, err := registry.BuildModule(ctx, module.ConfigItem{ID: module.WeatherStory})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule(weather story) error = %v", err)
|
||||
}
|
||||
story := moduleValue[WeatherStoryModule](t, storyOutput)
|
||||
if !story.Available || story.Title != "Rain Chances" || story.Description != "Scattered showers are possible." {
|
||||
t.Fatalf("WeatherStory = %#v, want structured story fields", story)
|
||||
}
|
||||
if story.PeriodBegins != "2026-05-29 at 6:00 AM" || story.PeriodEnds != "2026-05-29 at 6:00 PM" {
|
||||
t.Fatalf("WeatherStory period = %q/%q, want friendly local period labels", story.PeriodBegins, story.PeriodEnds)
|
||||
}
|
||||
data, err := json.Marshal(storyOutput.Value)
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal weather story: %v", err)
|
||||
}
|
||||
if !strings.Contains(string(data), "download_url") || !strings.Contains(string(data), "period_begins") || !strings.Contains(string(data), "period_ends") {
|
||||
t.Fatalf("weather story json = %s, want snake_case download_url", string(data))
|
||||
}
|
||||
if strings.Contains(string(data), "start_time") || strings.Contains(string(data), "end_time") {
|
||||
t.Fatalf("weather story json = %s, want period_begins/period_ends instead of start_time/end_time", string(data))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAreaForecastDiscussionModuleCanSelectSections(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
options any
|
||||
}{
|
||||
{name: "value", options: module.AreaForecastDiscussionOptions{Sections: []string{"short_term"}}},
|
||||
{name: "pointer", options: &module.AreaForecastDiscussionOptions{Sections: []string{"short_term"}}},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
output, err := registry.BuildModule(ctx, module.ConfigItem{
|
||||
ID: module.AreaForecastDiscussion,
|
||||
Options: tt.options,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule() error = %v", err)
|
||||
}
|
||||
afd := moduleValue[AreaForecastDiscussionModule](t, output)
|
||||
if afd.ShortTerm != "Showers increase this afternoon." {
|
||||
t.Fatalf("ShortTerm = %q, want selected short term section", afd.ShortTerm)
|
||||
}
|
||||
if afd.Product != "" || len(afd.KeyMessages) != 0 || afd.LongTerm != "" {
|
||||
t.Fatalf("AFD = %#v, want only short_term section", afd)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeatherStoryModuleOmitsEmptyContent(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
ctx.Collected.WeatherStory = &weatherdata.WeatherStory{OfficeID: "LSX", Priority: true, Order: 1}
|
||||
|
||||
output, err := registry.BuildModule(ctx, module.ConfigItem{ID: module.WeatherStory})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule() error = %v", err)
|
||||
}
|
||||
if output != nil {
|
||||
t.Fatalf("output = %#v, want omitted weather story", output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWeatherStoryModulePreservesZeroPriorityAndOrder(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
ctx.Collected.WeatherStory = &weatherdata.WeatherStory{Title: "Rain Chances"}
|
||||
|
||||
output, err := registry.BuildModule(ctx, module.ConfigItem{ID: module.WeatherStory})
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule() error = %v", err)
|
||||
}
|
||||
story := moduleValue[WeatherStoryModule](t, output)
|
||||
if !story.Available || story.Priority || story.Order != 0 {
|
||||
t.Fatalf("WeatherStory = %#v, want available story with zero priority and order", story)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAreaForecastDiscussionModuleUsesHourlyDefaultSections(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
ctx.Resolved.Definition = report.DefaultRegistry().MustLookup(report.Hourly)
|
||||
var item module.ConfigItem
|
||||
for _, candidate := range ctx.Resolved.Definition.Modules {
|
||||
if candidate.ID == module.AreaForecastDiscussion {
|
||||
item = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
if item.ID == "" {
|
||||
t.Fatal("hourly default modules missing area_forecast_discussion")
|
||||
}
|
||||
|
||||
output, err := registry.BuildModule(ctx, item)
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule() error = %v", err)
|
||||
}
|
||||
afd := moduleValue[AreaForecastDiscussionModule](t, output)
|
||||
if len(afd.KeyMessages) != 1 || afd.ShortTerm != "Showers increase this afternoon." {
|
||||
t.Fatalf("AFD = %#v, want key messages and short term", afd)
|
||||
}
|
||||
if afd.Product != "" || afd.LongTerm != "" {
|
||||
t.Fatalf("AFD = %#v, want product and long term omitted", afd)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAreaForecastDiscussionModuleUsesDailyDefaultSections(t *testing.T) {
|
||||
registry := MustDefaultModuleRegistry()
|
||||
ctx := testModuleContext()
|
||||
ctx.Resolved.Definition = report.DefaultRegistry().MustLookup(report.Daily)
|
||||
var item module.ConfigItem
|
||||
for _, candidate := range ctx.Resolved.Definition.Modules {
|
||||
if candidate.ID == module.AreaForecastDiscussion {
|
||||
item = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
if item.ID == "" {
|
||||
t.Fatal("daily default modules missing area_forecast_discussion")
|
||||
}
|
||||
|
||||
output, err := registry.BuildModule(ctx, item)
|
||||
if err != nil {
|
||||
t.Fatalf("BuildModule() error = %v", err)
|
||||
}
|
||||
afd := moduleValue[AreaForecastDiscussionModule](t, output)
|
||||
if afd.LongTerm != "Periodic rain chances continue." {
|
||||
t.Fatalf("LongTerm = %q, want selected long term section", afd.LongTerm)
|
||||
}
|
||||
if afd.Product != "" || len(afd.KeyMessages) != 0 || afd.ShortTerm != "" {
|
||||
t.Fatalf("AFD = %#v, want only long term section", afd)
|
||||
}
|
||||
}
|
||||
|
||||
func testModuleContext() ModuleContext {
|
||||
generatedAt := mustParseModuleTime("2026-05-29T08:00:00-05:00")
|
||||
definition := report.DefaultRegistry().MustLookup(report.Daily)
|
||||
resolved := report.Resolved{
|
||||
Definition: definition,
|
||||
GeneratedAt: generatedAt,
|
||||
Timezone: "America/Chicago",
|
||||
ValidPeriod: timeutil.Period{
|
||||
Start: mustParseModuleTime("2026-05-29T00:00:00-05:00"),
|
||||
End: mustParseModuleTime("2026-05-30T00:00:00-05:00"),
|
||||
},
|
||||
}
|
||||
isDay := true
|
||||
tempF := 74.4
|
||||
apparentF := 75.6
|
||||
humidity := 70.6
|
||||
windMph := 8.4
|
||||
windDirection := 190.0
|
||||
narrativeTempF := 81.0
|
||||
narrativePop := 60.0
|
||||
narrativeWind := 12.0
|
||||
narrativeWindDirection := 45.0
|
||||
hourlyTempF := 76.0
|
||||
hourlyPop := 70.0
|
||||
hourlyHumidity := 66.0
|
||||
hourlyWindMph := 14.0
|
||||
updatedAt := mustParseModuleTime("2026-05-29T07:30:00-05:00")
|
||||
ctx := ModuleContext{
|
||||
Resolved: resolved,
|
||||
Collected: facts.CollectedFacts{
|
||||
Current: &weatherdata.Current{
|
||||
ConditionText: "Partly cloudy",
|
||||
IsDay: &isDay,
|
||||
TemperatureF: &tempF,
|
||||
ApparentTemperatureF: &apparentF,
|
||||
RelativeHumidityPercent: &humidity,
|
||||
WindSpeedMph: &windMph,
|
||||
WindDirectionDegrees: &windDirection,
|
||||
},
|
||||
Narrative: &weatherdata.ForecastRun{
|
||||
LocationID: "test-grid",
|
||||
LocationName: "Testville",
|
||||
IssuedAt: mustParseModuleTime("2026-05-29T10:30:00-05:00"),
|
||||
UpdatedAt: &updatedAt,
|
||||
Product: "narrative",
|
||||
Periods: []weatherdata.ForecastPeriod{
|
||||
{
|
||||
Name: "Today",
|
||||
StartTime: mustParseModuleTime("2026-05-29T06:00:00-05:00"),
|
||||
EndTime: mustParseModuleTime("2026-05-29T18:00:00-05:00"),
|
||||
IsDay: &isDay,
|
||||
TextDescription: "Morning storms, then partly sunny.",
|
||||
TemperatureF: floatPtr(narrativeTempF),
|
||||
WindSpeedMph: &narrativeWind,
|
||||
WindDirectionDegrees: &narrativeWindDirection,
|
||||
ProbabilityOfPrecipitationPercent: &narrativePop,
|
||||
},
|
||||
},
|
||||
},
|
||||
Hourly: &weatherdata.ForecastRun{
|
||||
LocationID: "test-grid",
|
||||
LocationName: "Testville",
|
||||
IssuedAt: mustParseModuleTime("2026-05-29T10:30:00-05:00"),
|
||||
UpdatedAt: &updatedAt,
|
||||
Product: "hourly",
|
||||
Periods: []weatherdata.ForecastPeriod{
|
||||
{
|
||||
StartTime: mustParseModuleTime("2026-05-29T08:00:00-05:00"),
|
||||
EndTime: mustParseModuleTime("2026-05-29T09:00:00-05:00"),
|
||||
TextDescription: "Showers likely.",
|
||||
TemperatureF: &hourlyTempF,
|
||||
WindSpeedMph: &hourlyWindMph,
|
||||
WindDirectionDegrees: &windDirection,
|
||||
ProbabilityOfPrecipitationPercent: &hourlyPop,
|
||||
RelativeHumidityPercent: &hourlyHumidity,
|
||||
},
|
||||
{
|
||||
StartTime: mustParseModuleTime("2026-05-30T08:00:00-05:00"),
|
||||
EndTime: mustParseModuleTime("2026-05-30T09:00:00-05:00"),
|
||||
TextDescription: "Tomorrow showers.",
|
||||
},
|
||||
},
|
||||
},
|
||||
Alerts: &weatherdata.AlertRun{Alerts: []json.RawMessage{
|
||||
json.RawMessage(`{"event":"Flood Watch","headline":"Flooding possible","severity":"Moderate"}`),
|
||||
}},
|
||||
Discussion: &weatherdata.Discussion{
|
||||
Product: "discussion",
|
||||
KeyMessages: []string{"Scattered showers are possible."},
|
||||
ShortTerm: &weatherdata.DiscussionSection{Text: "Showers increase this afternoon."},
|
||||
LongTerm: &weatherdata.DiscussionSection{Text: "Periodic rain chances continue."},
|
||||
},
|
||||
WeatherStory: &weatherdata.WeatherStory{
|
||||
OfficeID: "LSX",
|
||||
StartTime: mustParseModuleTime("2026-05-29T06:00:00-05:00"),
|
||||
EndTime: mustParseModuleTime("2026-05-29T18:00:00-05:00"),
|
||||
UpdatedAt: &updatedAt,
|
||||
Title: "Rain Chances",
|
||||
Description: "Scattered showers are possible.",
|
||||
AltText: "Weather story graphic with rain chances.",
|
||||
Priority: true,
|
||||
Order: 1,
|
||||
DownloadURL: "https://example.invalid/story.png",
|
||||
},
|
||||
SourceProvenance: []weatherdata.Source{{Name: "alerts", FetchedAt: generatedAt}},
|
||||
SourceWarnings: []weatherdata.SourceWarning{{
|
||||
Source: "daily",
|
||||
Code: "missing_source",
|
||||
Severity: "warning",
|
||||
Message: "daily source is missing",
|
||||
Endpoint: "/forecast/daily",
|
||||
CompletenessImpact: "source omitted",
|
||||
}},
|
||||
},
|
||||
Derived: facts.DerivedFacts{
|
||||
ValidPeriodHourlyPeriods: []weatherdata.ForecastPeriod{
|
||||
{
|
||||
StartTime: mustParseModuleTime("2026-05-29T08:00:00-05:00"),
|
||||
EndTime: mustParseModuleTime("2026-05-29T09:00:00-05:00"),
|
||||
TextDescription: "Showers likely.",
|
||||
TemperatureF: &hourlyTempF,
|
||||
WindSpeedMph: &hourlyWindMph,
|
||||
WindDirectionDegrees: &windDirection,
|
||||
ProbabilityOfPrecipitationPercent: &hourlyPop,
|
||||
RelativeHumidityPercent: &hourlyHumidity,
|
||||
},
|
||||
},
|
||||
ValidPeriodNarrativePeriods: []weatherdata.ForecastPeriod{
|
||||
{
|
||||
Name: "Today",
|
||||
StartTime: mustParseModuleTime("2026-05-29T06:00:00-05:00"),
|
||||
EndTime: mustParseModuleTime("2026-05-29T18:00:00-05:00"),
|
||||
IsDay: &isDay,
|
||||
TextDescription: "Morning storms, then partly sunny.",
|
||||
TemperatureF: floatPtr(narrativeTempF),
|
||||
WindSpeedMph: &narrativeWind,
|
||||
WindDirectionDegrees: &narrativeWindDirection,
|
||||
ProbabilityOfPrecipitationPercent: &narrativePop,
|
||||
},
|
||||
},
|
||||
AlertOverlaps: []forecast.AlertOverlap{{
|
||||
Event: "Flood Watch",
|
||||
Headline: "Flooding possible",
|
||||
Severity: "Moderate",
|
||||
}},
|
||||
},
|
||||
Units: "us",
|
||||
Timezone: "America/Chicago",
|
||||
Location: &LocationContext{
|
||||
ID: "home",
|
||||
Name: "Brentwood",
|
||||
Region: "St. Louis Metro",
|
||||
Timezone: "America/Chicago",
|
||||
},
|
||||
}
|
||||
ctx.Identity = BuildPreparedIdentity(BuildContext{
|
||||
Resolved: ctx.Resolved,
|
||||
Bundle: ctx.Collected.Bundle(),
|
||||
Units: ctx.Units,
|
||||
Timezone: ctx.Timezone,
|
||||
Location: ctx.Location,
|
||||
})
|
||||
return ctx
|
||||
}
|
||||
|
||||
func moduleValue[T any](t *testing.T, output *module.Output) T {
|
||||
t.Helper()
|
||||
var value T
|
||||
data, err := json.Marshal(output.Value)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal module value: %v", err)
|
||||
}
|
||||
if err := json.Unmarshal(data, &value); err != nil {
|
||||
t.Fatalf("decode module value: %v", err)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func moduleDataPackageValue[T any](t *testing.T, output *module.Output) T {
|
||||
t.Helper()
|
||||
var value T
|
||||
data, err := json.Marshal(output.DataPackageValue())
|
||||
if err != nil {
|
||||
t.Fatalf("marshal module data package value: %v", err)
|
||||
}
|
||||
if err := json.Unmarshal(data, &value); err != nil {
|
||||
t.Fatalf("decode module data package value: %v", err)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func mustMarshalModuleJSON(t *testing.T, value any) string {
|
||||
t.Helper()
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal module value: %v", err)
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
|
||||
func mustParseModuleTime(value string) time.Time {
|
||||
parsed, err := time.Parse(time.RFC3339, value)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
104
internal/briefing/current_conditions_module.go
Normal file
104
internal/briefing/current_conditions_module.go
Normal file
@@ -0,0 +1,104 @@
|
||||
package briefing
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/module"
|
||||
)
|
||||
|
||||
type CurrentConditionsModule struct {
|
||||
ConditionText string `json:"condition_text,omitempty"`
|
||||
ConditionTextLower string `json:"condition_text_lower,omitempty"`
|
||||
IsDay *bool `json:"is_day,omitempty"`
|
||||
TemperatureC *int `json:"temperature_c,omitempty"`
|
||||
TemperatureF *int `json:"temperature_f,omitempty"`
|
||||
ApparentTemperatureC *int `json:"apparent_temperature_c,omitempty"`
|
||||
ApparentTemperatureF *int `json:"apparent_temperature_f,omitempty"`
|
||||
DewpointC *int `json:"dewpoint_c,omitempty"`
|
||||
DewpointF *int `json:"dewpoint_f,omitempty"`
|
||||
RelativeHumidityPercent *int `json:"relative_humidity_percent,omitempty"`
|
||||
WindSpeedKmh *int `json:"wind_speed_kmh,omitempty"`
|
||||
WindSpeedMph *int `json:"wind_speed_mph,omitempty"`
|
||||
WindDirection string `json:"wind_direction,omitempty"`
|
||||
WindDirectionText string `json:"wind_direction_text,omitempty"`
|
||||
}
|
||||
|
||||
type CurrentConditionsPromptExport struct {
|
||||
ConditionText string `json:"condition_text,omitempty"`
|
||||
IsDay *bool `json:"is_day,omitempty"`
|
||||
TemperatureC *int `json:"temperature_c,omitempty"`
|
||||
TemperatureF *int `json:"temperature_f,omitempty"`
|
||||
ApparentTemperatureC *int `json:"apparent_temperature_c,omitempty"`
|
||||
ApparentTemperatureF *int `json:"apparent_temperature_f,omitempty"`
|
||||
DewpointC *int `json:"dewpoint_c,omitempty"`
|
||||
DewpointF *int `json:"dewpoint_f,omitempty"`
|
||||
RelativeHumidityPercent *int `json:"relative_humidity_percent,omitempty"`
|
||||
WindSpeedKmh *int `json:"wind_speed_kmh,omitempty"`
|
||||
WindSpeedMph *int `json:"wind_speed_mph,omitempty"`
|
||||
WindDirection string `json:"wind_direction,omitempty"`
|
||||
}
|
||||
|
||||
func buildCurrentConditionsModule(ctx ModuleContext, _ any) (*module.Output, error) {
|
||||
current := ctx.Collected.Current
|
||||
if current == nil {
|
||||
return nil, nil
|
||||
}
|
||||
value := CurrentConditionsModule{
|
||||
ConditionText: current.ConditionText,
|
||||
ConditionTextLower: strings.ToLower(current.ConditionText),
|
||||
IsDay: copyBool(current.IsDay),
|
||||
TemperatureC: roundedInt(current.TemperatureC),
|
||||
TemperatureF: roundedInt(current.TemperatureF),
|
||||
ApparentTemperatureC: roundedInt(current.ApparentTemperatureC),
|
||||
ApparentTemperatureF: roundedInt(current.ApparentTemperatureF),
|
||||
DewpointC: roundedInt(current.DewpointC),
|
||||
DewpointF: roundedInt(current.DewpointF),
|
||||
RelativeHumidityPercent: roundedInt(current.RelativeHumidityPercent),
|
||||
WindSpeedKmh: roundedInt(current.WindSpeedKmh),
|
||||
WindSpeedMph: roundedInt(current.WindSpeedMph),
|
||||
WindDirection: windDirectionLabel(current.WindDirectionDegrees),
|
||||
WindDirectionText: windDirectionTextLabel(current.WindDirectionDegrees),
|
||||
}
|
||||
if value.isEmpty() {
|
||||
return nil, nil
|
||||
}
|
||||
return &module.Output{ID: module.CurrentConditions, StanzaName: "current_conditions", Value: value}, nil
|
||||
}
|
||||
|
||||
func exportCurrentConditionsPromptValue(value any) (any, error) {
|
||||
rich, ok := value.(CurrentConditionsModule)
|
||||
if !ok {
|
||||
return nil, unexpectedPromptExportValue(value, CurrentConditionsModule{})
|
||||
}
|
||||
return CurrentConditionsPromptExport{
|
||||
ConditionText: rich.ConditionText,
|
||||
IsDay: copyBool(rich.IsDay),
|
||||
TemperatureC: copyInt(rich.TemperatureC),
|
||||
TemperatureF: copyInt(rich.TemperatureF),
|
||||
ApparentTemperatureC: copyInt(rich.ApparentTemperatureC),
|
||||
ApparentTemperatureF: copyInt(rich.ApparentTemperatureF),
|
||||
DewpointC: copyInt(rich.DewpointC),
|
||||
DewpointF: copyInt(rich.DewpointF),
|
||||
RelativeHumidityPercent: copyInt(rich.RelativeHumidityPercent),
|
||||
WindSpeedKmh: copyInt(rich.WindSpeedKmh),
|
||||
WindSpeedMph: copyInt(rich.WindSpeedMph),
|
||||
WindDirection: rich.WindDirection,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (v CurrentConditionsModule) isEmpty() bool {
|
||||
return v.ConditionText == "" &&
|
||||
v.ConditionTextLower == "" &&
|
||||
v.IsDay == nil &&
|
||||
v.TemperatureC == nil &&
|
||||
v.TemperatureF == nil &&
|
||||
v.ApparentTemperatureC == nil &&
|
||||
v.ApparentTemperatureF == nil &&
|
||||
v.DewpointC == nil &&
|
||||
v.DewpointF == nil &&
|
||||
v.RelativeHumidityPercent == nil &&
|
||||
v.WindSpeedKmh == nil &&
|
||||
v.WindSpeedMph == nil &&
|
||||
v.WindDirection == "" &&
|
||||
v.WindDirectionText == ""
|
||||
}
|
||||
24
internal/briefing/daily_planning_module.go
Normal file
24
internal/briefing/daily_planning_module.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package briefing
|
||||
|
||||
import "gitea.maximumdirect.net/eric/weatherreporter/internal/module"
|
||||
|
||||
type DailyPlanningModule struct {
|
||||
MorningReadiness []string `json:"morning_readiness,omitempty"`
|
||||
CommuteSchoolWorkdayConcerns []string `json:"commute_school_workday_concerns,omitempty"`
|
||||
OvernightChangeWatch []string `json:"overnight_change_watch,omitempty"`
|
||||
}
|
||||
|
||||
func buildDailyPlanningModule(ctx ModuleContext, _ any) (*module.Output, error) {
|
||||
summary := ctx.Derived.FirstDailySummary()
|
||||
if summary == nil {
|
||||
return &module.Output{ID: module.DailyPlanning, StanzaName: "daily_planning", Value: DailyPlanningModule{}}, nil
|
||||
}
|
||||
planning := buildMorningCommuteOvernightPlanning(summary)
|
||||
value := DailyPlanningModule{}
|
||||
if planning != nil {
|
||||
value.MorningReadiness = append([]string(nil), planning.MorningReadiness...)
|
||||
value.CommuteSchoolWorkdayConcerns = append([]string(nil), planning.CommuteSchoolWorkdayConcerns...)
|
||||
value.OvernightChangeWatch = append([]string(nil), planning.OvernightChangeWatch...)
|
||||
}
|
||||
return &module.Output{ID: module.DailyPlanning, StanzaName: "daily_planning", Value: value}, nil
|
||||
}
|
||||
153
internal/briefing/derived_daily_summary_module.go
Normal file
153
internal/briefing/derived_daily_summary_module.go
Normal file
@@ -0,0 +1,153 @@
|
||||
package briefing
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/forecast"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/module"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/weatherdata"
|
||||
)
|
||||
|
||||
type DerivedDailySummaryModule struct {
|
||||
Date string `json:"date,omitempty"`
|
||||
HighTempF *int `json:"high_temp_f,omitempty"`
|
||||
LowTempF *int `json:"low_temp_f,omitempty"`
|
||||
DailyPrecipitationProbability *int `json:"daily_precipitation_probability,omitempty"`
|
||||
MostLikelyPrecipitationHour string `json:"most_likely_precipitation_hour,omitempty"`
|
||||
ThunderMentioned bool `json:"thunder_mentioned"`
|
||||
MaxWindGustMph *int `json:"max_wind_gust_mph,omitempty"`
|
||||
ApparentTemperatureMaxF *int `json:"apparent_temperature_max_f,omitempty"`
|
||||
DominantConditions []string `json:"dominant_conditions,omitempty"`
|
||||
Hazards []string `json:"hazards,omitempty"`
|
||||
}
|
||||
|
||||
func buildDerivedDailySummaryModule(ctx ModuleContext, _ any) (*module.Output, error) {
|
||||
summary := ctx.Derived.FirstDailySummary()
|
||||
if summary == nil {
|
||||
return nil, fmt.Errorf("daily summary facts are required")
|
||||
}
|
||||
value, err := derivedDailySummaryValue(*summary, ctx.Derived.PrecipTiming, ctx.Timezone)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &module.Output{ID: module.DerivedDailySummary, StanzaName: "derived_daily_summary", Value: value}, nil
|
||||
}
|
||||
|
||||
func derivedDailySummaryValue(summary forecast.DailySummary, timing forecast.PrecipTiming, timezone string) (DerivedDailySummaryModule, error) {
|
||||
value := DerivedDailySummaryModule{
|
||||
Date: friendlyDateLabel(summary.Date, timezone),
|
||||
ThunderMentioned: timing.ThunderMentioned,
|
||||
}
|
||||
conditions := map[string]struct{}{}
|
||||
hazards := map[string]struct{}{}
|
||||
var temperature forecast.Range
|
||||
var apparent forecast.Range
|
||||
var maxPop *forecast.TimedValue
|
||||
var maxGust *forecast.TimedValue
|
||||
for _, daypart := range summary.Dayparts {
|
||||
addRange(&temperature, daypart.Temperature)
|
||||
addRange(&apparent, daypart.ApparentTemperature)
|
||||
maxTimedValue(&maxPop, daypart.MaxPrecipitationProbability)
|
||||
maxTimedValue(&maxGust, daypart.PeakWindGust)
|
||||
if daypart.DominantCondition != "" {
|
||||
conditions[daypart.DominantCondition] = struct{}{}
|
||||
}
|
||||
for _, hazard := range hazardsForIndicators(daypart.Indicators) {
|
||||
hazards[hazard] = struct{}{}
|
||||
}
|
||||
}
|
||||
for _, alert := range summary.AlertOverlaps {
|
||||
if alert.Event != "" {
|
||||
hazards[alert.Event] = struct{}{}
|
||||
}
|
||||
}
|
||||
narrativeTemperature := narrativeTemperatureRange(summary.NarrativePeriods)
|
||||
if narrativeTemperature.Max != nil {
|
||||
value.HighTempF = roundedInt(narrativeTemperature.Max)
|
||||
} else {
|
||||
value.HighTempF = roundedInt(temperature.Max)
|
||||
}
|
||||
if narrativeTemperature.Min != nil {
|
||||
value.LowTempF = roundedInt(narrativeTemperature.Min)
|
||||
} else {
|
||||
value.LowTempF = roundedInt(temperature.Min)
|
||||
}
|
||||
value.ApparentTemperatureMaxF = roundedInt(apparent.Max)
|
||||
narrativePrecipitation := narrativeMaxPrecipitation(summary.NarrativePeriods)
|
||||
if narrativePrecipitation != nil {
|
||||
value.DailyPrecipitationProbability = roundedInt(&narrativePrecipitation.Value)
|
||||
} else if maxPop != nil {
|
||||
value.DailyPrecipitationProbability = roundedInt(&maxPop.Value)
|
||||
}
|
||||
if maxPop != nil {
|
||||
value.MostLikelyPrecipitationHour = mostLikelyPrecipitationHour(maxPop, timezone)
|
||||
}
|
||||
if maxGust != nil {
|
||||
value.MaxWindGustMph = roundedInt(&maxGust.Value)
|
||||
}
|
||||
value.DominantConditions = sortedSet(conditions)
|
||||
value.Hazards = sortedSet(hazards)
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func narrativeTemperatureRange(periods []weatherdata.ForecastPeriod) forecast.Range {
|
||||
var out forecast.Range
|
||||
for _, period := range periods {
|
||||
addNarrativeHigh(&out, period.TemperatureFMax)
|
||||
addNarrativeLow(&out, period.TemperatureFMin)
|
||||
if period.TemperatureF != nil && period.IsDay != nil {
|
||||
if *period.IsDay {
|
||||
addNarrativeHigh(&out, period.TemperatureF)
|
||||
} else {
|
||||
addNarrativeLow(&out, period.TemperatureF)
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func addNarrativeHigh(target *forecast.Range, value *float64) {
|
||||
if value == nil {
|
||||
return
|
||||
}
|
||||
if target.Max == nil || *value > *target.Max {
|
||||
copied := *value
|
||||
target.Max = &copied
|
||||
}
|
||||
}
|
||||
|
||||
func addNarrativeLow(target *forecast.Range, value *float64) {
|
||||
if value == nil {
|
||||
return
|
||||
}
|
||||
if target.Min == nil || *value < *target.Min {
|
||||
copied := *value
|
||||
target.Min = &copied
|
||||
}
|
||||
}
|
||||
|
||||
func narrativeMaxPrecipitation(periods []weatherdata.ForecastPeriod) *forecast.TimedValue {
|
||||
var maxPop *forecast.TimedValue
|
||||
for _, period := range periods {
|
||||
if period.ProbabilityOfPrecipitationPercent == nil {
|
||||
continue
|
||||
}
|
||||
value := forecast.TimedValue{
|
||||
Value: *period.ProbabilityOfPrecipitationPercent,
|
||||
Time: period.StartTime,
|
||||
}
|
||||
maxTimedValue(&maxPop, &value)
|
||||
}
|
||||
return maxPop
|
||||
}
|
||||
|
||||
func mostLikelyPrecipitationHour(maxPop *forecast.TimedValue, timezone string) string {
|
||||
if maxPop == nil || maxPop.Value <= 0 {
|
||||
return ""
|
||||
}
|
||||
percent := roundedInt(&maxPop.Value)
|
||||
if percent == nil {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%d%% at %s", *percent, clockLabel(maxPop.Time, timezone))
|
||||
}
|
||||
403
internal/briefing/derived_daypart_summaries_module.go
Normal file
403
internal/briefing/derived_daypart_summaries_module.go
Normal file
@@ -0,0 +1,403 @@
|
||||
package briefing
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/forecast"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/module"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/timeutil"
|
||||
"gitea.maximumdirect.net/eric/weatherreporter/internal/weatherdata"
|
||||
)
|
||||
|
||||
type DerivedDaypartSummaryModule struct {
|
||||
Date string `json:"date,omitempty"`
|
||||
DisplayName string `json:"display_name,omitempty"`
|
||||
PeriodBegins string `json:"period_begins,omitempty"`
|
||||
PeriodEnds string `json:"period_ends,omitempty"`
|
||||
TempRangeF string `json:"temp_range_f,omitempty"`
|
||||
TemperaturePhraseF string `json:"temperature_phrase_f,omitempty"`
|
||||
ApparentTempRangeF string `json:"apparent_temp_range_f,omitempty"`
|
||||
MaxPopPercent *int `json:"max_pop_percent,omitempty"`
|
||||
MaxPopTime string `json:"max_pop_time,omitempty"`
|
||||
MaxPopTimeLabel string `json:"max_pop_time_label,omitempty"`
|
||||
MentionPrecipitation bool `json:"mention_precipitation,omitempty"`
|
||||
MaxWindGustMph *int `json:"max_wind_gust_mph,omitempty"`
|
||||
MaxWindGustTime string `json:"max_wind_gust_time,omitempty"`
|
||||
DominantCondition string `json:"dominant_condition,omitempty"`
|
||||
DominantConditionLower string `json:"dominant_condition_lower,omitempty"`
|
||||
DominantConditionDisplay string `json:"dominant_condition_display,omitempty"`
|
||||
TemperatureTrend string `json:"temperature_trend,omitempty"`
|
||||
TemperatureStartPhraseF string `json:"temperature_start_phrase_f,omitempty"`
|
||||
TemperatureEndPhraseF string `json:"temperature_end_phrase_f,omitempty"`
|
||||
TemperaturePeakPhraseF string `json:"temperature_peak_phrase_f,omitempty"`
|
||||
TemperatureSteadyPhraseF string `json:"temperature_steady_phrase_f,omitempty"`
|
||||
NotableConditions []string `json:"notable_conditions,omitempty"`
|
||||
Snow bool `json:"snow,omitempty"`
|
||||
Ice bool `json:"ice,omitempty"`
|
||||
Fog bool `json:"fog,omitempty"`
|
||||
Heat bool `json:"heat,omitempty"`
|
||||
Cold bool `json:"cold,omitempty"`
|
||||
Wind bool `json:"wind,omitempty"`
|
||||
RelevantAlertCount int `json:"relevant_alert_count,omitempty"`
|
||||
}
|
||||
|
||||
type DerivedDaypartSummaryPromptExport struct {
|
||||
Date string `json:"date,omitempty"`
|
||||
DisplayName string `json:"display_name,omitempty"`
|
||||
PeriodBegins string `json:"period_begins,omitempty"`
|
||||
PeriodEnds string `json:"period_ends,omitempty"`
|
||||
TempRangeF string `json:"temp_range_f,omitempty"`
|
||||
ApparentTempRangeF string `json:"apparent_temp_range_f,omitempty"`
|
||||
MaxPopPercent *int `json:"max_pop_percent,omitempty"`
|
||||
MaxPopTime string `json:"max_pop_time,omitempty"`
|
||||
MentionPrecipitation bool `json:"mention_precipitation,omitempty"`
|
||||
MaxWindGustMph *int `json:"max_wind_gust_mph,omitempty"`
|
||||
MaxWindGustTime string `json:"max_wind_gust_time,omitempty"`
|
||||
DominantCondition string `json:"dominant_condition,omitempty"`
|
||||
TemperatureTrend string `json:"temperature_trend,omitempty"`
|
||||
TemperatureStartPhraseF string `json:"temperature_start_phrase_f,omitempty"`
|
||||
TemperatureEndPhraseF string `json:"temperature_end_phrase_f,omitempty"`
|
||||
TemperaturePeakPhraseF string `json:"temperature_peak_phrase_f,omitempty"`
|
||||
TemperatureSteadyPhraseF string `json:"temperature_steady_phrase_f,omitempty"`
|
||||
NotableConditions []string `json:"notable_conditions,omitempty"`
|
||||
Snow bool `json:"snow,omitempty"`
|
||||
Ice bool `json:"ice,omitempty"`
|
||||
Fog bool `json:"fog,omitempty"`
|
||||
Heat bool `json:"heat,omitempty"`
|
||||
Cold bool `json:"cold,omitempty"`
|
||||
Wind bool `json:"wind,omitempty"`
|
||||
RelevantAlertCount int `json:"relevant_alert_count,omitempty"`
|
||||
}
|
||||
|
||||
func buildDerivedDaypartSummariesModule(ctx ModuleContext, _ any) (*module.Output, error) {
|
||||
if len(ctx.Derived.DaypartSummaries) == 0 {
|
||||
return nil, fmt.Errorf("daypart summary facts are required")
|
||||
}
|
||||
value := map[string]DerivedDaypartSummaryModule{}
|
||||
prefixDates := multipleSummaryDates(ctx.Derived.DailySummaries)
|
||||
for _, daypart := range ctx.Derived.DaypartSummaries {
|
||||
key := daypartKey(daypart, prefixDates)
|
||||
if existing, exists := value[key]; exists {
|
||||
return nil, fmt.Errorf("daypart summary key %q collides with display name %q", key, existing.DisplayName)
|
||||
}
|
||||
value[key] = derivedDaypartSummaryValue(daypart, ctx.Timezone)
|
||||
}
|
||||
return &module.Output{ID: module.DerivedDaypartSummaries, StanzaName: "derived_daypart_summaries", Value: value}, nil
|
||||
}
|
||||
|
||||
func exportDerivedDaypartSummariesPromptValue(value any) (any, error) {
|
||||
rich, ok := value.(map[string]DerivedDaypartSummaryModule)
|
||||
if !ok {
|
||||
return nil, unexpectedPromptExportValue(value, map[string]DerivedDaypartSummaryModule{})
|
||||
}
|
||||
out := make(map[string]DerivedDaypartSummaryPromptExport, len(rich))
|
||||
for key, daypart := range rich {
|
||||
out[key] = derivedDaypartSummaryPromptValue(daypart)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func derivedDaypartSummaryPromptValue(rich DerivedDaypartSummaryModule) DerivedDaypartSummaryPromptExport {
|
||||
maxPopTime := rich.MaxPopTime
|
||||
if rich.MaxPopTimeLabel != "" {
|
||||
maxPopTime = rich.MaxPopTimeLabel
|
||||
}
|
||||
return DerivedDaypartSummaryPromptExport{
|
||||
Date: rich.Date,
|
||||
DisplayName: rich.DisplayName,
|
||||
PeriodBegins: rich.PeriodBegins,
|
||||
PeriodEnds: rich.PeriodEnds,
|
||||
TempRangeF: rich.TempRangeF,
|
||||
ApparentTempRangeF: rich.ApparentTempRangeF,
|
||||
MaxPopPercent: copyInt(rich.MaxPopPercent),
|
||||
MaxPopTime: maxPopTime,
|
||||
MentionPrecipitation: rich.MentionPrecipitation,
|
||||
MaxWindGustMph: copyInt(rich.MaxWindGustMph),
|
||||
MaxWindGustTime: rich.MaxWindGustTime,
|
||||
DominantCondition: rich.DominantCondition,
|
||||
TemperatureTrend: rich.TemperatureTrend,
|
||||
TemperatureStartPhraseF: rich.TemperatureStartPhraseF,
|
||||
TemperatureEndPhraseF: rich.TemperatureEndPhraseF,
|
||||
TemperaturePeakPhraseF: rich.TemperaturePeakPhraseF,
|
||||
TemperatureSteadyPhraseF: rich.TemperatureSteadyPhraseF,
|
||||
NotableConditions: append([]string(nil), rich.NotableConditions...),
|
||||
Snow: rich.Snow,
|
||||
Ice: rich.Ice,
|
||||
Fog: rich.Fog,
|
||||
Heat: rich.Heat,
|
||||
Cold: rich.Cold,
|
||||
Wind: rich.Wind,
|
||||
RelevantAlertCount: rich.RelevantAlertCount,
|
||||
}
|
||||
}
|
||||
|
||||
func derivedDaypartSummaryValue(daypart forecast.DaypartSummary, timezone string) DerivedDaypartSummaryModule {
|
||||
temperature := daypartTemperatureDisplay(daypart)
|
||||
value := DerivedDaypartSummaryModule{
|
||||
Date: localDateLabel(daypart.Period.Start, timezone),
|
||||
DisplayName: capitalizeFirst(strings.TrimSpace(daypart.Name)),
|
||||
PeriodBegins: friendlyPeriodBeginsLabel(daypart.Period, timezone),
|
||||
PeriodEnds: friendlyPeriodEndsLabel(daypart.Period, timezone),
|
||||
TempRangeF: rangeLabel(daypart.Temperature),
|
||||
TemperaturePhraseF: temperaturePhraseF(daypart.Temperature),
|
||||
TemperatureTrend: temperature.Trend,
|
||||
TemperatureStartPhraseF: temperature.StartPhrase,
|
||||
TemperatureEndPhraseF: temperature.EndPhrase,
|
||||
TemperaturePeakPhraseF: temperature.PeakPhrase,
|
||||
TemperatureSteadyPhraseF: temperature.SteadyPhrase,
|
||||
ApparentTempRangeF: daypartApparentRangeLabel(daypart.ApparentTemperature),
|
||||
DominantCondition: daypart.DominantCondition,
|
||||
DominantConditionLower: strings.ToLower(daypart.DominantCondition),
|
||||
DominantConditionDisplay: capitalizeFirst(strings.TrimSpace(daypart.DominantCondition)),
|
||||
NotableConditions: append([]string(nil), daypart.NotableConditions...),
|
||||
Snow: daypart.Indicators.Snow,
|
||||
Ice: daypart.Indicators.Ice,
|
||||
Fog: daypart.Indicators.Fog,
|
||||
Heat: daypart.Indicators.Heat,
|
||||
Cold: daypart.Indicators.Cold,
|
||||
Wind: daypart.Indicators.Wind,
|
||||
RelevantAlertCount: len(daypart.AlertOverlaps),
|
||||
}
|
||||
if daypart.MaxPrecipitationProbability != nil {
|
||||
value.MaxPopPercent = roundedInt(&daypart.MaxPrecipitationProbability.Value)
|
||||
value.MaxPopTime = clockLabel(daypart.MaxPrecipitationProbability.Time, timezone)
|
||||
value.MaxPopTimeLabel = hourMinuteLabel(daypart.MaxPrecipitationProbability.Time, timezone)
|
||||
value.MentionPrecipitation = mentionHourlyForecastPrecipitation(&daypart.MaxPrecipitationProbability.Value, hourlyForecastPrecipMentionProbabilityThreshold)
|
||||
}
|
||||
if daypart.PeakWindGust != nil {
|
||||
value.MaxWindGustMph = roundedInt(&daypart.PeakWindGust.Value)
|
||||
value.MaxWindGustTime = clockLabel(daypart.PeakWindGust.Time, timezone)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
type daypartTemperaturePresentation struct {
|
||||
Trend string
|
||||
StartPhrase string
|
||||
EndPhrase string
|
||||
PeakPhrase string
|
||||
SteadyPhrase string
|
||||
}
|
||||
|
||||
type temperaturePoint struct {
|
||||
value int
|
||||
bandIndex int
|
||||
phrase string
|
||||
}
|
||||
|
||||
const (
|
||||
temperatureTrendRising = "rising"
|
||||
temperatureTrendFalling = "falling"
|
||||
temperatureTrendPeaking = "peaking"
|
||||
temperatureTrendSteady = "steady"
|
||||
)
|
||||
|
||||
func daypartTemperatureDisplay(daypart forecast.DaypartSummary) daypartTemperaturePresentation {
|
||||
points := daypartTemperaturePoints(daypart.HourlyPeriods)
|
||||
if len(points) == 0 {
|
||||
return daypartSteadyTemperatureDisplay(temperaturePhraseF(daypart.Temperature))
|
||||
}
|
||||
if len(points) == 1 {
|
||||
return daypartSteadyTemperatureDisplay(points[0].phrase)
|
||||
}
|
||||
|
||||
first := points[0]
|
||||
last := points[len(points)-1]
|
||||
peak, peakIndex := peakTemperaturePoint(points)
|
||||
if peakIndex > 0 && peakIndex < len(points)-1 && peak.bandIndex > first.bandIndex && peak.bandIndex > last.bandIndex {
|
||||
return daypartTemperaturePresentation{
|
||||
Trend: temperatureTrendPeaking,
|
||||
PeakPhrase: peak.phrase,
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case first.bandIndex < last.bandIndex:
|
||||
return daypartTemperaturePresentation{
|
||||
Trend: temperatureTrendRising,
|
||||
StartPhrase: first.phrase,
|
||||
EndPhrase: last.phrase,
|
||||
}
|
||||
case first.bandIndex > last.bandIndex:
|
||||
return daypartTemperaturePresentation{
|
||||
Trend: temperatureTrendFalling,
|
||||
StartPhrase: first.phrase,
|
||||
EndPhrase: last.phrase,
|
||||
}
|
||||
default:
|
||||
return daypartSteadyTemperatureDisplay(temperaturePhraseF(daypart.Temperature))
|
||||
}
|
||||
}
|
||||
|
||||
func daypartSteadyTemperatureDisplay(phrase string) daypartTemperaturePresentation {
|
||||
if phrase == "" {
|
||||
return daypartTemperaturePresentation{}
|
||||
}
|
||||
return daypartTemperaturePresentation{
|
||||
Trend: temperatureTrendSteady,
|
||||
SteadyPhrase: phrase,
|
||||
}
|
||||
}
|
||||
|
||||
func daypartTemperaturePoints(periods []weatherdata.ForecastPeriod) []temperaturePoint {
|
||||
sorted := append([]weatherdata.ForecastPeriod(nil), periods...)
|
||||
sort.SliceStable(sorted, func(i int, j int) bool {
|
||||
return sorted[i].StartTime.Before(sorted[j].StartTime)
|
||||
})
|
||||
points := make([]temperaturePoint, 0, len(sorted))
|
||||
for _, period := range sorted {
|
||||
temperature := forecastPeriodTemperatureF(period)
|
||||
if temperature == nil {
|
||||
continue
|
||||
}
|
||||
rounded := roundedInt(temperature)
|
||||
if rounded == nil {
|
||||
continue
|
||||
}
|
||||
points = append(points, temperaturePoint{
|
||||
value: *rounded,
|
||||
bandIndex: temperatureBandIndex(*rounded),
|
||||
phrase: temperatureBandPhrase(*rounded),
|
||||
})
|
||||
}
|
||||
return points
|
||||
}
|
||||
|
||||
func peakTemperaturePoint(points []temperaturePoint) (temperaturePoint, int) {
|
||||
peak := points[0]
|
||||
peakIndex := 0
|
||||
for index, point := range points[1:] {
|
||||
if point.value > peak.value {
|
||||
peak = point
|
||||
peakIndex = index + 1
|
||||
}
|
||||
}
|
||||
return peak, peakIndex
|
||||
}
|
||||
|
||||
func forecastPeriodTemperatureF(period weatherdata.ForecastPeriod) *float64 {
|
||||
switch {
|
||||
case period.TemperatureF != nil:
|
||||
return period.TemperatureF
|
||||
case period.TemperatureFMax != nil:
|
||||
return period.TemperatureFMax
|
||||
case period.TemperatureFMin != nil:
|
||||
return period.TemperatureFMin
|
||||
case period.TemperatureC != nil:
|
||||
value := celsiusToFahrenheit(*period.TemperatureC)
|
||||
return &value
|
||||
case period.TemperatureCMax != nil:
|
||||
value := celsiusToFahrenheit(*period.TemperatureCMax)
|
||||
return &value
|
||||
case period.TemperatureCMin != nil:
|
||||
value := celsiusToFahrenheit(*period.TemperatureCMin)
|
||||
return &value
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func celsiusToFahrenheit(value float64) float64 {
|
||||
return value*9/5 + 32
|
||||
}
|
||||
|
||||
func temperatureBandIndex(value int) int {
|
||||
decade, remainder := temperatureBandParts(value)
|
||||
band := temperatureBandQualifierIndex(remainder)
|
||||
return decade*3 + band
|
||||
}
|
||||
|
||||
func temperaturePhraseF(value forecast.Range) string {
|
||||
if value.Min == nil && value.Max == nil {
|
||||
return ""
|
||||
}
|
||||
if value.Min != nil && value.Max != nil {
|
||||
low := roundedInt(value.Min)
|
||||
high := roundedInt(value.Max)
|
||||
if low == nil || high == nil {
|
||||
return ""
|
||||
}
|
||||
lowPhrase := temperatureBandPhrase(*low)
|
||||
highPhrase := temperatureBandPhrase(*high)
|
||||
if lowPhrase == highPhrase {
|
||||
return lowPhrase
|
||||
}
|
||||
return lowPhrase + " to " + highPhrase
|
||||
}
|
||||
if value.Min != nil {
|
||||
low := roundedInt(value.Min)
|
||||
if low == nil {
|
||||
return ""
|
||||
}
|
||||
return temperatureBandPhrase(*low)
|
||||
}
|
||||
high := roundedInt(value.Max)
|
||||
if high == nil {
|
||||
return ""
|
||||
}
|
||||
return temperatureBandPhrase(*high)
|
||||
}
|
||||
|
||||
func temperatureBandPhrase(value int) string {
|
||||
if value < 0 {
|
||||
decade, remainder := temperatureBandParts(-value)
|
||||
qualifier := temperatureBandQualifier(remainder)
|
||||
if decade == 0 {
|
||||
return fmt.Sprintf("%s single digits below zero", qualifier)
|
||||
}
|
||||
return fmt.Sprintf("%s %ds below zero", qualifier, decade)
|
||||
}
|
||||
decade, remainder := temperatureBandParts(value)
|
||||
qualifier := temperatureBandQualifier(remainder)
|
||||
return fmt.Sprintf("%s %ds", qualifier, decade)
|
||||
}
|
||||
|
||||
func temperatureBandParts(value int) (int, int) {
|
||||
decade := value / 10
|
||||
if value < 0 && value%10 != 0 {
|
||||
decade--
|
||||
}
|
||||
return decade * 10, value - decade*10
|
||||
}
|
||||
|
||||
func temperatureBandQualifierIndex(remainder int) int {
|
||||
switch {
|
||||
case remainder <= 3:
|
||||
return 0
|
||||
case remainder >= 7:
|
||||
return 2
|
||||
default:
|
||||
return 1
|
||||
}
|
||||
}
|
||||
|
||||
func temperatureBandQualifier(remainder int) string {
|
||||
switch temperatureBandQualifierIndex(remainder) {
|
||||
case 0:
|
||||
return "low"
|
||||
case 2:
|
||||
return "upper"
|
||||
default:
|
||||
return "mid"
|
||||
}
|
||||
}
|
||||
|
||||
func multipleSummaryDates(summaries []forecast.DailySummary) bool {
|
||||
seen := map[string]struct{}{}
|
||||
for _, summary := range summaries {
|
||||
seen[summary.Date] = struct{}{}
|
||||
}
|
||||
return len(seen) > 1
|
||||
}
|
||||
|
||||
func daypartKey(daypart forecast.DaypartSummary, prefixDate bool) string {
|
||||
key := forecast.CanonicalDaypartKey(daypart.Name)
|
||||
if key == "" {
|
||||
key = "unnamed"
|
||||
}
|
||||
if !prefixDate {
|
||||
return key
|
||||
}
|
||||
return daypart.Period.Start.Format(timeutil.DateLayout) + "_" + key
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user