diff --git a/CLAUDE.md b/CLAUDE.md index 1df2d36..cb057cf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -82,6 +82,9 @@ test → build on every push/PR. | `CDSE_CLIENT_ID` / `CDSE_CLIENT_SECRET` | `eo_search`, `eo_render`, `eo_index`, `eo_compare` | Free Copernicus Data Space OAuth client | | `FIRMS_MAP_KEY` | `fires_in` | Free NASA FIRMS map key | | `GEE_SERVICE_ACCOUNT_JSON` / `GEE_PROJECT` | `gee_query` | Earth Engine service-account key (path or inline JSON) + EE-registered Cloud project — see `docs/research/2026-09-26_google-earth-engine.md` | +| `GFW_FISHING_TOKEN` | `fishing_activity`, rule `mpa_fishing`, `api/marine/fishing.json` | Global *Fishing* Watch API v3 token (non-commercial terms; not the Global *Forest* Watch `GFW_API_KEY`). Daily cap `EARTHDECK_MAX_GFW_FISHING_CALLS` (default 200) | +| `AISSTREAM_KEY` | `api/marine/ships.json` (export only) | aisstream.io websocket key — runner-side 20 s sample, aggregates only; never shipped to the browser | +| `EARTHDECK_MAX_GDELT_CALLS` | `watch export` "In the news" | GDELT DOC lookups per export (default 40; zero-key, paced ≤1 req/5.5 s, 12 h cache; `--no-news` disables) | | `EARTHDECK_DASHBOARD_URL` | card push target | default `http://127.0.0.1:5005` | | `EARTHDECK_DASHBOARD_PORT` | dashboard server | default `5005` | diff --git a/CONTINUITY.md b/CONTINUITY.md index ed4b47e..5b81975 100644 --- a/CONTINUITY.md +++ b/CONTINUITY.md @@ -39,8 +39,16 @@ reference is [CLAUDE.md](CLAUDE.md); the phase plan is [ROADMAP.md](ROADMAP.md). $71/yr, refund refused by AWS, auto-renew OFF; Marc dislikes the name but uses it since it's paid). The public name is the neutral **"Earth Watch"** (`src/site.config.ts`); "Vital Earth" is a taken trademark. **The site is anonymous**: no owner name, email or - GitHub handle anywhere (test in `test/site-export.test.ts` fails on any); right of reply - has no channel yet (a forwarding mailbox on the domain is a follow-up). Do NOT register + GitHub handle anywhere (test in `test/site-export.test.ts` fails on any). Right of reply = + the **public reply wall** (2026-09-27; no email, nobody reads an inbox): `earthdeck-reply` + Lambda behind a Function URL (`POST /reply`, src/replies/intake.ts) → `replies/inbox/`; + the analyst's reviewer (Sonnet) screens ≤ 50/run → `replies/public/` (+ `commented` ledger + event, text hash only) or `replies/rejected/`; the export renders them + the form + (`--reply-url` = stack output ReplyUrl, set on the runner as EARTHDECK_REPLY_URL). + deploy.sh creates `/earthdeck/REPLY_SALT` once. LIVE since 2026-09-27 (end-to-end + tested: Marc's test reply accepted by the reviewer, then removed by hand = delete the + `replies/public//.json` object + export; the export now deletes stale site + files under api/ and watch/). Do NOT register or buy anything without showing Marc the exact item + price first. IPv6 is disabled on CloudFront on purpose (AAAA-only resolver answers broke the fresh domain on IPv6-less networks); Tailscale MagicDNS on Marc's Mac negative-cached the name for an hour. @@ -52,6 +60,21 @@ reference is [CLAUDE.md](CLAUDE.md); the phase plan is [ROADMAP.md](ROADMAP.md). (new stack + migrate state, or keep internal names); domain (registration only after trademark check + Marc's explicit OK on the exact name + price); README/CLAUDE/VISION; `checkpoint` signer name stays "earthdeck" unless the key is rotated. Do it in one PR. +2a. **2026-09-27 state**: interactive MapLibre globe on the public site (click-to-case, URL + share links, time scrubber + replay, Whole-Earth mode, offline search, GFW-alert and + before/after overlays, weather layers: clouds, satellite rain, wind, cyclone cones); + favicon/og/manifest set. New rules live on AWS: `indicator_threshold` (sea ice, marine + heatwave, rivers w/ seasonal gate, PM2.5, ENSO, M7+ quakes), `indicator_trend` (annual + LPI/RLI/fish/pH/tree-loss/MPA, one case per indicator-year), `weather_extreme` (heat, + cyclone cone via NHC+GDACS→EONET, extreme rain); watchlists `indicators.json` (30) and + `weather.json` (18) in the scheduled hand-written sweep. First real sweep opened 14 cases. + `natural_value` now uses MapBiomas (Brazil) / Dynamic World via **Earth Engine** (project + mystic-hull-373410, service account terrakeep-ee, key `~/.config/vital/gee-key.json`, + Community tier, non-commercial until 2028-03-27) — pasture = converted, São Félix + $1.98bn → $1.02bn/yr. **Keys added to .env** (not yet in SSM/Lambda): GEE_*, GFW_FISHING_TOKEN + (Global Fishing Watch, non-commercial), AISSTREAM_KEY — the GEE path on Lambda needs the key + content in SSM (deploy.sh + runner change) before forest findings get the MapBiomas note there. + Next queued: ships (aisstream) + fishing effort (GFW) as map layers and an MPA-fishing rule. 2b. **Scale-out state (2026-09-26 late)**: `earthdeck discover` generates 549 AOIs (`watchlists/generated/`, 19 API calls, 53 s; re-run every ~14 days — doctor warns when stale). Runner sweeps `all-generated` in 8 shards per 6-h window (13.5-min budget each), @@ -62,7 +85,47 @@ reference is [CLAUDE.md](CLAUDE.md); the phase plan is [ROADMAP.md](ROADMAP.md). when spent — detection always runs. TODO: measure Copernicus PU per `eo_compare`/S5P call (free tier 10k PU/month) and set the cap from data. Name: **TerraKeep**, slogan "Keeping Earth within its limits." — package/repo/stack rename still pending (3b). -3c. **Queued by Marc 2026-09-26 (in this order, one at a time — "take it slowly")**: +2c. **2026-09-27 afternoon state (all LIVE on vitalearth.io, branch `worktree-earth-watch-m3`, + 432 tests)**: site v4 = full-screen globe + floating panel with modes Cases / Planet / + Live / Metrics / About (`web/src/site/{hub,panel}.ts`, `map/explore.ts`); click-to-case + stays in-map (`#case=`, static case pages redirect JS readers, crawlers get the page); + Metrics from `src/watch/metrics.ts` → `api/metrics.json`; layer registry + (`web/src/layers/registry.ts`, every module in layers/ self-registers). Marine: + `fishing_activity` tool (GFW 4Wings, grouped only — never per-vessel), `mpa_fishing@1.0` + rule (effort inside the reserve's legal boundary), `watchlists/marine.json` (16 reserves, + 50 tiles), runner export `api/marine/{fishing,ships}.json` (keys only on the runner). + First sweep: Phoenix Islands ×2 + Galápagos confirmed — both allow some licensed fishing, + watch the reviewer. `improvement@1.0` rule (forest_recovery, flaring_decline, + bleaching_relief ≥ NOAA Alert Level 1, air_quality_clean, fires_absent; NDVI confirmation + opt-in `confirmWithNdvi`), `watchlists/good-news.json`; topic "Good news" chip (also + flaring_stopped). VNF parser bug fixed (sci-notation inflated 2023 totals 10×). QA pass: + fixed-width replay/caption/chips, panel-internal scroll, indicator blind spots filtered to + the case's indicator, globe hit-test fix (nearest dot ≤ 12 px; `pnpm test:e2e` + Playwright), cluster zoom ≥ 1.5. SSM now has GFW_FISHING_TOKEN, AISSTREAM_KEY, GEE_*, + REPLY_SALT. "In the news" per case (GDELT DOC 2.0 keyword search, `src/clients/gdelt.ts`, + `src/watch/news.ts`, `api/news/.json`, context not evidence, `--no-news` to disable) + is merged and deployed but UNPROVEN: GDELT answered 429 to the first call from Lambda and + from the worker's Mac, so no real case has headlines yet; it fails soft (one 429 stops the + export's lookups, cache 12 h). If it keeps failing or returns junk, add `--no-news` to the + runner's export args. **Situation briefing** (LIVE 2026-09-27): `src/watch/situation.ts` + computes level quiet/watch/urgent by fixed rules (TRUST.md "The daily Situation"; the + 3-in-a-region rule counts only acute rules, never flaring/good news, 5° box, 3 distinct + AOIs); analyst job writes one Opus briefing/day reviewed by Sonnet (≈$0.10), stored as + `situation/.json` beside the ledger (not in the Merkle tree), fallback = rules-only + text; export → `api/situation.json`; site strip above the map + top of Planet mode. + Today: Watch (sea ice both poles p10, 50 confirmations/7 d). Known nits: attribution bar + overlaps the Replay button in Planet mode when the ocean-heat layer is on; old situation + files may not be deleted from S3. Open with Marc: keep running after Mon 08:03 stop (session cron), + analyst cap 20, SNS email confirm, rotate aisstream key (was pasted in chat), hide Live + toggles whose data file is missing, old `assets/` bundles never deleted. +3c. **Queued by Marc 2026-09-26/27 (in this order, one at a time — "take it slowly")**: + -1. **Indicator-threshold rule** (2026-09-27, top of queue, in progress): one generic rule + `indicator_threshold@1` over the existing zero-key indicator tools — sea ice below + p10 (NSIDC), marine heatwave at a reef/coast point (OISST), river discharge > 2× mean + (GloFAS), PM2.5 > WHO for N days in watched cities (CAMS), ENSO phase declared (ONI), + M7+ quake in a watched region (USGS) — case type "threshold crossed", second signal = + persistence (next window) or a second dataset. Plus a **trend rule** for annual + indices (LPI, RLI, fish stocks, ocean pH): one case per year per indicator. 1. **Backtest harness** — `earthdeck backtest --event `: replay rules with the clock set to a past date for 8–10 documented events (2019 Amazon fires, 2020 Black Summer, 2023 Canada, 2023 Maui, Rumaila flaring 2024, São Félix 2025 loss, Permian methane diff --git a/README.md b/README.md index 7673fa8..e4f8122 100644 --- a/README.md +++ b/README.md @@ -72,6 +72,8 @@ Then just ask: *"What's the state of the planet right now?"* · *"Is El Niño co | `climate_history` | How a place's climate changed: ERA5 temperature/precip/wind, annual trend per decade | 1940→ | | `air_quality` | PM2.5 / PM10 / O₃ / NO₂ / US AQI for any point (Copernicus CAMS), WHO-guideline flags | 48 h | | `river_discharge` | Daily river flow at any point (GloFAS) — flood/drought signal vs the period mean | 1984→ | +| `weather_now` | Weather now + past week + 7-day forecast for any point (Open-Meteo): max/min, feels-like, rain, wind — each day's max vs the ERA5 1991–2020 normal, plus ERA5's own independent reading of the elapsed days | now ± 7 d | +| `storms` | Every active tropical cyclone: NOAA NHC/CPHC advisories (position, Saffir–Simpson category, forecast track + cone) and GDACS for the other basins, cross-checked with NASA EONET; optional bbox / min category | live | | `earthdata_search` | Discover datasets across NASA's full Earth-science archive (~50k collections, CMR) by topic/bbox/time | catalog | | `world_pulse` | Vital signs in three groups — civilization, life (Living Planet Index, Red List Index, fish stocks, protected areas, tree cover loss), planet (ocean pH, nitrogen, pesticides, water, plastic, ozone) — each improving/worsening/flat | per indicator | @@ -171,13 +173,30 @@ primary signal, and marks it *confirmed* only when the rule's **independent seco agrees (`forest_loss`: GFW alerts → NDVI drop in a Sentinel-2 median composite; `fires_in_protected`: VIIRS cluster → EONET event or re-detection on a later pass; `flaring`: night-time heat persisting ≥ N nights → a VNF annual flare site or a later pass). -`methane_anomaly` (tier 2): Sentinel-5P CH₄ anomaly vs 90 days → EMIT plume in the AOI). +`methane_anomaly` (tier 2): Sentinel-5P CH₄ anomaly vs 90 days → EMIT plume in the AOI; +`weather_extreme` (tier 0, `watchlists/weather.json`): heat over a city's bar for ≥ 2 days → ERA5 agrees or it +persists; a category ≥ 1 cyclone cone over a region → NASA EONET; ≥ 150 mm/day → GloFAS discharge ≥ 2× or persistence). +Two zero-key tier-1 rules widen the watch beyond forests and flares +(`watchlists/indicators.json`, 30 AOIs): + +| Rule · `indicator` | Crosses the line when… | Confirmed by | +| --- | --- | --- | +| `indicator_threshold` · `sea_ice` | NSIDC daily extent (Arctic / Antarctic) is below the 1981–2010 p10 for the day | a later day still below p10 (revisit) | +| `indicator_threshold` · `marine_heatwave` | OISST at a reef/sea point is ≥ `minAnomalyC` (1.5 °C) above the same season of the last 10 years for ≥ `minDays` (5) | a later day still that warm (revisit) | +| `indicator_threshold` · `river_discharge` | GloFAS discharge ≥ `ratio` (2×) the 10-year mean (optionally also ≥ `minSeasonalRatio` × the same month) | an EONET flood within 200 km (provider), else a later day still high | +| `indicator_threshold` · `air_quality` | CAMS PM2.5 daily mean > the WHO 15 µg/m³ guideline for ≥ `minDays` (3) full days | a later full day still above (revisit) | +| `indicator_threshold` · `enso` | ONI meets NOAA's event definition (≥ 5 seasons beyond ±0.5 °C) — one global case per event | OISST at the Niño3.4 centre has the same-sign anomaly (method) | +| `indicator_threshold` · `quake` | USGS M ≥ `minMagnitude` (7.0) inside the AOI box | USGS marks it reviewed with `sig` ≥ `minSig` (600) — same provider (method) | +| `indicator_trend` | a new year's value of an annual world-pulse indicator (Living Planet Index, Red List Index, fish stocks, ocean pH, tree cover loss, marine protected areas) continues a worsening — or improving (tag `improvement`) — 10-year trend | the same value on a later read (method: data stability) | + +`indicator_trend` runs one AOI per indicator (`wp-`, `cooldownDays: 1`) and reads its +own earlier cases via `ledger_list`, so each indicator-year opens exactly one case, ever. Every rule must declare its **blind spots** and keeps a **regional baseline** (the AOI vs its neighbourhood ring — "did it stop, or did it move?"); every finding carries **context** (ENSO phase, nearby EONET events). Watermarks make late or missed runs self-heal; failures are recorded as coverage gaps, never silence. **Control AOIs** (expected quiet) measure our own false-positive rate. Needs `GFW_API_KEY` + CDSE creds (forest) and `FIRMS_MAP_KEY` -(fires); pairs whose keys are missing are skipped, not failed. +(fires); pairs whose keys are missing are skipped, not failed. The indicator rules need no key. **Triage from Claude** — `ledger_list`, `ledger_get`, `ledger_verify` (read) and `ledger_advance`, `ledger_narrate`, `ledger_review`, `ledger_propose_attribution` (append) @@ -386,6 +405,12 @@ Tests mock the network, so the whole suite runs with zero credentials — CI - NOAA Coral Reef Watch CoralTemp v3.1 5 km products via CoastWatch / PacIOOS ERDDAP (free; credit NOAA CRW). - Our World in Data (CC BY 4.0) for `world_pulse`; upstream producers and licences are listed per indicator. - `natural_value`: CLMS Global Land Cover 2020, 10 m (© European Union, Copernicus Land Monitoring Service; DOI 10.2909/602507b2-96c7-47bb-b79d-7ba25e97d0a9; free and open, attribute and state modifications); ecosystem-service unit values from Costanza et al. (2014) and de Groot et al. (2012), organism values from Chami et al. (IMF) — cited per entry in the result. +- Weather: forecast data by [Open-Meteo.com](https://open-meteo.com/) (CC BY 4.0; ECMWF, DWD, NOAA models) with ERA5 + (Copernicus Climate Change Service) normals; tropical cyclones from NOAA/NWS NHC & CPHC (U.S. public data, + [weather.gov/disclaimer](https://www.weather.gov/disclaimer)) and [GDACS](https://www.gdacs.org/) (UN OCHA / EC JRC, + provided as is); map overlays from NASA GIBS (VIIRS, GPM IMERG) and, on the local dashboard only, + [RainViewer](https://www.rainviewer.com/) radar (personal/educational use). Source catalogue with licences: + `docs/research/2026-09-27_live-data-sources.md`. - Basemap & geocoding: NASA Blue Marble; OpenStreetMap Nominatim. - Attribution: protected areas © OpenStreetMap contributors (ODbL) via Overpass; LandMark Indigenous & community lands (CC BY-SA 4.0) via the GFW Data API; emissions from diff --git a/TRUST.md b/TRUST.md index 58884a3..aa64a82 100644 --- a/TRUST.md +++ b/TRUST.md @@ -63,6 +63,43 @@ To name a responsible party (an operator, an owner): a retraction, but they never publish or suppress a finding on their own. The evidence and the rules above decide. +## The daily Situation — how the level is set + +Once a day the site shows one level for the whole watch: **quiet**, **watch** or +**urgent**. The level is set by the fixed rules below, never by the AI. Each rule that +fires is listed under "Why this level", pointing at the cases or indicators behind it. + +It is **urgent** if any of these is true: + +- the El Niño / La Niña phase (NOAA's definition: five seasons in a row beyond ±0.5 °C) + was newly declared or changed this month, or an ENSO case was opened this month; +- an earthquake of magnitude 7 or more became a case in the last 48 hours; +- an extreme-heat or tropical-cyclone case was published in the last 48 hours; +- Arctic or Antarctic sea ice is below the lowest value ever recorded for that date; +- cases were confirmed within one day at three or more different watched places in the + same region (a 5° × 5° box). Only rules about something happening now count here: forest + loss, fires in protected land, extreme weather, methane, fishing inside marine reserves, + and the earthquake, marine-heatwave, river-flood and air-pollution indicators. Gas + flaring, flaring that stopped, and good-news cases never count toward urgent; they can + only raise the level to watch through the 7-day rule below. + +It is **watch** if none of those holds but any of these does: + +- at least one case was confirmed by a second, independent signal in the last 7 days; +- a world indicator just moved outside its usual range (above its 90th or below its 10th + percentile, when the reading before was inside); +- sea ice is in the lowest tenth of 1981–2010 for the date. + +Otherwise it is **quiet**. + +An AI then writes a short briefing from a fixed set of facts (the level and its reasons, +what changed since yesterday, new and good-news cases, the indicators, the false alarms we +caught). Every number in it must appear in those facts, it may not name people, and a +second, separate AI must accept it. If any of that fails, the site shows the rules' own +plain sentences instead. At most one AI briefing is written a day. The briefing is kept +next to the signed ledger for 30 days, not inside it: the ledger records only events on +individual cases. + ## Changing these rules Each publish entry names the policy it was made under. Changing the rules means a new diff --git a/docs/research/2026-09-27_gods-eye-view-map.md b/docs/research/2026-09-27_gods-eye-view-map.md new file mode 100644 index 0000000..73fca4b --- /dev/null +++ b/docs/research/2026-09-27_gods-eye-view-map.md @@ -0,0 +1,136 @@ +# God's Eye View → the TerraKeep map (2026-09-27) + +Source: [bilawalsidhu/gods-eye-view](https://github.com/bilawalsidhu/gods-eye-view), read at `b210ab0`. +It is a Cesium 3D-globe "spy-satellite simulator": live flights, ships, satellites, CCTV, weather, +wildfires, with GLSL "sensor looks". The code is MIT. **The bundled data is not.** Its TeleGeography +cables are CC BY-NC-SA, its Bhote Koshi imagery and derived coordinates are CC BY-NC, its OSM +extracts are ODbL, and its 3D models each have their own licence. Google tiles and OpenSky +restrict commercial use. We took ideas and patterns only: no code, no data, no assets. + +## What they do well + +- **Every layer has the same shape.** Each data source (e.g. `src/layers/firms/`) is split into + `source` / `model` / `rendering` / `cards` / `selection` / `lifecycle`. A source is just + `getSnapshot({signal})`. When it has no key it returns `keyRequired`. Malformed payloads are + refused, never drawn. +- **Degradation is honest.** The loading-feedback model keeps `loading`, `error`, + `unavailable`, `keyRequired` and `degraded` apart. It also knows that "empty" or "zoom in" + are prompts, not failures. A chip that can't be used says why, and never flips its state + before the switch actually succeeds. +- **The share link is a handoff.** `src/sharelink.js` writes the camera, style, layers and + tracked target into the URL hash. Its rules: + - Writes use `history.replaceState`, debounced, and are versioned (`v=2`). + - Layer tokens are one letter each, from a fixed registry. + - A single unknown token rejects the whole layer set (fail closed). + - Fields have length caps, and numbers are clamped on both read and write. + - Nothing is written until the restore has finished. + - Any gesture from the recipient beats a pending restore flight. + - A copy-time `at=` stamp lets a stale tracked target say "expired" instead of silently + pointing at nothing. +- **Keyless search is layered and strict.** Coordinates come first. The parser accepts decimal + degrees only: a sign, or one N/S/E/W letter per part. It rejects a sign plus a letter together, + two letters on the same axis, and trailing text. Then come bundled exact names, then + Photon/Nominatim, each with a timeout and a cache. +- **Selection is guarded.** A focus request is validated before it takes the camera, and a + generation stamp stops a slow request from yanking the view after a newer one. Framing is + set per kind of thing. Escape closes only the innermost panel and returns focus to the button + that opened it. +- **Time is one clock.** Weather replay has a single clock over the union of every product's + frames. Each product has a `maxGapMs`, and the UI labels it "synced" vs "nearest". Play waits + until every layer has loaded the current frame. The slider is native, with `aria-valuetext`. +- **Global Context** enters a named bundle of layers as one transaction. On exit it restores + what you had, plus what you added inside minus what you removed. It restores layers, not the + camera. +- **Budgets are explicit.** Rendering happens only on demand, using named "holds", which cut + idle GPU use by about 60 %. First-run hints are suppressed on shared links, and their storage + access survives private-mode Safari. + +## What transfers to a cases-and-evidence site, and what doesn't + +Their product is a live-feed toy: things move, and the fun is following them. Ours is a +**record**: a case is a claim with evidence, a status and a date, and it must not move. So: + +- **Tracking becomes selecting a case.** Our "target" is a case id. The card shows only what + the ledger says (headline, status, place, the value of nature at stake, the date seen) and + links to the full case page. There are no trails. The time scrubber takes their place: cases + fade in as `observedAt` passes. +- **Their weather replay becomes a replay of the record.** The clock runs over case dates, not + radar frames. A window of 30 / 90 / 365 days or all time, a day slider, and a Replay that + sweeps it. It is linear on purpose: it shows time passing, not an object moving. The stats + strip counts only the window. +- **Share links matter even more for us.** A journalist, a reviewer or the party named in a + case should be able to send exactly what they saw: camera, layers, time window, selected + case and evidence overlays. We copied the discipline (versioned, fail-closed tokens, clamped, + no writes before a restore or a gesture) with far fewer fields. +- **Degradation.** Every overlay is decoration over a record that already exists as HTML. If + WebGL, GIBS, GFW or HLS fail, the reader still has the static map, the pins and the list, so + failure is silent. There are no "LOAD FAILED" chips. +- **Global Context** is our "Whole Earth" button: all cases, all statuses including false + alarms, all time. Unlike theirs, pressing it again (or Escape) **also restores the camera**. + For a reader who wanders off, that is the point of the button. + +## What we skipped, and why + +- **Cesium, 3D Tiles and 3D models.** They are heavy, need an ion token for the good terrain, + and a 3D city adds nothing to a forest-loss polygon. MapLibre 5.8 (already a dependency) has + a **globe projection**, which gives us the "whole planet" feeling without them. +- **Anything that needs a key, or a key-holding proxy.** That rules out Google tiles and FIRMS + map tiles, which need a `MAP_KEY`. The public site is static, anonymous and keyless. Fire + cases show only their cluster centroid, which is deliberate in the rule itself: detections in + Indigenous land are never pinned precisely. +- **GLSL sensor looks, bloom, the scope mask, cockpit, voice, SDR and CCTV.** They add + atmosphere, not evidence. Restraint matches the site. +- **Remote geocoders (Photon, Nominatim).** Search stays offline. It uses the watched places + (AOIs from the exported ledger) plus coordinates, so the map makes no calls a reader didn't + cause. +- **Ambient labels, decluttering and trails.** We have tens of cases, not thousands of moving + contacts. DOM markers with a hover tooltip are enough, and they give us focus, `aria-label` + and CSS transitions for free. +- **NC or share-alike datasets.** We avoid them. Our sources are NASA GIBS (public domain) and + GFW integrated alerts (CC BY 4.0), whose tiles are keyless and CORS-open, plus OSM labels via + GIBS and OpenFreeMap as a fallback basemap (ODbL, with attribution). **One exception, for the + basemap only:** the zoomed-in EOxCloudless 2025 mosaic is CC BY-NC-SA 4.0 (free for + non-commercial use with EOX's attribution). It is display imagery, never evidence, and the + site must stay non-commercial while it is used. If that changes, switch to the 2016 layer + (CC BY 4.0) or a keyed provider. + +## The interactions we adopted + +1. **Lazy upgrade in place.** The landing and cases index ship the static NASA image with link + pins, which works for crawlers, no-JS readers and the first paint. The MapLibre chunk and + `api/map.json` load on hover, tap or focus, or after the page has been idle on a connection + that isn't in save-data mode. A `#map:` link upgrades at once. +2. **Globe projection** with a zoom-dependent basemap (`web/src/layers/basemap.ts`, shared with + the dashboard). At z0–7 it shows NASA GIBS VIIRS daily true colour (yesterday, so it has + the clouds and smoke). Over z6–8 it crossfades to the EOxCloudless Sentinel-2 2025 mosaic + (10 m, sharp to about z14). OpenFreeMap place names and roads sit on top. A corner caption + says which imagery you see, so the mosaic is never taken for today. If GIBS fails, the map + falls back to OpenFreeMap. +3. **Layer toggles.** Status (Published / Being checked / Wrong or dropped) and case type + (forest loss, fires, new flaring, flaring stopped, methane), with counts. +4. **Click to open.** A marker opens a card with the headline, status, place, living value, + date and "Open case". The list and the map highlight each other. The camera flies with the + site's `--ease-in-out` (`cubic-bezier(0.77, 0, 0.175, 1)`), framed per case type, and jumps + under reduced motion. +5. **Keyboard.** Arrow keys cycle the visible cases, Enter opens the selected one, and Escape + closes the innermost thing (layers panel, then card, then Whole Earth). Map keyboard panning + is off so the arrows are ours. +6. **Evidence overlays per case.** Forest cases get GFW integrated alerts, in true colour, for + the case's dates. Non-fire, non-methane cases get HLS 30 m Sentinel-2/Landsat before/after + stacks with a crossfade slider (cheaper than a swipe, and just as legible). Each overlay is + bounded to the case area, and an empty day is simply transparent. +7. **Time window**, scrubber and Replay. The stats strip follows the window. +8. **Share links**: `#map:v=1&c=…&z=…&p=…&b=…&g=…&k=…&w=…&t=…&s=…&o=…`, plus a Copy-link + button. The URL is only rewritten after a gesture or a restore. +9. **Keyless search** over the watched places, case titles and coordinates. +10. **Whole Earth** (Global Context): the whole planet with every layer on, then back to + exactly where you were. +11. **Phone.** The map is about 45 vh, the card becomes a bottom sheet, and there is no hover + dependence: tooltips appear on mouse hover only, a tap selects, and the zoom buttons give + way to pinch. + +## Later, if useful + +- The copy-time `at=` stamp: "this case changed since the link was shared". +- A tilt/north-up toggle button. Today it's the compass control plus right-drag. +- Render-on-demand holds, if we ever animate more than one thing at a time. diff --git a/docs/research/2026-09-27_live-data-sources.md b/docs/research/2026-09-27_live-data-sources.md new file mode 100644 index 0000000..63e1afc --- /dev/null +++ b/docs/research/2026-09-27_live-data-sources.md @@ -0,0 +1,97 @@ +# Live data sources for a planetary-health watch — catalogue (2026-09-27) + +**Question.** God's Eye View (GEV, `bilawalsidhu/gods-eye-view`, MIT code, per-source data +terms) puts ~40 live feeds on one globe. Which of them — plus what earthdeck already has — +belong in TerraKeep, whose job is *keeping Earth within its limits*, not tracking people or +planes? For each source: endpoint, key, licence, refresh, and a verdict: + +- **layer** — context on the map (no finding, no ledger entry); +- **rule** — drives or confirms a watch rule (threshold/event + an independent second signal); +- **skip** — with the reason: *privacy* (cameras, plate readers), *irrelevance* (flights, + transit), *cost/licence* (paid, non-commercial or no-redistribution terms). + +Sources: GEV `README.md`, `DATA_SOURCES.md`, `THIRD_PARTY_NOTICES.md`, `server/providers/*` +(ideas, endpoints and licence facts only — no code or bundled data copied). Every endpoint +marked ✓ was called live on 2026-09-27. Anything not verified is marked UNCONFIRMED. + +## 1. Weather (first, because heat, storms and floods are where people die first) + +| Source | Endpoint | Key | Licence / terms | Refresh | Verdict | +| --- | --- | --- | --- | --- | --- | +| **Open-Meteo forecast** (ECMWF IFS, DWD ICON, NOAA GFS blend) ✓ | `api.open-meteo.com/v1/forecast` | no | Data CC BY 4.0; free API is non-commercial, ~10k calls/day, >2 weeks or >10 vars count as several calls | 15 min current, hourly models | **rule + layer — built.** `weather_now`; heat (≥ abs °C or ≥ +anomaly for ≥ N days) and extreme rain (≥ mm/day) in `weather_extreme@1.0`; wind-arrow layer (multi-location `current=`, CORS `*` ✓) | +| **ERA5 via Open-Meteo archive** ✓ (have) | `archive-api.open-meteo.com/v1/archive?models=era5` | no | CC BY 4.0 (Copernicus C3S) | daily, ~6-day latency | **rule — built.** 1991–2020 normals (30 one-year windows, ±3 d) and the heat *confirmation*. Finding: the default `best_match` back-fills the last days with forecast data, so it is **not** independent — `models=era5` returns honest nulls instead | +| **ECMWF Open Data** (IFS 0.25° GRIB2) | `data.ecmwf.int/forecasts` | no | CC BY 4.0 + ECMWF terms (attribution, modification notice, liability disclaimer) | 6-hourly | **skip for now** — needs a GRIB decoder (new dep); Open-Meteo already serves IFS as JSON | +| **NOAA GFS** on AWS Open Data | `noaa-gfs-bdp-pds.s3.amazonaws.com` | no | U.S. public domain | 6-hourly | **skip for now** — same reason (GRIB byte ranges + ecCodes WASM in GEV) | +| **NOAA NHC / CPHC** ✓ | `www.nhc.noaa.gov/CurrentStorms.json` + `mapservices.weather.noaa.gov/tropical/rest/services/tropical/NHC_tropical_weather_summary/MapServer/{5 points,7 cone}/query?f=geojson` | no | U.S. public data, weather.gov disclaimer; no CORS on nhc.noaa.gov → server-side | per advisory (3–6 h) | **rule + layer — built.** `storms`; cyclone cone ∩ AOI → candidate. `maxAllowableOffset=0.05` keeps a basin's cones ≈4 KB. Atlantic + E/C Pacific only | +| **GDACS** (UN OCHA / EC JRC) ✓ | `gdacs.org/gdacsapi/api/events/geteventlist/SEARCH?eventlist=TC` + `…/polygons/getgeometry` (`Class=Poly_Cones`) | no | "as is", automatic, not human-reviewed; no explicit reuse licence found — UNCONFIRMED | per advisory | **rule + layer — built.** Fills NHC's gap (Bay of Bengal, NW Pacific, S Indian Ocean, Australia). Winds may be 10-min (reads ~1 category low) — a stated blind spot | +| **NASA EONET "Severe Storms"** ✓ (have) | `eonet.gsfc.nasa.gov/api/v3/events?category=severeStorms` | no | NASA open data | hours | **rule — built.** Cyclone *confirmation*. Honest caveat: EONET republishes NHC/JTWC, so it is an independent pipeline, not an independent observation | +| **JTWC** | `metoc.navy.mil/jtwc` | no | U.S. military site, no licence statement, access flaky | per warning | **skip** — GDACS + EONET already carry JTWC tracks | +| **NASA GIBS VIIRS true colour** ✓ (have as basemap/snapshots) | `gibs.earthdata.nasa.gov/wmts/epsg3857/best/VIIRS_SNPP_CorrectedReflectance_TrueColor/default/default/…Level9` | no | NASA public domain; acknowledgement requested | daily | **layer — built** ("Satellite clouds"; `default` time = latest day) | +| **NASA GIBS GPM IMERG** ✓ | `…/IMERG_Precipitation_Rate_30min/default/default/…Level6` | no | NASA public domain | 30 min, ~4 h latency | **layer — built** (global satellite rain; the public-site-safe radar substitute) | +| **NASA GIBS geostationary IR** (GOES-East/West, Himawari Band 13) ✓ | `…/GOES-East_ABI_Band13_Clean_Infrared/…`, `…/Himawari_AHI_Band13_Clean_Infrared/…` | no | public domain | 10 min | **layer — next** (near-live clouds; no Meteosat layer found in the 3857 set — UNCONFIRMED) | +| **RainViewer** radar ✓ | `api.rainviewer.com/public/weather-maps.json` → `tilecache.rainviewer.com/v2/radar/{path}/256/{z}/{x}/{y}/2/1_1.png` | no | "free for personal or educational use"; credit "Weather data by RainViewer" + link; not for high-volume commercial | 10 min | **layer — local dashboard only** (`publicSafe: false`); a public site needs their written OK | +| **NOAA nowCOAST** radar (MRMS), GOES IR, lightning density | `nowcoast.noaa.gov/geoserver/observations/{weather_radar,satellite,lightning_detection}/ows` (WMS 1.1.1) | no | NOAA disclaimer; lightning is a NOAA Level-5 derived product whose public distribution is permitted (not raw Vaisala strikes) | 2–15 min | **layer — next.** Americas/Pacific only; lightning density is the only keyless lightning with clear redistribution terms | +| **Blitzortung** lightning | community network, no official API | — | data for private, non-commercial use; redistribution not permitted | seconds | **skip — licence** | +| **Soil moisture / drought** (Open-Meteo `soil_moisture_0_to_7cm…`, ERA5-Land) | same Open-Meteo APIs | no | CC BY 4.0 | hourly / daily | **rule — next.** Soil-moisture anomaly vs 1991–2020 for ≥ N weeks; confirm with GloFAS low flow or Sentinel-2 NDVI drop (have both) | +| **GloFAS** discharge ✓ (have) | `flood-api.open-meteo.com/v1/flood` | no | CC BY 4.0 (Copernicus EMS) | daily, +7 d forecast | **rule — built** as the rain confirmation (≥ 2× 2-year mean); a standalone flood rule is cheap next | +| **CAMS air quality** (have) | `air-quality-api.open-meteo.com` | no | CC BY 4.0 | hourly | **rule — next** (PM2.5 ≫ WHO for days; confirm with FIRMS smoke source or a second city station) | + +## 2. Everything else GEV carries + +| Source | Endpoint | Key | Licence / terms | Refresh | Verdict | +| --- | --- | --- | --- | --- | --- | +| **Global Fishing Watch API** | `gateway.api.globalfishingwatch.org` | free token | CC BY-NC 4.0 data; API terms non-commercial | ~3-day lag | **rule — later, high value:** apparent fishing inside a no-take MPA (protected_areas, have) → confirm with GFW SAR vessel detections or a later pass. Beware the name clash with Global *Forest* Watch (`src/clients/gfw.ts`) | +| **AISStream.io** (live AIS) | `wss://stream.aisstream.io` | free key | beta, no formal ToS; AIS is public broadcast | seconds | **later** — ship context for oil-spill cases (Sentinel-1 slick + nearest tanker track); WebSocket collector = real effort | +| **CelesTrak** TLEs | `celestrak.org/NORAD/elements/gp.php?GROUP=…` | no | U.S.-government origin, citation requested | daily | **layer/case context — later:** "Sentinel-2 passes here at hh:mm" on a case page. Needs SGP4 (dep) — ESA's published S1/S2 acquisition plans (KML) may be cheaper, UNCONFIRMED | +| **USGS earthquakes** (have) | `earthquake.usgs.gov/…/summary/*.geojson` | no | public domain | minutes | have (`quakes`) | +| **NASA FIRMS** (have) | `firms.modaps.eosdis.nasa.gov/api/area/csv/{key}/…` | free key | public domain | ~3 h | have (fire rules) | +| **NIFC WFIGS** fire perimeters | ArcGIS feature service (`data-nifc.opendata.arcgis.com`) | no | U.S. public domain | 5 min | **layer — next** (US only; perimeters beside FIRMS points) | +| **InciWeb** | `inciweb.wildfire.gov` | no | U.S. public incident info | hours | skip — narrative links, US only | +| **OSM dams** (OpenInfraMap) | Overpass (live) | no | ODbL (attribution + share-alike on the derived DB) | live | **layer — later** (flood/drought context; GRanD/GDW are better global dam sets, UNCONFIRMED licence) | +| **OSM datacenters** | Overpass (live) | no | ODbL | live | **layer — later, low** (energy/water demand context) | +| **Natural Earth** regions | naturalearthdata.com | no | public domain | static | **layer/text — later, cheap:** plain-language place names in titles ("Mozambique Channel") | +| **GDELT DOC 2.0** | `api.gdeltproject.org/api/v2/doc/doc` | no | free with citation + link | 15 min | **later** — news corroboration on a case, never a confirmation | +| **Google News RSS** | news.google.com/rss | no | personal, non-commercial only | — | **skip — licence** | +| **OpenSky / adsb.lol / adsbdb** flights, military flights | various | opt. | OpenSky non-commercial; adsb.lol ODbL; adsbdb route data "may not be copied" | seconds | **skip — irrelevance** (aviation emissions are better from Climate TRACE, have) | +| **Launch Library 2** | `ll.thespacedevs.com/2.3.0` | opt. | use/share, 15 calls/h anon | 15 min | **skip — irrelevance** | +| **CCTV packs** (Austin, TxDOT, Caltrans, TfL, Ontario 511, Fintraffic, DriveBC, Calgary, NSW, Tallinn, DelDOT …) | city APIs | mostly no | mixed OGL / CC BY / "public" | 10 s–10 min | **skip — privacy** (people and plates in frame) and irrelevance | +| **ALPR locations** (OSM `surveillance:type=ALPR`) | Overpass | no | ODbL | live | **skip — privacy/surveillance** is outside the mission | +| **OSM military installations** | Overpass | no | ODbL | live | **skip — irrelevance** | +| **Traffic** (TomTom), **transit** GTFS-RT, **bikeshare** GBFS, **OSRM** routing, **Radio Browser** | various | TomTom key | TomTom paid tier; others open | seconds | **skip — irrelevance/cost** | +| **Esri World Imagery**, **Google 3D Tiles / Places**, **Cesium ion** | ArcGIS / Google / Cesium | Google/ion keys | proprietary; Google content may not be cached | — | **skip — cost/licence** (GIBS + Sentinel-2 already free) | +| **TeleGeography cables**, **Bhote Koshi pack** | bundled in GEV | — | CC BY-NC(-SA) | static | **skip — licence** (non-commercial) and irrelevance | +| **Re:Earth terrain**, **Photon** geocoder | keyless | no | CC BY 4.0 / ODbL fair use | — | skip — we have Nominatim; no 3D terrain need | + +## 3. Ranked by value ÷ effort + +| # | Source → use | Value for the watch | Effort | Status | +| --- | --- | --- | --- | --- | +| 1 | Open-Meteo forecast + ERA5 normals → heat & rain rule, wind layer | very high (heat is the top weather killer) | low | **built** | +| 2 | NHC/CPHC + GDACS (+ EONET) → cyclone rule + cones layer | very high | low | **built** | +| 3 | GIBS VIIRS + IMERG → clouds / satellite-rain layers | high (public-site-safe) | very low | **built** | +| 4 | Open-Meteo soil moisture + ERA5-Land → drought rule | high | low (same client) | next | +| 5 | GloFAS → standalone flood rule (discharge vs return-period proxy) | high | low (have client) | next | +| 6 | GIBS geostationary IR (GOES-E/W, Himawari) → 10-min clouds | medium | very low | next | +| 7 | NOAA nowCOAST radar + lightning density → Americas layers | medium | low | next | +| 8 | Global Fishing Watch → fishing-in-MPA rule | very high | medium (key, NC licence) | later | +| 9 | CAMS → air-pollution episode rule | high | low–medium (needs a good second signal) | later | +| 10 | CelesTrak / ESA acquisition plans → "next satellite pass" on cases | medium | medium | later | + +Also worth doing after these: NIFC perimeters (US fires), Natural Earth names for titles, +AISStream for oil-spill context. + +## 4. What was built in this slice (2026-09-27) + +- `weather_now`, `storms` tools (`src/clients/weather.ts`, `src/clients/storms.ts`, + `src/tools/weather.ts`) with provenance blocks; `series` / `events` cards (storm cones ride + along as `payload.stormGeoJson`). +- `weather_extreme@1.0` (`src/watch/rules/weatherExtreme.ts`, tier 0) and + `watchlists/weather.json` (12 cities, 6 cyclone regions, per-climate thresholds). +- `web/src/layers/weather.ts` — `addLayer(map, spec)` / `mountLayerToggles(...)` for clouds, + satellite rain, RainViewer radar (local only), wind arrows and storm cones; wired into the + live dashboard. The public map can import the same module and pass `publicSite: true`. + +Live check the same day: 7 active cyclones (Polo cat 3 and Nolo cat 1→4 forecast in the +E Pacific, Surigae cat 3 near Okinawa, Odalys cat 1, Fay, Gonzalo, TC 01B in the Bay of +Bengal) — none with a category ≥ 1 cone over the six watched regions; no city over its heat +or rain bar (closest: Kuwait City +7.0 °C today vs a +7 bar, one day only). diff --git a/docs/screenshots/map-basemap-z13.jpg b/docs/screenshots/map-basemap-z13.jpg new file mode 100644 index 0000000..137c2df Binary files /dev/null and b/docs/screenshots/map-basemap-z13.jpg differ diff --git a/docs/screenshots/map-basemap-z3.jpg b/docs/screenshots/map-basemap-z3.jpg new file mode 100644 index 0000000..1dc1438 Binary files /dev/null and b/docs/screenshots/map-basemap-z3.jpg differ diff --git a/docs/screenshots/map-basemap-z9.jpg b/docs/screenshots/map-basemap-z9.jpg new file mode 100644 index 0000000..0289688 Binary files /dev/null and b/docs/screenshots/map-basemap-z9.jpg differ diff --git a/docs/screenshots/map-v3-case-overlay.jpg b/docs/screenshots/map-v3-case-overlay.jpg new file mode 100644 index 0000000..ec54862 Binary files /dev/null and b/docs/screenshots/map-v3-case-overlay.jpg differ diff --git a/docs/screenshots/map-v3-cases.jpg b/docs/screenshots/map-v3-cases.jpg new file mode 100644 index 0000000..e9e430a Binary files /dev/null and b/docs/screenshots/map-v3-cases.jpg differ diff --git a/docs/screenshots/map-v3-landing.jpg b/docs/screenshots/map-v3-landing.jpg new file mode 100644 index 0000000..e34868a Binary files /dev/null and b/docs/screenshots/map-v3-landing.jpg differ diff --git a/docs/screenshots/map-v3-mobile.jpg b/docs/screenshots/map-v3-mobile.jpg new file mode 100644 index 0000000..e3ea5d9 Binary files /dev/null and b/docs/screenshots/map-v3-mobile.jpg differ diff --git a/docs/screenshots/ui-v4-about.jpg b/docs/screenshots/ui-v4-about.jpg new file mode 100644 index 0000000..e23cc28 Binary files /dev/null and b/docs/screenshots/ui-v4-about.jpg differ diff --git a/docs/screenshots/ui-v4-case.jpg b/docs/screenshots/ui-v4-case.jpg new file mode 100644 index 0000000..fe62d9d Binary files /dev/null and b/docs/screenshots/ui-v4-case.jpg differ diff --git a/docs/screenshots/ui-v4-cases.jpg b/docs/screenshots/ui-v4-cases.jpg new file mode 100644 index 0000000..59964bd Binary files /dev/null and b/docs/screenshots/ui-v4-cases.jpg differ diff --git a/docs/screenshots/ui-v4-incase.jpg b/docs/screenshots/ui-v4-incase.jpg new file mode 100644 index 0000000..e60d9f1 Binary files /dev/null and b/docs/screenshots/ui-v4-incase.jpg differ diff --git a/docs/screenshots/ui-v4-live.jpg b/docs/screenshots/ui-v4-live.jpg new file mode 100644 index 0000000..6c0614a Binary files /dev/null and b/docs/screenshots/ui-v4-live.jpg differ diff --git a/docs/screenshots/ui-v4-metrics.jpg b/docs/screenshots/ui-v4-metrics.jpg new file mode 100644 index 0000000..5196fd6 Binary files /dev/null and b/docs/screenshots/ui-v4-metrics.jpg differ diff --git a/docs/screenshots/ui-v4-mobile.jpg b/docs/screenshots/ui-v4-mobile.jpg new file mode 100644 index 0000000..e2b3f50 Binary files /dev/null and b/docs/screenshots/ui-v4-mobile.jpg differ diff --git a/docs/screenshots/ui-v4-planet.jpg b/docs/screenshots/ui-v4-planet.jpg new file mode 100644 index 0000000..dc76af3 Binary files /dev/null and b/docs/screenshots/ui-v4-planet.jpg differ diff --git a/docs/screenshots/ui-v4-qa-live.jpg b/docs/screenshots/ui-v4-qa-live.jpg new file mode 100644 index 0000000..a86389b Binary files /dev/null and b/docs/screenshots/ui-v4-qa-live.jpg differ diff --git a/docs/screenshots/ui-v4-qa-phone.jpg b/docs/screenshots/ui-v4-qa-phone.jpg new file mode 100644 index 0000000..d240460 Binary files /dev/null and b/docs/screenshots/ui-v4-qa-phone.jpg differ diff --git a/docs/screenshots/ui-v4-qa-replay.jpg b/docs/screenshots/ui-v4-qa-replay.jpg new file mode 100644 index 0000000..61a29be Binary files /dev/null and b/docs/screenshots/ui-v4-qa-replay.jpg differ diff --git a/docs/screenshots/ui-v4-qa-reply.jpg b/docs/screenshots/ui-v4-qa-reply.jpg new file mode 100644 index 0000000..e3764a5 Binary files /dev/null and b/docs/screenshots/ui-v4-qa-reply.jpg differ diff --git a/infra/earthdeck.yaml b/infra/earthdeck.yaml index a71cb8c..7a8c940 100644 --- a/infra/earthdeck.yaml +++ b/infra/earthdeck.yaml @@ -67,6 +67,12 @@ Resources: - Id: expire-old-versions Status: Enabled NoncurrentVersionExpiration: { NoncurrentDays: 90 } + # Reply-wall rate counters (per salted IP hash per UTC day) are only needed for a day. + - Id: expire-reply-rate-counters + Status: Enabled + Prefix: replies/rate/ + ExpirationInDays: 2 + NoncurrentVersionExpiration: { NoncurrentDays: 1 } Tags: [{ Key: Project, Value: earthdeck }] SiteBucket: @@ -377,6 +383,8 @@ Resources: EARTHDECK_DISTRIBUTION_ID: !Ref Distribution EARTHDECK_SSM_PREFIX: /earthdeck EARTHDECK_SITE_URL: !Sub "https://${DomainName}" + # The reply wall's intake; the export renders the form against it (--reply-url). + EARTHDECK_REPLY_URL: !GetAtt ReplyFunctionUrl.FunctionUrl # No EARTHDECK_CONTACT: the public site is anonymous — no personal email is ever exported. # Per-UTC-day caps (counted in ledger/watch/quota.json); see infra/README.md "Quotas". EARTHDECK_MAX_CDSE_CALLS: "40" @@ -400,6 +408,120 @@ Resources: MaximumRetryAttempts: 0 MaximumEventAgeInSeconds: 21600 + # ── reply wall: public intake (Function URL → S3 replies/inbox/) ───────────────────── + # Anyone may POST a reply; nobody reads an inbox. The analyst's reviewer model screens + # replies/inbox/ and moves them to replies/public/ (shown) or replies/rejected/. + ReplyLogGroup: + Type: AWS::Logs::LogGroup + Condition: WithFunction + DeletionPolicy: Delete + Properties: + LogGroupName: /aws/lambda/earthdeck-reply + RetentionInDays: 14 + Tags: [{ Key: Project, Value: earthdeck }] + + ReplyRole: + Type: AWS::IAM::Role + Condition: WithFunction + Properties: + RoleName: earthdeck-reply + AssumeRolePolicyDocument: + Version: "2012-10-17" + Statement: + - Effect: Allow + Principal: { Service: lambda.amazonaws.com } + Action: sts:AssumeRole + Policies: + - PolicyName: earthdeck-reply + PolicyDocument: + Version: "2012-10-17" + Statement: + - Sid: Logs + Effect: Allow + Action: [logs:CreateLogStream, logs:PutLogEvents] + Resource: !Sub ${ReplyLogGroup.Arn} + - Sid: WriteInbox + Effect: Allow + Action: s3:PutObject + Resource: !Sub ${StateBucket.Arn}/replies/inbox/* + - Sid: ReadCaseIndex + Effect: Allow + Action: s3:GetObject + Resource: !Sub ${StateBucket.Arn}/replies/cases.json + - Sid: RateCounters + Effect: Allow + Action: [s3:GetObject, s3:PutObject] + Resource: !Sub ${StateBucket.Arn}/replies/rate/* + - Sid: Salt + Effect: Allow + Action: ssm:GetParameter + Resource: !Sub arn:${AWS::Partition}:ssm:${AWS::Region}:${AWS::AccountId}:parameter/earthdeck/REPLY_SALT + - Sid: DecryptSaltViaSsm + Effect: Allow + Action: kms:Decrypt + Resource: !Sub arn:${AWS::Partition}:kms:${AWS::Region}:${AWS::AccountId}:key/* + Condition: + StringEquals: + kms:ViaService: !Sub ssm.${AWS::Region}.amazonaws.com + StringLike: + kms:EncryptionContext:PARAMETER_ARN: !Sub arn:${AWS::Partition}:ssm:${AWS::Region}:${AWS::AccountId}:parameter/earthdeck/REPLY_SALT + Tags: [{ Key: Project, Value: earthdeck }] + + ReplyFunction: + Type: AWS::Lambda::Function + Condition: WithFunction + DependsOn: ReplyLogGroup + Properties: + FunctionName: earthdeck-reply + Description: earthdeck public reply wall intake (POST /reply → replies/inbox/) + Runtime: nodejs22.x + Architectures: [arm64] + Handler: dist/runner/reply-lambda.handler + Code: + S3Bucket: !Ref ArtifactsBucket + S3Key: !Ref ArtifactKey + Role: !GetAtt ReplyRole.Arn + Timeout: 10 + MemorySize: 256 + # Caps what a flood can cost (and write): at most 2 requests in flight. + ReservedConcurrentExecutions: 2 + Environment: + Variables: + EARTHDECK_STATE_BUCKET: !Ref StateBucket + EARTHDECK_REPLY_SALT_PARAM: /earthdeck/REPLY_SALT + Tags: [{ Key: Project, Value: earthdeck }] + + ReplyFunctionUrl: + Type: AWS::Lambda::Url + Condition: WithFunction + Properties: + TargetFunctionArn: !GetAtt ReplyFunction.Arn + AuthType: NONE + Cors: + AllowOrigins: [!Sub "https://${DomainName}"] + AllowMethods: [POST] + AllowHeaders: [content-type] + MaxAge: 86400 + + ReplyUrlPublic: + Type: AWS::Lambda::Permission + Condition: WithFunction + Properties: + FunctionName: !Ref ReplyFunction + Action: lambda:InvokeFunctionUrl + Principal: "*" + FunctionUrlAuthType: NONE + + # Newer accounts also require lambda:InvokeFunction for public Function URLs (scoped to URL calls). + ReplyUrlInvoke: + Type: AWS::Lambda::Permission + Condition: WithFunction + Properties: + FunctionName: !Ref ReplyFunction + Action: lambda:InvokeFunction + Principal: "*" + InvokedViaFunctionUrl: true + # ── schedules ───────────────────────────────────────────────────────────────────────── SchedulerRole: Type: AWS::IAM::Role @@ -677,5 +799,9 @@ Outputs: Value: !Ref RunnerLogGroup AlertTopicArn: Value: !Ref AlertTopic + ReplyUrl: + Condition: WithFunction + Description: Public reply wall intake (the site's form posts to reply) + Value: !GetAtt ReplyFunctionUrl.FunctionUrl SiteUrl: Value: !Sub https://${DomainName}/ diff --git a/package.json b/package.json index 6e31c8b..e8aa9c1 100644 --- a/package.json +++ b/package.json @@ -62,6 +62,7 @@ "typecheck": "tsc --noEmit", "typecheck:test": "tsc -p tsconfig.test.json", "test": "node --import tsx --test test/*.test.ts", + "test:e2e": "node --test test/e2e/*.e2e.mjs", "test:watch": "node --import tsx --test --watch test/*.test.ts", "schema": "tsx scripts/export-schema.ts" }, @@ -77,6 +78,7 @@ "@aws-sdk/client-ssm": "3.1141.0", "@types/node": "25.9.0", "maplibre-gl": "5.8.0", + "playwright": "1.58.2", "tsx": "4.22.2", "typescript": "6.0.3", "vite": "7.1.5" diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 40a960c..8b332eb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -36,6 +36,9 @@ importers: maplibre-gl: specifier: 5.8.0 version: 5.8.0 + playwright: + specifier: 1.58.2 + version: 1.58.2 tsx: specifier: 4.22.2 version: 4.22.2 @@ -838,6 +841,11 @@ packages: resolution: {integrity: sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==} engines: {node: '>= 0.8'} + fsevents@2.3.2: + resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -1010,6 +1018,16 @@ packages: resolution: {integrity: sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==} engines: {node: '>=16.20.0'} + playwright-core@1.58.2: + resolution: {integrity: sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==} + engines: {node: '>=18'} + hasBin: true + + playwright@1.58.2: + resolution: {integrity: sha512-vA30H8Nvkq/cPBnNw4Q8TWz1EJyqgpuinBcHET0YVJVFldr8JDNiU9LaWAE1KqSkRYazuaBhTpB5ZzShOezQ6A==} + engines: {node: '>=18'} + hasBin: true + postcss@8.5.15: resolution: {integrity: sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==} engines: {node: ^10 || ^12 || >=14} @@ -1971,6 +1989,9 @@ snapshots: fresh@2.0.0: {} + fsevents@2.3.2: + optional: true + fsevents@2.3.3: optional: true @@ -2123,6 +2144,14 @@ snapshots: pkce-challenge@5.0.1: {} + playwright-core@1.58.2: {} + + playwright@1.58.2: + dependencies: + playwright-core: 1.58.2 + optionalDependencies: + fsevents: 2.3.2 + postcss@8.5.15: dependencies: nanoid: 3.3.12 diff --git a/schema/finding-event.v1.json b/schema/finding-event.v1.json index d88f2d7..1ec5ba6 100644 --- a/schema/finding-event.v1.json +++ b/schema/finding-event.v1.json @@ -710,6 +710,7 @@ "sensor", "provider", "revisit", + "method", "human" ] } @@ -1395,6 +1396,120 @@ "reason" ], "additionalProperties": false + }, + { + "type": "object", + "properties": { + "v": { + "type": "number", + "const": 1 + }, + "eventId": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + }, + "findingId": { + "type": "string", + "pattern": "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" + }, + "at": { + "type": "string", + "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$" + }, + "actor": { + "type": "string", + "pattern": "^(system|reviewer|model):[^\\s].*$" + }, + "prev": { + "anyOf": [ + { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + }, + { + "type": "null" + } + ] + }, + "kind": { + "type": "string", + "const": "commented" + }, + "reply": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "^[0-9A-HJKMNP-TV-Z]{26}$" + }, + "role": { + "type": "string", + "enum": [ + "resident", + "operator", + "company", + "official", + "researcher", + "other" + ] + }, + "receivedAt": { + "type": "string", + "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$" + }, + "textSha256": { + "type": "string", + "pattern": "^[0-9a-f]{64}$" + } + }, + "required": [ + "id", + "role", + "receivedAt", + "textSha256" + ], + "additionalProperties": false + }, + "verdict": { + "type": "object", + "properties": { + "accept": { + "type": "boolean", + "const": true + }, + "reason": { + "type": "string", + "minLength": 1, + "maxLength": 500 + }, + "flags": { + "maxItems": 0, + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": [ + "accept", + "reason", + "flags" + ], + "additionalProperties": false + } + }, + "required": [ + "v", + "eventId", + "findingId", + "at", + "actor", + "prev", + "kind", + "reply", + "verdict" + ], + "additionalProperties": false } ] }, diff --git a/scripts/deploy.sh b/scripts/deploy.sh index 1e38bde..39467e9 100755 --- a/scripts/deploy.sh +++ b/scripts/deploy.sh @@ -5,7 +5,8 @@ # 2. first deploy only: create the stack without the function (DeployFunction=false) so the # artifacts bucket exists before the function that needs a zip in it (chicken-and-egg) # 3. upload the zip to the artifacts bucket -# 4. SSM SecureStrings under /earthdeck/ — created only if absent, values from ./.env, +# 4. SSM SecureStrings under /earthdeck/ — created only if absent, values from ./.env +# (REPLY_SALT: random, for the reply wall's IP hashing), # /earthdeck/ledger-key adopted from .env / data/ledger/ledger.key or freshly generated. # Done before the function deploy so the first scheduled run already has them. # 5. full deploy (function, schedules, alarm) @@ -22,7 +23,7 @@ DOMAIN=${EARTHDECK_DOMAIN:-vitalearth.io} HOSTED_ZONE_ID=${EARTHDECK_HOSTED_ZONE_ID:-Z07362552JHZID1QJ2DSR} NOTIFY_EMAIL=me@marcsperzel.com SSM_PREFIX=/earthdeck -SECRETS=(GFW_API_KEY CDSE_CLIENT_ID CDSE_CLIENT_SECRET FIRMS_MAP_KEY ANTHROPIC_API_KEY) +SECRETS=(GFW_API_KEY CDSE_CLIENT_ID CDSE_CLIENT_SECRET FIRMS_MAP_KEY ANTHROPIC_API_KEY GFW_FISHING_TOKEN AISSTREAM_KEY GEE_PROJECT GEE_SERVICE_ACCOUNT_JSON) ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" cd "$ROOT" @@ -123,7 +124,12 @@ awsx s3 cp "$ZIP" "s3://$ARTIFACTS/$ARTIFACT_KEY" --only-show-errors say "secrets under $SSM_PREFIX/ (create-if-absent; values never printed)" for name in "${SECRETS[@]}"; do - put_secret "$SSM_PREFIX/$name" "$(env_value "$name")" + value=$(env_value "$name") + # Locally GEE_SERVICE_ACCOUNT_JSON may be a path to the key file; Lambda has no such file, so store its JSON. + if [ "$name" = GEE_SERVICE_ACCOUNT_JSON ] && [ -n "$value" ] && [ -f "${value/#\~/$HOME}" ]; then + value=$(tr -d '\n' <"${value/#\~/$HOME}") + fi + put_secret "$SSM_PREFIX/$name" "$value" done # Ledger signing seed: base64 of 32 bytes (what src/ledger/checkpoint.ts keyFromSeed loads). @@ -148,6 +154,10 @@ else echo " source: $SRC — public key (publish this as ledger.pub): $PUB" fi +# Reply-wall salt: the intake hashes each IP with it (per-IP daily cap) and never stores the IP. +# Random, created once, never printed; rotating it only resets today's counters. +put_secret "$SSM_PREFIX/REPLY_SALT" "$(node -e "process.stdout.write(require('node:crypto').randomBytes(32).toString('base64'))")" + say "deploy stack (function + schedules + alarm)" cfn_deploy true "$ARTIFACT_KEY" diff --git a/scripts/site-icons.mjs b/scripts/site-icons.mjs new file mode 100644 index 0000000..6e0d8cc --- /dev/null +++ b/scripts/site-icons.mjs @@ -0,0 +1,59 @@ +#!/usr/bin/env node +// One-off, dev-only: render the site's icon set and social card from web/site/public/favicon.svg +// into committed PNGs (web/site/public/). Not part of `pnpm build` — the PNGs are checked in, so +// no image tooling is a dependency. Needs Playwright (any recent version with Chromium) on the +// NODE_PATH, e.g. `NODE_PATH=$(npm root -g) node scripts/site-icons.mjs`, and ImageMagick for +// favicon.ico. Re-run after changing the mark or SITE.name / SITE.byline. +// +// apple-touch-icon.png 180 · icon-192.png · icon-512.png · favicon.ico (16/32/48) · og.png 1200×630 + +import { execFileSync } from "node:child_process"; +import { readFileSync, rmSync } from "node:fs"; +import { createRequire } from "node:module"; +import { join } from "node:path"; + +const require = createRequire(import.meta.url); +const { chromium } = require("playwright"); +const PUB = new URL("../web/site/public/", import.meta.url).pathname; +const svg = readFileSync(join(PUB, "favicon.svg"), "utf8"); +// Branding comes from src/site.config.ts; parsed textually so this script needs no TS loader. +const cfg = readFileSync(new URL("../src/site.config.ts", import.meta.url), "utf8"); +const name = /^\s*name:\s*"([^"]+)"/m.exec(cfg)[1]; +const tagline = [.../^\s*tagline:\s*\[([^\]]+)\]/m.exec(cfg)[1].matchAll(/"([^"]+)"/g)].map((m) => m[1]).join(" "); + +const browser = await chromium.launch(); +const shot = async (html, w, h, out) => { + const p = await browser.newPage({ viewport: { width: w, height: h }, deviceScaleFactor: 1 }); + await p.setContent(html, { waitUntil: "networkidle" }); + await p.screenshot({ path: join(PUB, out), omitBackground: false }); + await p.close(); +}; +const iconPage = (px, pad) => + `` + + `
${svg.replace("`; + +// Touch/PWA icons: full-bleed square (the OS rounds the corners), mark inset a little. +await shot(iconPage(180, 0), 180, 180, "apple-touch-icon.png"); +await shot(iconPage(192, 0), 192, 192, "icon-192.png"); +await shot(iconPage(512, 0), 512, 512, "icon-512.png"); +for (const s of [16, 32, 48]) await shot(iconPage(s, 0), s, s, `fav-${s}.png`); +execFileSync("magick", [join(PUB, "fav-16.png"), join(PUB, "fav-32.png"), join(PUB, "fav-48.png"), join(PUB, "favicon.ico")]); +for (const s of [16, 32, 48]) rmSync(join(PUB, `fav-${s}.png`)); + +// Social card: the mark, the wordmark and the slogan on the site's dark ground, a faint horizon. +const og = ` + + + + + + +
+
${svg.replace(" +
${name}
+
+
${tagline}
+`; +await shot(og, 1200, 630, "og.png"); +await browser.close(); +console.log(`icons + og.png → ${PUB}`); diff --git a/src/analyst/analyst.ts b/src/analyst/analyst.ts index 2c4e339..a30b0ff 100644 --- a/src/analyst/analyst.ts +++ b/src/analyst/analyst.ts @@ -13,6 +13,7 @@ import { OverviewError } from "../errors.js"; import * as schema from "../ledger/schema.js"; import type { Finding } from "../ledger/schema.js"; import type { EventInput, Ledger } from "../ledger/store.js"; +import { reviewReplies } from "../replies/review.js"; import { uuidv7 } from "../util.js"; import type { Journal } from "../watch/journal.js"; import type { QuotaGovernor } from "../watch/quota.js"; @@ -29,6 +30,8 @@ import { type Narration, type Review, } from "./checks.js"; +import { runSituation } from "./situation.js"; +import type { IndicatorInputs } from "../watch/situation.js"; /** Most capable Opus narrates; a different model family reviews (claude-api skill defaults). */ export const DEFAULT_NARRATOR = "claude-opus-5"; @@ -48,6 +51,10 @@ export interface AnalystOptions { log?: (line: string) => void; /** Daily case count + USD spend cap (quota.json). Omitted = no daily limits. */ quota?: QuotaGovernor; + /** Local mirror of the reply wall (`replies/`): after the cases, the reviewer screens its inbox. */ + repliesDir?: string; + /** The daily Situation briefing (src/analyst/situation.ts): omitted = not run. */ + situation?: { ledgerDir: string; indicators: () => Promise; only?: boolean }; } export interface AnalystReport { @@ -61,6 +68,10 @@ export interface AnalystReport { errors: { findingId: string; message: string }[]; calls: number; costUsd: number; + /** Public replies screened this run (null = no replies dir / dry run). */ + replies: null | { accepted: number; rejected: number; errors: number; left: number }; + /** Today's Situation (null = not run). */ + situation: null | { level: string; source: string; skipped: boolean; headline: string }; } const NARRATOR_SYSTEM = `You write the public narration of one environmental finding for Earth Watch, an evidence-first public ledger. You are given the finding as JSON: its rule, evidence (with numeric values), the independent confirming signal, context (regional baseline ring, ENSO phase, nearby natural events), the rule's blind spots and the AOI tags. @@ -119,6 +130,10 @@ export function novelty(f: Finding): number { return Math.round(base * (boost > 0 ? boost : 1) * 1000) / 1000; } +/** Case-type tag for good news (e.g. flaring_stopped, improvement@1.0); selected as its own group. */ +const IMPROVEMENT_GROUP = "improvement"; +const isImprovement = (f: Finding) => f.aoi?.tags?.includes("improvement") === true; + /** Higher score first; ties by observedAt desc, then findingId. */ const byNovelty = (a: Selected, b: Selected) => b.score - a.score || (a.finding.observedAt < b.finding.observedAt ? 1 : a.finding.observedAt > b.finding.observedAt ? -1 : 0) || (a.finding.findingId < b.finding.findingId ? -1 : a.finding.findingId > b.finding.findingId ? 1 : 0); @@ -127,21 +142,29 @@ const byNovelty = (a: Selected, b: Selected) => * Work for this run, deterministic. Narrations awaiting review go first (already paid for); * the rest is a round-robin across rules — each round takes the most novel remaining finding * of every rule (rules ordered by that finding) — so one cheap-to-confirm rule can't fill `max`. + * Findings tagged `improvement` form one group of their own, and the first round leads with it. */ export function select(ledger: AnalystLedger, max: number): Selected[] { const review: Selected[] = []; const groups = new Map(); for (const f of ledger.list({ status: ["confirmed"] })) { if (!f.narration) { - const g = groups.get(f.rule.name) ?? []; + // Good news is its own group, whatever rule found it, so it always gets a turn. + const key = isImprovement(f) ? IMPROVEMENT_GROUP : f.rule.name; + const g = groups.get(key) ?? []; g.push({ finding: f, needs: "narrate", score: novelty(f) }); - groups.set(f.rule.name, g); + groups.set(key, g); } else if (!f.reviews.some((r) => r.actor.startsWith("model:") && r.at >= f.narration!.at)) review.push({ finding: f, needs: "review", score: novelty(f) }); } const out = review.sort(byNovelty).slice(0, max); const queues = [...groups.values()].map((g) => g.sort(byNovelty)); + let first = true; while (out.length < max && queues.some((q) => q.length)) { const round = queues.filter((q) => q.length).map((q) => q.shift()!).sort(byNovelty); + // The first round leads with a good-news case, so a busy run never crowds it out. + const good = first ? round.findIndex((s) => isImprovement(s.finding)) : -1; + if (good > 0) round.unshift(...round.splice(good, 1)); + first = false; out.push(...round.slice(0, max - out.length)); } return out; @@ -156,14 +179,14 @@ export async function runAnalyst(o: AnalystOptions): Promise { const apiKey = o.apiKey; const dryRun = Boolean(o.dryRun); const runId = uuidv7(); - const report: AnalystReport = { runId, dryRun, selected: 0, narrated: [], published: [], held: [], rejected: [], errors: [], calls: 0, costUsd: 0 }; + const report: AnalystReport = { runId, dryRun, selected: 0, narrated: [], published: [], held: [], rejected: [], errors: [], calls: 0, costUsd: 0, replies: null, situation: null }; const j = (kind: string, rec: Record = {}) => o.journal.append({ t: new Date().toISOString(), sweepId: runId, kind: `analyst_${kind}`, ...rec }); const q = o.quota; const limit = Math.min(o.max ?? 5, q ? q.analystCasesLeft() : Infinity); - const work = limit > 0 ? select(o.ledger, limit) : []; + const work = limit > 0 && !o.situation?.only ? select(o.ledger, limit) : []; report.selected = work.length; - if (q && q.analystCasesLeft() === 0) log(`daily analyst case cap reached (${q.caps.analystCases}) — nothing to do until tomorrow (UTC)`); + if (q && q.analystCasesLeft() === 0 && !o.situation?.only) log(`daily analyst case cap reached (${q.caps.analystCases}) — nothing to do until tomorrow (UTC)`); j("start", { narrator, reviewer, dryRun, selected: work.length }); if (work.length) { log(`selection (round-robin by rule, novelty-ranked): ${work.map((w, i) => `${i + 1}. ${w.finding.rule.name} ${w.score} [${w.finding.findingId}]${w.needs === "review" ? " review" : ""}`).join(" · ")}`); @@ -269,6 +292,62 @@ export async function runAnalyst(o: AnalystOptions): Promise { log(` ✗ ${message}`); } } + if (o.repliesDir && !dryRun) { + // The reply wall: same reviewer model, low effort, counted in the same daily $ budget. + const rr = await reviewReplies({ + dir: o.repliesDir, + ledger: o.ledger, + reviewer, + quota: q, + log, + journal: (kind, rec) => j(kind, rec), + call: async (system, user, schema) => { + try { + const r = await callJson({ apiKey, model: reviewer, system, user, schema, effort: "low", maxTokens: 2_000 }); + report.calls++; + report.costUsd += r.costUsd ?? 0; + j("call", { purpose: "reply_review", model: r.model, usage: r.usage, costUsd: r.costUsd, ms: r.ms, requestSha256: r.requestSha256, responseSha256: r.responseSha256 }); + if (q) j("spend", { day: q.day, callUsd: r.costUsd, dayUsd: q.addAnalystUsd(r.costUsd ?? 0), limitUsd: q.caps.analystUsd }); + return r; + } catch (err) { + report.calls++; + throw err; + } + }, + }); + report.replies = { accepted: rr.accepted.length, rejected: rr.rejected.length, errors: rr.errors.length, left: rr.left }; + if (rr.accepted.length || rr.rejected.length || rr.errors.length) log(`replies: ${rr.accepted.length} accepted · ${rr.rejected.length} rejected · ${rr.errors.length} errors · ${rr.left} waiting`); + } + if (o.situation) { + // After the cases, so today's briefing sees today's publications. Same budget, same journal. + const sr = await runSituation({ + findings: o.ledger.list(), + indicators: await o.situation.indicators(), + ledgerDir: o.situation.ledgerDir, + narrator, + reviewer, + quota: q, + dryRun, + log, + call: async (purpose, model, system, user, schema) => { + try { + const r = await callJson({ apiKey, model, system, user, schema, maxTokens: 8_000 }); + report.calls++; + report.costUsd += r.costUsd ?? 0; + j("call", { purpose, model: r.model, usage: r.usage, costUsd: r.costUsd, ms: r.ms, requestSha256: r.requestSha256, responseSha256: r.responseSha256 }); + if (q) j("spend", { day: q.day, callUsd: r.costUsd, dayUsd: q.addAnalystUsd(r.costUsd ?? 0), limitUsd: q.caps.analystUsd }); + log(` ↳ ${purpose} ${r.model} · ${r.usage.input_tokens} in / ${r.usage.output_tokens} out · ${r.costUsd == null ? "cost n/a" : `$${r.costUsd.toFixed(4)}`}`); + return r; + } catch (err) { + report.calls++; + j("call", { purpose, model, message: err instanceof Error ? err.message : String(err) }); + throw err; + } + }, + }); + report.situation = { level: sr.record.level, source: sr.record.source, skipped: sr.skipped, headline: sr.record.text.headline }; + j("situation", { date: sr.record.date, level: sr.record.level, source: sr.record.source, skipped: sr.skipped, dossierHash: sr.record.dossierHash, verdict: sr.record.verdict, problems: sr.record.problems }); + } j("end", { published: report.published.length, held: report.held.length, rejected: report.rejected.length, narrated: report.narrated.length, errors: report.errors.length, calls: report.calls, costUsd: report.costUsd }); return report; } diff --git a/src/analyst/checks.ts b/src/analyst/checks.ts index 189711a..f334e95 100644 --- a/src/analyst/checks.ts +++ b/src/analyst/checks.ts @@ -70,6 +70,10 @@ export const REVIEW_JSON_SCHEMA = { // ---- Dossier ------------------------------------------------------------------------------- /** Everything a model may know about a finding — and nothing else. */ +// HOOK (deliberately unused): "In the news" headlines (src/watch/news.ts, cached under +// /news/.json) could be offered to the narrator here as clearly-labelled +// *context* one day. They must never reach the reviewer's checks or count as confirmation — +// GDELT matches by place name and keyword, not by location, and is noisy. export function dossier(f: Finding) { const ev = (e: Evidence) => ({ id: e.id, kind: e.kind, source: e.source, datetime: e.datetime, method: e.method, summary: e.summary, values: e.values, href: e.href }); return { @@ -109,6 +113,16 @@ const rounds = (known: number, narrated: number) => { return same(Math.round(known * f) / f, narrated); }; +/** Numbers in `output` that do not appear (even rounded) in `source`; small counting integers 0–10 excepted. */ +export function numbersNotIn(output: string, source: string): number[] { + const known = numbersIn(source).map(Math.abs); + return numbersIn(output).filter((v) => { + const a = Math.abs(v); + if (Number.isInteger(a) && a <= 10) return false; + return !known.some((k) => same(k, a) || rounds(k, a)); + }); +} + /** * Violations (empty = faithful): every key number must appear verbatim in its cited * evidence's `values` or `summary`; every other number in the headline/narrative must @@ -130,12 +144,7 @@ export function faithfulness(f: Finding, n: Narration): string[] { } const { findingId: _id, ...facts } = dossier(f); // the UUID's digits are not facts const text = JSON.stringify(facts); - const known = numbersIn(text).map(Math.abs); - for (const v of numbersIn(`${n.headline}\n${n.narrative}`)) { - const a = Math.abs(v); - if (Number.isInteger(a) && a <= 10) continue; - if (!known.some((k) => same(k, a) || rounds(k, a))) problems.push(`the number ${v} in the headline/narrative does not appear (even rounded) in the finding's evidence or context`); - } + for (const v of numbersNotIn(`${n.headline}\n${n.narrative}`, text)) problems.push(`the number ${v} in the headline/narrative does not appear (even rounded) in the finding's evidence or context`); for (const name of personalNames(`${n.headline}\n${n.narrative}\n${n.caveats.join("\n")}\n${n.keyNumbers.map((k) => k.label).join("\n")}`, text)) { problems.push(`possible personal name "${name}" — never name people; if it is a place or institution, copy it exactly as it appears in the finding`); } diff --git a/src/analyst/cli.ts b/src/analyst/cli.ts index e1bddf6..353a801 100644 --- a/src/analyst/cli.ts +++ b/src/analyst/cli.ts @@ -1,13 +1,14 @@ // `earthdeck analyst --once` — narrate, review and (when the gates pass) publish confirmed // findings. Like `watch`, there is no loop: schedule `--once` after each sweep. -import { join } from "node:path"; +import { dirname, join, resolve } from "node:path"; import { anthropicApiKey, ledgerDir } from "../config.js"; import { OverviewError } from "../errors.js"; import { Ledger } from "../ledger/store.js"; import { Journal } from "../watch/journal.js"; import { capsFromEnv, QuotaGovernor } from "../watch/quota.js"; import { DEFAULT_NARRATOR, DEFAULT_REVIEWER, runAnalyst } from "./analyst.js"; +import { fetchIndicatorInputs } from "./situation.js"; const out = (s: string) => process.stdout.write(`${s}\n`); @@ -17,7 +18,11 @@ export async function runAnalystCli(args: string[]): Promise { return i >= 0 ? args[i + 1] : undefined; }; if (!args.includes("--once")) { - out("usage: earthdeck analyst --once [--max N] [--dry-run] [--model-narrator id] [--model-reviewer id]"); + out("usage: earthdeck analyst --once [--max N] [--dry-run] [--model-narrator id] [--model-reviewer id] [--replies dir] [--no-situation | --situation-only]"); + out(" Situation: after the cases, the daily briefing (level by fixed rules; at most one model briefing per UTC day,"); + out(" skipped when today's inputs are unchanged) is written to /situation/.json."); + out(" --replies: the reply wall mirror (inbox/ public/ rejected/); default /../replies. Up to 50 inbox replies"); + out(" per run are screened by the reviewer model, inside the same daily $ budget."); out(" --max defaults to EARTHDECK_MAX_ANALYST_CASES (10), which is also the per-UTC-day case cap;"); out(" the run stops once today's API spend reaches EARTHDECK_MAX_ANALYST_USD (3)."); out(` Narrates confirmed findings (${DEFAULT_NARRATOR}), has a different model review them (${DEFAULT_REVIEWER}),`); @@ -33,10 +38,14 @@ export async function runAnalystCli(args: string[]): Promise { const ledger = Ledger.open(dir, { createKey: !dryRun }); const journal = new Journal(join(dir, "watch")); const quota = new QuotaGovernor(journal.dir, caps); + const repliesDir = opt("--replies") ?? process.env.EARTHDECK_REPLIES_DIR ?? join(dirname(resolve(dir)), "replies"); out(`earthdeck analyst — ledger ${dir}${dryRun ? " — DRY RUN (one narration call per finding, nothing appended)" : ""}`); let r: Awaited>; try { - r = await runAnalyst({ ledger, journal, apiKey: anthropicApiKey(), narrator: opt("--model-narrator"), reviewer: opt("--model-reviewer"), max, dryRun, quota, log: out }); + const situation = args.includes("--no-situation") + ? undefined + : { ledgerDir: dir, only: args.includes("--situation-only"), indicators: () => fetchIndicatorInputs(join(dirname(resolve(dir)), "pulse.json"), 45_000, out) }; + r = await runAnalyst({ ledger, journal, apiKey: anthropicApiKey(), narrator: opt("--model-narrator"), reviewer: opt("--model-reviewer"), max, dryRun, quota, repliesDir: args.includes("--situation-only") ? undefined : repliesDir, situation, log: out }); } catch (err) { if (!(err instanceof OverviewError)) throw err; process.stderr.write(`earthdeck analyst: ${err.message}\n`); @@ -44,6 +53,7 @@ export async function runAnalystCli(args: string[]): Promise { return; } out(""); - out(`analyst ${r.runId}: ${r.selected} selected · ${r.narrated.length} narrated · ${r.published.length} published · ${r.held.length} held · ${r.rejected.length} rejected · ${r.errors.length} errors · ${r.calls} API calls ≈ $${r.costUsd.toFixed(4)} · today $${quota.analystUsd().toFixed(4)} of $${caps.analystUsd}`); + out(`analyst ${r.runId}: ${r.selected} selected · ${r.narrated.length} narrated · ${r.published.length} published · ${r.held.length} held · ${r.rejected.length} rejected · ${r.errors.length} errors · ${r.calls} API calls ≈ $${r.costUsd.toFixed(4)} · today $${quota.analystUsd().toFixed(4)} of $${caps.analystUsd}${r.replies ? ` · replies ${r.replies.accepted} accepted / ${r.replies.rejected} rejected / ${r.replies.left} waiting` : ""}`); + if (r.situation) out(`situation: ${r.situation.level} (${r.situation.source}${r.situation.skipped ? ", unchanged" : ""}) — ${r.situation.headline}`); if (r.errors.length) process.exitCode = 1; } diff --git a/src/analyst/situation.ts b/src/analyst/situation.ts new file mode 100644 index 0000000..f711bfd --- /dev/null +++ b/src/analyst/situation.ts @@ -0,0 +1,186 @@ +// The daily Situation briefing: the level comes from fixed rules (src/watch/situation.ts); the +// narrator writes a short briefing around it from a dossier, the deterministic checks +// (numbers, no persons, known ids) and a second model decide whether it may go out. Any +// failure → the rules-only text. One model briefing per UTC day, inside the analyst's $ budget. + +import { existsSync, readFileSync } from "node:fs"; +import { z } from "zod"; +import type { Finding } from "../ledger/schema.js"; +import { + buildDossier, + dossierHash, + fallbackBriefing, + readSituation, + SITUATION_NOTE, + writeSituation, + type Briefing, + type Dossier, + type IndicatorInputs, + type SituationRecord, +} from "../watch/situation.js"; +import type { QuotaGovernor } from "../watch/quota.js"; +import type { JsonCallResult } from "./anthropic.js"; +import { numbersNotIn, personalNames } from "./checks.js"; + +export const briefingSchema = z.object({ + headline: z.string().min(1).max(90), + summary: z.string().min(1).max(1200), + items: z + .array(z.object({ caseId: z.string().min(1).optional(), indicator: z.string().min(1).optional(), line: z.string().min(1).max(240) }).refine((i) => Boolean(i.caseId) !== Boolean(i.indicator), "each item names exactly one of caseId or indicator")) + .max(6), +}); +export const verdictSchema = z.object({ accept: z.boolean(), reason: z.string().min(1).max(600) }); + +const str = { type: "string" }; +export const BRIEFING_JSON_SCHEMA = { + type: "object", + additionalProperties: false, + required: ["headline", "summary", "items"], + properties: { + headline: str, + summary: str, + items: { type: "array", items: { type: "object", additionalProperties: false, required: ["line"], properties: { caseId: str, indicator: str, line: str } } }, + }, +}; +export const VERDICT_JSON_SCHEMA = { type: "object", additionalProperties: false, required: ["accept", "reason"], properties: { accept: { type: "boolean" }, reason: str } }; + +export const BRIEFER_SYSTEM = `You write the daily Situation briefing for TerraKeep, an evidence-first public watch of the planet. You are given a dossier as JSON: today's level (quiet, watch or urgent — decided by fixed rules, not by you) with the reasons behind it, counts of case changes since yesterday, newly published cases with their headlines, good-news cases, planet indicators with their latest value and what normal is, and the false alarms our own checks caught. + +Write for a general reader in plain language: what, if anything, is urgent on the planet today, and a short summary of our findings. + +Rules: +- Return JSON: headline (at most 90 characters), summary (3 to 5 sentences), items (at most 6, each one line, pointing at exactly one caseId or one indicator from the dossier). +- Do not change or argue with the level; explain it. If the level is quiet, say so plainly. +- Every number you write must appear in the dossier (you may round it). Do not compute new numbers (no differences, percentages or totals that are not in the dossier). +- Never name, describe or speculate about individual people. Places, assets and institutions only, as they appear in the dossier. +- No blame, no alarmism, no advice. Good news counts as news.`; + +export const CHECKER_SYSTEM = `You are the independent second reviewer of TerraKeep's daily Situation briefing. You get the dossier (JSON facts) and a draft briefing written by a different model. Accept only if every statement and number is supported by the dossier, the level is reported as given (not upgraded or downplayed), no individual person is named or identifiable, and the tone is calm and plain. Return {accept, reason} with a short, specific reason.`; + +/** Deterministic checks on a parsed briefing: numbers from the dossier, ids from the dossier, no persons. */ +export function checkBriefing(d: Dossier, b: Briefing): string[] { + const problems: string[] = []; + const text = JSON.stringify(d); + const out = [b.headline, b.summary, ...b.items.map((i) => i.line)].join("\n"); + for (const v of numbersNotIn(out, text)) problems.push(`the number ${v} does not appear (even rounded) in the dossier`); + const caseIds = new Set([...d.reasons.flatMap((r) => r.caseIds), ...d.newPublished.map((c) => c.caseId), ...d.goodNews.map((c) => c.caseId), ...d.falseAlarmsCaught.caseIds]); + const indicators = new Set([...d.indicators.map((i) => i.indicator), ...d.reasons.flatMap((r) => (r.indicator ? [r.indicator] : []))]); + for (const i of b.items) { + if (i.caseId && !caseIds.has(i.caseId)) problems.push(`item cites case ${i.caseId}, which is not in the dossier`); + if (i.indicator && !indicators.has(i.indicator)) problems.push(`item cites indicator ${i.indicator}, which is not in the dossier`); + } + for (const name of personalNames(out, text)) problems.push(`possible personal name "${name}"`); + const sentences = b.summary.split(/(?<=[.!?])\s+/).filter((s) => s.trim()).length; + if (sentences < 3 || sentences > 5) problems.push(`summary has ${sentences} sentences, not 3–5`); + return problems; +} + +/** Pure: does the draft parse and pass the deterministic checks? */ +export function parseBriefing(d: Dossier, data: unknown): { briefing: Briefing | null; problems: string[] } { + const p = briefingSchema.safeParse(data); + if (!p.success) return { briefing: null, problems: p.error.issues.map((i) => `${i.path.join(".") || "output"}: ${i.message}`) }; + return { briefing: p.data, problems: checkBriefing(d, p.data) }; +} + +export type SituationCall = (purpose: "situation_brief" | "situation_review", model: string, system: string, user: string, schema: Record) => Promise; + +export interface SituationOptions { + findings: readonly Finding[]; + indicators: IndicatorInputs; + ledgerDir: string; + narrator: string; + reviewer: string; + call: SituationCall; + quota?: QuotaGovernor; + /** Compute and call the models, but write nothing. */ + dryRun?: boolean; + now?: Date; + log?: (s: string) => void; +} + +export interface SituationResult { + record: SituationRecord; + skipped: boolean; + written: boolean; +} + +/** Once per UTC day: skip when today's record exists and the dossier is unchanged. */ +export async function runSituation(o: SituationOptions): Promise { + const now = o.now ?? new Date(); + const log = o.log ?? (() => {}); + const dossier = buildDossier(o.findings, o.indicators, now); + const hash = dossierHash(dossier); + const prior = readSituation(o.ledgerDir, dossier.date); + if (prior && prior.dossierHash === hash) { + log(`situation ${dossier.date}: ${prior.level}, inputs unchanged — skipped`); + return { record: prior, skipped: true, written: false }; + } + const base = { v: 1 as const, date: dossier.date, generatedAt: now.toISOString(), level: dossier.level, reasons: dossier.reasons, dossierHash: hash, dossier, note: SITUATION_NOTE }; + const rules = (problems: string[], verdict: SituationRecord["verdict"], cost: number, briefings: number): SituationRecord => ({ ...base, text: fallbackBriefing(dossier.level, dossier.reasons), source: "rules", models: null, verdict, problems, modelBriefings: briefings, costUsd: cost }); + + let rec: SituationRecord; + const used = prior?.modelBriefings ?? 0; + if (used >= 1) { + // The day's one model briefing is spent. Same level → keep its text (its numbers were checked + // against the earlier dossier, which is kept with it); a new level → the rules-only text. + if (prior && prior.source === "model" && prior.level === dossier.level) { + rec = { ...prior, generatedAt: now.toISOString() }; + log(`situation ${dossier.date}: ${dossier.level} unchanged — keeping today's briefing (1 per day)`); + } else { + rec = rules(["daily briefing already written; the level changed since, so the rules-only text is shown"], null, prior?.costUsd ?? 0, used); + log(`situation ${dossier.date}: level now ${dossier.level} — rules-only text (1 model briefing per day)`); + } + } else if (o.quota?.analystBudgetSpent()) { + rec = rules(["daily analyst budget spent"], null, 0, 0); + log(`situation ${dossier.date}: ${dossier.level} — budget spent, rules-only text`); + } else { + let cost = 0; + const facts = JSON.stringify(dossier, null, 2); + try { + const draft = await o.call("situation_brief", o.narrator, BRIEFER_SYSTEM, `Dossier:\n${facts}`, BRIEFING_JSON_SCHEMA); + cost += draft.costUsd ?? 0; + const { briefing, problems } = parseBriefing(dossier, draft.data); + if (!briefing || problems.length) { + rec = { ...rules(problems, null, cost, 1), draft: briefing ?? null }; + log(`situation: draft failed the checks → rules-only: ${problems.join(" | ")}`); + } else { + const rv = await o.call("situation_review", o.reviewer, CHECKER_SYSTEM, `Dossier:\n${facts}\n\nDraft briefing (by ${draft.model}):\n${JSON.stringify(briefing, null, 2)}`, VERDICT_JSON_SCHEMA); + cost += rv.costUsd ?? 0; + const v = verdictSchema.safeParse(rv.data); + if (!v.success) rec = rules([`review JSON invalid: ${v.error.issues.map((i) => i.message).join("; ")}`], null, cost, 1); + else if (!v.data.accept) rec = { ...rules([], v.data, cost, 1), models: { narrator: draft.model, reviewer: rv.model }, draft: briefing }; + else rec = { ...base, text: briefing, source: "model", models: { narrator: draft.model, reviewer: rv.model }, verdict: v.data, problems: [], modelBriefings: 1, costUsd: cost }; + log(`situation: reviewer ${v.success ? (v.data.accept ? "accepted" : `rejected — ${v.data.reason}`) : "returned invalid JSON"}`); + } + } catch (err) { + rec = rules([`model call failed: ${err instanceof Error ? err.message : String(err)}`], null, cost, 1); + log(`situation: ${rec.problems[0]} → rules-only`); + } + } + if (!o.dryRun) writeSituation(o.ledgerDir, rec); + else log(`situation (dry run — not written):\n${JSON.stringify({ level: rec.level, reasons: rec.reasons, text: rec.text, source: rec.source, verdict: rec.verdict, problems: rec.problems, draft: rec.draft, costUsd: rec.costUsd }, null, 2)}`); + log(`situation ${dossier.date}: ${rec.level} (${rec.source}) — ${rec.text.headline}`); + return { record: rec, skipped: false, written: !o.dryRun }; +} + +/** Best-effort indicator inputs: ONI + both poles' sea ice live, world pulse live with the cache as fallback. */ +export async function fetchIndicatorInputs(pulseCache: string | null, timeoutMs = 45_000, log: (s: string) => void = () => {}): Promise { + const guard = (p: Promise, what: string): Promise => { + let timer: NodeJS.Timeout | undefined; + const t = new Promise((res) => (timer = setTimeout(() => (log(` situation: ${what} timed out`), res(null)), timeoutMs))); + return Promise.race([p.catch((e: Error) => (log(` situation: ${what} unavailable (${e.message})`), null)), t]).finally(() => clearTimeout(timer)); + }; + const ind = await import("../clients/indicators.js"); + const pole = async (p: "north" | "south") => ({ pole: p, daily: await ind.fetchSeaIce(p), clim: await ind.fetchSeaIceClimatology(p) }); + const { worldPulse } = await import("../tools/worldpulse.js"); + const [oni, north, south, pulse] = await Promise.all([guard(ind.fetchOni(), "ONI"), guard(pole("north"), "Arctic sea ice"), guard(pole("south"), "Antarctic sea ice"), guard(worldPulse(), "world pulse")]); + let rows = pulse && pulse.rows.some((r) => r.status === "ok") ? pulse.rows : null; + if (!rows && pulseCache && existsSync(pulseCache)) { + try { + rows = (JSON.parse(readFileSync(pulseCache, "utf8")) as { rows?: typeof rows }).rows ?? null; + } catch { + rows = null; + } + } + return { oni, seaIce: [north, south].filter((x): x is NonNullable => x !== null), pulse: rows }; +} diff --git a/src/clients/ais.ts b/src/clients/ais.ts new file mode 100644 index 0000000..2e3fecf --- /dev/null +++ b/src/clients/ais.ts @@ -0,0 +1,203 @@ +// Ship density from a short aisstream.io sample — runner-side only (the key is a secret, so +// it never reaches a browser). Opens the websocket for ≤ `seconds` (default 20) over a few +// bounding boxes, keeps each vessel's latest position *in memory only*, and returns a +// density grid + counts by ship type. The output carries no MMSI, name, call sign, IMO, +// destination or track — only per-cell vessel counts, per-region totals and per-type totals. +// +// Protocol (verified live 2026-09-27): connect wss://stream.aisstream.io/v0/stream, then within +// 3 s send {APIKey, BoundingBoxes: [[[lat, lon], [lat, lon]], …], FilterMessageTypes}. Frames +// arrive as binary JSON: {MessageType, MetaData: {MMSI, ShipName, latitude, longitude, +// time_utc}, Message: {: {...}}}; the first is a SubscriptionConfirmation. +// Ship type (AIS code) only comes in ShipStaticData (every ~6 min) / StaticDataReport, so a +// 20 s sample leaves most vessels "unknown". Coverage is terrestrial (volunteer receivers): +// busy straits fill up, open-ocean reserves stay nearly empty — absence is not evidence. + +import type { BBox } from "../types.js"; + +export const AISSTREAM_URL = "wss://stream.aisstream.io/v0/stream"; +export const AIS_ATTRIBUTION = "AIS: aisstream.io (terrestrial receivers, short sample)"; + +export interface AisRegion { + id: string; + name: string; + bbox: BBox; +} + +/** Busy straits (good terrestrial coverage) + a few reserves near coasts. */ +export const AIS_REGIONS: AisRegion[] = [ + { id: "gibraltar", name: "Strait of Gibraltar", bbox: [-6.6, 35.6, -4.8, 36.4] }, + { id: "dover", name: "Strait of Dover", bbox: [0.8, 50.6, 2.2, 51.3] }, + { id: "singapore", name: "Singapore Strait", bbox: [103.5, 1.0, 104.5, 1.5] }, + { id: "hormuz", name: "Strait of Hormuz", bbox: [55.8, 25.8, 57.2, 27.0] }, + { id: "bosphorus", name: "Bosphorus", bbox: [28.9, 40.95, 29.2, 41.25] }, + { id: "panama", name: "Panama Canal approaches", bbox: [-80.0, 8.7, -79.4, 9.5] }, + { id: "galapagos", name: "Galápagos Marine Reserve", bbox: [-92.68, -2.09, -88.57, 2.36] }, + { id: "revillagigedo", name: "Revillagigedo", bbox: [-115.48, 17.65, -110.07, 20.01] }, +]; + +export type ShipClass = "cargo" | "tanker" | "passenger" | "fishing" | "tug_service" | "pleasure_sailing" | "high_speed" | "other" | "unknown"; +const CLASSES: ShipClass[] = ["cargo", "tanker", "passenger", "fishing", "tug_service", "pleasure_sailing", "high_speed", "other", "unknown"]; + +/** AIS ship-type code (ITU-R M.1371) → coarse class. */ +export function shipClass(code: number | undefined): ShipClass { + if (code === undefined || !Number.isFinite(code) || code <= 0) return "unknown"; + if (code === 30) return "fishing"; + if (code === 31 || code === 32 || code === 33 || code === 34 || code === 35 || (code >= 50 && code <= 59)) return "tug_service"; + if (code === 36 || code === 37) return "pleasure_sailing"; + if (code >= 40 && code <= 49) return "high_speed"; + if (code >= 60 && code <= 69) return "passenger"; + if (code >= 70 && code <= 79) return "cargo"; + if (code >= 80 && code <= 89) return "tanker"; + return "other"; +} + +export interface ShipDensity { + generatedAt: string; + sampleSeconds: number; + cellDeg: number; + messages: number; + vessels: number; + byType: Record; + regions: { id: string; name: string; bbox: BBox; vessels: number }[]; + cells: { lon: number; lat: number; count: number }[]; + attribution: string; + privacy: string; +} + +const inBox = (b: BBox, lon: number, lat: number) => lon >= b[0] && lon <= b[2] && lat >= b[1] && lat <= b[3]; + +/** Folds aisstream frames into per-vessel latest state; `result()` emits only aggregates. */ +export class AisAggregator { + private readonly vessels = new Map(); + private messages = 0; + + add(frame: unknown): void { + const f = frame as { MessageType?: string; MetaData?: { MMSI?: unknown; latitude?: unknown; longitude?: unknown }; Message?: Record> }; + if (!f || typeof f !== "object" || !f.MessageType || f.MessageType === "SubscriptionConfirmation") return; + const id = f.MetaData?.MMSI; + if (id === undefined || id === null) return; + this.messages++; + const key = String(id); + const v = this.vessels.get(key) ?? { lon: NaN, lat: NaN }; + const body = f.Message?.[f.MessageType] ?? {}; + if (f.MessageType === "ShipStaticData" && typeof body.Type === "number") v.type = body.Type; + if (f.MessageType === "StaticDataReport") { + const t = (body.ReportB as { ShipType?: unknown } | undefined)?.ShipType; + if (typeof t === "number") v.type = t; + } + const lat = Number(f.MetaData?.latitude); + const lon = Number(f.MetaData?.longitude); + if (Number.isFinite(lat) && Number.isFinite(lon) && Math.abs(lat) <= 90 && Math.abs(lon) <= 180 && !(lat === 0 && lon === 0)) { + v.lat = lat; + v.lon = lon; + } + this.vessels.set(key, v); + } + + result(o: { regions: AisRegion[]; sampleSeconds: number; cellDeg?: number; now?: Date }): ShipDensity { + const cellDeg = o.cellDeg ?? 0.1; + const placed = [...this.vessels.values()].filter((v) => Number.isFinite(v.lat)); + const byType = Object.fromEntries(CLASSES.map((c) => [c, 0])) as Record; + for (const v of placed) byType[shipClass(v.type)]++; + const cells = new Map(); + const snap = (x: number) => Math.round((Math.floor(x / cellDeg) * cellDeg + cellDeg / 2) * 1e4) / 1e4; + for (const v of placed) { + const lon = snap(v.lon); + const lat = snap(v.lat); + const k = `${lon},${lat}`; + const c = cells.get(k) ?? { lon, lat, count: 0 }; + c.count++; + cells.set(k, c); + } + return { + generatedAt: (o.now ?? new Date()).toISOString(), + sampleSeconds: o.sampleSeconds, + cellDeg, + messages: this.messages, + vessels: placed.length, + byType, + regions: o.regions.map((r) => ({ ...r, vessels: placed.filter((v) => inBox(r.bbox, v.lon, v.lat)).length })), + cells: [...cells.values()].sort((a, b) => b.count - a.count || a.lon - b.lon || a.lat - b.lat), + attribution: AIS_ATTRIBUTION, + privacy: `Aggregated: vessel counts per ${cellDeg}° cell, per region and per ship type from one short sample. No MMSI, names, call signs, IMO numbers, destinations or tracks are stored or published.`, + }; + } +} + +/** The subscription message (bbox → aisstream's [[lat, lon], [lat, lon]] corners). */ +export function subscription(key: string, regions: AisRegion[]): string { + return JSON.stringify({ + APIKey: key, + BoundingBoxes: regions.map((r) => [[r.bbox[1], r.bbox[0]], [r.bbox[3], r.bbox[2]]]), + FilterMessageTypes: ["PositionReport", "StandardClassBPositionReport", "ExtendedClassBPositionReport", "ShipStaticData", "StaticDataReport"], + }); +} + +type WsLike = { + onopen: (() => void) | null; + onmessage: ((e: { data: unknown }) => void) | null; + onerror: ((e: unknown) => void) | null; + onclose: (() => void) | null; + send(data: string): void; + close(): void; +}; + +/** Sample aisstream for `seconds` (capped at 20) and return aggregates only. Never throws on a quiet stream. */ +export async function sampleAis( + key: string, + o: { regions?: AisRegion[]; seconds?: number; cellDeg?: number; WebSocketImpl?: new (url: string) => WsLike } = {}, +): Promise { + const regions = o.regions ?? AIS_REGIONS; + const seconds = Math.min(20, Math.max(1, o.seconds ?? 20)); + const Impl = o.WebSocketImpl ?? (globalThis as unknown as { WebSocket?: new (url: string) => WsLike }).WebSocket; + if (!Impl) throw new Error("no WebSocket implementation (Node ≥ 22 has one built in)"); + const agg = new AisAggregator(); + const pending: Promise[] = []; + let error: string | null = null; + await new Promise((resolve) => { + const ws = new Impl(AISSTREAM_URL); + const timer = setTimeout(() => { + try { + ws.close(); + } catch { + /* already closed */ + } + resolve(); + }, seconds * 1000); + ws.onopen = () => ws.send(subscription(key, regions)); + ws.onmessage = (e) => { + pending.push( + decode(e.data).then((text) => { + try { + const j = JSON.parse(text) as { error?: string }; + if (j && typeof j.error === "string") error = j.error; + else agg.add(j); + } catch { + /* skip malformed frame */ + } + }), + ); + }; + ws.onerror = () => { + error ??= "websocket error"; + }; + ws.onclose = () => { + clearTimeout(timer); + resolve(); + }; + }); + await Promise.all(pending); + const r = agg.result({ regions, sampleSeconds: seconds, cellDeg: o.cellDeg }); + // aisstream reports a bad key as {"error": "..."} then closes: surface that (the message + // never contains the key itself), but a merely quiet sample is a valid, empty result. + if (error && r.messages === 0) throw new Error(`aisstream: ${error}`); + return r; +} + +async function decode(data: unknown): Promise { + if (typeof data === "string") return data; + if (data instanceof ArrayBuffer) return Buffer.from(data).toString("utf8"); + if (ArrayBuffer.isView(data)) return Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString("utf8"); + if (data && typeof (data as Blob).arrayBuffer === "function") return Buffer.from(await (data as Blob).arrayBuffer()).toString("utf8"); + return String(data); +} diff --git a/src/clients/gdelt.ts b/src/clients/gdelt.ts new file mode 100644 index 0000000..77ff473 --- /dev/null +++ b/src/clients/gdelt.ts @@ -0,0 +1,155 @@ +// GDELT DOC 2.0 — "In the news" context for a case: recent headlines matching the case's place +// name + topic keywords. Zero-key, open (https://blog.gdeltproject.org/gdelt-doc-2-0-api-debuts/). +// +// Verified live 2026-09-27: the GEO 2.0 endpoint (api/v2/geo/geo) answers 404 — it is gone, +// so there is no radius search; matching is by place name + keywords over article text, which +// is noisy. The DOC API asks for ≤1 request per 5 s and answers an over-rate request with HTTP +// 200 and a plain-text "Please limit requests…" notice instead of JSON — treated as a rate +// limit (fail soft, never retried). Only headline metadata is kept: no bodies, no images. + +import { OverviewError } from "../errors.js"; + +export const GDELT_DOC = "https://api.gdeltproject.org/api/v2/doc/doc"; +export const GDELT_USER_AGENT = "earthdeck-news/0.3 (+https://vitalearth.io; open-data environmental watch)"; +/** GDELT asks for one request every 5 seconds. */ +export const GDELT_MIN_INTERVAL_MS = 5_500; + +export interface NewsItem { + title: string; + url: string; + domain: string; + /** ISO 8601 (GDELT's `20260927T093000Z` normalised). */ + seendate: string; + language: string; + sourcecountry: string; +} + +/** The subset of a finding the query builder needs. */ +export interface NewsSubject { + rule: { name: string; params?: Record }; + aoi?: { name?: string }; + title: string; +} + +/** Topic keywords per rule (OR-ed). Phrases are quoted in the query. */ +export function topicKeywords(s: NewsSubject): string[] { + const p = s.rule.params ?? {}; + const kind = String(p.kind ?? p.indicator ?? p.hazard ?? ""); + switch (s.rule.name) { + case "forest_loss": + return ["deforestation", "logging", "land clearing"]; + case "fires_in_protected": + case "fires_absent": + return ["wildfire", "forest fire", "bushfire"]; + case "flaring": + case "flaring_stopped": + return ["gas flaring", "flaring", "oil field"]; + case "methane_anomaly": + return ["methane", "gas leak", "gas flaring"]; + case "mpa_fishing": + return ["illegal fishing", "fishing fleet", "fishing vessels"]; + case "weather_extreme": + return ["heatwave", "cyclone", "flood", "extreme weather"]; + case "indicator_threshold": + if (kind === "marine_heatwave") return ["marine heatwave", "coral bleaching", "ocean temperature"]; + if (kind === "sea_ice") return ["sea ice"]; + if (kind === "air_quality") return ["smog", "air pollution", "air quality"]; + if (kind === "river_discharge") return ["flood", "drought", "river level"]; + return []; + case "improvement": + if (/forest/.test(kind)) return ["deforestation", "logging"]; + if (/flar/.test(kind)) return ["gas flaring", "flaring"]; + if (/reef|coral/.test(kind)) return ["coral bleaching", "marine heatwave"]; + if (/air/.test(kind)) return ["smog", "air pollution"]; + if (/fire/.test(kind)) return ["wildfire", "forest fire"]; + return []; + default: + return []; + } +} + +/** + * The place to search for, cleaned of watch bookkeeping: "Flare field near Eleme, Rivers + * (Nigeria) — 20 registered sites" → "Eleme"; "Mavinga National Park (AGO) — tile 3/4" → + * "Mavinga National Park". Global / hemispheric subjects ("World: …", "Arctic sea ice") give the + * region word only when it is a real place; otherwise null (no place → no news query). + */ +export function newsPlace(s: NewsSubject): string | null { + let n = (s.aoi?.name ?? "").trim(); + if (!n || /^world\b/i.test(n)) return null; + if (/^(arctic|antarctic) sea ice$/i.test(n)) return n.split(" ")[0]!; + n = n.replace(/\s+[—–-]\s+(tile \d+\/\d+|\d+ registered sites?)\s*$/i, ""); + n = n.replace(/^flare field near\s+/i, ""); + n = n.replace(/\s*\([^)]*\)\s*/g, " ").trim(); + n = n.split(",")[0]!.trim(); + n = n.replace(/["()]/g, "").trim(); + // GDELT rejects keywords shorter than 3 characters; very short names are also too ambiguous. + return n.length >= 4 ? n : null; +} + +/** DOC 2.0 query string, or null when the case has no place or no topic. */ +export function newsQuery(s: NewsSubject): string | null { + const place = newsPlace(s); + const kw = topicKeywords(s); + if (!place || kw.length === 0) return null; + const q = (w: string) => (w.includes(" ") ? `"${w}"` : w); + const topic = kw.length === 1 ? q(kw[0]!) : `(${kw.map(q).join(" OR ")})`; + return `"${place}" ${topic}`; +} + +export function gdeltUrl(query: string, opts: { timespan?: string; maxrecords?: number } = {}): string { + return `${GDELT_DOC}?${new URLSearchParams({ + query, + mode: "ArtList", + format: "json", + timespan: opts.timespan ?? "7d", + maxrecords: String(opts.maxrecords ?? 10), + sort: "hybridrel", + })}`; +} + +function isoSeen(s: string): string { + const m = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/.exec(s); + return m ? `${m[1]}-${m[2]}-${m[3]}T${m[4]}:${m[5]}:${m[6]}Z` : s; +} + +/** Keep only headline metadata; drop malformed rows, non-http(s) URLs and duplicate titles. */ +export function parseArticles(body: unknown): NewsItem[] { + const arts = (body as { articles?: unknown })?.articles; + if (!Array.isArray(arts)) return []; + const out: NewsItem[] = []; + const seen = new Set(); + for (const a of arts as Record[]) { + const str = (k: string) => (typeof a?.[k] === "string" ? (a[k] as string).trim() : ""); + const url = str("url"); + const title = str("title").replace(/\s+/g, " "); + if (!title || !/^https?:\/\//i.test(url)) continue; + const key = title.toLowerCase(); + if (seen.has(key)) continue; + seen.add(key); + out.push({ title: title.slice(0, 300), url, domain: str("domain"), seendate: isoSeen(str("seendate")), language: str("language"), sourcecountry: str("sourcecountry") }); + } + return out; +} + +/** + * One DOC 2.0 ArtList call. 15 s timeout, never retried. Throws OverviewError with status 429 + * on a rate-limit answer (real 429 or GDELT's plain-text notice) so callers can stop for the run. + */ +export async function gdeltArticles(query: string, opts: { timespan?: string; maxrecords?: number; timeoutMs?: number } = {}): Promise { + const res = await fetch(gdeltUrl(query, opts), { + headers: { "user-agent": GDELT_USER_AGENT, accept: "application/json" }, + signal: AbortSignal.timeout(opts.timeoutMs ?? 15_000), + }); + const text = await res.text(); + if (res.status === 429 || /please limit requests/i.test(text)) throw new OverviewError("GDELT rate limit (429)", 429); + if (!res.ok) throw new OverviewError(`GDELT DOC request failed (${res.status})`, res.status, text.slice(0, 200)); + if (!text.trim()) return []; // GDELT answers an empty body when nothing matched + let body: unknown; + try { + body = JSON.parse(text); + } catch { + throw new OverviewError(`GDELT DOC answered non-JSON: ${text.slice(0, 120)}`, res.status); + } + return parseArticles(body); +} diff --git a/src/clients/gfw.ts b/src/clients/gfw.ts index 09ccb38..61a926e 100644 --- a/src/clients/gfw.ts +++ b/src/clients/gfw.ts @@ -50,8 +50,9 @@ export function bboxToPolygon(bbox: BBox): { type: "Polygon"; coordinates: numbe * SQL dialect rejects `IN` ("Unsupported filter operator") and numeric comparison against * encoded fields — string equality OR-chained is the form it accepts (verified live). */ -export function alertsWhere(dateFrom: string, minConfidence: GfwConfidence): string { +export function alertsWhere(dateFrom: string, minConfidence: GfwConfidence, dateTo?: string): string { let where = `${DATE_FIELD} >= '${dateFrom}'`; + if (dateTo) where += ` AND ${DATE_FIELD} <= '${dateTo}'`; if (minConfidence !== "nominal") { const allowed = GFW_CONFIDENCES.slice(GFW_CONFIDENCES.indexOf(minConfidence)); where += ` AND (${allowed.map((c) => `${CONF_FIELD} = '${c}'`).join(" OR ")})`; @@ -63,18 +64,18 @@ export function alertsWhere(dateFrom: string, minConfidence: GfwConfidence): str // SUM(area__ha) as `area__ha` (verified live), so the SQL stays alias-free. /** Totals + area grouped by confidence level. */ -export function alertsSummarySql(dateFrom: string, minConfidence: GfwConfidence): string { +export function alertsSummarySql(dateFrom: string, minConfidence: GfwConfidence, dateTo?: string): string { return ( `SELECT ${CONF_FIELD}, COUNT(*), SUM(area__ha) FROM results ` + - `WHERE ${alertsWhere(dateFrom, minConfidence)} GROUP BY ${CONF_FIELD}` + `WHERE ${alertsWhere(dateFrom, minConfidence, dateTo)} GROUP BY ${CONF_FIELD}` ); } /** Daily alert counts (drives the dashboard series chart). */ -export function alertsDailySql(dateFrom: string, minConfidence: GfwConfidence): string { +export function alertsDailySql(dateFrom: string, minConfidence: GfwConfidence, dateTo?: string): string { return ( `SELECT ${DATE_FIELD}, COUNT(*) FROM results ` + - `WHERE ${alertsWhere(dateFrom, minConfidence)} GROUP BY ${DATE_FIELD} ORDER BY ${DATE_FIELD}` + `WHERE ${alertsWhere(dateFrom, minConfidence, dateTo)} GROUP BY ${DATE_FIELD} ORDER BY ${DATE_FIELD}` ); } @@ -170,12 +171,14 @@ export async function integratedAlerts( bbox: BBox, dateFrom: string, minConfidence: GfwConfidence, + /** Inclusive last day (YYYY-MM-DD); omitted = up to the latest alert. */ + dateTo?: string, ): Promise<{ summary: GfwAlertsSummary; daily: GfwDailyCount[] }> { assertBBox(bbox); const geometry = bboxToPolygon(bbox); const [summaryRows, dailyRows] = await Promise.all([ - gfwQuery(apiKey, GFW_ALERTS_DATASET, alertsSummarySql(dateFrom, minConfidence), geometry), - gfwQuery(apiKey, GFW_ALERTS_DATASET, alertsDailySql(dateFrom, minConfidence), geometry), + gfwQuery(apiKey, GFW_ALERTS_DATASET, alertsSummarySql(dateFrom, minConfidence, dateTo), geometry), + gfwQuery(apiKey, GFW_ALERTS_DATASET, alertsDailySql(dateFrom, minConfidence, dateTo), geometry), ]); return { summary: parseSummaryRows(summaryRows), daily: parseDailyRows(dailyRows) }; } diff --git a/src/clients/gfwfishing.ts b/src/clients/gfwfishing.ts new file mode 100644 index 0000000..85d1b71 --- /dev/null +++ b/src/clients/gfwfishing.ts @@ -0,0 +1,247 @@ +// Global Fishing Watch (NOT Global *Forest* Watch — that is ./gfw.ts) — apparent fishing +// effort from the 4Wings report API. Aggregated only: hours per grid cell, per day, per flag +// state and per gear type. Vessel identities are never requested (no VESSEL_ID group-by) +// and the parser keeps only an allow-list of fields, so nothing vessel-level can leak even +// if the upstream response grows new columns. The per-cell `vesselIDs` field GFW returns is +// a distinct-vessel *count* — we drop it too (summing it across cells double-counts anyway). +// +// Request shape (verified live 2026-09-27, API v3): +// POST https://gateway.api.globalfishingwatch.org/v3/4wings/report +// ?spatial-resolution=LOW|HIGH (LOW = 0.1°, HIGH = 0.01° cells; MEDIUM → 422) +// &temporal-resolution=DAILY|MONTHLY|ENTIRE +// &group-by=FLAG|GEARTYPE (one dimension per request) +// &datasets[0]=public-global-fishing-effort:latest (resolved to :v4.0 in the reply) +// &date-range=YYYY-MM-DD,YYYY-MM-DD +// &format=JSON +// Authorization: Bearer +// body: {"geojson": } or {"region": {"dataset": "public-mpa-all", "id": ""}} +// reply: {"total":1, "entries":[{"public-global-fishing-effort:v4.0":[{date, flag|geartype, hours, lat, lon, vesselIDs}]}]} +// Quirks: data lags ~4 days (a 30-day window ending today holds ~26 days); ENTIRE rows carry +// date "from,to"; `public-mpa-all` region ids are WDPA site_pids (strings, e.g. "555556875_1"), +// unknown ids → 422 "Region not found"; one dimension per group-by, so flag + gear = two +// requests (made sequentially — GFW limits concurrent reports per token, UNCONFIRMED how hard). +// PRIVACY QUIRK: with NO group-by the report defaults to per-vessel rows (callsign, ship name, +// MMSI, entry/exit timestamps — seen live). So `group-by` is mandatory here, always FLAG or +// GEARTYPE, and the allow-list parser is the second line of defence. +// +// Terms: data CC BY-NC 4.0, API non-commercial; attribution "Global Fishing Watch, . +// www.globalfishingwatch.org" rides in every result's provenance. + +import { USER_AGENT } from "../config.js"; +import { OverviewError } from "../errors.js"; +import type { BBox } from "../types.js"; +import { addDays } from "../util.js"; + +export const GFW_FISHING_API = "https://gateway.api.globalfishingwatch.org/v3"; +export const FISHING_DATASET = "public-global-fishing-effort:latest"; +export const MPA_REGION_DATASET = "public-mpa-all"; +export const FISHING_LICENCE = "CC BY-NC 4.0 (data) — Global Fishing Watch API terms: non-commercial use only"; +export const FISHING_SOURCE = "Global Fishing Watch 4Wings — apparent fishing effort (AIS, model-inferred)"; + +/** GFW's required attribution line. */ +export function fishingAttribution(year: number): string { + return `Global Fishing Watch, ${year}. www.globalfishingwatch.org`; +} + +export type SpatialRes = "LOW" | "HIGH"; +export type TemporalRes = "DAILY" | "MONTHLY" | "ENTIRE"; +export type GroupBy = "FLAG" | "GEARTYPE"; +export type FishingArea = { bbox: BBox } | { mpaId: string }; + +export const CELL_DEG: Record = { LOW: 0.1, HIGH: 0.01 }; + +export function gfwFishingToken(env: NodeJS.ProcessEnv = process.env): string | null { + return env.GFW_FISHING_TOKEN?.trim() || null; +} + +/** The report URL (query string only — the area goes in the body). */ +export function reportUrl(o: { from: string; to: string; spatial: SpatialRes; temporal: TemporalRes; groupBy: GroupBy }): string { + if (o.groupBy !== "FLAG" && o.groupBy !== "GEARTYPE") throw new Error("gfwfishing: group-by must be FLAG or GEARTYPE (no group-by = per-vessel rows)"); + const q = [ + `spatial-resolution=${o.spatial}`, + `temporal-resolution=${o.temporal}`, + `group-by=${o.groupBy}`, + `datasets[0]=${FISHING_DATASET}`, + `date-range=${o.from},${o.to}`, + "format=JSON", + ]; + return `${GFW_FISHING_API}/4wings/report?${q.join("&")}`; +} + +export function reportBody(area: FishingArea): string { + if ("mpaId" in area) return JSON.stringify({ region: { dataset: MPA_REGION_DATASET, id: area.mpaId } }); + const [w, s, e, n] = area.bbox; + return JSON.stringify({ geojson: { type: "Polygon", coordinates: [[[w, s], [e, s], [e, n], [w, n], [w, s]]] } }); +} + +/** One aggregated effort cell. Allow-listed fields only — see the header. */ +export interface EffortRow { + date: string; + lat: number; + lon: number; + hours: number; + flag?: string; + gear?: string; +} + +/** Parse a report reply into allow-listed rows + the resolved dataset version. */ +export function parseReport(json: unknown): { dataset: string; rows: EffortRow[] } { + const entries = (json as { entries?: Array> })?.entries; + if (!Array.isArray(entries)) throw new OverviewError("GFW 4Wings report: unexpected reply (no entries[])", undefined, JSON.stringify(json).slice(0, 300)); + let dataset = FISHING_DATASET; + const rows: EffortRow[] = []; + for (const entry of entries) { + for (const [key, list] of Object.entries(entry ?? {})) { + dataset = key; + if (!Array.isArray(list)) continue; + for (const r of list as Array>) { + const hours = Number(r.hours); + const lat = Number(r.lat); + const lon = Number(r.lon); + if (![hours, lat, lon].every(Number.isFinite)) continue; + const row: EffortRow = { date: String(r.date ?? ""), lat, lon, hours }; + if (typeof r.flag === "string") row.flag = r.flag || "UNK"; + if (typeof r.geartype === "string") row.gear = r.geartype || "unknown"; + rows.push(row); + } + } + } + return { dataset, rows }; +} + +async function report(token: string, area: FishingArea, o: Parameters[0]): Promise<{ dataset: string; rows: EffortRow[] }> { + const res = await fetch(reportUrl(o), { + method: "POST", + headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json", "user-agent": USER_AGENT }, + body: reportBody(area), + }); + const text = await res.text(); + if (res.status === 401 || res.status === 403) throw new OverviewError(`Global Fishing Watch rejected the token (${res.status}) — check GFW_FISHING_TOKEN`, res.status, text.slice(0, 300)); + if (res.status === 429) throw new OverviewError("Global Fishing Watch rate limit (429) — too many requests; retry later", 429, text.slice(0, 300)); + if (!res.ok) { + let detail = text.slice(0, 300); + try { + const j = JSON.parse(text) as { messages?: { title?: string; detail?: string }[] }; + if (j.messages?.length) detail = j.messages.map((m) => `${m.title ?? ""}: ${m.detail ?? ""}`).join("; "); + } catch { + /* keep raw */ + } + throw new OverviewError(`Global Fishing Watch report failed (${res.status}): ${detail}`, res.status, text.slice(0, 300)); + } + try { + return parseReport(JSON.parse(text)); + } catch (e) { + if (e instanceof OverviewError) throw e; + throw new OverviewError("Global Fishing Watch returned non-JSON", res.status, text.slice(0, 300)); + } +} + +export interface FishingQuery { + area: FishingArea; + from: string; + to: string; + resolution?: SpatialRes; + /** Second request grouped by gear type (default true). */ + byGear?: boolean; + /** Also sum the hours of cells whose centre lies inside this box. */ + clip?: BBox; + /** Top cells by hours to return (default 0 — totals only). */ + maxCells?: number; +} + +export interface FishingSummary { + dataset: string; + area: { kind: "bbox"; bbox: BBox } | { kind: "mpa"; regionDataset: string; id: string }; + from: string; + to: string; + resolution: SpatialRes; + cellDeg: number; + totalHours: number; + /** Distinct grid cells with any effort. */ + cells: number; + activeDays: number; + lastDataDate: string | null; + byFlag: { flag: string; hours: number }[]; + byGear: { gear: string; hours: number }[] | null; + /** One row per calendar day from `from` to the last day with data (zero-filled). */ + daily: { date: string; hours: number }[]; + clip: { bbox: BBox; hours: number; share: number | null } | null; + grid: { lon: number; lat: number; hours: number }[]; +} + +const r1 = (v: number) => Math.round(v * 10) / 10; +const cellKey = (lon: number, lat: number) => `${lon.toFixed(3)},${lat.toFixed(3)}`; +export const inBBox = (b: BBox, lon: number, lat: number) => lon >= b[0] && lon <= b[2] && lat >= b[1] && lat <= b[3]; + +/** Aggregate DAILY+FLAG rows (and optional ENTIRE+GEARTYPE rows) into the tool's summary. */ +export function summarize(q: FishingQuery, dataset: string, flagRows: EffortRow[], gearRows: EffortRow[] | null): FishingSummary { + const resolution = q.resolution ?? "LOW"; + const sumBy = (rows: EffortRow[], key: (r: EffortRow) => string) => { + const m = new Map(); + for (const r of rows) m.set(key(r), (m.get(key(r)) ?? 0) + r.hours); + return [...m.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])); + }; + const total = flagRows.reduce((a, r) => a + r.hours, 0); + const days = new Map(sumBy(flagRows, (r) => r.date.slice(0, 10))); + const dates = [...days.keys()].filter((d) => /^\d{4}-\d{2}-\d{2}$/.test(d)).sort(); + const lastDataDate = dates.at(-1) ?? null; + const daily: { date: string; hours: number }[] = []; + if (lastDataDate) for (let d = q.from; d <= lastDataDate; d = addDays(d, 1)) daily.push({ date: d, hours: r1(days.get(d) ?? 0) }); + const cellHours = new Map(); + for (const r of flagRows) { + const k = cellKey(r.lon, r.lat); + const c = cellHours.get(k) ?? { lon: r.lon, lat: r.lat, hours: 0 }; + c.hours += r.hours; + cellHours.set(k, c); + } + let clip: FishingSummary["clip"] = null; + if (q.clip) { + const h = [...cellHours.values()].filter((c) => inBBox(q.clip!, c.lon, c.lat)).reduce((a, c) => a + c.hours, 0); + clip = { bbox: q.clip, hours: r1(h), share: total > 0 ? Math.round((h / total) * 1000) / 1000 : null }; + } + const grid = [...cellHours.values()] + .sort((a, b) => b.hours - a.hours || a.lon - b.lon || a.lat - b.lat) + .slice(0, Math.max(0, q.maxCells ?? 0)) + .map((c) => ({ lon: c.lon, lat: c.lat, hours: r1(c.hours) })); + return { + dataset, + area: "mpaId" in q.area ? { kind: "mpa", regionDataset: MPA_REGION_DATASET, id: q.area.mpaId } : { kind: "bbox", bbox: q.area.bbox }, + from: q.from, + to: q.to, + resolution, + cellDeg: CELL_DEG[resolution], + totalHours: r1(total), + cells: cellHours.size, + activeDays: dates.filter((d) => (days.get(d) ?? 0) > 0).length, + lastDataDate, + byFlag: sumBy(flagRows, (r) => r.flag ?? "UNK").map(([flag, hours]) => ({ flag, hours: r1(hours) })), + byGear: gearRows ? sumBy(gearRows, (r) => r.gear ?? "unknown").map(([gear, hours]) => ({ gear, hours: r1(hours) })) : null, + daily, + clip, + grid, + }; +} + +/** Apparent fishing effort in a bbox or a WDPA MPA over [from, to]: 1 request (+1 for gear). */ +export async function fishingEffort(token: string, q: FishingQuery): Promise { + const spatial = q.resolution ?? "LOW"; + const flag = await report(token, q.area, { from: q.from, to: q.to, spatial, temporal: "DAILY", groupBy: "FLAG" }); + const gear = q.byGear === false ? null : await report(token, q.area, { from: q.from, to: q.to, spatial: "LOW", temporal: "ENTIRE", groupBy: "GEARTYPE" }); + return summarize(q, flag.dataset, flag.rows, gear?.rows ?? null); +} + +/** + * Per-cell totals over [from, to] (ENTIRE, grouped by flag and summed per cell — never + * ungrouped, see the header) — for the public map's coarse effort grid. + */ +export async function effortGrid(token: string, area: FishingArea, from: string, to: string, spatial: SpatialRes = "LOW"): Promise<{ dataset: string; cells: { lon: number; lat: number; hours: number }[] }> { + const r = await report(token, area, { from, to, spatial, temporal: "ENTIRE", groupBy: "FLAG" }); + const m = new Map(); + for (const row of r.rows) { + const k = cellKey(row.lon, row.lat); + const c = m.get(k) ?? { lon: row.lon, lat: row.lat, hours: 0 }; + c.hours += row.hours; + m.set(k, c); + } + return { dataset: r.dataset, cells: [...m.values()].map((c) => ({ ...c, hours: r1(c.hours) })).filter((c) => c.hours > 0) }; +} diff --git a/src/clients/naturalvalue.ts b/src/clients/naturalvalue.ts index 55e4d84..d0c7f80 100644 --- a/src/clients/naturalvalue.ts +++ b/src/clients/naturalvalue.ts @@ -8,6 +8,9 @@ // sourced it is absent, never estimated here. import { getCopernicus } from "./copernicus.js"; +import { DW_CLASSES, GEE_SOURCES, MAPBIOMAS_CLASSES, geeClient, landCoverExpression, pickScale, type GeeClient } from "./gee.js"; +import { bboxAreaKm2 } from "./protected.js"; +import { geeCreds } from "../config.js"; import { OverviewError } from "../errors.js"; import type { BBox } from "../types.js"; import { round } from "../series.js"; @@ -448,3 +451,197 @@ export function assumeBiome(lat: number): { biome: BiomeId; assumption: string } assumption: `ASSUMPTION: no land-cover measurement; the whole box is treated as ${BIOMES[biome]?.label ?? biome} from its latitude (${round(lat, 2)}°). This overstates value wherever the land is already cleared, farmed or built on — pass \`biome\` or enable CDSE land cover.`, }; } + +// ---- land USE via Earth Engine (MapBiomas / Dynamic World) ----------------------------------- +// +// Provider order when GEE is configured: MapBiomas (Brazil) → Dynamic World → CLMS/CDSE → assumed. +// Each class is either NATURAL (valued with a registry biome, or explicitly unvalued) or CONVERTED +// (pasture, crops, mosaic, urban, mining, bare). Converted land is never in the living natural +// value; where the registry has a sourced value for it (Costanza 2014 cropland / urban) that value +// is reported separately as a reference, never summed. + +export type LandCoverProvider = "mapbiomas-ee" | "dynamicworld-ee" | "clms-cdse" | "assumed"; +export type GeeLandCoverDataset = "mapbiomas" | "dynamic-world"; + +/** "forest" resolves to tropical/temperate/boreal by latitude (forestBiome). */ +export interface ClassValuation { + use: "natural" | "converted"; + biome: BiomeId | "forest" | null; + basis: string; +} + +const B_FOREST = "Costanza 2014 forest unit value, tropical/temperate/boreal by latitude"; +const B_GRASS = "Costanza 2014 grass/rangelands — natural herbaceous/shrub/savanna vegetation (Costanza has no savanna or shrubland biome; same approximation the CLMS path uses for shrubland)"; +const B_WATER = "Costanza 2014 lakes/rivers (all water, as on the CLMS path)"; +const B_NATURAL_NONE = "natural, but no sourced unit value → excluded (0)"; +const B_PASTURE = "no sourced ESV for planted pasture → excluded (0). Costanza's grass/rangelands value is for rangeland and is not transferred to pasture sown on cleared forest"; +const B_CROP = "converted → excluded; Costanza 2014 cropland value shown as a separate reference only"; +const B_URBAN = "converted → excluded; Costanza 2014 urban value shown as a separate reference only"; +const B_CONV_NONE = "converted, no sourced value → excluded (0)"; + +const nat = (biome: ClassValuation["biome"], basis: string): ClassValuation => ({ use: "natural", biome, basis }); +const conv = (biome: "cropland" | "urban" | null, basis: string): ClassValuation => ({ use: "converted", biome, basis }); + +/** MapBiomas Brazil Collection 10 legend → valuation. Codes 0 (no data) and 27 (not observed) are dropped. */ +export const MAPBIOMAS_VALUATION: Record = { + 3: nat("forest", B_FOREST), + 6: nat("forest", `${B_FOREST}; floodable (várzea/igapó) forest valued as forest, not wetland — the conservative choice`), + 49: nat("forest", `${B_FOREST} (wooded restinga)`), + 4: nat("grassland", B_GRASS), + 12: nat("grassland", B_GRASS), + 13: nat("grassland", B_GRASS), + 50: nat("grassland", B_GRASS), + 5: nat("mangrove", "Costanza 2014 tidal marsh/mangroves"), + 11: nat("wetland", "Costanza 2014 swamps/floodplains"), + 33: nat("lakes_rivers", B_WATER), + 32: nat(null, B_NATURAL_NONE), + 29: nat(null, B_NATURAL_NONE), + 23: nat(null, B_NATURAL_NONE), + 15: conv(null, B_PASTURE), + 21: conv(null, "mosaic of pasture and agriculture — no sourced value → excluded (0)"), + 9: conv(null, `${B_CONV_NONE} (Costanza has no plantation biome)`), + 19: conv("cropland", B_CROP), 39: conv("cropland", B_CROP), 20: conv("cropland", B_CROP), 40: conv("cropland", B_CROP), + 62: conv("cropland", B_CROP), 41: conv("cropland", B_CROP), 36: conv("cropland", B_CROP), 46: conv("cropland", B_CROP), + 47: conv("cropland", B_CROP), 35: conv("cropland", B_CROP), 48: conv("cropland", B_CROP), + 24: conv("urban", B_URBAN), + 30: conv(null, B_CONV_NONE), + 75: conv(null, B_CONV_NONE), + 25: conv(null, B_CONV_NONE), + 31: conv(null, B_CONV_NONE), +}; + +/** Dynamic World V1 labels → valuation. */ +export const DW_VALUATION: Record = { + 0: nat("lakes_rivers", B_WATER), + 1: nat("forest", `${B_FOREST}; DW 'trees' also includes plantations and orchards`), + 2: nat("grassland", `${B_GRASS}; DW 'grass' also includes PASTURE, parks and lawns — it cannot separate them`), + 3: nat("wetland", "Costanza 2014 swamps/floodplains"), + 5: nat("grassland", B_GRASS), + 8: nat(null, B_NATURAL_NONE), + 4: conv("cropland", B_CROP), + 6: conv("urban", B_URBAN), + 7: conv(null, B_CONV_NONE), +}; + +const GEE_DROP: Record = { mapbiomas: [0, 27], "dynamic-world": [] }; + +/** + * MapBiomas Brazil coverage extent (Brazil incl. offshore islands). Inside it we try MapBiomas; + * because the rectangle also holds parts of neighbouring countries, the classified-pixel + * coverage check in geeLandCoverFromResult is what really decides. + */ +export const MAPBIOMAS_BRAZIL_BBOX: BBox = [-74.0, -33.8, -28.8, 5.3]; +export const MAPBIOMAS_YEAR = 2024; // last year of Collection 10 +export const DW_WINDOW_DAYS = 182; +const MIN_COVERAGE: Record = { mapbiomas: 0.9, "dynamic-world": 0.5 }; + +export function insideMapBiomasBrazil([w, s, e, n]: BBox): boolean { + const [W, S, E, N] = MAPBIOMAS_BRAZIL_BBOX; + return w >= W && s >= S && e <= E && n <= N; +} + +/** Earth Engine datasets to try, in order, for this box. */ +export function geeDatasetsFor(bbox: BBox): GeeLandCoverDataset[] { + return insideMapBiomasBrazil(bbox) ? ["mapbiomas", "dynamic-world"] : ["dynamic-world"]; +} + +/** Is Earth Engine usable? null = not configured (behaviour unchanged); string = configured but broken. */ +export function geeStatus(): true | null | string { + try { + return geeCreds() ? true : null; + } catch (err) { + return err instanceof Error ? err.message : String(err); + } +} + +export interface GeeLandCover { + provider: "mapbiomas-ee" | "dynamicworld-ee"; + source: string; + year?: number; + window?: { from: string; to: string }; + scaleM: number; + coveragePct: number; + classes: { code: number; name: string; sharePct: number; ha: number; use: "natural" | "converted" | "unmapped"; biome: BiomeId | null; basis: string }[]; + naturalHa: number; + convertedHa: number; + unmappedHa: number; + /** Valued natural biomes as shares of the WHOLE area (converted/unvalued = 0). */ + mix: BiomeShare[]; + /** Converted classes with a sourced registry value (cropland/urban), as shares of the whole area — reference only. */ + convertedReferenceMix: BiomeShare[]; +} + +/** Pure: a reduceRegion frequencyHistogram → natural/converted split + valued biome mix. */ +export function geeLandCoverFromResult( + result: unknown, + dataset: GeeLandCoverDataset, + bbox: BBox, + scaleM: number, + meta: { year?: number; window?: { from: string; to: string } } = {}, +): GeeLandCover { + const band = dataset === "mapbiomas" ? "classification" : "label"; + const table = dataset === "mapbiomas" ? MAPBIOMAS_VALUATION : DW_VALUATION; + const names = dataset === "mapbiomas" ? MAPBIOMAS_CLASSES : DW_CLASSES; + const hist = (result as Record | null)?.[band]; + const entries = Object.entries((hist && typeof hist === "object" ? hist : {}) as Record) + .map(([c, v]) => [Number(c), Number(v)] as const) + .filter(([c, v]) => Number.isFinite(c) && Number.isFinite(v) && v > 0 && !GEE_DROP[dataset].includes(c)); + const total = entries.reduce((a, [, v]) => a + v, 0); + const areaHa = bboxAreaKm2(bbox) * 100; + const coverage = (total * scaleM * scaleM) / 1e4 / areaHa; + if (total === 0 || coverage < MIN_COVERAGE[dataset]) { + throw new OverviewError(`${dataset}: classified pixels cover ${Math.round(coverage * 100)} % of the box (need ≥ ${MIN_COVERAGE[dataset] * 100} %) — outside coverage or no scenes`); + } + const lat = (bbox[1] + bbox[3]) / 2; + const mix = new Map(); + const ref = new Map(); + const ha = { natural: 0, converted: 0, unmapped: 0 }; + const classes: GeeLandCover["classes"] = []; + for (const [code, n] of [...entries].sort((a, b) => b[1] - a[1])) { + const share = n / total; + const v = table[code]; + const biome = v?.biome === "forest" ? forestBiome(lat) : (v?.biome ?? null); + const use = v?.use ?? "unmapped"; + ha[use] += share * areaHa; + if (biome) { + const into = use === "natural" ? mix : ref; + into.set(biome, (into.get(biome) ?? 0) + share); + } + classes.push({ code, name: names[code]?.name ?? `class_${code}`, sharePct: round(share * 100, 1), ha: Math.round(share * areaHa), use, biome, basis: v?.basis ?? "not in the legend → excluded" }); + } + const toMix = (m: Map) => [...m.entries()].map(([biome, share]) => ({ biome, share })); + return { + provider: dataset === "mapbiomas" ? "mapbiomas-ee" : "dynamicworld-ee", + source: GEE_SOURCES[dataset], + ...meta, + scaleM, + coveragePct: round(coverage * 100, 1), + classes, + naturalHa: Math.round(ha.natural), + convertedHa: Math.round(ha.converted), + unmappedHa: Math.round(ha.unmapped), + mix: toMix(mix), + convertedReferenceMix: toMix(ref), + }; +} + +/** Land use of a bbox from Earth Engine (needs GEE creds). `now` fixes the Dynamic World window. */ +export async function fetchGeeLandCover(bbox: BBox, dataset: GeeLandCoverDataset, client: GeeClient = geeClient(), now = new Date()): Promise { + const scaleM = pickScale(bbox, dataset === "mapbiomas" ? 30 : 10); + if (dataset === "mapbiomas") { + const result = await client.computeValue(landCoverExpression(bbox, dataset, { year: MAPBIOMAS_YEAR }, scaleM)); + return geeLandCoverFromResult(result, dataset, bbox, scaleM, { year: MAPBIOMAS_YEAR }); + } + const to = now.toISOString().slice(0, 10); + const from = new Date(now.getTime() - DW_WINDOW_DAYS * 86_400_000).toISOString().slice(0, 10); + const result = await client.computeValue(landCoverExpression(bbox, dataset, { dateFrom: from, dateTo: to }, scaleM)); + return geeLandCoverFromResult(result, dataset, bbox, scaleM, { window: { from, to } }); +} + +/** Pure: % of the classified area that MapBiomas calls converted (pasture, crops, urban, …), from gee_query classes. */ +export function mapbiomasConvertedPct(classes: { code: number; sharePct: number }[]): number | null { + const kept = classes.filter((c) => !GEE_DROP.mapbiomas.includes(c.code)); + const total = kept.reduce((a, c) => a + c.sharePct, 0); + if (total <= 0) return null; + return round((kept.filter((c) => MAPBIOMAS_VALUATION[c.code]?.use === "converted").reduce((a, c) => a + c.sharePct, 0) / total) * 100, 1); +} diff --git a/src/clients/openmeteo.ts b/src/clients/openmeteo.ts index 386e904..2eaf2ee 100644 --- a/src/clients/openmeteo.ts +++ b/src/clients/openmeteo.ts @@ -12,7 +12,7 @@ const FLOOD_BASE = "https://flood-api.open-meteo.com/v1/flood"; export const OPEN_METEO_ATTRIBUTION = "Open-Meteo.com (CC-BY 4.0)"; -interface OmDaily { +export interface OmDaily { daily?: { time?: string[] } & Record; hourly?: { time?: string[] } & Record; daily_units?: Record; @@ -21,7 +21,7 @@ interface OmDaily { reason?: string; } -async function omFetch(base: string, params: Record): Promise { +export async function omFetch(base: string, params: Record): Promise { const url = `${base}?${new URLSearchParams(params).toString()}`; const res = await fetch(url, { headers: { "user-agent": USER_AGENT } }); const json = (await res.json().catch(() => null)) as OmDaily | null; @@ -114,7 +114,7 @@ export async function airQuality( latitude: String(lat), longitude: String(lon), hourly: AIR_VARS.join(","), - past_days: String(Math.max(1, Math.min(7, pastDays))), + past_days: String(Math.max(1, Math.min(16, pastDays))), forecast_days: "1", timezone: "UTC", }); diff --git a/src/clients/storms.ts b/src/clients/storms.ts new file mode 100644 index 0000000..92c5d95 --- /dev/null +++ b/src/clients/storms.ts @@ -0,0 +1,351 @@ +// Active tropical cyclones, keyless, from two public feeds (endpoints verified live 2026-09-27): +// +// - NOAA NHC / CPHC — authoritative for the Atlantic and eastern/central North Pacific. +// `CurrentStorms.json` (status, intensity, advisory links) + the NWS tropical weather summary +// ArcGIS MapServer (layer 5 forecast points, layer 7 forecast cone) queried as GeoJSON. +// U.S. public data (weather.gov/disclaimer). NHC sends no CORS header → server-side only. +// - GDACS (UN OCHA / EC JRC) — every basin, incl. the Bay of Bengal, West Pacific, South Indian +// Ocean and Australia, which NHC does not cover. Event list + per-event geometry (uncertainty +// cone polygon, track lines). Provided "as is", automatic, not human-reviewed. +// +// NHC wins where both cover a storm (deduped by name). Wind speeds are normalized to knots and +// the Saffir–Simpson category is derived from them (1-min sustained for NHC/JTWC; other RSMCs +// use 10-min winds, which reads ~1 category low — a stated blind spot of the rule). + +import { USER_AGENT } from "../config.js"; +import { OverviewError } from "../errors.js"; +import type { BBox, EonetEvent } from "../types.js"; +import { addDays } from "../util.js"; + +export const NHC_CURRENT = "https://www.nhc.noaa.gov/CurrentStorms.json"; +export const NHC_GIS = "https://mapservices.weather.noaa.gov/tropical/rest/services/tropical/NHC_tropical_weather_summary/MapServer"; +export const GDACS_LIST = "https://www.gdacs.org/gdacsapi/api/events/geteventlist/SEARCH"; + +type Position = [number, number]; +export type ConeGeometry = { type: "Polygon"; coordinates: Position[][] } | { type: "MultiPolygon"; coordinates: Position[][][] }; + +export interface TrackPoint { + lat: number; + lon: number; + /** Valid time (RFC 3339) when known. */ + t: string | null; + /** Hours ahead of the advisory (0 = analysis). */ + tauH: number | null; + maxWindKt: number | null; + category: number | null; +} + +export interface Storm { + id: string; + name: string; + source: "noaa-nhc" | "gdacs"; + basin: string; + /** Classification as the source states it (TD, TS, HU, STS, "Tropical Storm", …). */ + classification: string; + maxWindKt: number | null; + /** Saffir–Simpson category from the current wind (0 = below hurricane force). */ + category: number | null; + /** Highest category anywhere on the forecast track (≥ current). */ + peakCategory: number | null; + pressureMb: number | null; + position: { lat: number; lon: number } | null; + advisory: { number: string | null; issued: string | null; url: string | null }; + track: TrackPoint[]; + cone: ConeGeometry | null; + /** [west, south, east, north] over the cone + track + position. */ + bbox: BBox | null; +} + +/** Saffir–Simpson category from 1-min sustained wind in knots (0 below hurricane force). */ +export function saffirSimpson(kt: number | null): number | null { + if (kt == null || !Number.isFinite(kt)) return null; + if (kt >= 137) return 5; + if (kt >= 113) return 4; + if (kt >= 96) return 3; + if (kt >= 83) return 2; + if (kt >= 64) return 1; + return 0; +} + +export function categoryLabel(cat: number | null, classification = ""): string { + if (cat != null && cat >= 1) return `category ${cat}`; + if (/TD|depression/i.test(classification)) return "tropical depression"; + return "tropical storm"; +} + +async function getJson(url: string): Promise { + const res = await fetch(url, { headers: { "user-agent": USER_AGENT, accept: "application/json" } }); + if (!res.ok) { + const body = await res.text().catch(() => ""); + throw new OverviewError(`storm feed request failed (${res.status}) ${url.split("?")[0]}`, res.status, body.slice(0, 300)); + } + return (await res.json()) as T; +} + +const num = (v: unknown): number | null => { + const n = typeof v === "string" ? Number(v) : v; + return typeof n === "number" && Number.isFinite(n) ? n : null; +}; + +// ---- geometry --------------------------------------------------------------------------- + +function rings(g: ConeGeometry): Position[][] { + return g.type === "Polygon" ? [g.coordinates[0] ?? []] : g.coordinates.map((p) => p[0] ?? []); +} + +export function geometryBBox(points: Position[]): BBox | null { + if (points.length === 0) return null; + let w = Infinity, s = Infinity, e = -Infinity, n = -Infinity; + for (const [x, y] of points) { + w = Math.min(w, x); e = Math.max(e, x); + s = Math.min(s, y); n = Math.max(n, y); + } + return [w, s, e, n]; +} + +function pointInRing(x: number, y: number, ring: Position[]): boolean { + let inside = false; + for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { + const [xi, yi] = ring[i]!; + const [xj, yj] = ring[j]!; + if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) inside = !inside; + } + return inside; +} + +function segmentsCross(a: Position, b: Position, c: Position, d: Position): boolean { + const o = (p: Position, q: Position, r: Position) => Math.sign((q[0] - p[0]) * (r[1] - p[1]) - (q[1] - p[1]) * (r[0] - p[0])); + return o(a, b, c) !== o(a, b, d) && o(c, d, a) !== o(c, d, b); +} + +/** Does a cone (outer rings) touch a bbox? Vertex-in-box, box-corner-in-cone, or edges cross. */ +export function coneIntersectsBBox(cone: ConeGeometry, bbox: BBox): boolean { + const [w, s, e, n] = bbox; + const corners: Position[] = [[w, s], [e, s], [e, n], [w, n]]; + const edges: [Position, Position][] = [[corners[0]!, corners[1]!], [corners[1]!, corners[2]!], [corners[2]!, corners[3]!], [corners[3]!, corners[0]!]]; + for (const ring of rings(cone)) { + if (ring.some(([x, y]) => x >= w && x <= e && y >= s && y <= n)) return true; + if (corners.some(([x, y]) => pointInRing(x, y, ring))) return true; + for (let i = 1; i < ring.length; i++) for (const [p, q] of edges) if (segmentsCross(ring[i - 1]!, ring[i]!, p, q)) return true; + } + return false; +} + +/** A storm "touches" a bbox if its cone intersects it, or (no cone) a track point/position lies in it. */ +export function stormTouchesBBox(storm: Storm, bbox: BBox): boolean { + if (storm.cone && coneIntersectsBBox(storm.cone, bbox)) return true; + const [w, s, e, n] = bbox; + const pts = [...storm.track, ...(storm.position ? [storm.position] : [])]; + return pts.some((p) => p.lon >= w && p.lon <= e && p.lat >= s && p.lat <= n); +} + +function finishStorm(s: Omit): Storm { + const pts: Position[] = []; + if (s.cone) for (const r of rings(s.cone)) pts.push(...r); + for (const p of s.track) pts.push([p.lon, p.lat]); + if (s.position) pts.push([s.position.lon, s.position.lat]); + const cats = [s.category, ...s.track.map((p) => p.category)].filter((c): c is number => c != null); + return { ...s, peakCategory: cats.length ? Math.max(...cats) : null, bbox: geometryBBox(pts) }; +} + +const round3 = (v: number) => Math.round(v * 1000) / 1000; +function roundGeom(g: ConeGeometry): ConeGeometry { + return g.type === "Polygon" + ? { type: "Polygon", coordinates: g.coordinates.map((r) => r.map(([x, y]) => [round3(x), round3(y)] as Position)) } + : { type: "MultiPolygon", coordinates: g.coordinates.map((p) => p.map((r) => r.map(([x, y]) => [round3(x), round3(y)] as Position))) }; +} + +// ---- NHC / CPHC -------------------------------------------------------------------------- + +interface NhcActive { + id: string; + name: string; + classification: string; + intensity: string; + pressure: string; + latitudeNumeric: number; + longitudeNumeric: number; + lastUpdate?: string; + publicAdvisory?: { advNum?: string; issuance?: string; url?: string }; +} +interface GeoJsonFC { + features?: Array<{ geometry: { type: string; coordinates: unknown } | null; properties: Record }>; +} + +/** NHC `validtime` "DD/HHMM" → RFC 3339, anchored on the advisory month (rolls over month end). */ +export function nhcValidTime(validtime: unknown, issued: string | null): string | null { + if (typeof validtime !== "string" || !issued) return null; + const m = /^(\d{2})\/(\d{2})(\d{2})$/.exec(validtime); + if (!m) return null; + const base = new Date(issued); + const d = new Date(Date.UTC(base.getUTCFullYear(), base.getUTCMonth(), Number(m[1]), Number(m[2]), Number(m[3]))); + if (d.getTime() < base.getTime() - 5 * 86_400_000) d.setUTCMonth(d.getUTCMonth() + 1); + return d.toISOString().replace(/\.\d{3}Z$/, "Z"); +} + +function gisQuery(layer: number, extra: Record = {}): string { + const p = new URLSearchParams({ where: "1=1", outFields: "*", returnGeometry: "true", f: "geojson", outSR: "4326", ...extra }); + return `${NHC_GIS}/${layer}/query?${p.toString()}`; +} + +export async function nhcStorms(): Promise { + const current = await getJson<{ activeStorms?: NhcActive[] }>(NHC_CURRENT); + const active = current.activeStorms ?? []; + if (active.length === 0) return []; + // Cone generalized server-side (~0.05°) so a whole basin's cones stay a few KB. + const [points, cones] = await Promise.all([ + getJson(gisQuery(5)).catch(() => ({ features: [] }) as GeoJsonFC), + getJson(gisQuery(7, { maxAllowableOffset: "0.05", geometryPrecision: "3" })).catch(() => ({ features: [] }) as GeoJsonFC), + ]); + // GIS features carry `idp_source` like "al062026-028_5day_pts" → storm id "al062026". + const sid = (p: Record) => String(p.idp_source ?? "").split("-")[0]!.toLowerCase(); + return active.map((a) => { + const id = a.id.toLowerCase(); + const issued = a.publicAdvisory?.issuance ?? a.lastUpdate ?? null; + const kt = num(a.intensity); + const track: TrackPoint[] = (points.features ?? []) + .filter((f) => sid(f.properties) === id && f.geometry?.type === "Point") + .map((f) => { + const [lon, lat] = f.geometry!.coordinates as number[]; + const w = num(f.properties.maxwind); + return { lat: round3(lat!), lon: round3(lon!), t: nhcValidTime(f.properties.validtime, issued), tauH: num(f.properties.tau), maxWindKt: w, category: saffirSimpson(w) }; + }) + .sort((x, y) => (x.tauH ?? 0) - (y.tauH ?? 0)); + const coneF = (cones.features ?? []).find((f) => sid(f.properties) === id && (f.geometry?.type === "Polygon" || f.geometry?.type === "MultiPolygon")); + return finishStorm({ + id, + name: a.name, + source: "noaa-nhc", + basin: id.slice(0, 2).toUpperCase(), + classification: a.classification, + maxWindKt: kt, + category: saffirSimpson(kt), + pressureMb: num(a.pressure), + position: { lat: a.latitudeNumeric, lon: a.longitudeNumeric }, + advisory: { number: a.publicAdvisory?.advNum ?? null, issued, url: a.publicAdvisory?.url ?? null }, + track, + cone: coneF ? roundGeom(coneF.geometry as ConeGeometry) : null, + }); + }); +} + +// ---- GDACS ------------------------------------------------------------------------------- + +interface GdacsEvent { + geometry: { type: string; coordinates: number[] }; + properties: { + eventid: number; + episodeid: number; + eventname?: string; + name?: string; + iscurrent?: string | boolean; + todate?: string; + alertlevel?: string; + source?: string; + severitydata?: { severity?: number; severityunit?: string; severitytext?: string }; + url?: { geometry?: string; report?: string }; + }; +} + +/** "SURIGAE-26" → "Surigae" (GDACS names carry a year suffix and are upper-case). */ +export function gdacsStormName(eventname: string | undefined): string { + const base = (eventname ?? "").replace(/-\d{2}$/, ""); + return base.charAt(0) + base.slice(1).toLowerCase(); +} + +function kmhToKt(v: number | null): number | null { + return v == null ? null : Math.round(v / 1.852); +} + +export async function gdacsStorms(today: string, maxEvents = 12): Promise { + const params = new URLSearchParams({ eventlist: "TC", fromdate: addDays(today, -10), todate: today, alertlevel: "green;orange;red" }); + const list = await getJson<{ features?: GdacsEvent[] }>(`${GDACS_LIST}?${params.toString()}`); + const current = (list.features ?? []).filter((f) => String(f.properties.iscurrent) === "true").slice(0, maxEvents); + return Promise.all( + current.map(async (f) => { + const p = f.properties; + const sev = p.severitydata; + const kt = sev?.severityunit === "km/h" ? kmhToKt(num(sev.severity)) : null; + let cone: ConeGeometry | null = null; + const track: TrackPoint[] = []; + if (p.url?.geometry) { + try { + const g = await getJson(p.url.geometry); + for (const feat of g.features ?? []) { + const cls = String(feat.properties.Class ?? ""); + if (cls === "Poly_Cones" && (feat.geometry?.type === "Polygon" || feat.geometry?.type === "MultiPolygon")) cone = roundGeom(feat.geometry as ConeGeometry); + // Track segments are LineStrings labelled with the stage (TD/TS/HU …). + if (cls.startsWith("Line_") && feat.geometry?.type === "LineString") { + for (const [lon, lat] of feat.geometry.coordinates as number[][]) { + const last = track[track.length - 1]; + if (last && last.lon === round3(lon!) && last.lat === round3(lat!)) continue; + track.push({ lat: round3(lat!), lon: round3(lon!), t: null, tauH: null, maxWindKt: null, category: null }); + } + } + } + } catch { + /* list entry still stands without geometry */ + } + } + const [lon, lat] = f.geometry.coordinates; + return finishStorm({ + id: `gdacs-tc-${p.eventid}`, + name: gdacsStormName(p.eventname), + source: "gdacs" as const, + basin: "global", + classification: sev?.severitytext?.split(" (")[0] ?? "Tropical cyclone", + maxWindKt: kt, + category: saffirSimpson(kt), + pressureMb: null, + position: lat != null && lon != null ? { lat, lon } : null, + advisory: { number: String(p.episodeid), issued: p.todate ? `${p.todate.slice(0, 19)}Z` : null, url: p.url?.report ?? null }, + track, + cone, + }); + }), + ); +} + +export interface StormsResult { + storms: Storm[]; + sources: { nhc: "ok" | string; gdacs: "ok" | string }; +} + +/** NHC first, then GDACS for everything NHC does not already cover (deduped by name). */ +export async function activeStorms(today: string): Promise { + const sources: StormsResult["sources"] = { nhc: "ok", gdacs: "ok" }; + const [nhc, gd] = await Promise.all([ + nhcStorms().catch((e: unknown) => ((sources.nhc = e instanceof Error ? e.message : String(e)), [] as Storm[])), + gdacsStorms(today).catch((e: unknown) => ((sources.gdacs = e instanceof Error ? e.message : String(e)), [] as Storm[])), + ]); + if (sources.nhc !== "ok" && sources.gdacs !== "ok") throw new OverviewError(`both storm feeds failed — NHC: ${sources.nhc}; GDACS: ${sources.gdacs}`); + const names = new Set(nhc.map((s) => s.name.toLowerCase())); + return { storms: [...nhc, ...gd.filter((s) => !names.has(s.name.toLowerCase()))], sources }; +} + +// ---- EONET cross-check ------------------------------------------------------------------ + +type EonetLike = Pick; + +/** EONET severe-storm events that plausibly are this storm: same name, or within `km`. */ +export function matchEonet(storm: Pick, events: EonetLike[], km = 500): EonetLike | null { + const name = storm.name.trim().toLowerCase(); + const byName = name.length >= 3 ? events.find((e) => new RegExp(`\\b${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i").test(e.title)) : undefined; + if (byName) return byName; + if (!storm.position) return null; + const { lat, lon } = storm.position; + let best: { e: EonetLike; d: number } | null = null; + for (const e of events) { + if (!e.coordinates) continue; + const d = haversineKm(lat, lon, e.coordinates[1], e.coordinates[0]); + if (d <= km && (!best || d < best.d)) best = { e, d }; + } + return best?.e ?? null; +} + +export function haversineKm(lat1: number, lon1: number, lat2: number, lon2: number): number { + const r = (x: number) => (x * Math.PI) / 180; + const a = Math.sin(r(lat2 - lat1) / 2) ** 2 + Math.cos(r(lat1)) * Math.cos(r(lat2)) * Math.sin(r(lon2 - lon1) / 2) ** 2; + return 2 * 6371 * Math.asin(Math.min(1, Math.sqrt(a))); +} + diff --git a/src/clients/usgs.ts b/src/clients/usgs.ts index 7633ce7..797fbf6 100644 --- a/src/clients/usgs.ts +++ b/src/clients/usgs.ts @@ -19,6 +19,10 @@ export interface Quake { tsunami: boolean; alert: string | null; // PAGER: green/yellow/orange/red url: string; + /** USGS significance 0–1000+ (magnitude, felt reports, PAGER); null when absent. */ + sig: number | null; + /** "reviewed" (seismologist-checked) or "automatic"; null when absent. */ + status: string | null; } interface RawFeature { @@ -30,6 +34,8 @@ interface RawFeature { tsunami?: number | null; alert?: string | null; url?: string | null; + sig?: number | null; + status?: string | null; }; geometry?: { coordinates?: unknown }; } @@ -56,6 +62,8 @@ export function parseQuakes(json: unknown): Quake[] { tsunami: p.tsunami === 1, alert: p.alert ?? null, url: p.url ?? "", + sig: typeof p.sig === "number" ? p.sig : null, + status: p.status ?? null, }); } return out; diff --git a/src/clients/vnf.ts b/src/clients/vnf.ts index 395bb64..7703f15 100644 --- a/src/clients/vnf.ts +++ b/src/clients/vnf.ts @@ -167,12 +167,13 @@ export function parseVnfKml(kml: string): VnfSite[] { const out: VnfSite[] = []; for (const pm of kml.split("").slice(1)) { const ll = /Lat=(-?[\d.]+),\s*Lon=(-?[\d.]+)/.exec(pm); - const bcm = /BCM_total=(-?[\d.]+)/.exec(pm); + // Values can be in scientific notation ("BCM_total=2.67e-05", seen in the 2023 file) — read the exponent. + const bcm = /BCM_total=(-?[\d.]+(?:e[-+]?\d+)?)/i.exec(pm); if (!ll || !bcm) continue; const lat = Number(ll[1]); const lon = Number(ll[2]); if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue; - const row = /\d{4}<\/td>[-\d.]+<\/td>(\d+)<\/td>([\d.]+)%/.exec(pm); + const row = /\d{4}<\/td>[-\d.]+(?:e[-+]?\d+)?<\/td>(\d+)<\/td>([\d.]+)%/i.exec(pm); const vector = /Vector: (\d+)<\/b>/.exec(pm)?.[1]; out.push({ id: /([^<]+)<\/name>/.exec(pm)?.[1]?.trim() || `vnf-${vector ?? out.length + 1}`, @@ -314,7 +315,8 @@ export async function flaringReport(mapKey: string, bbox: BBox, o: FlaringOption const latestNear = sitesIn(near, a.sites); const prevNear = sitesIn(near, p.sites); for (const cl of persistent) cl.novel = !nearestSite(cl.lat, cl.lon, latestNear, NOVEL_KM) && !nearestSite(cl.lat, cl.lon, prevNear, NOVEL_KM); - previous = { available: true, year: p.year, sensor: p.sensor, file: p.url, sitesInBbox: sitesIn(bbox, p.sites).length }; + const prevLocal = sitesIn(bbox, p.sites); + previous = { available: true, year: p.year, sensor: p.sensor, file: p.url, sitesInBbox: prevLocal.length, bcmTotal: round(prevLocal.reduce((sum, x) => sum + x.bcm, 0), 3) }; } catch (err) { previous = { available: false, reason: err instanceof Error ? err.message : String(err) }; } diff --git a/src/clients/weather.ts b/src/clients/weather.ts new file mode 100644 index 0000000..5d9190d --- /dev/null +++ b/src/clients/weather.ts @@ -0,0 +1,295 @@ +// Weather for a point: Open-Meteo forecast API (current + past days + 7-day forecast, keyless, +// CC BY 4.0) and an ERA5 daily-max normal for 1991–2020 from the existing archive API, so a +// hot day is always reported next to what is normal for that place and time of year. +// +// Two ERA5 details that matter for honesty (both observed live 2026-09-27): +// - The archive API's default `best_match` fills the most recent days with forecast data, so +// it is NOT independent of the forecast. We ask for `models=era5` explicitly, which leaves +// the last ~6 days null (ERA5's real latency) — that null is the truth, not a bug. +// - Open-Meteo counts >2 weeks of data as several calls, so the 30-year normal is fetched as +// 30 short windows (one per year, ~2 weeks each) instead of one 30-year request. + +import { OverviewError } from "../errors.js"; +import { round } from "../series.js"; +import { addDays } from "../util.js"; +import { OPEN_METEO_ATTRIBUTION, omFetch, type OmDaily } from "./openmeteo.js"; + +const FORECAST_BASE = "https://api.open-meteo.com/v1/forecast"; +const ARCHIVE_BASE = "https://archive-api.open-meteo.com/v1/archive"; + +export const NORMAL_PERIOD = { from: 1991, to: 2020 } as const; +/** ± days around each date pooled into its normal (7-day window × 30 years = 210 samples). */ +export const NORMAL_HALF_WINDOW = 3; + +const DAILY_VARS = [ + "temperature_2m_max", + "temperature_2m_min", + "apparent_temperature_max", + "precipitation_sum", + "wind_speed_10m_max", + "wind_gusts_10m_max", +] as const; +const CURRENT_VARS = [ + "temperature_2m", + "apparent_temperature", + "relative_humidity_2m", + "precipitation", + "wind_speed_10m", + "wind_direction_10m", + "weather_code", +] as const; + +export interface WeatherDay { + date: string; + /** "past" = model analysis of an elapsed day, "today", or "forecast". */ + kind: "past" | "today" | "forecast"; + tmaxC: number | null; + tminC: number | null; + /** Open-Meteo apparent temperature (Steadman "feels like"; our heat-index proxy). */ + apparentMaxC: number | null; + precipMm: number | null; + windMaxKmh: number | null; + gustMaxKmh: number | null; + /** ERA5 1991–2020 mean daily max for this calendar window (±3 d); null if unavailable. */ + tmaxNormalC: number | null; + tmaxAnomalyC: number | null; +} + +export interface WeatherCurrent { + time: string; + temperatureC: number | null; + apparentC: number | null; + humidityPct: number | null; + precipMm: number | null; + windKmh: number | null; + windDirDeg: number | null; + weatherCode: number | null; +} + +export interface Era5Day { + date: string; + tmaxC: number | null; + precipMm: number | null; +} + +export interface WeatherReport { + lat: number; + lon: number; + /** Grid cell Open-Meteo actually answered for. */ + gridLat: number; + gridLon: number; + elevationM: number | null; + timezone: string; + today: string; + current: WeatherCurrent; + days: WeatherDay[]; + /** ERA5 reanalysis for the past days (independent of the forecast; ~6-day latency → nulls). */ + era5: Era5Day[]; + normals: { period: string; halfWindowDays: number; available: boolean; error?: string }; + provenance: WeatherProvenance; +} + +export interface WeatherProvenance { + dataSource: string; + forecastModel: string; + reanalysis: string; + retrievedAt: string; + disclaimer: string; +} + +const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null); + +function col(json: OmDaily, variable: string): (number | null)[] { + const v = json.daily?.[variable]; + return Array.isArray(v) ? v.map(num) : []; +} + +/** Forecast API call: current + `pastDays` elapsed days + today + forecast, in local time. */ +export async function forecastPoint(lat: number, lon: number, pastDays = 7, forecastDays = 7) { + const json = (await omFetch(FORECAST_BASE, { + latitude: String(lat), + longitude: String(lon), + current: CURRENT_VARS.join(","), + daily: DAILY_VARS.join(","), + past_days: String(Math.max(0, Math.min(14, pastDays))), + forecast_days: String(Math.max(1, Math.min(16, forecastDays))), + timezone: "auto", + })) as OmDaily & { + latitude?: number; + longitude?: number; + elevation?: number; + timezone?: string; + current?: Record; + }; + const times = json.daily?.time; + if (!Array.isArray(times) || times.length === 0) throw new OverviewError("Open-Meteo forecast response has no daily block"); + const c = json.current ?? {}; + const current: WeatherCurrent = { + time: String(c.time ?? ""), + temperatureC: num(c.temperature_2m), + apparentC: num(c.apparent_temperature), + humidityPct: num(c.relative_humidity_2m), + precipMm: num(c.precipitation), + windKmh: num(c.wind_speed_10m), + windDirDeg: num(c.wind_direction_10m), + weatherCode: num(c.weather_code), + }; + // "today" in the place's own time zone: the current observation's local date. + const today = current.time.slice(0, 10) || times[Math.min(times.length - 1, Math.max(0, pastDays))]!; + const tmax = col(json, "temperature_2m_max"); + const tmin = col(json, "temperature_2m_min"); + const app = col(json, "apparent_temperature_max"); + const pr = col(json, "precipitation_sum"); + const wmax = col(json, "wind_speed_10m_max"); + const gmax = col(json, "wind_gusts_10m_max"); + const days: WeatherDay[] = times.map((t, i) => { + const date = String(t); + return { + date, + kind: date < today ? "past" : date === today ? "today" : "forecast", + tmaxC: tmax[i] ?? null, + tminC: tmin[i] ?? null, + apparentMaxC: app[i] ?? null, + precipMm: pr[i] ?? null, + windMaxKmh: wmax[i] ?? null, + gustMaxKmh: gmax[i] ?? null, + tmaxNormalC: null, + tmaxAnomalyC: null, + }; + }); + return { + gridLat: num(json.latitude) ?? lat, + gridLon: num(json.longitude) ?? lon, + elevationM: num(json.elevation), + timezone: String(json.timezone ?? "UTC"), + today, + current, + days, + }; +} + +/** ERA5-only daily max temperature + precipitation (no forecast back-fill). */ +export async function era5Daily(lat: number, lon: number, start: string, end: string): Promise { + const json = await omFetch(ARCHIVE_BASE, { + latitude: String(lat), + longitude: String(lon), + start_date: start, + end_date: end, + daily: "temperature_2m_max,precipitation_sum", + models: "era5", + timezone: "auto", + }); + const times = json.daily?.time ?? []; + const tmax = col(json, "temperature_2m_max"); + const pr = col(json, "precipitation_sum"); + return times.map((t, i) => ({ date: String(t), tmaxC: tmax[i] ?? null, precipMm: pr[i] ?? null })); +} + +/** Shift a YYYY-MM-DD date by whole years (Feb 29 → Mar 1 in non-leap years). */ +export function shiftYears(date: string, years: number): string { + const d = new Date(`${date}T00:00:00Z`); + d.setUTCFullYear(d.getUTCFullYear() + years); + return d.toISOString().slice(0, 10); +} + +const normalsCache = new Map>(); + +/** + * ERA5 1991–2020 mean daily max for each date in [first, last], pooling ±NORMAL_HALF_WINDOW + * days × 30 years. One small request per year (Open-Meteo weights long spans as many calls). + * Memoized per process: a sweep's detect + confirm reuse it. + */ +export async function tmaxNormals(lat: number, lon: number, first: string, last: string): Promise> { + const key = `${lat.toFixed(2)},${lon.toFixed(2)},${first},${last}`; + const hit = normalsCache.get(key); + if (hit) return hit; + const h = NORMAL_HALF_WINDOW; + const winStart = addDays(first, -h); + const winEnd = addDays(last, h); + const baseYear = Number(winStart.slice(0, 4)); + const years: number[] = []; + for (let y = NORMAL_PERIOD.from; y <= NORMAL_PERIOD.to; y++) years.push(y); + // Open-Meteo answers 429 "Too many concurrent requests" above ~2 in flight: pairs, one retry. + const fetchYear = async (y: number): Promise<(number | null)[]> => { + const delta = y - baseYear; + const get = () => era5Daily(lat, lon, shiftYears(winStart, delta), shiftYears(winEnd, delta)); + const rows = await get().catch(async (e: unknown) => { + if ((e as { status?: number }).status !== 429) throw e; + await new Promise((r) => setTimeout(r, 1500)); + return get(); + }); + return rows.map((r) => r.tmaxC); + }; + const perYear: (number | null)[][] = []; + for (let i = 0; i < years.length; i += 2) perYear.push(...(await Promise.all(years.slice(i, i + 2).map(fetchYear)))); + const out = new Map(); + for (let d = first, i = 0; d <= last; d = addDays(d, 1), i++) { + const pool: number[] = []; + for (const series of perYear) for (let k = i; k <= i + 2 * h; k++) { + const v = series[k]; + if (v != null) pool.push(v); + } + if (pool.length >= 30) out.set(d, round(pool.reduce((a, b) => a + b, 0) / pool.length, 1)); + } + normalsCache.set(key, out); + return out; +} + +/** Test hook: drop memoized normals. */ +export function clearNormalsCache(): void { + normalsCache.clear(); +} + +/** + * Everything `weather_now` returns: forecast days with ERA5 normals + anomalies, and ERA5's + * own view of the elapsed days. Normals/ERA5 failures degrade (nulls + flag), never throw. + */ +export async function weatherReport(lat: number, lon: number, opts: { pastDays?: number; forecastDays?: number; normals?: boolean } = {}): Promise { + if (lat < -90 || lat > 90 || lon < -180 || lon > 180) throw new OverviewError(`lat/lon out of range: ${lat}, ${lon}`); + const pastDays = opts.pastDays ?? 7; + const f = await forecastPoint(lat, lon, pastDays, opts.forecastDays ?? 7); + const first = f.days[0]!.date; + const last = f.days[f.days.length - 1]!.date; + let available = false; + let normalsError: string | undefined; + if (opts.normals !== false) { + try { + const normals = await tmaxNormals(lat, lon, first, last); + for (const d of f.days) { + const n = normals.get(d.date); + if (n == null) continue; + d.tmaxNormalC = n; + d.tmaxAnomalyC = d.tmaxC != null ? round(d.tmaxC - n, 1) : null; + } + available = normals.size > 0; + } catch (e) { + normalsError = e instanceof Error ? e.message : String(e); // context, not a blocker + } + } + let era5: Era5Day[] = []; + const pastEnd = addDays(f.today, -1); + if (pastDays > 0 && first <= pastEnd) { + try { + era5 = await era5Daily(lat, lon, first, pastEnd); + } catch { + era5 = []; + } + } + return { + lat, + lon, + ...f, + era5, + normals: { period: `${NORMAL_PERIOD.from}–${NORMAL_PERIOD.to}`, halfWindowDays: NORMAL_HALF_WINDOW, available, ...(normalsError ? { error: normalsError } : {}) }, + provenance: { + dataSource: OPEN_METEO_ATTRIBUTION, + forecastModel: "Open-Meteo forecast API, best_match (national/global NWP blend incl. ECMWF IFS, DWD ICON, NOAA GFS), local-time daily aggregates", + reanalysis: "ECMWF ERA5 (models=era5, 0.25°, ~6-day latency) via the Open-Meteo archive API", + retrievedAt: new Date().toISOString(), + disclaimer: + "Decision-support, not decision. 'past' and 'today' values are model analyses/short-range forecasts on a " + + "~2–11 km grid, not station observations; ERA5 normals are on a coarser 0.25° grid, so anomalies carry " + + "grid/elevation bias of ~1–2 °C, largest in mountains and on coasts.", + }, + }; +} diff --git a/src/index.ts b/src/index.ts index f045260..56440b0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -25,6 +25,8 @@ import { registerBiodiversityTools } from "./tools/biodiversity.js"; import { registerCoralTools } from "./tools/coral.js"; import { registerNaturalValueTools } from "./tools/naturalvalue.js"; import { registerGeeTools } from "./tools/gee.js"; +import { registerWeatherTools } from "./tools/weather.js"; +import { registerMarineTools } from "./tools/marine.js"; export function buildServer(): McpServer { const server = new McpServer( @@ -42,7 +44,7 @@ export function buildServer(): McpServer { "El Niño tracking (enso), ocean temperature history since 1981 (ocean_temp), CO₂ since " + "1958 (co2), the global temperature record since 1880 (global_temp), polar sea ice " + "(sea_ice), earthquakes (quakes), air quality (air_quality), per-place climate history " + - "since 1940 (climate_history), river discharge (river_discharge), planet_pulse — " + + "since 1940 (climate_history), river discharge (river_discharge), weather now + 7-day forecast vs the 1991–2020 normal (weather_now), active tropical cyclones with forecast cones (storms), planet_pulse — " + "the planet's vital signs in one call — world_pulse — civilization's vital signs (child " + "mortality, poverty, renewables…), the living world (Living Planet Index, Red List Index, " + "fish stocks…) and the planet (ocean pH, nitrogen, plastic…), each with an honest " + @@ -88,6 +90,8 @@ export function buildServer(): McpServer { registerCoralTools(server); registerNaturalValueTools(server); registerGeeTools(server); + registerWeatherTools(server); + registerMarineTools(server); return server; } diff --git a/src/ledger/schema.ts b/src/ledger/schema.ts index 40c2f1a..4916372 100644 --- a/src/ledger/schema.ts +++ b/src/ledger/schema.ts @@ -194,7 +194,7 @@ export const eventPayload = z.discriminatedUnion("kind", [ kind: z.literal("confirmed"), /** The independent second signal — different sensor physics, provider, or a later revisit. */ signal: evidence, - independence: z.enum(["sensor", "provider", "revisit", "human"]), + independence: z.enum(["sensor", "provider", "revisit", "method", "human"]), }), base.extend({ kind: z.literal("status_changed"), @@ -261,6 +261,26 @@ export const eventPayload = z.discriminatedUnion("kind", [ receivedAt: rfc3339, }), base.extend({ kind: z.literal("retracted"), reason: z.string().min(1).max(2000) }), + base.extend({ + kind: z.literal("commented"), + /** + * A public reply left under a public case (the site's reply wall), accepted by the + * reviewer model. Only a hash of the text is signed — the text itself lives beside the + * site (replies/public/), so the ledger never carries what a stranger wrote. No status + * change; unlike `replied` it needs no prior notice. + */ + reply: z.object({ + id: z.string().regex(/^[0-9A-HJKMNP-TV-Z]{26}$/, "reply id must be a ULID"), + role: z.enum(["resident", "operator", "company", "official", "researcher", "other"]), + receivedAt: rfc3339, + textSha256: sha256Hex, + }), + verdict: z.object({ + accept: z.literal(true), + reason: z.string().min(1).max(500), + flags: z.array(z.string()).max(0, "an accepted reply carries no flags"), + }), + }), ]); export type FindingEvent = z.infer; export type EventKind = FindingEvent["kind"]; @@ -414,6 +434,10 @@ export function checkAppend(f: Finding | null, ev: FindingEvent): void { if (f.notifications.length === 0) throw new Error("cannot record a reply: nobody was notified"); if (!["confirmed", "published", "notified", "no_response"].includes(f.status)) throw new Error(`cannot record a reply from status ${f.status}`); return; + case "commented": + if (!/^(model|reviewer):/.test(ev.actor)) throw new Error("a public reply must be accepted by a model: or reviewer: actor"); + if (!PUBLIC_STATUSES.includes(f.status)) throw new Error(`public replies are only taken on public cases (status is ${f.status})`); + return; case "evidence_added": case "retracted": return; diff --git a/src/replies/intake.ts b/src/replies/intake.ts new file mode 100644 index 0000000..69e69e6 --- /dev/null +++ b/src/replies/intake.ts @@ -0,0 +1,217 @@ +// The public reply wall's intake, AWS-free: `POST /reply` with `{caseId, text, role?}` from +// the site. Nobody reads an inbox — a reply is only stored here, and the analyst's reviewer +// model decides (src/replies/review.ts) whether it appears under the case. +// +// Rules (each one tested in test/replies.test.ts): +// - JSON body ≤ 8 KB; `website` is a honeypot and must be empty (bots get a fake 202); +// - text: HTML stripped, 20–2000 chars, no email / @handle, no phone number, no URL; +// - role ∈ ROLES (default "other"); no name / email / URL fields exist at all; +// - caseId must be in the public case index (state bucket `replies/cases.json`); +// - at most DAILY_CAP replies per IP per UTC day, counted under a salted SHA-256 of the +// IP — the raw IP is never stored, logged or returned. +// Stored as `replies/inbox//.json` = {caseId, text, role, receivedAt, ipHash}. + +import { createHash, randomBytes } from "node:crypto"; + +export const ROLES = ["resident", "operator", "company", "official", "researcher", "other"] as const; +export type Role = (typeof ROLES)[number]; +export const TEXT_MIN = 20; +export const TEXT_MAX = 2000; +export const DAILY_CAP = 5; +export const MAX_BODY = 8 * 1024; +export const INBOX_PREFIX = "replies/inbox/"; +export const PUBLIC_PREFIX = "replies/public/"; +export const REJECTED_PREFIX = "replies/rejected/"; +export const RATE_PREFIX = "replies/rate/"; +export const CASE_INDEX_KEY = "replies/cases.json"; +export const CASE_ID = /^[A-Za-z0-9-]{1,64}$/; +export const REPLY_ID = /^[0-9A-HJKMNP-TV-Z]{26}$/; + +export interface InboxReply { + caseId: string; + text: string; + role: Role; + receivedAt: string; + ipHash: string; +} + +// ── ids + hashing ──────────────────────────────────────────────────────────────────────── + +const CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; + +/** ULID: 48-bit ms time + 80 random bits, Crockford base32 (sortable by arrival). */ +export function ulid(now = Date.now(), rand: Buffer = randomBytes(10)): string { + let t = now; + let time = ""; + for (let i = 0; i < 10; i++) { + time = CROCKFORD[t % 32]! + time; + t = Math.floor(t / 32); + } + let bits = 0n; + for (const b of rand) bits = (bits << 8n) | BigInt(b); + let r = ""; + for (let i = 0; i < 16; i++) { + r = CROCKFORD[Number(bits & 31n)]! + r; + bits >>= 5n; + } + return time + r; +} + +/** Salted SHA-256 of an IP — the only form an IP ever takes after the request. */ +export function ipHash(ip: string, salt: string): string { + return createHash("sha256").update(`${salt}\n${ip.trim().toLowerCase()}`).digest("hex"); +} + +// ── text rules ────────────────────────────────────────────────────────────────────────── + +const CONTROL_CHARS = /[\u0000-\u0008\u000b-\u001f\u007f\u200b-\u200f\u2028\u2029\u202a-\u202e]/g; + +/** Tags out, common entities decoded, whitespace tidied (newlines kept, max one blank line). */ +export function stripHtml(s: string): string { + return s + .replace(/<(script|style)[^>]*>[\s\S]*?<\/\1\s*>/gi, " ") + .replace(/<[^>]*>/g, " ") + .replace(/&(nbsp|amp|lt|gt|quot|#39);/g, (_, e: string) => ({ nbsp: " ", amp: "&", lt: "<", gt: ">", quot: '"', "#39": "'" })[e]!) + .replace(/[<>]/g, " ") + .replace(CONTROL_CHARS, "") + .replace(/[ \t]+/g, " ") + .replace(/ *\n */g, "\n") + .replace(/\n{3,}/g, "\n\n") + .trim(); +} + +const EMAIL = /[\w.+-]+\s*(@|\(at\)|\[at\])\s*[\w-]+(\.[\w-]+)*\.[a-z]{2,}/i; +const HANDLE = /(^|[^\w])@[A-Za-z0-9_]{2,}/; +const URL_RE = /\bhttps?:\/\/|\bwww\.|\b[a-z0-9-]+\.(com|net|org|io|co|info|biz|ru|cn|xyz|top|me|ly|gl|gd|app|dev|link|site|online|shop|to|tk|click|live)\b/i; +const DATE_LIKE = /^\d{4}[-/.]\d{1,2}[-/.]\d{1,2}$|^\d{1,2}[-/.]\d{1,2}[-/.]\d{4}$/; + +/** A phone number: a run of ≥ 9 digits allowing spaces/dots/dashes/brackets (dates excluded). */ +export function hasPhone(text: string): boolean { + for (const m of text.matchAll(/\+?\d[\d ().-]{6,}\d/g)) { + const run = m[0].trim(); + if (DATE_LIKE.test(run)) continue; + if ((run.match(/\d/g) ?? []).length >= 9) return true; + } + return false; +} + +export type Rejection = "method" | "path" | "too_large" | "bad_json" | "bad_case" | "bad_role" | "too_short" | "too_long" | "contact_info" | "phone" | "link" | "unknown_case" | "rate_limited" | "unavailable"; + +export const MESSAGES: Record = { + method: "Use POST.", + path: "Not found.", + too_large: "That reply is too long.", + bad_json: "The reply could not be read.", + bad_case: "Unknown case.", + bad_role: "Pick one of the listed roles.", + too_short: `Please write at least ${TEXT_MIN} characters.`, + too_long: `Please keep it under ${TEXT_MAX} characters.`, + contact_info: "Please leave out email addresses and @handles — replies are anonymous.", + phone: "Please leave out phone numbers — replies are anonymous.", + link: "Please leave out links — describe what you see instead.", + unknown_case: "Replies are open on published cases only.", + rate_limited: `That is ${DAILY_CAP} replies from here today — please come back tomorrow.`, + unavailable: "Replies are closed for a moment. Please try again later.", +}; + +export type Checked = { ok: true; caseId: string; text: string; role: Role; honeypot: boolean } | { ok: false; reason: Rejection }; + +/** Everything that needs no storage: shape, honeypot, text rules. */ +export function checkBody(raw: string): Checked { + if (Buffer.byteLength(raw, "utf8") > MAX_BODY) return { ok: false, reason: "too_large" }; + let b: unknown; + try { + b = JSON.parse(raw); + } catch { + return { ok: false, reason: "bad_json" }; + } + if (!b || typeof b !== "object" || Array.isArray(b)) return { ok: false, reason: "bad_json" }; + const o = b as Record; + const honeypot = o.website !== undefined && o.website !== "" && o.website !== null; + if (typeof o.caseId !== "string" || !CASE_ID.test(o.caseId)) return { ok: false, reason: "bad_case" }; + const role = o.role === undefined || o.role === null || o.role === "" ? "other" : o.role; + if (typeof role !== "string" || !(ROLES as readonly string[]).includes(role)) return { ok: false, reason: "bad_role" }; + if (typeof o.text !== "string") return { ok: false, reason: "too_short" }; + const text = stripHtml(o.text); + if (text.length < TEXT_MIN) return { ok: false, reason: "too_short" }; + if (text.length > TEXT_MAX) return { ok: false, reason: "too_long" }; + if (EMAIL.test(text) || HANDLE.test(text)) return { ok: false, reason: "contact_info" }; + if (URL_RE.test(text)) return { ok: false, reason: "link" }; + if (hasPhone(text)) return { ok: false, reason: "phone" }; + return { ok: true, caseId: o.caseId, text, role: role as Role, honeypot }; +} + +// ── the request ───────────────────────────────────────────────────────────────────────── + +export interface IntakeStore { + get(key: string): Promise; + put(key: string, body: Buffer): Promise; +} + +export interface IntakeDeps { + store: IntakeStore; + /** SSM /earthdeck/REPLY_SALT; null/empty = intake closed (503). */ + salt(): Promise; + /** Public case ids (from CASE_INDEX_KEY), cached by the caller. */ + caseIds(): Promise>; + now(): Date; + id?(): string; +} + +export interface IntakeRequest { + method: string; + path: string; + body: string; + ip: string; +} + +export interface IntakeResponse { + status: number; + body: { id?: string; error?: Rejection; message?: string }; +} + +const fail = (status: number, reason: Rejection): IntakeResponse => ({ status, body: { error: reason, message: MESSAGES[reason] } }); + +export async function handleReply(req: IntakeRequest, deps: IntakeDeps): Promise { + if (req.path.replace(/\/+$/, "") !== "/reply") return fail(404, "path"); + if (req.method !== "POST") return fail(405, "method"); + const c = checkBody(req.body); + if (!c.ok) return fail(c.reason === "too_large" ? 413 : 400, c.reason); + const now = deps.now(); + const id = deps.id ? deps.id() : ulid(now.getTime()); + if (c.honeypot) return { status: 202, body: { id } }; // looks accepted; nothing is stored + + const salt = await deps.salt(); + if (!salt) return fail(503, "unavailable"); + let ids: Set; + try { + ids = await deps.caseIds(); + } catch { + return fail(503, "unavailable"); + } + if (!ids.has(c.caseId)) return fail(404, "unknown_case"); + + const hash = ipHash(req.ip, salt); + const rateKey = `${RATE_PREFIX}${now.toISOString().slice(0, 10)}/${hash}.json`; + const prev = await deps.store.get(rateKey); + let count = 0; + if (prev) { + try { + count = Number((JSON.parse(prev.toString("utf8")) as { n?: unknown }).n) || 0; + } catch { + count = 0; + } + } + if (count >= DAILY_CAP) return fail(429, "rate_limited"); + await deps.store.put(rateKey, Buffer.from(JSON.stringify({ n: count + 1 }))); + + const reply: InboxReply = { caseId: c.caseId, text: c.text, role: c.role, receivedAt: now.toISOString(), ipHash: hash }; + await deps.store.put(`${INBOX_PREFIX}${c.caseId}/${id}.json`, Buffer.from(JSON.stringify(reply))); + return { status: 202, body: { id } }; +} + +/** Public case ids out of a case index body: `{ids: [...]}` (written by the runner after each export). */ +export function parseCaseIndex(buf: Buffer): Set { + const j = JSON.parse(buf.toString("utf8")) as { ids?: unknown }; + return new Set(Array.isArray(j.ids) ? j.ids.filter((x): x is string => typeof x === "string" && CASE_ID.test(x)) : []); +} diff --git a/src/replies/review.ts b/src/replies/review.ts new file mode 100644 index 0000000..5a89d68 --- /dev/null +++ b/src/replies/review.ts @@ -0,0 +1,216 @@ +// The reply wall's only moderator: the same reviewer model that reviews cases. Runs inside +// the analyst job over a local mirror of the state bucket's `replies/` prefix +// +// /inbox//.json waiting (written by the intake Lambda) +// /public//.json accepted → shown under the case {id, caseId, text, role, receivedAt} +// /rejected//.json rejected, with the verdict (never shown) +// +// Accepted = the model says accept AND raises no flag. Every accepted reply also gets a +// signed `commented` ledger event (text hash only). The runner syncs the moves back to S3. + +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import type { EventInput } from "../ledger/store.js"; +import { PUBLIC_STATUSES, type Finding } from "../ledger/schema.js"; +import type { QuotaGovernor } from "../watch/quota.js"; +import type { JsonCallResult } from "../analyst/anthropic.js"; +import { CASE_ID, REPLY_ID, ROLES, TEXT_MAX, type InboxReply, type Role } from "./intake.js"; + +export const FLAGS = ["spam", "abuse", "pii", "off_topic", "names_person", "legal_threat"] as const; +export type Flag = (typeof FLAGS)[number]; +export interface ReplyVerdict { + accept: boolean; + reason: string; + flags: Flag[]; +} +export interface PublicReply { + id: string; + caseId: string; + text: string; + role: Role; + receivedAt: string; +} + +/** At most this many replies reviewed per analyst run (≈ $0.005 each with Sonnet at low effort). */ +export const MAX_REPLIES_PER_RUN = 50; + +export const REPLY_REVIEWER_SYSTEM = `You screen anonymous public replies left under one case on Earth Watch, a public, evidence-first record of environmental change seen from satellites. Nobody else reads them before they appear: your verdict decides. + +Accept a reply only if it is a good-faith contribution about this case or this place: what the writer sees on the ground, context, a correction, a disagreement, a question. Disagreement and criticism of the case are welcome. + +Reject, and set the matching flags, if the reply: +- spam: advertising, promotion, repeated or meaningless text; +- abuse: insults, harassment, hate, threats of violence; +- pii: contact details or anything that identifies a private person (addresses, plates, ids); +- off_topic: has nothing to do with this case or place; +- names_person: names or points at an individual natural person (companies, agencies and places are fine); +- legal_threat: threatens legal action or makes defamatory accusations of crimes against someone. + +accept must be false whenever any flag is set. reason: one short sentence.`; + +export const REPLY_VERDICT_JSON_SCHEMA = { + type: "object", + additionalProperties: false, + required: ["accept", "reason", "flags"], + properties: { + accept: { type: "boolean" }, + reason: { type: "string" }, + flags: { type: "array", items: { type: "string", enum: [...FLAGS] } }, + }, +} as const; + +/** Strict: exactly {accept: boolean, reason: non-empty string, flags: known flags}; else null. Any flag forces accept = false. */ +export function parseVerdict(data: unknown): ReplyVerdict | null { + if (!data || typeof data !== "object" || Array.isArray(data)) return null; + const o = data as Record; + const keys = Object.keys(o).sort().join(","); + if (keys !== "accept,flags,reason") return null; + if (typeof o.accept !== "boolean" || typeof o.reason !== "string" || !o.reason.trim() || !Array.isArray(o.flags)) return null; + if (!o.flags.every((f) => typeof f === "string" && (FLAGS as readonly string[]).includes(f))) return null; + const flags = [...new Set(o.flags as Flag[])]; + return { accept: o.accept && flags.length === 0, reason: o.reason.trim().slice(0, 500), flags }; +} + +/** An inbox file's content, or null if it is not a well-formed reply for this case. */ +export function parseInbox(raw: string, caseId: string): InboxReply | null { + try { + const o = JSON.parse(raw) as Record; + if (o.caseId !== caseId || typeof o.text !== "string" || !o.text.trim() || o.text.length > TEXT_MAX) return null; + if (typeof o.role !== "string" || !(ROLES as readonly string[]).includes(o.role)) return null; + if (typeof o.receivedAt !== "string" || Number.isNaN(Date.parse(o.receivedAt))) return null; + return { caseId, text: o.text, role: o.role as Role, receivedAt: o.receivedAt, ipHash: typeof o.ipHash === "string" ? o.ipHash : "" }; + } catch { + return null; + } +} + +/** Inbox entries oldest first (ULIDs sort by time). */ +export function listInbox(dir: string): { caseId: string; id: string; path: string }[] { + const inbox = join(dir, "inbox"); + if (!existsSync(inbox)) return []; + const out: { caseId: string; id: string; path: string }[] = []; + for (const caseId of readdirSync(inbox)) { + if (!CASE_ID.test(caseId)) continue; + for (const f of readdirSync(join(inbox, caseId))) { + const id = f.replace(/\.json$/, ""); + if (f.endsWith(".json") && REPLY_ID.test(id)) out.push({ caseId, id, path: join(inbox, caseId, f) }); + } + } + return out.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)); +} + +/** Public replies of one case, oldest first. */ +export function readPublicReplies(dir: string, caseId: string): PublicReply[] { + const d = join(dir, "public", caseId); + if (!CASE_ID.test(caseId) || !existsSync(d)) return []; + const out: PublicReply[] = []; + for (const f of readdirSync(d).sort()) { + const id = f.replace(/\.json$/, ""); + if (!f.endsWith(".json") || !REPLY_ID.test(id)) continue; + try { + const o = JSON.parse(readFileSync(join(d, f), "utf8")) as Record; + if (typeof o.text !== "string" || typeof o.receivedAt !== "string" || typeof o.role !== "string" || !(ROLES as readonly string[]).includes(o.role)) continue; + out.push({ id, caseId, text: o.text.slice(0, TEXT_MAX), role: o.role as Role, receivedAt: o.receivedAt }); + } catch { + /* unreadable → not shown */ + } + } + return out; +} + +export interface ReviewRepliesOptions { + dir: string; + ledger: { get(id: string): Finding | null | undefined; append(ev: EventInput): unknown }; + reviewer: string; + /** One reviewer call (the analyst wires callJson + spend accounting). */ + call(system: string, user: string, schema: Record): Promise; + quota?: QuotaGovernor; + max?: number; + log?: (s: string) => void; + journal?: (kind: string, rec: Record) => void; +} + +export interface ReviewRepliesReport { + accepted: string[]; + rejected: string[]; + errors: { id: string; message: string }[]; + left: number; +} + +const sha256 = (s: string) => createHash("sha256").update(s).digest("hex"); + +function move(dir: string, from: string, bucket: "public" | "rejected", caseId: string, id: string, body: unknown): void { + const d = join(dir, bucket, caseId); + mkdirSync(d, { recursive: true }); + writeFileSync(join(d, `${id}.json`), JSON.stringify(body)); + rmSync(from, { force: true }); +} + +export async function reviewReplies(o: ReviewRepliesOptions): Promise { + const log = o.log ?? (() => {}); + const j = o.journal ?? (() => {}); + const report: ReviewRepliesReport = { accepted: [], rejected: [], errors: [], left: 0 }; + const inbox = listInbox(o.dir); + const max = Math.min(o.max ?? MAX_REPLIES_PER_RUN, MAX_REPLIES_PER_RUN); + let done = 0; + for (const item of inbox) { + if (done >= max) break; + if (o.quota?.analystBudgetSpent()) { + log(` replies: daily analyst budget spent — ${inbox.length - done} left for tomorrow`); + break; + } + done++; + const reject = (verdict: ReplyVerdict, reply: unknown, by: string | null) => { + move(o.dir, item.path, "rejected", item.caseId, item.id, { id: item.id, reply, verdict, reviewedBy: by, reviewedAt: new Date().toISOString() }); + report.rejected.push(item.id); + j("reply_rejected", { caseId: item.caseId, replyId: item.id, reason: verdict.reason, flags: verdict.flags, by }); + log(` ✗ reply ${item.id} on ${item.caseId}: ${verdict.reason}${verdict.flags.length ? ` [${verdict.flags.join(", ")}]` : ""}`); + }; + const reply = parseInbox(readFileSync(item.path, "utf8"), item.caseId); + if (!reply) { + reject({ accept: false, reason: "malformed inbox entry", flags: [] }, null, null); + continue; + } + const f = o.ledger.get(item.caseId); + if (!f || !PUBLIC_STATUSES.includes(f.status) || f.status === "retracted") { + reject({ accept: false, reason: `case is not open for replies (${f ? f.status : "not in the ledger"})`, flags: [] }, reply, null); + continue; + } + try { + const caseText = f.narration?.text ?? `${f.title}\n\n${f.summary}`; + const user = `The case (${f.aoi?.name ?? f.aoi?.id ?? "unnamed place"}):\n${caseText}\n\nThe reply (writer says they are: ${reply.role}):\n"""\n${reply.text}\n"""`; + const res = await o.call(REPLY_REVIEWER_SYSTEM, user, REPLY_VERDICT_JSON_SCHEMA as unknown as Record); + const verdict = parseVerdict(res.data); + const by = `model:${res.model}`; + if (!verdict) { + reject({ accept: false, reason: "reviewer returned no valid verdict", flags: [] }, reply, by); + continue; + } + if (!verdict.accept) { + reject(verdict, reply, by); + continue; + } + o.ledger.append({ + kind: "commented", + findingId: item.caseId, + actor: by, + reply: { id: item.id, role: reply.role, receivedAt: reply.receivedAt, textSha256: sha256(reply.text) }, + verdict: { accept: true, reason: verdict.reason, flags: [] }, + }); + const pub: PublicReply = { id: item.id, caseId: item.caseId, text: reply.text, role: reply.role, receivedAt: reply.receivedAt }; + move(o.dir, item.path, "public", item.caseId, item.id, pub); + report.accepted.push(item.id); + j("reply_accepted", { caseId: item.caseId, replyId: item.id, reason: verdict.reason, by }); + log(` ✓ reply ${item.id} on ${item.caseId} accepted (${reply.role})`); + } catch (err) { + // Left in the inbox: retried next run. + const message = err instanceof Error ? err.message : String(err); + report.errors.push({ id: item.id, message }); + j("reply_error", { caseId: item.caseId, replyId: item.id, message }); + log(` ! reply ${item.id}: ${message}`); + } + } + report.left = listInbox(o.dir).length; + return report; +} diff --git a/src/runner/aws.ts b/src/runner/aws.ts index fec0aff..cf329a2 100644 --- a/src/runner/aws.ts +++ b/src/runner/aws.ts @@ -66,6 +66,40 @@ export async function readParameters(region: string, prefix: string): Promise<{ return out; } +/** One parameter, decrypted; null when it does not exist. */ +export async function readParameter(region: string, name: string): Promise { + const m = await load("@aws-sdk/client-ssm"); + const ssm = new m.SSMClient({ region }); + try { + const r = await ssm.send(new m.GetParameterCommand({ Name: name, WithDecryption: true })); + return r.Parameter?.Value ?? null; + } catch (e) { + if ((e as { name?: string }).name === "ParameterNotFound") return null; + throw e; + } +} + +/** Get (null when the key is absent) + put on one bucket — all the reply intake needs. */ +export async function s3KeyValue(region: string, bucket: string): Promise<{ get(key: string): Promise; put(key: string, body: Buffer): Promise }> { + const m = await load("@aws-sdk/client-s3"); + const s3 = new m.S3Client({ region }); + return { + async get(key) { + try { + const r = await s3.send(new m.GetObjectCommand({ Bucket: bucket, Key: key })); + return r.Body ? Buffer.from(await r.Body.transformToByteArray()) : Buffer.alloc(0); + } catch (e) { + const name = (e as { name?: string }).name; + if (name === "NoSuchKey" || name === "NotFound" || name === "AccessDenied") return null; + throw e; + } + }, + async put(key, body) { + await s3.send(new m.PutObjectCommand({ Bucket: bucket, Key: key, Body: body, ContentType: "application/json; charset=utf-8" })); + }, + }; +} + export async function cloudFrontInvalidator(region: string): Promise<(distributionId: string) => Promise> { const m = await load("@aws-sdk/client-cloudfront"); const cf = new m.CloudFrontClient({ region }); diff --git a/src/runner/core.ts b/src/runner/core.ts index b94f933..60a7381 100644 --- a/src/runner/core.ts +++ b/src/runner/core.ts @@ -11,13 +11,14 @@ import { spawn } from "node:child_process"; import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; import { dirname, join, relative, sep } from "node:path"; import { z } from "zod"; +import { PUBLIC_STATUSES } from "../ledger/schema.js"; // ── payload ────────────────────────────────────────────────────────────────────────────── /** The hand-written watchlists (`watchlists/.json`). */ -export const WATCHLISTS = ["amazon", "congo-borneo", "controls", "methane", "flaring"] as const; +export const WATCHLISTS = ["amazon", "congo-borneo", "controls", "methane", "flaring", "indicators", "weather", "good-news", "marine"] as const; /** - * A sweep target: one hand-written list, `all-handwritten` (those five), `all-generated` + * A sweep target: one hand-written list, `all-handwritten` (all of those), `all-generated` * (every file in `watchlists/generated/`), or one generated list `generated/`. */ export type WatchlistName = (typeof WATCHLISTS)[number] | "all-handwritten" | "all-generated" | `generated/${string}`; @@ -98,7 +99,7 @@ export function sweepTiming(remainingMs: number, requestedSec?: number): { timeB } /** argv for `node dist/cli.js …`. A sweep without a watchlist sweeps the whole directory. */ -export function cliArgs(step: Step, siteDir: string): string[] { +export function cliArgs(step: Step, siteDir: string, repliesDir?: string): string[] { if (step.job === "sweep") { return [ "watch", @@ -109,17 +110,19 @@ export function cliArgs(step: Step, siteDir: string): string[] { ...(step.timeBudgetSec !== undefined ? ["--time-budget", String(step.timeBudgetSec)] : []), ]; } - if (step.job === "analyst") return ["analyst", "--once"]; - // Public-site metadata comes from the function's environment (set by the stack). + if (step.job === "analyst") return ["analyst", "--once", ...(repliesDir ? ["--replies", repliesDir] : [])]; + // Public-site metadata comes from the function's environment (set by the stack). No + // --contact: the site is anonymous; replies go through the reply wall (EARTHDECK_REPLY_URL). const siteUrl = process.env.EARTHDECK_SITE_URL; - const contact = process.env.EARTHDECK_CONTACT; + const replyUrl = process.env.EARTHDECK_REPLY_URL; return [ "watch", "export", "--out", siteDir, ...(siteUrl ? ["--base-url", siteUrl] : []), - ...(contact ? ["--contact", contact] : []), + ...(replyUrl ? ["--reply-url", replyUrl] : []), + ...(repliesDir ? ["--replies", repliesDir] : []), "--trust", "TRUST.md", ]; @@ -179,6 +182,26 @@ export function checkpointArchiveKey(at: Date): string { return `${CHECKPOINT_ARCHIVE_PREFIX}${at.toISOString().replace(/\.\d+Z$/, "Z").replace(/:/g, "-")}`; } +// ── reply wall mirror (state bucket `replies/` ↔ local dir) ───────────────────────────── + +export const REPLIES_PREFIX = "replies/"; +/** State-bucket key the reply intake reads to know which cases take replies. */ +export const REPLY_CASE_INDEX_KEY = "replies/cases.json"; +const REPLY_PARTS = new Set(["inbox", "public", "rejected"]); + +/** `replies///.json` → the same path relative to the local dir; anything else → null. */ +export function repliesRelPath(key: string): string | null { + const m = /^replies\/([a-z]+)\/([A-Za-z0-9-]{1,64})\/([0-9A-Z]{26})\.json$/.exec(key); + return m && REPLY_PARTS.has(m[1]!) ? key.slice(REPLIES_PREFIX.length) : null; +} + +/** Public case ids for the intake, from the export's api/map.json. */ +export function caseIndexFrom(mapJson: string, publicStatuses: readonly string[]): { ids: string[] } { + const j = JSON.parse(mapJson) as { cases?: { id?: unknown; status?: unknown }[] }; + const ids = (j.cases ?? []).filter((c) => typeof c.id === "string" && typeof c.status === "string" && publicStatuses.includes(c.status)).map((c) => c.id as string); + return { ids: [...new Set(ids)].sort() }; +} + // ── static-site headers ────────────────────────────────────────────────────────────────── const TYPES: Record = { @@ -194,6 +217,7 @@ const TYPES: Record = { md: "text/markdown; charset=utf-8", xml: "application/xml", svg: "image/svg+xml", + webmanifest: "application/manifest+json", png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", @@ -293,6 +317,8 @@ export interface RunnerConfig { budgetMs(): number; /** Raw time left in the invocation, ms (Lambda `getRemainingTimeInMillis`); enables sweep time budgets. */ remainingMs?(): number; + /** Local mirror of the state bucket's `replies/` (analyst: inbox; export: public). Omitted = no reply wall. */ + repliesDir?: string; } export interface StepResult { @@ -399,6 +425,48 @@ async function downloadLedger(cfg: RunnerConfig, deps: RunnerDeps): Promise/` into `//`; returns the keys pulled. */ +async function downloadReplies(cfg: RunnerConfig, deps: RunnerDeps, part: "inbox" | "public"): Promise { + const dir = cfg.repliesDir!; + rmSync(dir, { recursive: true, force: true }); + mkdirSync(dir, { recursive: true }); + const keys: string[] = []; + for (const key of await deps.store.list(cfg.stateBucket, `${REPLIES_PREFIX}${part}/`)) { + const rel = repliesRelPath(key); + if (!rel) continue; + const dest = join(dir, rel); + mkdirSync(dirname(dest), { recursive: true }); + writeFileSync(dest, await deps.store.get(cfg.stateBucket, key)); + keys.push(key); + } + return keys; +} + +/** After the analyst: push public/ + rejected/ files, drop inbox keys that were moved. */ +async function syncReplies(cfg: RunnerConfig, deps: RunnerDeps, pulled: string[]): Promise<{ put: number; removed: number }> { + const dir = cfg.repliesDir!; + const local = new Set(walk(dir)); + const put = [...local].filter((rel) => !rel.startsWith("inbox/") && repliesRelPath(REPLIES_PREFIX + rel)); + await uploadDir(cfg.stateBucket, dir, (rel) => REPLIES_PREFIX + rel, put, deps); + const gone = pulled.filter((key) => !local.has(key.slice(REPLIES_PREFIX.length))); + if (gone.length) await deps.store.remove(cfg.stateBucket, gone); + return { put: put.length, removed: gone.length }; +} + +/** Site-bucket prefixes the export owns outright: anything there it no longer writes is stale. */ +export const SITE_PRUNE_PREFIXES = ["api/", "watch/"] as const; + +/** + * Pure: site-bucket keys to delete after an export — under api/ and watch/ only, absent from the + * new export. Never ledger/ (or anything else outside those prefixes), and never hashed bundles + * under an assets/ folder: a page cached a few minutes ago may still ask for the old one. + */ +export function sitePruneKeys(existing: readonly string[], exported: ReadonlySet): string[] { + return existing + .filter((k) => SITE_PRUNE_PREFIXES.some((p) => k.startsWith(p)) && !exported.has(k) && !k.split("/").includes("assets") && !k.split("/").includes("..")) + .sort(); +} + async function uploadDir(bucket: string, dir: string, keyOf: (rel: string) => string, rels: string[], deps: RunnerDeps): Promise { for (const rel of rels) { const key = keyOf(rel); @@ -428,6 +496,7 @@ export async function runStep(step: Step, cfg: RunnerConfig, deps: RunnerDeps, a const env = { ...cfg.env, EARTHDECK_LEDGER_DIR: cfg.ledgerDir }; if (step.job === "export") rmSync(cfg.siteDir, { recursive: true, force: true }); + const pulledReplies = cfg.repliesDir && (step.job === "analyst" || step.job === "export") ? await downloadReplies(cfg, deps, step.job === "analyst" ? "inbox" : "public") : []; let runStepAs = step; let timeoutMs = cfg.budgetMs(); if (step.job === "sweep" && cfg.remainingMs) { @@ -438,7 +507,7 @@ export async function runStep(step: Step, cfg: RunnerConfig, deps: RunnerDeps, a base.timeBudgetSec = t.timeBudgetSec; timeoutMs = t.killAfterMs; } - const run = await deps.exec(cliArgs(runStepAs, cfg.siteDir), { env, timeoutMs }); + const run = await deps.exec(cliArgs(runStepAs, cfg.siteDir, cfg.repliesDir), { env, timeoutMs }); const outputTail = run.output.slice(-2_000); if (step.job === "export") { @@ -446,8 +515,18 @@ export async function runStep(step: Step, cfg: RunnerConfig, deps: RunnerDeps, a const files = walk(cfg.siteDir); if (files.length === 0) return done({ ok: false, status: "failed", exitCode: 0, reason: `export wrote nothing to ${cfg.siteDir}`, outputTail }); await uploadDir(cfg.siteBucket, cfg.siteDir, (rel) => rel, files, deps); - await deps.invalidateAll(cfg.distributionId); - return done({ ok: true, status: "ok", exitCode: 0, filesUploaded: files.length, outputTail }); + // Mirror deletions too (e.g. a reply taken down → its api/replies/.json goes away). + const exported = new Set(files); + const stale: string[] = []; + for (const p of SITE_PRUNE_PREFIXES) stale.push(...sitePruneKeys(await deps.store.list(cfg.siteBucket, p), exported)); + if (stale.length) await deps.store.remove(cfg.siteBucket, stale); + await deps.invalidateAll(cfg.distributionId); // "/*": covers the deleted paths as well + if (cfg.repliesDir && existsSync(join(cfg.siteDir, "api", "map.json"))) { + // The intake (reply Lambda) takes replies only for cases in this index. + const index = caseIndexFrom(readFileSync(join(cfg.siteDir, "api", "map.json"), "utf8"), PUBLIC_STATUSES); + await deps.store.put(cfg.stateBucket, REPLY_CASE_INDEX_KEY, Buffer.from(JSON.stringify(index)), { contentType: "application/json; charset=utf-8" }); + } + return done({ ok: true, status: "ok", exitCode: 0, filesUploaded: files.length, filesDeleted: stale.length, outputTail }); } if (!writing) { @@ -471,12 +550,18 @@ export async function runStep(step: Step, cfg: RunnerConfig, deps: RunnerDeps, a checkpointArchived = checkpointArchiveKey(deps.now()); await deps.store.put(cfg.stateBucket, checkpointArchived, readFileSync(join(cfg.ledgerDir, "checkpoint")), { contentType: "text/plain; charset=utf-8" }); } + let repliesNote = ""; + if (step.job === "analyst" && cfg.repliesDir) { + // Only after the ledger (with its `commented` events) is safely back in the bucket. + const r = await syncReplies(cfg, deps, pulledReplies); + if (r.put || r.removed) repliesNote = `; replies: ${r.put} written, ${r.removed} inbox removed`; + } const ok = run.code === 0; return done({ ok, status: ok ? "ok" : "failed", uploaded: true, - reason: ok ? decision.reason : `job exited ${run.code}; ${decision.reason} (kept)`, + reason: (ok ? decision.reason : `job exited ${run.code}; ${decision.reason} (kept)`) + repliesNote, filesUploaded: plan.put.length, filesDeleted: plan.remove.length, ...(checkpointArchived ? { checkpointArchived } : {}), diff --git a/src/runner/lambda.ts b/src/runner/lambda.ts index 9d61cf2..4353423 100644 --- a/src/runner/lambda.ts +++ b/src/runner/lambda.ts @@ -41,6 +41,7 @@ export async function handler(event: unknown, context?: LambdaContext): Promise< distributionId: need("EARTHDECK_DISTRIBUTION_ID"), ledgerDir: "/tmp/ledger", siteDir: "/tmp/site", + repliesDir: "/tmp/replies", env: { ...process.env, ...secrets, HOME: "/tmp" }, budgetMs: () => (context ? context.getRemainingTimeInMillis() - RESERVE_MS : 780_000), // Sweeps get `--time-budget` = remaining − 90 s from this (see sweepTiming in core.ts). diff --git a/src/runner/reply-lambda.ts b/src/runner/reply-lambda.ts new file mode 100644 index 0000000..2c80dfd --- /dev/null +++ b/src/runner/reply-lambda.ts @@ -0,0 +1,52 @@ +// AWS Lambda entry for the public reply wall (handler `dist/runner/reply-lambda.handler`, +// same zip as the runner). Invoked through a Lambda Function URL (auth NONE; CORS for the +// site origin only, set on the URL in infra/earthdeck.yaml). The logic is in +// src/replies/intake.ts; this file only adapts the Function URL event and wires S3 + SSM. +// +// The raw source IP is read here, hashed with the salt inside handleReply and dropped: it is +// never logged, stored or returned. + +import { handleReply, parseCaseIndex, CASE_INDEX_KEY } from "../replies/intake.js"; +import { readParameter, s3KeyValue } from "./aws.js"; + +interface UrlEvent { + rawPath?: string; + body?: string | null; + isBase64Encoded?: boolean; + requestContext?: { http?: { method?: string; sourceIp?: string } }; +} + +const INDEX_TTL_MS = 5 * 60_000; +let salt: string | null = null; +let index: { at: number; ids: Set } | null = null; + +export async function handler(event: UrlEvent): Promise<{ statusCode: number; headers: Record; body: string }> { + const region = process.env.AWS_REGION ?? "us-east-1"; + const bucket = process.env.EARTHDECK_STATE_BUCKET ?? ""; + const saltName = process.env.EARTHDECK_REPLY_SALT_PARAM ?? "/earthdeck/REPLY_SALT"; + const store = await s3KeyValue(region, bucket); + const raw = event.body ?? ""; + const res = await handleReply( + { + method: event.requestContext?.http?.method ?? "GET", + path: event.rawPath ?? "/", + body: event.isBase64Encoded ? Buffer.from(raw, "base64").toString("utf8") : raw, + ip: event.requestContext?.http?.sourceIp ?? "", + }, + { + store, + salt: async () => (salt ??= await readParameter(region, saltName)), + caseIds: async () => { + if (index && Date.now() - index.at < INDEX_TTL_MS) return index.ids; + const buf = await store.get(CASE_INDEX_KEY); + if (!buf) throw new Error("case index missing"); + index = { at: Date.now(), ids: parseCaseIndex(buf) }; + return index.ids; + }, + now: () => new Date(), + }, + ); + // One line per request, without the IP or the text. + console.log(JSON.stringify({ status: res.status, error: res.body.error ?? null })); + return { statusCode: res.status, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }, body: JSON.stringify(res.body) }; +} diff --git a/src/site.config.ts b/src/site.config.ts index 69022b9..a66f985 100644 --- a/src/site.config.ts +++ b/src/site.config.ts @@ -29,14 +29,24 @@ export const SITE = { organization: { name: "TerraKeep", url: "https://vitalearth.io" }, /** Footer credit. */ credit: "Built on open data", - /** Static social card, relative to the site root (1200×630; carries no product name). */ + /** Static social card, relative to the site root: 1200×630 PNG with the mark, the name and the slogan (scripts/site-icons.mjs). */ ogImage: "og.png", + /** Square logo for JSON-LD `Organization.logo` (and the web app manifest), relative to the site root. */ + logo: "icon-512.png", + /** Browser chrome + manifest colour — the page background token (--bg-0). */ + themeColor: "#07090d", /** * Licence URL for the published findings data (JSON-LD `Dataset.license`). Unset until a * licence is chosen — the upstream sources carry their own terms (see the site footer). */ dataLicense: null as string | null, locale: "en", + /** + * The reply wall's intake origin (Lambda Function URL; the form posts to `/reply`). + * Unset here — the runner passes the stack's ReplyUrl output as `--reply-url`. No email: + * nobody reads an inbox; the reviewer model screens every reply before it appears. + */ + replyEndpoint: null as string | null, } as const; export type SiteConfig = typeof SITE; diff --git a/src/tools/climate.ts b/src/tools/climate.ts index fe986e8..e0768d6 100644 --- a/src/tools/climate.ts +++ b/src/tools/climate.ts @@ -99,12 +99,18 @@ export function registerClimateTools(server: McpServer): void { "Current + recent air quality for any point, from the Copernicus CAMS model via " + "Open-Meteo, no key: PM2.5, PM10, ozone, NO₂ (µg/m³) and the US AQI, hourly for the " + "last 2 days. Returns the latest values and a 48-hour series; flags unhealthy levels " + - "(WHO 24h PM2.5 guideline: 15 µg/m³). Posts a chart card to the dashboard.", - inputSchema: { lat: latSchema, lon: lonSchema }, + "(WHO 24h PM2.5 guideline: 15 µg/m³). `pastDays` (1–16) widens the window; the " + + "result then carries PM2.5 daily means (UTC days, hours up to now only). " + + "Posts a chart card to the dashboard.", + inputSchema: { + lat: latSchema, + lon: lonSchema, + pastDays: z.number().int().min(1).max(16).optional().describe("Days of history (default 2, max 16)."), + }, }, - async ({ lat, lon }) => + async ({ lat, lon, pastDays }) => safe(async () => { - const r = await airQuality(lat, lon); + const r = await airQuality(lat, lon, pastDays ?? 2); const latestOf = (k: string) => summarize(r.series[k] ?? []).latest; const pm25 = latestOf("pm2_5"); const aqi = latestOf("us_aqi"); @@ -141,6 +147,7 @@ export function registerClimateTools(server: McpServer): void { units: r.units, summary, pm25Last48h: pm25Series, + pm25Daily: dailyMeans(r.series.pm2_5 ?? [], nowIso()), dashboard: pushed ? "pushed" : "dashboard offline", }; }), @@ -202,6 +209,24 @@ export function registerClimateTools(server: McpServer): void { ); } +/** + * UTC-day means of an hourly series, using only hours at or before `now` (the CAMS feed + * appends forecast hours). `hours` is how many valid hours each mean rests on. + */ +export function dailyMeans(points: { t: string; v: number | null }[], now: string): { t: string; v: number; hours: number }[] { + const nowKey = now.slice(0, 16); + const acc = new Map(); + for (const p of points) { + if (p.v === null || p.t.slice(0, 16) > nowKey) continue; + const d = p.t.slice(0, 10); + const a = acc.get(d) ?? { sum: 0, n: 0 }; + a.sum += p.v; + a.n += 1; + acc.set(d, a); + } + return [...acc.entries()].sort(([a], [b]) => (a < b ? -1 : 1)).map(([t, a]) => ({ t, v: round(a.sum / a.n, 1), hours: a.n })); +} + /** Calendar-year sums for accumulation variables (precipitation, snowfall). */ function annualSum(points: { t: string; v: number | null }[]): { t: string; v: number }[] { const sums = new Map(); diff --git a/src/tools/forest.ts b/src/tools/forest.ts index 3606cf7..2ccfd16 100644 --- a/src/tools/forest.ts +++ b/src/tools/forest.ts @@ -31,14 +31,15 @@ export function registerForestTools(server: McpServer): void { bbox: z .tuple([z.number(), z.number(), z.number(), z.number()]) .describe("Bounding box [west, south, east, north] in degrees (≤ 4 deg² area)"), - days: z.number().int().min(1).max(365).optional().describe("Look back N days (default 90)."), + days: z.number().int().min(1).max(365).optional().describe("Look back N days, ending on endDate (default 90)."), + endDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional().describe("Last day of the window, YYYY-MM-DD (default today UTC) — e.g. the same window a year earlier."), minConfidence: z .enum(GFW_CONFIDENCES) .optional() .describe("Minimum alert confidence: nominal (default, all), high, or highest."), }, }, - async ({ bbox, days, minConfidence }) => + async ({ bbox, days, endDate, minConfidence }) => safe(async () => { const key = gfwApiKey(); if (!key) { @@ -59,9 +60,9 @@ export function registerForestTools(server: McpServer): void { } const conf = (minConfidence ?? "nominal") as GfwConfidence; const lookback = days ?? 90; - const dateTo = isoDate(0); + const dateTo = endDate ?? isoDate(0); const dateFrom = addDays(dateTo, -lookback); - const { summary, daily } = await integratedAlerts(key, box, dateFrom, conf); + const { summary, daily } = await integratedAlerts(key, box, dateFrom, conf, endDate); // The layer only covers the tropics — flag AOIs that poke outside it. const coverageNote = diff --git a/src/tools/marine.ts b/src/tools/marine.ts new file mode 100644 index 0000000..05d9c92 --- /dev/null +++ b/src/tools/marine.ts @@ -0,0 +1,104 @@ +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { z } from "zod"; +import { FISHING_LICENCE, FISHING_SOURCE, fishingAttribution, fishingEffort, gfwFishingToken, type FishingArea, type FishingSummary, type SpatialRes } from "../clients/gfwfishing.js"; +import { pushCard } from "../dashboard/push.js"; +import { OverviewError } from "../errors.js"; +import { safe } from "../result.js"; +import type { BBox } from "../types.js"; +import { addDays, assertBBox, newId, nowIso } from "../util.js"; + +const DATE = /^\d{4}-\d{2}-\d{2}$/; +const bboxSchema = z.tuple([z.number(), z.number(), z.number(), z.number()]); + +export interface FishingActivityArgs { + bbox?: BBox; + mpaId?: string; + days?: number; + from?: string; + to?: string; + resolution?: SpatialRes; + byGear?: boolean; + clipBBox?: BBox; + maxCells?: number; +} + +/** The `fishing_activity` body, separate from MCP registration so tests call it directly. */ +export async function fishingActivity(a: FishingActivityArgs, env: NodeJS.ProcessEnv = process.env): Promise }> { + const token = gfwFishingToken(env); + if (!token) throw new OverviewError("fishing_activity needs GFW_FISHING_TOKEN (free Global Fishing Watch API token, non-commercial terms)"); + if ((a.bbox ? 1 : 0) + (a.mpaId ? 1 : 0) !== 1) throw new OverviewError("give exactly one of bbox or mpaId"); + if (a.bbox) { + assertBBox(a.bbox); + if ((a.bbox[2] - a.bbox[0]) * (a.bbox[3] - a.bbox[1]) > 2500) throw new OverviewError("bbox too large (> 2500 deg²) — split it, or query an MPA by mpaId"); + } + if (a.clipBBox) assertBBox(a.clipBBox); + const to = a.to ?? new Date().toISOString().slice(0, 10); + const from = a.from ?? addDays(to, -(a.days ?? 30)); + if (!DATE.test(from) || !DATE.test(to) || from >= to) throw new OverviewError(`bad date range ${from}..${to}`); + if (Date.parse(to) - Date.parse(from) > 366 * 86_400_000) throw new OverviewError("date range longer than 366 days"); + const area: FishingArea = a.bbox ? { bbox: a.bbox } : { mpaId: a.mpaId! }; + const r = await fishingEffort(token, { area, from, to, resolution: a.resolution ?? "LOW", byGear: a.byGear, clip: a.clipBBox, maxCells: a.maxCells ?? 0 }); + const where = a.mpaId ? `WDPA MPA ${a.mpaId}` : `bbox ${JSON.stringify(a.bbox)}`; + const top = r.byFlag.slice(0, 3).map((f) => `${f.flag} ${f.hours} h`).join(", "); + const summary = + `${r.totalHours} hours of apparent fishing in ${where}, ${from}..${r.lastDataDate ?? to} (${r.activeDays} active days, ${r.cells} cells at ${r.cellDeg}°)` + + (top ? `; by flag: ${top}` : "") + + (r.byGear?.length ? `; top gear: ${r.byGear[0]!.gear} ${r.byGear[0]!.hours} h` : "") + + (r.clip ? `; ${r.clip.hours} h in the clip box` : "") + + "."; + return { + ...r, + summary, + provenance: { + dataSource: FISHING_SOURCE, + dataset: r.dataset, + attribution: fishingAttribution(Number(to.slice(0, 4))), + licence: FISHING_LICENCE, + request: { endpoint: "POST /v3/4wings/report", area: r.area, dateRange: [from, to], spatial: r.resolution, groupBy: ["FLAG", ...(r.byGear ? ["GEARTYPE"] : [])] }, + retrievedAt: nowIso(), + privacy: "Aggregated effort only (hours per cell/day/flag/gear). No vessel names, IDs, MMSI or call signs are requested or returned.", + disclaimer: + "Apparent fishing effort is inferred by a model from AIS tracks: vessels without AIS (or with it switched off / spoofed) are invisible, " + + "transiting can be misread as fishing, and data lag ~4 days. Fishing inside an MPA may be legal in some zones. Decision-support, not a finding of wrongdoing.", + }, + }; +} + +/** Register marine tools: fishing_activity (Global Fishing Watch apparent fishing effort). */ +export function registerMarineTools(server: McpServer): void { + server.registerTool( + "fishing_activity", + { + title: "Apparent fishing effort (Global Fishing Watch)", + description: + "Hours of apparent fishing (AIS-based, model-inferred) in a bbox or inside a WDPA marine protected area " + + "(mpaId = WDPA site_pid, e.g. '11753' Galápagos Marine Reserve) over a date range — total hours, by flag state, " + + "by gear type, a daily series, and optionally the top grid cells and the hours inside a clip box. Aggregated only: " + + "never names or identifies vessels. Needs GFW_FISHING_TOKEN (non-commercial terms). Data lag ~4 days.", + inputSchema: { + bbox: bboxSchema.optional().describe("[west, south, east, north]; must not cross the antimeridian (split it)."), + mpaId: z.string().regex(/^[0-9]+(_[0-9]+)?$/).optional().describe("WDPA site_pid of a marine protected area (GFW region dataset public-mpa-all)."), + days: z.number().int().min(1).max(366).optional().describe("Window ending `to` (default 30)."), + from: z.string().regex(DATE).optional(), + to: z.string().regex(DATE).optional().describe("Default today (UTC)."), + resolution: z.enum(["LOW", "HIGH"]).optional().describe("LOW = 0.1° cells (default), HIGH = 0.01°."), + byGear: z.boolean().optional().describe("Also break down by gear type (one extra request; default true)."), + clipBBox: bboxSchema.optional().describe("Also sum hours in cells whose centre lies in this box."), + maxCells: z.number().int().min(0).max(2000).optional().describe("Top cells by hours to return (default 0)."), + }, + }, + async (args) => + safe(async () => { + const r = await fishingActivity(args as FishingActivityArgs); + await pushCard({ + id: newId(), + type: "series", + ts: nowIso(), + title: `Fishing effort · ${r.totalHours} h`, + ...(args.bbox ? { bbox: args.bbox as BBox } : {}), + payload: { series: [{ label: "Apparent fishing", unit: "h", points: r.daily.map((d) => ({ t: d.date, v: d.hours })) }], summary: r.summary, source: String(r.provenance.attribution) }, + }); + return r; + }), + ); +} diff --git a/src/tools/naturalvalue.ts b/src/tools/naturalvalue.ts index 83ebbad..665b668 100644 --- a/src/tools/naturalvalue.ts +++ b/src/tools/naturalvalue.ts @@ -11,15 +11,20 @@ import { ORGANISMS, SERVICE_LABEL, assumeBiome, + fetchGeeLandCover, fetchLandCoverMix, + geeDatasetsFor, + geeStatus, valueMix, type BiomeId, type BiomeShare, + type GeeLandCover, } from "../clients/naturalvalue.js"; import { pushCard } from "../dashboard/push.js"; import { OverviewError } from "../errors.js"; import { safe } from "../result.js"; import type { BBox } from "../types.js"; +import { round } from "../series.js"; import { assertBBox, bboxCenter, newId, nowIso } from "../util.js"; import { bboxAreaKm2 } from "./biodiversity.js"; @@ -42,9 +47,11 @@ export function registerNaturalValueTools(server: McpServer): void { description: "Order-of-magnitude value of the work an area's living ecosystems do every year — climate " + "and water regulation, erosion control, food and raw materials, habitat, recreation — so " + - "'alive' has a number next to 'cleared'. For a bbox or place: land-cover mix (CLMS 10 m " + - "global land cover 2020, WorldCover legend, via Copernicus Data Space — needs CDSE creds; " + - "else a stated latitude assumption or the `biome` you pass), area by biome, annual living " + + "'alive' has a number next to 'cleared'. For a bbox or place: land-cover mix — with Earth " + + "Engine configured, land USE from MapBiomas (Brazil, separates pasture from grassland) or " + + "Dynamic World (elsewhere), valuing natural land only and reporting converted ha separately; " + + "else CLMS 10 m global land cover 2020 via Copernicus Data Space (CDSE creds); else a stated " + + "latitude assumption or the `biome` you pass — area by biome, annual living " + "value (low/mid/high, 2020 USD), the value over a horizon (undiscounted and NPV), a " + "per-service breakdown, per-organism reference values (whale, elephant, tree) and a method " + "block with blind spots. BENEFIT TRANSFER from global per-biome unit values (Costanza et al. " + @@ -70,32 +77,56 @@ export function registerNaturalValueTools(server: McpServer): void { let mix: BiomeShare[]; let landCoverUsed: Record; const assumptions: string[] = []; + let geeLc: GeeLandCover | undefined; if (biome) { mix = [{ biome, share: 1 }]; - landCoverUsed = { source: "user", note: `whole area treated as ${BIOMES[biome].label} (biome given)` }; + landCoverUsed = { provider: "user", source: "user", note: `whole area treated as ${BIOMES[biome].label} (biome given)` }; } else if (landCover === "assume") { const a = assumeBiome(bboxCenter(where.bbox)[1]); mix = [{ biome: a.biome, share: 1 }]; assumptions.push(a.assumption); - landCoverUsed = { source: "assumption", note: a.assumption }; + landCoverUsed = { provider: "assumed", source: "assumption", note: a.assumption }; } else { - try { - const lc = await fetchLandCoverMix(where.bbox); - mix = lc.mix; - landCoverUsed = { - source: LAND_COVER.name, - licence: LAND_COVER.licence, - doi: LAND_COVER.doi, - legend: "ESA WorldCover's 11 LCCS classes, but numbered differently (e.g. 50 = herbaceous wetland, 90 = built-up, 100 = water)", - pixels: lc.pixels, - classes: lc.classes, - }; - } catch (err) { - const a = assumeBiome(bboxCenter(where.bbox)[1]); - mix = [{ biome: a.biome, share: 1 }]; - const why = err instanceof Error ? err.message : String(err); - assumptions.push(`land cover unavailable (${why.slice(0, 160)}) — ${a.assumption}`); - landCoverUsed = { source: "assumption", note: assumptions.at(-1) }; + // Earth Engine land USE first (MapBiomas in Brazil, else Dynamic World) — only when configured. + const fallbacks: string[] = []; + const gee = geeStatus(); + if (typeof gee === "string") fallbacks.push(`earth engine: ${gee.slice(0, 160)}`); + if (gee === true) { + for (const ds of geeDatasetsFor(where.bbox)) { + try { + geeLc = await fetchGeeLandCover(where.bbox, ds); + break; + } catch (err) { + fallbacks.push(`${ds}: ${(err instanceof Error ? err.message : String(err)).slice(0, 160)}`); + } + } + } + const fb = fallbacks.length ? { fallbacks } : {}; + if (geeLc) { + mix = geeLc.mix; + const { mix: _m, convertedReferenceMix: _r, ...rest } = geeLc; + landCoverUsed = { ...rest, ...fb }; + } else { + try { + const lc = await fetchLandCoverMix(where.bbox); + mix = lc.mix; + landCoverUsed = { + provider: "clms-cdse", + ...fb, + source: LAND_COVER.name, + licence: LAND_COVER.licence, + doi: LAND_COVER.doi, + legend: "ESA WorldCover's 11 LCCS classes, but numbered differently (e.g. 50 = herbaceous wetland, 90 = built-up, 100 = water)", + pixels: lc.pixels, + classes: lc.classes, + }; + } catch (err) { + const a = assumeBiome(bboxCenter(where.bbox)[1]); + mix = [{ biome: a.biome, share: 1 }]; + const why = err instanceof Error ? err.message : String(err); + assumptions.push(`land cover unavailable (${why.slice(0, 160)}) — ${a.assumption}`); + landCoverUsed = { provider: "assumed", ...fb, source: "assumption", note: assumptions.at(-1) }; + } } } @@ -110,12 +141,25 @@ export function registerNaturalValueTools(server: McpServer): void { ...CLEARED_COMPARATOR, } : null; + // Converted land (Earth Engine providers only): reported, never in the living value. + const converted = geeLc + ? { + ha: geeLc.convertedHa, + sharePct: round((geeLc.convertedHa / areaHa) * 100, 1), + byClass: geeLc.classes.filter((c) => c.use === "converted").map((c) => ({ code: c.code, name: c.name, ha: c.ha, sharePct: c.sharePct, basis: c.basis })), + referenceAnnualUsd: valueMix(geeLc.convertedReferenceMix, areaHa).annualUsd, + referenceNote: + "Costanza et al. 2014 cropland / urban unit values for the converted classes that have one — a reference, NOT included in annualUsd. " + + "Pasture, mosaic, plantation, mining and bare land have no sourced unit value and are 0.", + } + : null; const top = [...v.byBiome].sort((a, b) => b.annualUsd.mid - a.annualUsd.mid)[0]; const summary = `${Math.round(areaHa).toLocaleString("en-US")} ha${where.place ? ` around ${where.place.split(",")[0]}` : ""}: ` + `living ecosystems worth ~${usd(v.annualUsd.mid)}/yr (band ${usd(v.annualUsd.low)}–${usd(v.annualUsd.high)}), ` + `~${usd(v.horizon.undiscountedUsd.mid)} over ${years} yr undiscounted or ${usd(v.horizon.npvUsd.mid)} NPV at ${(rate * 100).toFixed(1)} %` + (top ? `; largest share ${BIOMES[top.biome].label} (${Math.round(top.sharePct)} %)` : "") + + (converted ? `; ${converted.ha.toLocaleString("en-US")} ha (${converted.sharePct} %) is converted land (mostly ${converted.byClass[0]?.name ?? "n/a"}) and is not valued` : "") + `. Benefit transfer, order of magnitude — not a price for sale.`; const pushed = await pushCard({ @@ -130,6 +174,7 @@ export function registerNaturalValueTools(server: McpServer): void { { label: `${years} yr (undiscounted)`, value: usd(v.horizon.undiscountedUsd.mid) }, { label: `${years} yr NPV @ ${(rate * 100).toFixed(1)} %`, value: usd(v.horizon.npvUsd.mid) }, { label: "Area", value: `${Math.round(areaHa).toLocaleString("en-US")} ha` }, + ...(converted ? [{ label: "Converted (not valued)", value: `${converted.ha.toLocaleString("en-US")} ha`, sub: `${converted.sharePct} % · ${String(landCoverUsed.provider)}` }] : []), ...v.byBiome.slice(0, 4).map((b) => ({ label: BIOMES[b.biome].label, value: `${Math.round(b.sharePct)} %`, sub: `${usd(b.annualUsd.mid)}/yr` })), ...v.services.slice(0, 3).map((s) => ({ label: SERVICE_LABEL[s.service], value: `${usd(s.annualUsd)}/yr` })), ], @@ -147,6 +192,7 @@ export function registerNaturalValueTools(server: McpServer): void { ...v.horizon, sensitivity: [0, 0.014, 0.02, 0.03, 0.07].map((r) => ({ discountRate: r, npvUsdMid: Math.round(v.annualUsd.mid * annuityFactor(years, r)) })), }, + ...(converted ? { converted } : {}), ...(cleared ? { clearedComparator: cleared } : {}), services: v.services, summary, @@ -157,7 +203,8 @@ export function registerNaturalValueTools(server: McpServer): void { method: { unit: "2020 US dollars", formula: - "annual = Σ_biome area_ha × unit value (USD/ha/yr, low/mid/high); horizon undiscounted = annual × T; " + + (geeLc ? "annual = Σ over NATURAL land-cover classes only (converted land = 0) of " : "annual = Σ_biome ") + + "area_ha × unit value (USD/ha/yr, low/mid/high); horizon undiscounted = annual × T; " + "NPV = annual × (1 − (1+r)^−T) / r (flows at year-end, constant real value)", transfer: "benefit transfer: global per-biome mean unit values (Costanza et al. 2014, Table 2; de Groot et al. 2012) moved to this place without local calibration; 2007 → 2020 USD via US CPI-U", band: "low/high = the per-biome band stated in the registry entry (see byBiome[].source); treat the mid as an order of magnitude", @@ -169,8 +216,7 @@ export function registerNaturalValueTools(server: McpServer): void { blindSpots: [ "Benefit transfer: a global average hectare of 'tropical forest' is not this hectare — no local calibration, condition, degradation or fragmentation is accounted for.", "The unit values are means of a skewed literature (few studies, many regions missing); the true local value can be an order of magnitude off either way.", - "Land cover is a 2020 snapshot at 10 m sampled at ≤256 px; recent clearing, cloud-era errors and mixed pixels shift the mix. Water is valued as lakes/rivers even where it is sea.", - "Pasture is not grassland: the land-cover map cannot tell cattle pasture on cleared forest from natural grassland, and both get Costanza's grass/rangeland value (~$5,200/ha/yr) — in deforestation frontiers this overstates the 'alive' total and understates the gap between forest and cleared land.", + ...(geeLc ? geeBlindSpots(geeLc) : CLMS_BLIND_SPOTS), "Plural values are not captured: sacred, relational and intrinsic values (IPBES 2022) and Indigenous stewardship have no dollar column here — the number is a floor for one kind of value, not the worth of the place.", "Distribution: who benefits (downstream towns, the global climate) is not who pays or who owns the land; the total hides that.", "Not a market price: nobody will pay this for the land, and clearing does not remove all of it at once (some services persist, some are lost for decades).", @@ -183,6 +229,29 @@ export function registerNaturalValueTools(server: McpServer): void { ); } +const CLMS_BLIND_SPOTS = [ + "Land cover is a 2020 snapshot at 10 m sampled at ≤256 px; recent clearing, cloud-era errors and mixed pixels shift the mix. Water is valued as lakes/rivers even where it is sea.", + "Pasture is not grassland: the land-cover map cannot tell cattle pasture on cleared forest from natural grassland, and both get Costanza's grass/rangeland value (~$5,200/ha/yr) — in deforestation frontiers this overstates the 'alive' total and understates the gap between forest and cleared land.", +]; + +/** Honest limits of the Earth Engine land-use providers. */ +function geeBlindSpots(lc: GeeLandCover): string[] { + const common = + "Converted land (pasture, crops, mosaic, urban, mining, bare) counts 0 in the living value — it still does some ecosystem work (a degraded pasture stores some carbon and water), so the total is a floor, not the loss if the rest were cleared. " + + "Savanna, shrub and other natural non-forest vegetation get Costanza's grass/rangeland value; water is valued as lakes/rivers even where it is sea."; + if (lc.provider === "mapbiomas-ee") { + return [ + `Land use is MapBiomas Brazil Collection 10 for ${lc.year} (annual, 30 m, computed at ${lc.scaleM} m): it lags today by the year(s) since ${lc.year}, so clearing since then is not in the mix. MapBiomas' own accuracy varies by biome and class (pasture vs. natural grassland is hardest in the Cerrado/Pampa).`, + common, + ]; + } + return [ + `Land cover is Dynamic World V1, the per-pixel MODE of near-real-time labels over ${lc.window?.from}…${lc.window?.to} (computed at ${lc.scaleM} m). Dynamic World is probabilistic — each label is a model's most likely class, so label noise, cloud gaps and seasonal flooding shift the mix.`, + "Dynamic World's 'grass' class includes pasture, parks and lawns as well as natural grassland, and 'trees' includes plantations and orchards — outside Brazil, pasture on cleared forest is still valued as grassland (~$5,200/ha/yr). Only crops, built-up and bare land are counted as converted.", + common, + ]; +} + async function resolveBBox(bbox: number[] | undefined, place: string | undefined): Promise<{ bbox: BBox; place?: string }> { if (bbox) { assertBBox(bbox as BBox); diff --git a/src/tools/weather.ts b/src/tools/weather.ts new file mode 100644 index 0000000..4badb13 --- /dev/null +++ b/src/tools/weather.ts @@ -0,0 +1,168 @@ +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { z } from "zod"; +import { events as eonetEvents } from "../clients/nasa.js"; +import { OPEN_METEO_ATTRIBUTION } from "../clients/openmeteo.js"; +import { activeStorms, categoryLabel, matchEonet, stormTouchesBBox, type Storm } from "../clients/storms.js"; +import { weatherReport, type WeatherReport } from "../clients/weather.js"; +import { pushCard } from "../dashboard/push.js"; +import { safe } from "../result.js"; +import type { BBox, EonetEvent } from "../types.js"; +import { assertBBox, isoDate, newId, nowIso } from "../util.js"; + +const latSchema = z.number().min(-90).max(90).describe("Latitude of the point."); +const lonSchema = z.number().min(-180).max(180).describe("Longitude of the point."); + +/** One-line plain-language reading of a weather report (also the card summary). */ +export function weatherSummary(r: WeatherReport, place?: string): string { + const where = place ?? `(${r.lat}, ${r.lon})`; + const today = r.days.find((d) => d.kind === "today"); + const hottest = r.days.filter((d) => d.kind === "forecast" && d.tmaxC != null).sort((a, b) => b.tmaxC! - a.tmaxC!)[0]; + const wettest = r.days.filter((d) => d.precipMm != null).sort((a, b) => b.precipMm! - a.precipMm!)[0]; + const anom = (a: number | null) => (a == null ? "" : `, ${a >= 0 ? "+" : ""}${a} °C vs ${r.normals.period} normal`); + return ( + `${where}: now ${r.current.temperatureC ?? "?"} °C (feels ${r.current.apparentC ?? "?"} °C), wind ${r.current.windKmh ?? "?"} km/h. ` + + (today ? `Today max ${today.tmaxC ?? "?"} °C${anom(today.tmaxAnomalyC)}, rain ${today.precipMm ?? "?"} mm. ` : "") + + (hottest ? `Hottest forecast day ${hottest.date}: ${hottest.tmaxC} °C${anom(hottest.tmaxAnomalyC)}. ` : "") + + (wettest && (wettest.precipMm ?? 0) >= 20 ? `Wettest day ${wettest.date}: ${wettest.precipMm} mm. ` : "") + ).trim(); +} + +/** Storms as one GeoJSON FeatureCollection (cones, tracks, positions) for map layers. */ +export function stormsGeoJson(storms: Storm[]): { type: "FeatureCollection"; features: unknown[] } { + const features: unknown[] = []; + for (const s of storms) { + const props = { id: s.id, name: s.name, source: s.source, category: s.category, peakCategory: s.peakCategory, maxWindKt: s.maxWindKt, classification: s.classification }; + if (s.cone) features.push({ type: "Feature", geometry: s.cone, properties: { ...props, part: "cone" } }); + if (s.track.length >= 2) features.push({ type: "Feature", geometry: { type: "LineString", coordinates: s.track.map((p) => [p.lon, p.lat]) }, properties: { ...props, part: "track" } }); + if (s.position) features.push({ type: "Feature", geometry: { type: "Point", coordinates: [s.position.lon, s.position.lat] }, properties: { ...props, part: "position" } }); + } + return { type: "FeatureCollection", features }; +} + +/** Register weather tools: weather_now (Open-Meteo + ERA5 normals), storms (NHC/CPHC + GDACS + EONET). */ +export function registerWeatherTools(server: McpServer): void { + server.registerTool( + "weather_now", + { + title: "Weather now + 7-day forecast vs normal (Open-Meteo, ERA5 1991–2020)", + description: + "Current weather and daily max/min temperature, feels-like (apparent) max, precipitation and wind for " + + "the past days, today and the next 7 days at any point — from the Open-Meteo forecast API (keyless; " + + "ECMWF/DWD/NOAA model blend) — each day's max compared with the ERA5 1991–2020 normal for that time of " + + "year (anomaly in °C), plus ERA5's own independent reading of the elapsed days (~6-day latency). Use " + + "geo_resolve first for place names. Posts a chart card.", + inputSchema: { + lat: latSchema, + lon: lonSchema, + place: z.string().max(120).optional().describe("Label for the summary (e.g. 'Delhi')."), + pastDays: z.number().int().min(0).max(14).optional().describe("Elapsed days to include (default 7)."), + forecastDays: z.number().int().min(1).max(16).optional().describe("Days including today (default 7)."), + normals: z.boolean().optional().describe("Compute ERA5 1991–2020 normals/anomalies (default true; ~30 small archive calls, memoized)."), + }, + }, + async ({ lat, lon, place, pastDays, forecastDays, normals }) => + safe(async () => { + const r = await weatherReport(lat, lon, { pastDays, forecastDays, normals }); + const summary = weatherSummary(r, place); + const pushed = await pushCard({ + id: newId(), + type: "series", + ts: nowIso(), + title: `Weather${place ? ` · ${place}` : ""} · now ${r.current.temperatureC ?? "?"} °C`, + bbox: [lon - 0.5, Math.max(-90, lat - 0.5), lon + 0.5, Math.min(90, lat + 0.5)], + payload: { + series: [ + { label: "Daily max", unit: "°C", points: r.days.map((d) => ({ t: d.date, v: d.tmaxC })) }, + { label: `Normal ${r.normals.period}`, unit: "°C", points: r.days.map((d) => ({ t: d.date, v: d.tmaxNormalC })) }, + ], + summary, + source: `Open-Meteo forecast + ERA5 via ${OPEN_METEO_ATTRIBUTION}`, + }, + }); + return { ...r, place: place ?? null, summary, dashboard: pushed ? "pushed" : "dashboard offline" }; + }), + ); + + server.registerTool( + "storms", + { + title: "Active tropical cyclones (NHC/CPHC + GDACS, EONET cross-check)", + description: + "Every active tropical cyclone, keyless: NOAA NHC/CPHC advisories for the Atlantic and eastern/central " + + "Pacific (position, intensity, Saffir–Simpson category, 5-day forecast track points, forecast cone) and " + + "GDACS for all other basins (Bay of Bengal, West Pacific, South Indian Ocean, Australia — cone + track). " + + "Each storm is cross-checked against NASA EONET 'Severe Storms'. Optional bbox keeps storms whose cone " + + "or track touches it; minCategory filters by current or forecast-peak category. Cone = uncertainty of " + + "the centre track, not storm size and not a landfall forecast. Posts an events card with the cones.", + inputSchema: { + bbox: z.tuple([z.number(), z.number(), z.number(), z.number()]).optional().describe("[west, south, east, north] — keep storms whose cone/track touches it."), + minCategory: z.number().int().min(0).max(5).optional().describe("Minimum Saffir–Simpson category (current or forecast peak). 0 = include tropical storms/depressions (default)."), + eonet: z.boolean().optional().describe("Cross-check against NASA EONET severe storms (default true)."), + }, + }, + async ({ bbox, minCategory, eonet }) => + safe(async () => { + const box = bbox as BBox | undefined; + if (box) assertBBox(box); + const { storms: all, sources } = await activeStorms(isoDate(0)); + const minCat = minCategory ?? 0; + const storms = all.filter((s) => (box ? stormTouchesBBox(s, box) : true) && Math.max(s.category ?? 0, s.peakCategory ?? 0) >= minCat); + let eonetList: EonetEvent[] = []; + let eonetStatus = "skipped"; + if (eonet !== false) { + try { + eonetList = await eonetEvents({ status: "open", category: "severeStorms", days: 30, limit: 100 }); + eonetStatus = "ok"; + } catch (e) { + eonetStatus = e instanceof Error ? e.message : String(e); + } + } + const out = storms.map((s) => { + const m = eonetStatus === "ok" ? matchEonet(s, eonetList) : null; + return { ...s, eonet: m ? { id: m.id, title: m.title } : null }; + }); + const geojson = stormsGeoJson(storms); + const label = (s: Storm) => `${s.name} (${categoryLabel(s.category, s.classification)}${s.maxWindKt != null ? `, ${s.maxWindKt} kt` : ""})`; + const summary = + out.length === 0 + ? `No active tropical cyclones${box ? " touching the bbox" : ""}${minCat ? ` at category ≥ ${minCat}` : ""}.` + : `${out.length} active tropical cyclone(s): ${out.map(label).join("; ")}.`; + const pushed = await pushCard({ + id: newId(), + type: "events", + ts: nowIso(), + title: `${out.length} active tropical cyclone(s)`, + bbox: box, + payload: { + events: out.map((s) => ({ + id: s.id, + title: s.name, + category: "Severe Storms", + coordinates: s.position ? [s.position.lon, s.position.lat] : null, + lastDate: s.advisory.issued, + magnitude: `${categoryLabel(s.category, s.classification)}${s.maxWindKt != null ? ` · ${s.maxWindKt} kt` : ""}`, + link: s.advisory.url ?? "", + })), + stormGeoJson: geojson, + }, + }); + return { + count: out.length, + storms: out, + geojson, + summary, + provenance: { + dataSource: "NOAA/NWS NHC & CPHC (CurrentStorms.json + tropical weather summary MapServer); GDACS (UN OCHA / EC JRC) for other basins; NASA EONET cross-check", + feeds: { ...sources, eonet: eonetStatus }, + retrievedAt: nowIso(), + disclaimer: + "Decision-support, not decision. Advisories are forecasts. The cone is the probable track of the " + + "centre (≈2/3 of historical errors), not the storm's size or impact area; hazards (surge, rain, wind) " + + "extend well outside it. GDACS categories come from wind speeds some agencies average over 10 min " + + "(reads lower than 1-min). Official warnings come only from national met services.", + }, + dashboard: pushed ? "pushed" : "dashboard offline", + }; + }), + ); +} diff --git a/src/tools/worldpulse.ts b/src/tools/worldpulse.ts index edbc5ec..3670f9f 100644 --- a/src/tools/worldpulse.ts +++ b/src/tools/worldpulse.ts @@ -20,6 +20,8 @@ export interface PulseRow { status: "ok" | "unavailable"; error?: string; latest?: { t: string; v: number | null } | null; + /** The valid point before `latest` (year-over-year comparisons), or null. */ + previous?: { t: string; v: number | null } | null; direction?: Assessment["direction"]; pace?: Assessment["pace"]; pctPerDecade?: number | null; @@ -40,6 +42,7 @@ export function pulseRow(ind: Indicator, points: { t: string; v: number | null } licence: ind.licence, status: "ok", latest: a.latest, + previous: points.filter((p) => p.v !== null).at(-2) ?? null, direction: a.direction, pace: a.pace, pctPerDecade: a.pctPerDecade, diff --git a/src/watch/export.ts b/src/watch/export.ts index fc860ea..e59c319 100644 --- a/src/watch/export.ts +++ b/src/watch/export.ts @@ -7,10 +7,18 @@ // api/ledger.json, api/ledger/.json, feed.json, feed.geojson — LedgerView's own bodies // ledger/{checkpoint,pub,entries.jsonl,tile/**} — the verification surface // api/stats.json counts + published false-positive rate per rule +// api/map.json the interactive map's cases + watched places (src/watch/map-data.ts) +// api/metrics.json the landing's Metrics mode: totals, timeline, stakes (src/watch/metrics.ts) +// api/situation.json, api/situation/.json the daily Situation (level by rules; src/watch/situation.ts) // api/pulse.json world_pulse snapshot (fresh, else cached, else omitted) +// api/storms.json active tropical cyclones as GeoJSON (live exports only, best-effort) +// api/marine/{fishing,ships}.json GFW fishing-effort grid / AIS ship density — only when the +// runner has GFW_FISHING_TOKEN / AISSTREAM_KEY (src/watch/marine-export.ts) // developers/index.html verify-it-yourself commands, feeds, API, schema (kept off the landing) // schema/finding-event.v1.json, trust.html (+ TRUST.md), sitemap.xml, robots.txt -// assets/**, og.png the built site bundle (dist/site, `pnpm build`) +// assets/**, og.png, favicon.{ico,svg}, apple-touch-icon.png, icon-{192,512}.png +// the built site bundle (dist/site, `pnpm build`; icons: scripts/site-icons.mjs) +// site.webmanifest name + icons for home screens, from SITE // // Every link is relative; absolute URLs appear only where the web demands them (canonical, // og:*, JSON-LD, sitemap), all from --base-url / SITE.baseUrl. The signing key (`ledger.key`) @@ -23,8 +31,15 @@ import { LedgerView } from "../dashboard/ledger-view.js"; import { PUBLIC_STATUSES, STATUSES, type Finding, type Status } from "../ledger/schema.js"; import { ledgerDir as defaultLedgerDir } from "../config.js"; import { SITE } from "../site.config.js"; +import { readPublicReplies } from "../replies/review.js"; import { readHeartbeat, type Heartbeat } from "./journal.js"; -import { casePage, developersPage, FALLBACK_TEMPLATE, fillTemplate, landingPage, robots, sitemap, trustPage, watchIndexPage, type CaseData, type Ctx } from "./site-render.js"; +import { mapData } from "./map-data.js"; +import { computeMetrics } from "./metrics.js"; +import { marineSnapshots } from "./marine-export.js"; +import { newsForCases } from "./news.js"; +import { listSituations } from "./situation.js"; +import { CallBudget, gdeltCapFromEnv } from "./quota.js"; +import { casePage, developersPage, FALLBACK_TEMPLATE, NEWS_NOTE, fillTemplate, landingPage, robots, sitemap, trustPage, watchIndexPage, webManifest, type CaseData, type Ctx } from "./site-render.js"; const PKG_ROOT = fileURLToPath(new URL("../../", import.meta.url)); // dist/watch → root, src/watch → root const MARKER = ".earthdeck-site"; @@ -148,15 +163,26 @@ export interface ExportOptions { ledgerDir?: string; /** Public origin for canonical/OG/JSON-LD/sitemap. Default SITE.baseUrl; null = none (no sitemap). */ baseUrl?: string | null; - /** Accepted for compatibility (the runner passes it) and ignored: the public site is anonymous. */ + /** Accepted for compatibility and ignored (off by default): the public site is anonymous. Replies go through the reply wall. */ contact?: string; + /** The reply wall's intake URL (`POST /reply`, the stack's ReplyUrl output). Default SITE.replyEndpoint; null = no form. */ + replyUrl?: string | null; + /** Local mirror of the reply wall (`public//.json` are shown). Default /../replies. */ + repliesDir?: string; /** Built site bundle (index.html template, assets/, og.png). Default dist/site; null = unstyled fallback. */ siteDir?: string | null; /** "auto": fetch a fresh world_pulse, fall back to the cache; "cache": cache only; "off": omit. */ pulse?: "auto" | "cache" | "off"; pulseCache?: string; pulseTimeoutMs?: number; + /** Marine layers (needs GFW_FISHING_TOKEN / AISSTREAM_KEY): "auto" refreshes stale caches, "cache" reads them, "off" (default here; the CLI passes "auto") omits. */ + marine?: "auto" | "cache" | "off"; + marineCacheDir?: string; trustFile?: string; + /** "In the news" headlines from GDELT for decided cases: "auto" fetches (paced, capped, cached + * 12 h), "cache" reads the cache only, "off" (default here; the CLI passes "auto") omits. */ + news?: "auto" | "cache" | "off"; + newsCacheDir?: string; /** Overwrite a non-empty directory that was not written by a previous export. */ force?: boolean; log?: (s: string) => void; @@ -168,6 +194,9 @@ export interface ExportReport { findings: number; publicFindings: number; pulse: "fresh" | "cached" | "none"; + marine: { fishing: boolean; ships: boolean }; + /** Cases that got an "In the news" section. */ + news: number; web: boolean; trust: boolean; sitemap: boolean; @@ -182,6 +211,10 @@ export async function exportSite(opts: ExportOptions): Promise { const rawBase = opts.baseUrl === undefined ? SITE.baseUrl : opts.baseUrl; const baseUrl = rawBase ? rawBase.replace(/\/+$/, "") : null; if (baseUrl && !/^https?:\/\/[^\s/"'<>]+(\/[^\s"'<>]*)?$/.test(baseUrl)) throw new Error(`--base-url must be an http(s) URL, got ${rawBase}`); + const rawReply = opts.replyUrl === undefined ? SITE.replyEndpoint : opts.replyUrl; + const replyEndpoint = rawReply ? `${rawReply.replace(/\/+$/, "")}/reply` : null; + if (replyEndpoint && !/^https:\/\/[^\s/"'<>]+(\/[^\s"'<>]*)?$/.test(replyEndpoint)) throw new Error(`--reply-url must be an https URL, got ${rawReply}`); + const repliesDir = opts.repliesDir ?? join(dirname(resolve(lDir)), "replies"); prepareOut(out, opts.force === true); const write = (rel: string, body: string | Buffer) => { @@ -229,10 +262,47 @@ export async function exportSite(opts: ExportOptions): Promise { now, ); write("api/stats.json", JSON.stringify(stats)); + write("api/map.json", JSON.stringify(mapData(findings, now))); + write("api/metrics.json", JSON.stringify(computeMetrics(findings, stats, now))); + // The daily Situation (written by the analyst into /situation/): latest + one file per day. + // A draft that failed the checks or the reviewer stays in the ledger dir, never on the site. + const situations = listSituations(lDir).map(({ draft: _draft, ...r }) => r); + const situation = situations[0] ?? null; + if (situation) write("api/situation.json", JSON.stringify(situation)); + for (const r of situations) write(`api/situation/${r.date}.json`, JSON.stringify(r)); // ---- world pulse ---- const pulse = await pulseSnapshot(opts.pulse ?? "auto", opts.pulseCache ?? join(dirname(resolve(lDir)), "pulse.json"), opts.pulseTimeoutMs ?? 45_000, log); if (pulse.json) write("api/pulse.json", pulse.json); + // Active tropical cyclones for the map's Live layers — live exports only, best-effort. + if ((opts.pulse ?? "auto") === "auto") { + const storms = await stormsSnapshot(now, Math.min(opts.pulseTimeoutMs ?? 45_000, 20_000), log); + if (storms) write("api/storms.json", storms); + } + + // ---- marine layers (server-side keys; each file only if the runner could produce it) ---- + const marine = await marineSnapshots({ + mode: opts.marine ?? "off", + cacheDir: opts.marineCacheDir ?? join(dirname(resolve(lDir)), "marine"), + watchlist: join(PKG_ROOT, "watchlists", "marine.json"), + now, + log, + }); + if (marine.fishing) write("api/marine/fishing.json", marine.fishing); + if (marine.ships) write("api/marine/ships.json", marine.ships); + + // ---- in the news (context only; never evidence) ---- + const newsMode = opts.news ?? "off"; + const news = + newsMode === "off" + ? new Map() + : await newsForCases(findings, { + cacheDir: opts.newsCacheDir ?? join(resolve(lDir), "news"), + budget: new CallBudget(newsMode === "auto" ? gdeltCapFromEnv() : 0), + now, + log, + }); + for (const [id, items] of news) write(`api/news/${id}.json`, JSON.stringify({ generatedAt: now.toISOString(), note: NEWS_NOTE, items })); const schemaFile = join(PKG_ROOT, "schema", "finding-event.v1.json"); if (existsSync(schemaFile)) write("schema/finding-event.v1.json", readFileSync(schemaFile)); @@ -250,19 +320,30 @@ export async function exportSite(opts: ExportOptions): Promise { // ---- pages ---- const ctx = (depth: number, path: string): Ctx => ({ depth, path, baseUrl, stats }); const published = findings.filter((f) => PUBLIC_STATUSES.includes(f.status)); - write("index.html", fillTemplate(tpl, 0, "landing", landingPage(ctx(0, ""), findings))); + write("index.html", fillTemplate(tpl, 0, "landing", landingPage(ctx(0, ""), findings, situation))); write("developers/index.html", fillTemplate(tpl, 1, "developers", developersPage(ctx(1, "developers/")))); write("watch/index.html", fillTemplate(tpl, 1, "watch", watchIndexPage(ctx(1, "watch/"), findings))); + let replyCount = 0; for (const d of cases) { const path = `watch/case/${d.finding.findingId}/`; - write(`${path}index.html`, fillTemplate(tpl, 3, "case", casePage(ctx(3, path), d))); + const isPublic = PUBLIC_STATUSES.includes(d.finding.status); + // Only public cases show replies (and take new ones); the reviewer only accepts on those anyway. + const replies = isPublic ? readPublicReplies(repliesDir, d.finding.findingId) : []; + if (replies.length) { + write(`api/replies/${d.finding.findingId}.json`, JSON.stringify({ caseId: d.finding.findingId, reviewedBy: "second model", replies: replies.map(({ id, text, role, receivedAt }) => ({ id, text, role, receivedAt })) })); + replyCount += replies.length; + } + write(`${path}index.html`, fillTemplate(tpl, 3, "case", casePage(ctx(3, path), d, { replies, replyEndpoint: isPublic && d.finding.status !== "retracted" ? replyEndpoint : null, news: news.get(d.finding.findingId) }))); } + if (replyCount) log(` replies: ${replyCount} public repl${replyCount === 1 ? "y" : "ies"} shown`); if (trust) { const md = readFileSync(trustFile, "utf8"); write("TRUST.md", md); write("trust.html", fillTemplate(tpl, 0, "trust", trustPage(ctx(0, "trust.html"), md))); } + write("site.webmanifest", webManifest()); + // ---- crawlers ---- write("robots.txt", robots(baseUrl)); if (baseUrl) { @@ -282,6 +363,8 @@ export async function exportSite(opts: ExportOptions): Promise { findings: findings.length, publicFindings: stats.cases.public, pulse: pulse.kind, + marine: { fishing: Boolean(marine.fishing), ships: Boolean(marine.ships) }, + news: news.size, web, trust, sitemap: baseUrl !== null, @@ -344,6 +427,23 @@ async function pulseSnapshot( return { kind: "none" }; } +async function stormsSnapshot(now: Date, timeoutMs: number, log: (s: string) => void): Promise { + let timer: NodeJS.Timeout | undefined; + try { + const [{ activeStorms }, { stormsGeoJson }] = await Promise.all([import("../clients/storms.js"), import("../tools/weather.js")]); + const timeout = new Promise((_, rej) => { + timer = setTimeout(() => rej(new Error(`timed out after ${timeoutMs} ms`)), timeoutMs); + }); + const r = await Promise.race([activeStorms(now.toISOString().slice(0, 10)), timeout]); + return JSON.stringify({ generatedAt: now.toISOString(), ...stormsGeoJson(r.storms) }); + } catch (e) { + log(` storms: ${(e as Error).message} — the cyclone layer is left out`); + return null; + } finally { + clearTimeout(timer); + } +} + function listFiles(root: string, rel = ""): string[] { const out: string[] = []; for (const e of readdirSync(join(root, rel), { withFileTypes: true })) { @@ -365,8 +465,8 @@ export async function runExportCli(args: string[]): Promise { if (!out) { process.stdout.write( [ - "usage: earthdeck watch export --out [--base-url https://…]", - " [--no-pulse | --pulse-cache ] [--trust TRUST.md] [--force]", + "usage: earthdeck watch export --out [--base-url https://…] [--reply-url https://…] [--replies ]", + " [--no-pulse | --pulse-cache ] [--no-marine] [--no-news] [--trust TRUST.md] [--force]", `Writes the public ${SITE.name} site (landing + case pages + ledger + feeds) as static files.`, `--base-url defaults to ${SITE.baseUrl} (src/site.config.ts); it drives canonical URLs, og:*, JSON-LD and sitemap.xml.`, "", @@ -379,15 +479,19 @@ export async function runExportCli(args: string[]): Promise { out, baseUrl: opt("--base-url"), contact: opt("--contact"), + replyUrl: opt("--reply-url"), + repliesDir: opt("--replies"), pulse: args.includes("--no-pulse") ? "off" : "auto", pulseCache: opt("--pulse-cache"), + marine: args.includes("--no-marine") ? "off" : "auto", + news: args.includes("--no-news") ? "off" : "auto", trustFile: opt("--trust"), force: args.includes("--force"), log: (s) => process.stdout.write(`${s}\n`), }); process.stdout.write( `exported ${report.findings} findings (${report.publicFindings} public) → ${report.out}\n` + - ` ${report.files.length} files · world pulse: ${report.pulse} · web bundle: ${report.web ? "yes" : "MISSING"} · TRUST.md: ${report.trust ? "rendered" : "not found"} · sitemap: ${report.sitemap ? "yes" : "no"}\n` + + ` ${report.files.length} files · world pulse: ${report.pulse} · marine: fishing ${report.marine.fishing ? "yes" : "no"}, ships ${report.marine.ships ? "yes" : "no"} · news: ${report.news} cases · web bundle: ${report.web ? "yes" : "MISSING"} · TRUST.md: ${report.trust ? "rendered" : "not found"} · sitemap: ${report.sitemap ? "yes" : "no"}\n` + ` preview: npx -y serve ${report.out}\n`, ); } diff --git a/src/watch/kernel.ts b/src/watch/kernel.ts index 6ed0ed4..c57b4d5 100644 --- a/src/watch/kernel.ts +++ b/src/watch/kernel.ts @@ -259,7 +259,7 @@ export async function sweep(o: SweepOptions): Promise { observedAt: candidate.observedAt, evidence: candidate.evidence, context, - blindSpots: rule.blindSpots, + blindSpots: rule.blindSpotsFor?.({ ...rule.defaults, ...params }) ?? rule.blindSpots, at: now, }; if (report.dryRun) { diff --git a/src/watch/map-data.ts b/src/watch/map-data.ts new file mode 100644 index 0000000..a422e00 --- /dev/null +++ b/src/watch/map-data.ts @@ -0,0 +1,180 @@ +// `api/map.json` — the one file the public site's interactive map reads. A compact projection of +// the ledger: per case its plain headline, status group, case type, topic, whether it is about the +// whole planet, a point, its outline and the dates the evidence overlays need; plus the watched +// places for the map's keyless search. Shapes mirror web/src/site/map/model.ts (MapCase, MapPlace, +// MapData). +// +// Deliberately coarse where the rules are: a fire case is its cluster centroid only — no +// detection points — because the people nearest a fire in Indigenous land must not get a +// precise public pin (see src/watch/rules/firesInProtected.ts). + +import { PUBLIC_STATUSES, type Finding, type Geometry } from "../ledger/schema.js"; +import { livingValueOf } from "./export.js"; +import { areaHaOf, fmtUsd, PLAIN_STATUS, plainArea, plainTitle } from "./site-render.js"; + +export type MapGroup = "published" | "checking" | "dropped"; +export type MapKind = "forest" | "fire" | "flaring" | "flaring-stopped" | "methane" | "other"; +/** What a case is about, in a reader's words — the Cases filter chips and the marker ring. */ +export type MapTopic = "forest" | "fire" | "flaring" | "methane" | "ocean" | "ice" | "air" | "weather" | "trend" | "good" | "quake" | "other"; + +export interface MapCase { + id: string; + title: string; + status: string; + statusLabel: string; + group: MapGroup; + kind: MapKind; + topic: MapTopic; + /** About the whole planet (world trend, sea ice, ENSO): shown in the Planet panel, never as a map marker. */ + global: boolean; + place: string | null; + /** Place · size · value of nature at stake — the same words the case rows use. */ + meta: string; + lon: number; + lat: number; + bbox: [number, number, number, number]; + observedAt: string; + /** Earliest evidence datetime — the "before" side of the imagery overlay. */ + firstSeen: string; + geometry: Geometry; + /** The watched indicator (indicator rules only) — ties a planet case to its world-pulse row. */ + indicator?: string; + /** Extra public points (registry sites where flaring stopped). Never fire detections. */ + points?: [number, number][]; +} + +export interface MapPlace { + id: string; + name: string; + lon: number; + lat: number; + bbox: [number, number, number, number]; +} + +export interface MapData { + v: 1; + generatedAt: string; + cases: MapCase[]; + places: MapPlace[]; +} + +const KIND_BY_RULE: Record = { + forest_loss: "forest", + fires_in_protected: "fire", + flaring: "flaring", + flaring_stopped: "flaring-stopped", + methane_anomaly: "methane", +}; + +const TOPIC_BY_RULE: Record = { + forest_loss: "forest", + fires_in_protected: "fire", + flaring: "flaring", + flaring_stopped: "good", + methane_anomaly: "methane", + weather_extreme: "weather", + indicator_trend: "trend", + improvement: "good", + mpa_fishing: "ocean", +}; +const TOPIC_BY_INDICATOR: Record = { + sea_ice: "ice", + marine_heatwave: "ocean", + enso: "ocean", + air_quality: "air", + river_discharge: "weather", + quake: "quake", +}; +/** Indicators whose "place" stands for the whole planet. */ +const GLOBAL_INDICATORS = new Set(["sea_ice", "enso"]); + +/** The indicator an indicator rule watched (`params.indicator` on its evidence), if any. */ +export function indicatorOf(f: Pick): string | null { + for (const e of f.evidence) { + const v = e.method.params?.indicator; + if (typeof v === "string" && v) return v; + } + return null; +} + +/** + * Pure: a case's topic from its rule and, for threshold rules, the indicator it watched; any case + * tagged `improvement` is good news. "other" means an unmapped rule — the export test fails on it. + */ +export function topicOf(rule: string, indicator: string | null, tags: readonly string[] = []): MapTopic { + if (tags.includes("improvement")) return "good"; + if (rule === "indicator_threshold") return (indicator ? TOPIC_BY_INDICATOR[indicator] : undefined) ?? "other"; + return TOPIC_BY_RULE[rule] ?? "other"; +} + +/** + * Pure: is a case about the whole planet rather than a place? World-trend AOIs (`wp-…`), any box + * spanning half the globe or more (sea ice), and planet-scale indicators (ENSO). + */ +export function isGlobalCase(x: { bbox: readonly number[]; aoiId?: string | null; indicator?: string | null }): boolean { + if (x.aoiId?.startsWith("wp-")) return true; + if (x.indicator && GLOBAL_INDICATORS.has(x.indicator)) return true; + const [w, , e] = x.bbox; + return typeof w === "number" && typeof e === "number" && e - w >= 180; +} + +export function groupOf(status: string): MapGroup { + if ((PUBLIC_STATUSES as readonly string[]).includes(status)) return "published"; + if (status === "candidate" || status === "confirmed") return "checking"; + return "dropped"; +} + +const r4 = (v: number) => Math.round(v * 1e4) / 1e4; +const finite = (b: readonly number[]) => b.length === 4 && b.every(Number.isFinite); + +function stoppedSites(f: Finding): [number, number][] | undefined { + const raw = f.evidence.find((e) => e.method.name === "flaring_stopped")?.method.params?.stoppedSites; + if (!Array.isArray(raw)) return undefined; + const pts = raw.filter((p): p is [number, number] => Array.isArray(p) && p.length === 2 && p.every((x) => typeof x === "number" && Number.isFinite(x))); + return pts.length ? pts.slice(0, 200).map(([x, y]) => [r4(x), r4(y)]) : undefined; +} + +/** Pure: the map's data file from the ledger's findings. */ +export function mapData(findings: readonly Finding[], now = new Date()): MapData { + const cases: MapCase[] = []; + const places = new Map(); + for (const f of findings) { + if (!finite(f.bbox)) continue; + const [w, s, e, n] = f.bbox; + const ha = areaHaOf(f); + const lv = livingValueOf(f); + const place = f.aoi?.name ?? null; + const ev = [...f.evidence, ...(f.confirmed ? [f.confirmed.signal] : [])].map((x) => x.datetime).filter(Boolean).sort(); + const pts = f.rule.name === "flaring_stopped" ? stoppedSites(f) : undefined; + const indicator = indicatorOf(f); + const global = isGlobalCase({ bbox: f.bbox, aoiId: f.aoi?.id, indicator }); + cases.push({ + id: f.findingId, + title: plainTitle(f), + status: f.status, + statusLabel: PLAIN_STATUS[f.status] ?? f.status.replace(/_/g, " "), + group: groupOf(f.status), + kind: KIND_BY_RULE[f.rule.name] ?? "other", + topic: topicOf(f.rule.name, indicator, f.aoi?.tags ?? []), + global, + place, + meta: [place, ha !== null ? plainArea(ha) : "", lv !== null ? `nature’s work worth ≈ ${fmtUsd(lv)} a year` : ""].filter(Boolean).join(" · "), + lon: r4((w + e) / 2), + lat: r4((s + n) / 2), + bbox: [r4(w), r4(s), r4(e), r4(n)], + observedAt: f.observedAt, + firstSeen: ev[0] ?? f.observedAt, + geometry: f.geometry, + ...(indicator ? { indicator } : {}), + ...(pts ? { points: pts } : {}), + }); + // Search places are places: a world-trend "AOI" is not somewhere to fly to. + if (f.aoi && place && !global) { + const p = places.get(f.aoi.id); + const b: [number, number, number, number] = p ? [Math.min(p.bbox[0], w), Math.min(p.bbox[1], s), Math.max(p.bbox[2], e), Math.max(p.bbox[3], n)] : [w, s, e, n]; + places.set(f.aoi.id, { id: f.aoi.id, name: place, lon: r4((b[0] + b[2]) / 2), lat: r4((b[1] + b[3]) / 2), bbox: b.map(r4) as MapPlace["bbox"] }); + } + } + cases.sort((a, b) => b.observedAt.localeCompare(a.observedAt)); + return { v: 1, generatedAt: now.toISOString(), cases, places: [...places.values()].sort((a, b) => a.name.localeCompare(b.name)) }; +} diff --git a/src/watch/marine-export.ts b/src/watch/marine-export.ts new file mode 100644 index 0000000..e5870d2 --- /dev/null +++ b/src/watch/marine-export.ts @@ -0,0 +1,173 @@ +// Marine layers for the public site, produced server-side at export time so no secret ever +// reaches a browser: +// api/marine/fishing.json Global Fishing Watch apparent fishing effort, last 30 days, 0.1° +// cells around every reserve in watchlists/marine.json (GeoJSON points) +// api/marine/ships.json aisstream.io ship density from one ≤ 20 s sample (GeoJSON points) +// Each is built only when its key is set (GFW_FISHING_TOKEN / AISSTREAM_KEY), cached next to +// the ledger dir, and refreshed at most every EARTHDECK_MARINE_FISHING_HOURS (24) / +// EARTHDECK_MARINE_SHIPS_HOURS (1) — so frequent exports don't spend the GFW token. Any +// failure falls back to the cache, else the file is simply omitted; the site works without. +// Neither file carries a vessel identity: fishing is hours per cell, ships are counts per cell. + +import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { sampleAis, type ShipDensity } from "../clients/ais.js"; +import { effortGrid, FISHING_LICENCE, fishingAttribution, gfwFishingToken } from "../clients/gfwfishing.js"; +import type { BBox } from "../types.js"; +import { addDays } from "../util.js"; +import { loadWatchlists } from "./watchlist.js"; + +export interface MarineOptions { + mode: "auto" | "cache" | "off"; + cacheDir: string; + watchlist: string; + env?: NodeJS.ProcessEnv; + now?: Date; + log?: (s: string) => void; + /** Injection points for tests. */ + grid?: typeof effortGrid; + sample?: typeof sampleAis; +} + +export interface MarineFiles { + fishing?: string; + ships?: string; +} + +interface Area { + mpaId: string; + name: string; + bbox: BBox; +} + +/** One query box per reserve (per side of the antimeridian): the union of its tiles. */ +export function fishingAreas(watchlistPath: string): Area[] { + const out = new Map(); + for (const wl of loadWatchlists(watchlistPath)) { + for (const a of wl.aois) { + const p = a.rules.find((r) => r.name === "mpa_fishing")?.params; + if (!p || typeof p.mpaId !== "string") continue; + const key = `${p.mpaId}|${a.bbox[0] < 0 ? "w" : "e"}`; + const name = typeof p.mpaName === "string" ? p.mpaName : a.name; + const b = a.bbox as BBox; + const cur = out.get(key); + out.set(key, cur ? { ...cur, bbox: [Math.min(cur.bbox[0], b[0]), Math.min(cur.bbox[1], b[1]), Math.max(cur.bbox[2], b[2]), Math.max(cur.bbox[3], b[3])] } : { mpaId: p.mpaId, name, bbox: b }); + } + } + return [...out.values()]; +} + +export async function buildFishingGeoJson(token: string, areas: Area[], now: Date, grid: typeof effortGrid = effortGrid, log: (s: string) => void = () => {}): Promise { + const to = now.toISOString().slice(0, 10); + const from = addDays(to, -30); + const features: unknown[] = []; + const summary: { mpaId: string; name: string; hours: number }[] = []; + let dataset = ""; + for (const a of areas) { + try { + const r = await grid(token, { bbox: a.bbox }, from, to, "LOW"); + dataset = r.dataset; + let hours = 0; + for (const c of r.cells) { + hours += c.hours; + features.push({ type: "Feature", geometry: { type: "Point", coordinates: [c.lon, c.lat] }, properties: { hours: c.hours } }); + } + const prev = summary.find((s) => s.mpaId === a.mpaId); + if (prev) prev.hours = Math.round((prev.hours + hours) * 10) / 10; + else summary.push({ mpaId: a.mpaId, name: a.name, hours: Math.round(hours * 10) / 10 }); + } catch (e) { + log(` marine: fishing grid for ${a.name}: ${(e as Error).message}`); + } + } + if (!summary.length) return null; + return JSON.stringify({ + type: "FeatureCollection", + features, + meta: { + kind: "fishing-effort", + generatedAt: now.toISOString(), + from, + to, + cellDeg: 0.1, + unit: "hours of apparent fishing per 0.1° cell, whole window", + dataset, + areas: summary, + attribution: fishingAttribution(now.getUTCFullYear()), + licence: FISHING_LICENCE, + note: "Boxes around watched marine reserves, not their legal boundaries. Apparent fishing is inferred from AIS; vessels without AIS are invisible. Aggregated — no vessel identities.", + }, + }); +} + +export function shipsGeoJson(d: ShipDensity): string { + const { cells, ...meta } = d; + return JSON.stringify({ + type: "FeatureCollection", + features: cells.map((c) => ({ type: "Feature", geometry: { type: "Point", coordinates: [c.lon, c.lat] }, properties: { count: c.count } })), + meta: { kind: "ship-density", ...meta }, + }); +} + +function fresh(path: string, hours: number, now: Date): boolean { + return existsSync(path) && now.getTime() - statSync(path).mtimeMs < hours * 3_600_000; +} + +function readCache(path: string): string | undefined { + try { + const s = readFileSync(path, "utf8"); + const j = JSON.parse(s) as { type?: string }; + return j.type === "FeatureCollection" ? s : undefined; + } catch { + return undefined; + } +} + +export async function marineSnapshots(o: MarineOptions): Promise { + if (o.mode === "off") return {}; + const env = o.env ?? process.env; + const now = o.now ?? new Date(); + const log = o.log ?? (() => {}); + const hours = (name: string, d: number) => { + const v = Number(env[name]); + return Number.isFinite(v) && v >= 0 && env[name]?.trim() ? v : d; + }; + const fishingPath = join(o.cacheDir, "fishing.json"); + const shipsPath = join(o.cacheDir, "ships.json"); + const save = (path: string, body: string) => { + try { + mkdirSync(o.cacheDir, { recursive: true }); + writeFileSync(path, body); + } catch { + /* cache is best-effort */ + } + }; + const out: MarineFiles = {}; + + // Keys gate producing; "cache" mode (e.g. a re-export without keys) only reads what a keyed run left. + const token = gfwFishingToken(env); + if (token || o.mode === "cache") { + if (token && o.mode === "auto" && !fresh(fishingPath, hours("EARTHDECK_MARINE_FISHING_HOURS", 24), now)) { + try { + const body = await buildFishingGeoJson(token, fishingAreas(o.watchlist), now, o.grid, log); + if (body) save(fishingPath, body); + } catch (e) { + log(` marine: fishing grid failed: ${(e as Error).message} — using the cache`); + } + } + out.fishing = readCache(fishingPath); + } + + const aisKey = env.AISSTREAM_KEY?.trim(); + if (aisKey || o.mode === "cache") { + if (aisKey && o.mode === "auto" && !fresh(shipsPath, hours("EARTHDECK_MARINE_SHIPS_HOURS", 1), now)) { + try { + const d = await (o.sample ?? sampleAis)(aisKey, { seconds: 20 }); + save(shipsPath, shipsGeoJson(d)); + } catch (e) { + log(` marine: AIS sample failed: ${(e as Error).message} — using the cache`); + } + } + out.ships = readCache(shipsPath); + } + return out; +} diff --git a/src/watch/metrics.ts b/src/watch/metrics.ts new file mode 100644 index 0000000..5090806 --- /dev/null +++ b/src/watch/metrics.ts @@ -0,0 +1,151 @@ +// `api/metrics.json` — every report on one screen (the landing's Metrics mode). Computed at export +// time so the page stays static: totals by status and topic, cases over time, the places with the +// most cases, the published false-alarm rate per rule, and what's at stake — each stake metric +// carries the ids of the cases behind it, so a click can filter the map to exactly those. +// +// Stakes count only cases that passed a second, independent check (confirmed or public, not +// resolved or retracted) — the same set as the living-value tile. A metric with no case behind it +// is left out rather than shown as 0: "no data" is not "nothing at stake". + +import type { Finding, Status } from "../ledger/schema.js"; +import { livingValueOf, type SiteStats } from "./export.js"; +import { groupOf, indicatorOf, isGlobalCase, topicOf, type MapGroup, type MapTopic } from "./map-data.js"; +import { areaHaOf, fmtUsd, GLOBAL_NATURE_VALUE } from "./site-render.js"; + +export interface StakeMetric { + key: string; + label: string; + value: number; + /** The number as a person reads it ("$3.4M a year", "1,240 ha"). */ + display: string; + /** One plain line: what the number is, and what it is not. */ + explain: string; + caseIds: string[]; +} + +export interface Metrics { + v: 1; + generatedAt: string; + totals: { all: number; byGroup: Record; byTopic: Partial> }; + timeline: { bucket: "day" | "week" | "month"; points: { t: string; published: number; checking: number; dropped: number }[] }; + places: { name: string; n: number; caseIds: string[] }[]; + rules: { rule: string; label: string; falsePositives: number; decided: number; rate: number | null }[]; + stake: StakeMetric[]; + nature: { lowUsd: number; highUsd: number; source: string }; +} + +/** Confirmed or public, and not closed — the cases whose stakes we stand behind. */ +const AT_STAKE: readonly Status[] = ["confirmed", "published", "notified", "replied", "no_response", "ignored"]; + +export const RULE_LABEL: Record = { + forest_loss: "Forest loss", + fires_in_protected: "Fires in protected land", + flaring: "Gas flaring", + flaring_stopped: "Flaring stopped", + methane_anomaly: "Methane", + indicator_threshold: "Planet indicators", + indicator_trend: "World trends", + weather_extreme: "Extreme weather", +}; + +/** Largest numeric value under any of `keys` across a finding's evidence (incl. the confirming signal). */ +export function maxValue(f: Finding, keys: readonly string[]): number | null { + let best: number | null = null; + for (const e of [...f.evidence, ...(f.confirmed ? [f.confirmed.signal] : [])]) { + for (const k of keys) { + const v = e.values?.[k]; + if (typeof v === "number" && Number.isFinite(v) && v > 0 && (best === null || v > best)) best = v; + } + } + return best; +} + +const DAY_MS = 86_400_000; +const int = (v: number) => Math.round(v).toLocaleString("en-US"); +const sig = (v: number) => (v >= 100 ? int(v) : String(Number(v.toPrecision(2)))); + +/** Start of the bucket holding `iso`, as YYYY-MM-DD (weeks start on Monday, UTC). */ +export function bucketOf(iso: string, bucket: "day" | "week" | "month"): string | null { + const t = Date.parse(iso); + if (Number.isNaN(t)) return null; + const d = new Date(t); + if (bucket === "month") return `${d.toISOString().slice(0, 7)}-01`; + const day = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()); + if (bucket === "day") return new Date(day).toISOString().slice(0, 10); + const dow = (d.getUTCDay() + 6) % 7; // Monday = 0 + return new Date(day - dow * DAY_MS).toISOString().slice(0, 10); +} + +/** Pure: the Metrics screen's numbers from the ledger's findings (and the export's stats for the rates). */ +export function computeMetrics(findings: readonly Finding[], stats: Pick, now = new Date()): Metrics { + const byGroup: Record = { published: 0, checking: 0, dropped: 0 }; + const byTopic: Partial> = {}; + const places = new Map(); + for (const f of findings) { + byGroup[groupOf(f.status)] += 1; + const indicator = indicatorOf(f); + const topic = topicOf(f.rule.name, indicator); + byTopic[topic] = (byTopic[topic] ?? 0) + 1; + if (f.aoi?.name && !isGlobalCase({ bbox: f.bbox, aoiId: f.aoi.id, indicator })) { + const p = places.get(f.aoi.id) ?? { name: f.aoi.name, ids: [] }; + p.ids.push(f.findingId); + places.set(f.aoi.id, p); + } + } + + // Cases over time, by when the watch opened them: days for a young ledger, then weeks, then months. + const times = findings.map((f) => Date.parse(f.createdAt)).filter((t) => !Number.isNaN(t)); + const span = times.length ? (Math.max(...times) - Math.min(...times)) / DAY_MS : 0; + const bucket = span <= 45 ? "day" : span <= 400 ? "week" : "month"; + const series = new Map(); + for (const f of findings) { + const b = bucketOf(f.createdAt, bucket); + if (!b) continue; + const row = series.get(b) ?? { published: 0, checking: 0, dropped: 0 }; + row[groupOf(f.status)] += 1; + series.set(b, row); + } + const points = [...series.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([t, r]) => ({ t, ...r })); + + const rules = Object.entries(stats.falsePositiveRate.byRule) + .map(([rule, c]) => ({ rule, label: RULE_LABEL[rule] ?? rule.replace(/_/g, " "), falsePositives: c.falsePositives, decided: c.decided, rate: c.rate })) + .sort((a, b) => b.decided - a.decided || a.label.localeCompare(b.label)); + + // What's at stake — only where a case carries the number, only cases we stand behind. + const open = findings.filter((f) => AT_STAKE.includes(f.status)); + const stake: StakeMetric[] = []; + const sum = (key: string, label: string, pick: (f: Finding) => number | null, display: (v: number) => string, explain: (n: number) => string) => { + let total = 0; + const ids: string[] = []; + for (const f of open) { + const v = pick(f); + if (v !== null && v > 0) { + total += v; + ids.push(f.findingId); + } + } + if (ids.length) stake.push({ key, label, value: total, display: display(total), explain: explain(ids.length), caseIds: ids }); + }; + const nCases = (n: number) => `${n} checked case${n === 1 ? "" : "s"}`; + sum("living_value", "Nature’s work at stake", livingValueOf, (v) => `${fmtUsd(v)} a year`, (n) => `A rough estimate of what the land in ${nCases(n)} does for people each year — clean water, carbon, food. Order of magnitude only.`); + sum("forest_ha", "Forest lost", (f) => (topicOf(f.rule.name, null) === "forest" ? areaHaOf(f) : null), (v) => `${int(v)} ha`, (n) => `Hectares of forest cleared in ${nCases(n)} (one football pitch ≈ 0.7 ha).`); + sum("flare_bcm", "Gas flared", (f) => (f.rule.name === "flaring" ? maxValue(f, ["bcm", "vnfTopBcm"]) : null), (v) => `${sig(v)} bn m³ a year`, (n) => `Gas burned off at the sites in ${nCases(n)}, from yearly satellite flare estimates — wasted energy and CO₂.`); + sum("flare_stopped_bcm", "Flaring stopped", (f) => (f.rule.name === "flaring_stopped" ? maxValue(f, ["stopped_bcm"]) : null), (v) => `${sig(v)} bn m³ a year`, (n) => `Good news: yearly flaring at sites that went dark, across ${nCases(n)}.`); + sum("methane_t", "Methane released", (f) => maxValue(f, ["ch4_t", "methane_t", "ch4_tonnes"]), (v) => `${int(v)} t`, (n) => `Tonnes of methane estimated in ${nCases(n)} — a gas about 80× stronger than CO₂ over 20 years.`); + sum("fishing_hours", "Fishing in protected water", (f) => maxValue(f, ["fishing_hours", "apparent_fishing_hours"]), (v) => `${int(v)} h`, (n) => `Hours of apparent fishing counted in ${nCases(n)}.`); + sum("people_bad_air", "People breathing bad air", (f) => (topicOf(f.rule.name, indicatorOf(f)) === "air" ? maxValue(f, ["population", "people", "pop"]) : null), (v) => int(v), (n) => `People living in the cities of ${nCases(n)} while fine-particle pollution ran above the WHO limit.`); + + return { + v: 1, + generatedAt: now.toISOString(), + totals: { all: findings.length, byGroup, byTopic }, + timeline: { bucket, points }, + places: [...places.values()] + .map((p) => ({ name: p.name, n: p.ids.length, caseIds: p.ids })) + .sort((a, b) => b.n - a.n || a.name.localeCompare(b.name)) + .slice(0, 8), + rules, + stake, + nature: { lowUsd: GLOBAL_NATURE_VALUE.usdPerYear.low, highUsd: GLOBAL_NATURE_VALUE.usdPerYear.high, source: GLOBAL_NATURE_VALUE.source }, + }; +} diff --git a/src/watch/news.ts b/src/watch/news.ts new file mode 100644 index 0000000..8eeea44 --- /dev/null +++ b/src/watch/news.ts @@ -0,0 +1,102 @@ +// "In the news" for the static site: per decided case, recent headlines from GDELT matched by +// place + topic (src/clients/gdelt.ts). Context only — never evidence, never fed to the +// analyst's narration or review. Cached per case under /news/.json (12 h TTL), +// paced ≤1 request / 5.5 s, capped per export (CallBudget), and failing soft: a failed or +// skipped lookup falls back to the stale cache, else the case simply has no news section. + +import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import type { Finding, Status } from "../ledger/schema.js"; +import { GDELT_MIN_INTERVAL_MS, gdeltArticles, newsPlace, newsQuery, topicKeywords, type NewsItem } from "../clients/gdelt.js"; +import { CallBudget } from "./quota.js"; + +/** Decided-true cases only: no candidates, false positives, expired or retracted. */ +export const NEWS_STATUSES: readonly Status[] = ["confirmed", "published", "notified", "replied", "no_response", "resolved"]; +export const NEWS_TTL_MS = 12 * 3600_000; +export const NEWS_MAX_ITEMS = 5; + +interface CacheFile { + fetchedAt: string; + query: string; + items: NewsItem[]; +} + +const fold = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase(); + +/** + * GDELT matches words anywhere in the article text, so most hits are off-topic. Keep a headline + * only when its title itself names the place or the topic. + */ +export function relevant(f: Finding, items: readonly NewsItem[]): NewsItem[] { + const place = newsPlace(f); + const words = [...(place ? [place] : []), ...topicKeywords(f)].map(fold); + return items.filter((n) => { + const t = fold(n.title); + return words.some((w) => t.includes(w)); + }); +} + +function readCache(file: string): CacheFile | null { + try { + const j = JSON.parse(readFileSync(file, "utf8")) as CacheFile; + return typeof j.fetchedAt === "string" && Array.isArray(j.items) ? j : null; + } catch { + return null; + } +} + +export interface NewsOptions { + cacheDir: string; + budget: CallBudget; + now: Date; + log?: (s: string) => void; + /** Injected for tests; default GDELT DOC 2.0. */ + fetchArticles?: (query: string) => Promise; + minIntervalMs?: number; +} + +/** caseId → ≤5 relevant headlines (only cases that have some). */ +export async function newsForCases(findings: readonly Finding[], o: NewsOptions): Promise> { + const out = new Map(); + const fetchArticles = o.fetchArticles ?? ((q: string) => gdeltArticles(q)); + const gap = o.minIntervalMs ?? GDELT_MIN_INTERVAL_MS; + const log = o.log ?? (() => {}); + let last = 0; + let fetched = 0; + let failed = 0; + for (const f of findings) { + if (!NEWS_STATUSES.includes(f.status)) continue; + const query = newsQuery(f); + if (!query) continue; + const file = join(o.cacheDir, `${f.findingId}.json`); + const cached = existsSync(file) ? readCache(file) : null; + const fresh = cached && cached.query === query && o.now.getTime() - Date.parse(cached.fetchedAt) < NEWS_TTL_MS; + let items = cached?.items ?? []; + if (!fresh && o.budget.take()) { + const wait = last + gap - Date.now(); + if (wait > 0) await new Promise((r) => setTimeout(r, wait)); + try { + items = relevant(f, await fetchArticles(query)).slice(0, NEWS_MAX_ITEMS); + fetched += 1; + try { + mkdirSync(o.cacheDir, { recursive: true }); + writeFileSync(file, JSON.stringify({ fetchedAt: o.now.toISOString(), query, items } satisfies CacheFile)); + } catch { + /* cache is best-effort */ + } + } catch (e) { + failed += 1; + const err = e as { status?: number; message?: string }; + if (err.status === 429) { + o.budget.stop(); + log(" news: GDELT rate limit — no more lookups this export (cached headlines still used)"); + } + } finally { + last = Date.now(); + } + } + if (items.length) out.set(f.findingId, items.slice(0, NEWS_MAX_ITEMS)); + } + if (fetched || failed) log(` news: ${fetched} lookups, ${failed} failed, ${out.size} cases with headlines`); + return out; +} diff --git a/src/watch/quota.ts b/src/watch/quota.ts index 7ef4a12..2c88d7f 100644 --- a/src/watch/quota.ts +++ b/src/watch/quota.ts @@ -9,13 +9,16 @@ import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { ToolError, type ToolCall } from "./rules/types.js"; -export type Provider = "cdse" | "gfw" | "firms"; -export const PROVIDERS: readonly Provider[] = ["cdse", "gfw", "firms"]; +/** `gfw` = Global *Forest* Watch Data API; `gfw_fishing` = Global *Fishing* Watch API (separate token + terms). */ +export type Provider = "cdse" | "gfw" | "firms" | "gfw_fishing"; +export const PROVIDERS: readonly Provider[] = ["cdse", "gfw", "firms", "gfw_fishing"]; export interface QuotaCaps { cdse: number; gfw: number; firms: number; + /** Optional so older callers' caps objects stay valid; missing → the default (200). */ + gfw_fishing?: number; analystCases: number; analystUsd: number; /** Per-rule sub-caps inside a provider's cap, keyed by ruleKey(rule name): e.g. methane may @@ -23,7 +26,9 @@ export interface QuotaCaps { perRule?: Record>>; } -const DEFAULT_CAPS: QuotaCaps = { cdse: 60, gfw: 400, firms: 300, analystCases: 10, analystUsd: 3, perRule: { METHANE_ANOMALY: { cdse: 10 } } }; +// gfw_fishing: conservative — GFW publishes no hard daily cap for the 4Wings report API; 200/day +// covers the marine watchlist (~46 tiles, 1 call each) + confirmations with room to spare. +const DEFAULT_CAPS: QuotaCaps = { cdse: 60, gfw: 400, firms: 300, gfw_fishing: 200, analystCases: 10, analystUsd: 3, perRule: { METHANE_ANOMALY: { cdse: 10 } } }; /** `methane-anomaly` / `methane_anomaly` → `METHANE_ANOMALY` (the env-var suffix form). */ export function ruleKey(rule: string): string { @@ -31,7 +36,7 @@ export function ruleKey(rule: string): string { } /** - * Caps from EARTHDECK_MAX_{CDSE,GFW,FIRMS}_CALLS, EARTHDECK_MAX_ANALYST_CASES, EARTHDECK_MAX_ANALYST_USD, + * Caps from EARTHDECK_MAX_{CDSE,GFW,FIRMS,GFW_FISHING}_CALLS, EARTHDECK_MAX_ANALYST_CASES, EARTHDECK_MAX_ANALYST_USD, * plus per-rule sub-caps EARTHDECK_MAX__CALLS_ (rule name upper-cased). */ export function capsFromEnv(env: NodeJS.ProcessEnv = process.env): QuotaCaps { @@ -46,6 +51,7 @@ export function capsFromEnv(env: NodeJS.ProcessEnv = process.env): QuotaCaps { cdse: n("EARTHDECK_MAX_CDSE_CALLS", DEFAULT_CAPS.cdse), gfw: n("EARTHDECK_MAX_GFW_CALLS", DEFAULT_CAPS.gfw), firms: n("EARTHDECK_MAX_FIRMS_CALLS", DEFAULT_CAPS.firms), + gfw_fishing: n("EARTHDECK_MAX_GFW_FISHING_CALLS", DEFAULT_CAPS.gfw_fishing!), analystCases: n("EARTHDECK_MAX_ANALYST_CASES", DEFAULT_CAPS.analystCases), analystUsd: n("EARTHDECK_MAX_ANALYST_USD", DEFAULT_CAPS.analystUsd), perRule: perRuleFromEnv(env, n), @@ -55,7 +61,7 @@ export function capsFromEnv(env: NodeJS.ProcessEnv = process.env): QuotaCaps { function perRuleFromEnv(env: NodeJS.ProcessEnv, n: (name: string, dflt: number) => number): NonNullable { const out: NonNullable = Object.fromEntries(Object.entries(DEFAULT_CAPS.perRule!).map(([k, v]) => [k, { ...v }])); for (const name of Object.keys(env).sort()) { - const m = /^EARTHDECK_MAX_(CDSE|GFW|FIRMS)_CALLS_(.+)$/.exec(name); + const m = /^EARTHDECK_MAX_(CDSE|GFW_FISHING|GFW|FIRMS)_CALLS_(.+)$/.exec(name); if (!m || env[name] === undefined || env[name]!.trim() === "") continue; const provider = m[1]!.toLowerCase() as Provider; (out[ruleKey(m[2]!)] ??= {})[provider] = n(name, 0); @@ -72,6 +78,7 @@ const TOOL_PROVIDER: Record = { methane_plumes: "cdse", fires_in: "firms", flaring: "firms", + fishing_activity: "gfw_fishing", }; /** Provider + billable units for one tool call (null = not governed, e.g. EONET/ENSO). */ @@ -84,6 +91,8 @@ export function costOf(tool: string, args: Record): { provider: const sources = Array.isArray(args.sources) ? args.sources.length : 2; return { provider, units: Math.max(1, Math.ceil(days / 5)) * sources }; } + // One 4Wings report for flag/daily/cells, plus one for the gear breakdown unless byGear: false. + if (tool === "fishing_activity") return { provider, units: args.byGear === false ? 1 : 2 }; return { provider, units: 1 }; } @@ -94,6 +103,7 @@ export function providersForRequires(requires: readonly string[]): Provider[] { if (k === "GFW_API_KEY") out.add("gfw"); else if (k.startsWith("CDSE_")) out.add("cdse"); else if (k === "FIRMS_MAP_KEY") out.add("firms"); + else if (k === "GFW_FISHING_TOKEN") out.add("gfw_fishing"); } return [...out]; } @@ -121,6 +131,7 @@ interface DayRecord { cdse?: number; gfw?: number; firms?: number; + gfw_fishing?: number; /** Per-rule provider usage (only for rules with a sub-cap), keyed by ruleKey. */ rules?: Record>>; analystCases?: number; @@ -161,7 +172,7 @@ export class QuotaGovernor { blocked(provider: Provider, units = 1, rule?: string): string | null { const hit = this.exhausted.get(provider); if (hit) return hit; - if (this.used(provider) + units > this.caps[provider]) return `quota:${provider}`; + if (this.used(provider) + units > (this.caps[provider] ?? DEFAULT_CAPS[provider]!)) return `quota:${provider}`; const sub = rule === undefined ? undefined : this.caps.perRule?.[ruleKey(rule)]?.[provider]; return sub !== undefined && this.ruleUsed(rule!, provider) + units > sub ? `quota:${provider}` : null; } @@ -236,6 +247,42 @@ export class QuotaGovernor { } } +// ── news (GDELT) ───────────────────────────────────────────────────────────────────────── +// Per export, not per day: the site export is the only caller, and GDELT asks for pacing +// (≤1 req / 5 s) rather than a daily cap. A rate-limit answer stops fetching for the run. + +const DEFAULT_GDELT_CALLS = 40; + +/** EARTHDECK_MAX_GDELT_CALLS — news lookups one export may make (default 40). */ +export function gdeltCapFromEnv(env: NodeJS.ProcessEnv = process.env): number { + const raw = env.EARTHDECK_MAX_GDELT_CALLS; + if (raw === undefined || raw.trim() === "") return DEFAULT_GDELT_CALLS; + const v = Number(raw); + if (!Number.isFinite(v) || v < 0) throw new Error(`EARTHDECK_MAX_GDELT_CALLS must be a non-negative number (got "${raw}")`); + return Math.floor(v); +} + +/** In-memory call budget for one run; `stop()` after a rate limit refuses the rest. */ +export class CallBudget { + private used = 0; + private stopped = false; + constructor(readonly cap: number) {} + take(): boolean { + if (this.stopped || this.used >= this.cap) return false; + this.used += 1; + return true; + } + stop(): void { + this.stopped = true; + } + get spent(): number { + return this.used; + } + get halted(): boolean { + return this.stopped; + } +} + function readDays(file: string): Record { try { const j = JSON.parse(readFileSync(file, "utf8")) as unknown; diff --git a/src/watch/rules/forestLoss.ts b/src/watch/rules/forestLoss.ts index 704dc3d..77e70f5 100644 --- a/src/watch/rules/forestLoss.ts +++ b/src/watch/rules/forestLoss.ts @@ -4,7 +4,7 @@ // provider). Baseline: alert density in a neighbourhood ring, so a quiet AOI next to a // loud region — or the reverse — is visible in the finding itself. -import { livingValueForFinding } from "../../clients/naturalvalue.js"; +import { MAPBIOMAS_YEAR, geeStatus, insideMapBiomasBrazil, livingValueForFinding, mapbiomasConvertedPct } from "../../clients/naturalvalue.js"; import type { Evidence } from "../../ledger/schema.js"; import type { BBox } from "../../types.js"; import { addDays, isoDate } from "../../util.js"; @@ -71,7 +71,13 @@ export const forestLoss = defineRule({ const observedAt = dayStart(r.window.to); // What the cleared area was doing alive (benefit transfer; GFW alerts are tropical-only). const living = livingValueForFinding(r.areaHa, "tropical_forest"); - const livingValues = { living_value_usd_yr: living.annualUsd, living_value_100y_usd: living.horizonUsd, living_value_100y_npv2_usd: living.npvUsd }; + const converted = await watchAreaConverted(ctx); + const livingValues = { + living_value_usd_yr: living.annualUsd, + living_value_100y_usd: living.horizonUsd, + living_value_100y_npv2_usd: living.npvUsd, + ...(converted ? { watch_area_converted_pct: converted.pct } : {}), + }; const evidence: Evidence[] = [ { id: `gfw-integrated-${ctx.aoi.id}-${r.window.from}..${r.window.to}`, @@ -111,7 +117,7 @@ export const forestLoss = defineRule({ values: { alerts: r.alertCount, ha: r.areaHa, ...livingValues }, geometry: bboxPolygon(ctx.aoi.bbox), baseline, - notes: [living.note], + notes: [living.note, ...(converted ? [`The watch area is ${converted.pct} % converted land (MapBiomas ${converted.year}: pasture, crops, mosaic, urban, mining).`] : [])], }; }, @@ -140,8 +146,24 @@ export const forestLoss = defineRule({ }, }); +/** + * Context only: how much of the watch area MapBiomas already calls converted. Brazil AOIs with + * Earth Engine configured; any failure → null (never blocks the finding). The lost area itself + * is still valued as forest — it was forest before the alert. + */ +async function watchAreaConverted(ctx: RuleContext): Promise<{ pct: number; year: number } | null> { + if (geeStatus() !== true || !insideMapBiomasBrazil(ctx.aoi.bbox)) return null; + try { + const r = (await ctx.call("gee_query", { query: "land_cover", dataset: "mapbiomas", year: MAPBIOMAS_YEAR, bbox: ctx.aoi.bbox })) as { classes?: { code: number; sharePct: number }[] }; + const pct = mapbiomasConvertedPct(r.classes ?? []); + return pct === null ? null : { pct, year: MAPBIOMAS_YEAR }; + } catch { + return null; + } +} + /** Largest ring ≤ ringKm whose bbox stays under the GFW area cap; null if the AOI itself is too big. */ -function fitRing(bbox: BBox, km: number): { bbox: BBox; km: number } | null { +export function fitRing(bbox: BBox, km: number): { bbox: BBox; km: number } | null { for (let k = km; k >= 5; k = Math.floor(k / 2)) { const r = ringBBox(bbox, k); if (bboxArea(r) <= GFW_MAX_AREA_DEG2 * 0.98) return { bbox: r, km: k }; diff --git a/src/watch/rules/improvement.ts b/src/watch/rules/improvement.ts new file mode 100644 index 0000000..a19bb20 --- /dev/null +++ b/src/watch/rules/improvement.ts @@ -0,0 +1,627 @@ +// improvement@1.0 — cases that open when something gets BETTER. "A watch, not a complaint +// feed." Same evidence standard as every other rule: a detector, an independent or later +// confirmation, and plain words about what it cannot see. Every case is tagged `improvement` +// (the site shows it as good news). One rule, parameterised per AOI by `params.kind`: +// +// forest_recovery GFW integrated alerts (ha) in the last `days` ≤ maxShareOfBaseline × the same +// window a year earlier, AND the AOI's alert density is below its ring +// → confirm: the next `confirmDays` window is still low (revisit), else a +// Sentinel-2 median NDVI that held or rose year on year (opt-in: +// confirmWithNdvi; CDSE — deferred when that quota is spent) +// flaring_decline VNF annual flared volume in the box fell ≥ minDropPct between the last two +// VNF years AND FIRMS night-time hot detections are lower than a year ago +// → confirm: the next window is still lower than a year earlier (revisit) +// bleaching_relief NOAA CRW Bleaching Alert Area was ≥ minPeakLevel in the last `days` and has +// been 0 ("No stress") for ≥ minClearDays → confirm: still 0 on a later day +// air_quality_clean CAMS PM2.5: the last 7 full days average below the WHO guideline after ≥ 7 +// days above it → confirm: a later day's 7-day mean is still below +// fires_absent a protected area with fire clusters in the same weeks last year has none +// this season so far → confirm: still none on a later sweep +// +// Year-on-year FIRMS comparisons use VIIRS NOAA-21 NRT for BOTH years: it is the only VIIRS NRT +// feed FIRMS keeps back to 2024 (NOAA-20/S-NPP NRT hold ~3 months; their SP archive lags ~3). + +import type { Evidence, Geometry } from "../../ledger/schema.js"; +import { EOG_VNF_HREF, FIRMS_HREF, VNF_CREDIT, windowChunks } from "../../clients/vnf.js"; +import type { FireDetection } from "../../types.js"; +import { addDays } from "../../util.js"; +import { flarePlace } from "./flaring.js"; +import { fitRing } from "./forestLoss.js"; +import { bboxArea, dayStart, defineRule, num, ringBBox, type Candidate, type Confirmation, type RuleContext, type ToolCall } from "./types.js"; + +export const IMPROVEMENT_KINDS = ["forest_recovery", "flaring_decline", "bleaching_relief", "air_quality_clean", "fires_absent"] as const; +export type ImprovementKind = (typeof IMPROVEMENT_KINDS)[number]; + +export const IMPROVEMENT_DEFAULTS: Record> = { + // lagDays: GFW alerts arrive 1–2 weeks late, so both windows end lagDays before the sweep — + // otherwise the fresh window is under-counted and every AOI looks like it recovered. + forest_recovery: { days: 90, lagDays: 14, minConfidence: "high", maxShareOfBaseline: 0.3, minBaselineHa: 20, confirmDays: 30, confirmWithNdvi: false, ndviTolerance: 0.02, minValidPct: 60 }, + flaring_decline: { days: 30, minDropPct: 30, minBaselineBcm: 0.05, minFirmsDropPct: 10, minFrp: 5, source: "VIIRS_NOAA21_NRT" }, + bleaching_relief: { days: 90, minPeakLevel: 3, minClearDays: 14 }, + air_quality_clean: { guideline: 15, window: 7, minDaysAbove: 7 }, + fires_absent: { days: 30, minFrp: 20, clusterMin: 3, cellDeg: 0.05, minHotLastYear: 10, source: "VIIRS_NOAA21_NRT", aliveRingKm: 100, revisitDays: 5 }, +}; + +const TAGS = ["improvement"]; +const BAA_LABEL = ["No stress", "Bleaching Watch", "Bleaching Warning", "Alert Level 1", "Alert Level 2"]; +const GFW_HREF = "https://data-api.globalforestwatch.org/dataset/gfw_integrated_alerts"; +const CRW_HREF = "https://coralreefwatch.noaa.gov/product/5km/"; +const CAMS_HREF = "https://open-meteo.com/en/docs/air-quality-api"; + +type P = Record; + +/** The kind an AOI asks for, with its defaults merged under the AOI's params. */ +export function improvementParams(params: P): { kind: ImprovementKind; p: P } { + const kind = params.kind as ImprovementKind; + if (!IMPROVEMENT_KINDS.includes(kind)) throw new Error(`improvement: params.kind must be one of ${IMPROVEMENT_KINDS.join(", ")} (got ${JSON.stringify(params.kind)})`); + return { kind, p: { ...IMPROVEMENT_DEFAULTS[kind], ...params } }; +} + +function method(kind: ImprovementKind, params: P): Evidence["method"] { + return { name: "improvement", version: "1.0", params: { kind, ...params } }; +} + +const today = (ctx: RuleContext) => ctx.now.slice(0, 10); +const round = (v: number, dp: number) => Math.round(v * 10 ** dp) / 10 ** dp; +const pct = (v: number) => Math.round(v); +const pointGeom = (lat: number, lon: number): Geometry => ({ type: "Point", coordinates: [round(lon, 3), round(lat, 3)] }); +const daysBetween = (a: string, b: string) => Math.round((Date.parse(dayStart(b)) - Date.parse(dayStart(a))) / 86_400_000); + +/** The point an AOI is about: explicit params.lat/lon, else the bbox centre. */ +function pointOf(ctx: RuleContext, p: P): { lat: number; lon: number } { + const [w, s, e, n] = ctx.aoi.bbox; + return { lat: num(p.lat, round((s + n) / 2, 3)), lon: num(p.lon, round((w + e) / 2, 3)) }; +} + +// One pull per tool+args per sweep (detect and confirm share it). Scoped to the sweep-level +// caller the kernel exposes as `base`, and to the sweep's `now`. +const memo = new WeakMap> }>(); +function shared(ctx: RuleContext, tool: string, args: Record): Promise { + const scope = (ctx.call as ToolCall & { base?: ToolCall }).base ?? ctx.call; + let slot = memo.get(scope); + if (!slot || slot.now !== ctx.now) memo.set(scope, (slot = { now: ctx.now, m: new Map() })); + const key = `${tool} ${JSON.stringify(args)}`; + let pr = slot.m.get(key); + if (!pr) { + pr = ctx.call(tool, args); + const m = slot.m; + m.set(key, pr); + pr.catch(() => m.delete(key)); + } + return pr; +} + +// ---- forest_recovery ----------------------------------------------------------------------- + +interface AlertsResult { + window: { from: string; to: string }; + alertCount: number; + areaHa: number; +} +interface CompareResult { + validPctA: number; + validPctB: number; + delta: { meanChange: number }; + provenanceA?: { scenes?: string[] }; + provenanceB?: { scenes?: string[] }; +} + +async function detectForest(ctx: RuleContext, p: P): Promise { + const days = num(p.days, 90); + const end = addDays(today(ctx), -num(p.lagDays, 14)); + const endLy = addDays(end, -365); + const base = { bbox: ctx.aoi.bbox, days, minConfidence: String(p.minConfidence) }; + const now = (await ctx.call("forest_alerts", { ...base, endDate: end })) as AlertsResult; + const ly = (await ctx.call("forest_alerts", { ...base, endDate: endLy })) as AlertsResult; + if (ly.areaHa < num(p.minBaselineHa, 20)) return null; // nothing much to recover from + const share = now.areaHa / ly.areaHa; + if (share > num(p.maxShareOfBaseline, 0.3)) return null; + // Below the neighbourhood too — otherwise the whole region calmed down (rain, a data change). + const ring = fitRing(ctx.aoi.bbox, 25); + if (!ring) return null; + const rr = (await ctx.call("forest_alerts", { ...base, bbox: ring.bbox, endDate: end })) as AlertsResult; + const aoiValue = now.areaHa / bboxArea(ctx.aoi.bbox); + const regionalValue = rr.areaHa / bboxArea(ring.bbox); + if (!(aoiValue < regionalValue)) return null; + + const drop = pct((1 - share) * 100); + const values = { ha_now: now.areaHa, ha_year_ago: ly.areaHa, alerts_now: now.alertCount, alerts_year_ago: ly.alertCount, share_of_year_ago: round(share, 3), drop_pct: drop, windowDays: days }; + const observedAt = dayStart(end); + const name = ctx.aoi.name ?? ctx.aoi.id; + const evidence: Evidence[] = [ + { + id: `gfw-integrated-${ctx.aoi.id}-${now.window.from}..${now.window.to}-yoy`, + kind: "alert", + source: "gfw-integrated-alerts", + datetime: observedAt, + href: GFW_HREF, + method: method("forest_recovery", { ...base, endDate: end, endDateYearAgo: endLy, maxShareOfBaseline: num(p.maxShareOfBaseline, 0.3) }), + summary: + `${now.areaHa} ha of alerts (≥ ${String(p.minConfidence)} confidence) in ${now.window.from}…${now.window.to} vs ${ly.areaHa} ha in the same window a year earlier ` + + `(${ly.window.from}…${ly.window.to}): ${round(share * 100, 1)} % of last year's level.`, + values, + }, + ]; + return { + title: `Forest loss near ${name} fell ${drop} % year on year`.slice(0, 200), + summary: + `Good news, if it holds: deforestation alerts near ${name} covered ${now.areaHa} ha in the ${days} days to ${end}, down from ${ly.areaHa} ha in the same weeks a year earlier (−${drop} %), ` + + `and the area is now quieter than its ${ring.km} km neighbourhood (${round(aoiValue, 1)} vs ${round(regionalValue, 1)} ha per deg²). ` + + `Alerts can lag and cloud can hide clearing, so this counts only if the next month stays low too.`, + observedAt, + evidence, + values, + baseline: { metric: "alert ha per deg²", ringKm: ring.km, aoiValue: round(aoiValue, 3), regionalValue: round(regionalValue, 3), ratio: regionalValue > 0 ? round(aoiValue / regionalValue, 3) : null }, + notes: [`Case type: improvement — forest loss down ${drop} % year on year (${now.areaHa} ha vs ${ly.areaHa} ha).`], + tags: TAGS, + }; +} + +async function confirmForest(ctx: RuleContext, p: P, c0: Pick): Promise { + const end = c0.observedAt.slice(0, 10); + const maxShare = num(p.maxShareOfBaseline, 0.3); + const minConfidence = String(p.minConfidence); + // 1. Persistence: the next window, once it is past the alert lag, is still low year on year. + const confirmDays = num(p.confirmDays, 30); + const nextEnd = addDays(end, confirmDays); + if (addDays(today(ctx), -num(p.lagDays, 14)) >= nextEnd) { + const args = { bbox: ctx.aoi.bbox, days: confirmDays, minConfidence }; + const now = (await ctx.call("forest_alerts", { ...args, endDate: nextEnd })) as AlertsResult; + const ly = (await ctx.call("forest_alerts", { ...args, endDate: addDays(nextEnd, -365) })) as AlertsResult; + if (now.areaHa === 0 || now.areaHa <= maxShare * ly.areaHa) { + return { + independence: "revisit", + signal: { + id: `gfw-integrated-${ctx.aoi.id}-${now.window.from}..${now.window.to}-yoy-persist`, + kind: "alert", + source: "gfw-integrated-alerts", + datetime: dayStart(nextEnd), + href: GFW_HREF, + method: method("forest_recovery", { ...args, endDate: nextEnd }), + summary: `Still low in the next ${confirmDays} days (${now.window.from}…${now.window.to}): ${now.areaHa} ha vs ${ly.areaHa} ha a year earlier.`, + values: { ha_now: now.areaHa, ha_year_ago: ly.areaHa }, + }, + }; + } + } + // 2. Opt-in (confirmWithNdvi): Sentinel-2 median NDVI held or rose, same weeks year on year. + if (p.confirmWithNdvi !== true) return null; + const dateA = addDays(end, -365); + const args = { bbox: ctx.aoi.bbox, dateA, dateB: end, index: "NDVI", composite: "median", width: 256 }; + let c: CompareResult; + try { + c = (await ctx.call("eo_compare", args)) as CompareResult; + } catch (err) { + if ((err as Error).name === "QuotaExceeded") throw err; // the kernel records it as a quota skip + return null; // no CDSE keys / no scenes: wait for the persistence window + } + if (Math.min(c.validPctA, c.validPctB) < num(p.minValidPct, 60)) return null; + if (c.delta.meanChange < -num(p.ndviTolerance, 0.02)) return null; + const scenes = [...(c.provenanceA?.scenes ?? []), ...(c.provenanceB?.scenes ?? [])]; + return { + independence: "sensor", + signal: { + id: `s2-ndvi-median-${ctx.aoi.id}-${dateA}..${end}-yoy`, + kind: "scene", + source: "sentinel-2-l2a", + datetime: dayStart(end), + method: method("forest_recovery", args), + summary: `Median-composite NDVI held year on year (${c.delta.meanChange >= 0 ? "+" : ""}${c.delta.meanChange.toFixed(3)}, ${dateA} → ${end}); valid pixels ${c.validPctA}% / ${c.validPctB}%.${scenes.length ? ` Scenes: ${scenes.slice(0, 6).join(", ")}` : ""}`, + values: { deltaNdvi: c.delta.meanChange, validPctA: c.validPctA, validPctB: c.validPctB }, + }, + }; +} + +// ---- flaring_decline ----------------------------------------------------------------------- + +interface FlaringResult { + window: { from: string; to: string; days: number }; + counts: { hotNightDetections: number; persistentClusters: number }; + vnf: { available: boolean; year?: number; bcmTotal?: number; sitesInBbox?: number; previous?: { available: boolean; year?: number; bcmTotal?: number; sitesInBbox?: number } }; +} + +function firmsArgs(ctx: RuleContext, p: P, endDate: string, days = num(p.days, 30)) { + return { bbox: ctx.aoi.bbox, days, endDate, minFrp: num(p.minFrp, 5), minNights: 1, sources: [String(p.source)], vnf: false, limit: 1 }; +} + +async function detectFlaring(ctx: RuleContext, p: P): Promise { + // 1. The registry fact first — one FIRMS transaction, and most fields stop here. + const reg = (await shared(ctx, "flaring", { bbox: ctx.aoi.bbox, days: 1, sources: [String(p.source)], limit: 1 })) as FlaringResult; + const prev = reg.vnf.previous; + if (!reg.vnf.available || !prev?.available || prev.bcmTotal == null || reg.vnf.bcmTotal == null) return null; + if (prev.bcmTotal < num(p.minBaselineBcm, 0.05)) return null; + const vnfDrop = ((prev.bcmTotal - reg.vnf.bcmTotal) / prev.bcmTotal) * 100; + if (vnfDrop < num(p.minDropPct, 30)) return null; + // 2. And the flares look dimmer now than a year ago (same satellite both years). + const end = today(ctx); + const now = (await ctx.call("flaring", firmsArgs(ctx, p, end))) as FlaringResult; + const ly = (await ctx.call("flaring", firmsArgs(ctx, p, addDays(end, -365)))) as FlaringResult; + const a = now.counts.hotNightDetections; + const b = ly.counts.hotNightDetections; + if (b <= 0) return null; + const firmsDrop = ((b - a) / b) * 100; + if (firmsDrop < num(p.minFirmsDropPct, 10)) return null; + + const place = flarePlace(ctx.aoi); + const observedAt = dayStart(now.window.to); + const values = { + vnf_bcm_latest: reg.vnf.bcmTotal, + vnf_bcm_previous: prev.bcmTotal, + vnf_drop_pct: pct(vnfDrop), + vnfYear: reg.vnf.year ?? 0, + hot_nights_now: a, + hot_nights_year_ago: b, + firms_drop_pct: pct(firmsDrop), + windowDays: now.window.days, + }; + const sensor = String(p.source).toLowerCase(); + const evidence: Evidence[] = [ + { + id: `eog-vnf-annual-${prev.year}-${reg.vnf.year}-${ctx.aoi.id}-drop`, + kind: "record", + source: "eog-vnf-annual", + datetime: `${reg.vnf.year}-12-31T00:00:00Z`, + href: EOG_VNF_HREF, + method: method("flaring_decline", { minDropPct: num(p.minDropPct, 30), minBaselineBcm: num(p.minBaselineBcm, 0.05) }), + summary: `VNF annual flared volume of the ${reg.vnf.sitesInBbox ?? "?"} registry sites in the box: ${prev.bcmTotal} BCM in ${prev.year} → ${reg.vnf.bcmTotal} BCM in ${reg.vnf.year} (−${pct(vnfDrop)} %). Credit: ${VNF_CREDIT}.`, + values: { vnf_bcm_latest: reg.vnf.bcmTotal, vnf_bcm_previous: prev.bcmTotal, vnf_drop_pct: pct(vnfDrop) }, + }, + { + id: `firms-${sensor}-flaring-yoy-${ctx.aoi.id}-${now.window.from}-${now.window.to}`, + kind: "alert", + source: `firms-${sensor}`, + datetime: observedAt, + href: FIRMS_HREF, + method: method("flaring_decline", firmsArgs(ctx, p, end)), + summary: `${a} night-time detections with FRP ≥ ${num(p.minFrp, 5)} MW in ${now.window.from}…${now.window.to}, vs ${b} in ${ly.window.from}…${ly.window.to} (−${pct(firmsDrop)} %, ${String(p.source)} both years).`, + values: { hot_nights_now: a, hot_nights_year_ago: b, firms_drop_pct: pct(firmsDrop) }, + }, + ]; + return { + title: `Gas flaring near ${place} fell ${pct(vnfDrop)} % year on year`.slice(0, 200), + summary: + `Good news, if it holds: the registered gas flares near ${place} burned ${reg.vnf.bcmTotal} billion m³ of gas in ${reg.vnf.year}, down from ${prev.bcmTotal} in ${prev.year} (−${pct(vnfDrop)} %, VIIRS Nightfire annual summary), ` + + `and the satellite sees fewer hot flare nights than a year ago (${a} vs ${b} detections in ${now.window.days} days). ` + + `A second month still below last year's level confirms it.`, + observedAt, + evidence, + values, + notes: [`Case type: improvement — flaring down ${pct(vnfDrop)} % year on year (VNF ${prev.year}→${reg.vnf.year}), FIRMS night detections down ${pct(firmsDrop)} %.`], + tags: TAGS, + }; +} + +async function confirmFlaring(ctx: RuleContext, p: P, c0: Pick): Promise { + const days = num(c0.values.windowDays, num(p.days, 30)); + const nextEnd = addDays(c0.observedAt.slice(0, 10), days); + if (today(ctx) <= nextEnd) return null; // the next window has not fully elapsed + const now = (await ctx.call("flaring", firmsArgs(ctx, p, nextEnd, days))) as FlaringResult; + const ly = (await ctx.call("flaring", firmsArgs(ctx, p, addDays(nextEnd, -365), days))) as FlaringResult; + const a = now.counts.hotNightDetections; + const b = ly.counts.hotNightDetections; + if (b <= 0 || ((b - a) / b) * 100 < num(p.minFirmsDropPct, 10)) return null; + const sensor = String(p.source).toLowerCase(); + return { + independence: "revisit", + signal: { + id: `firms-${sensor}-flaring-yoy-${ctx.aoi.id}-${now.window.from}-${now.window.to}-persist`, + kind: "alert", + source: `firms-${sensor}`, + datetime: dayStart(now.window.to), + href: FIRMS_HREF, + method: method("flaring_decline", firmsArgs(ctx, p, nextEnd, days)), + summary: `Second window still lower: ${a} night-time hot detections in ${now.window.from}…${now.window.to} vs ${b} a year earlier.`, + values: { hot_nights_now: a, hot_nights_year_ago: b }, + }, + }; +} + +// ---- bleaching_relief ---------------------------------------------------------------------- + +interface CoralResult { + gridCell: { lat: number; lon: number }; + latest: { date: string; dhw: number | null; alertLevel: number | null; alert: string | null }; + window: { strideDays: number }; + series: { t: string; dhw: number | null; baa: number | null }[]; +} + +/** Pure: when did the reef last have an alert, how bad was the window's peak, how long has it been clear? */ +export function bleachingRelief(r: Pick): { peak: number; peakDhw: number; lastAlert: string; clearDays: number } | null { + if (r.latest.alertLevel !== 0) return null; + const pts = r.series.filter((x) => x.baa !== null && x.t <= r.latest.date); + const alerts = pts.filter((x) => x.baa! >= 1); + const last = alerts[alerts.length - 1]; + if (!last) return null; + // A strided series: the true last alert day may sit up to stride−1 days after the sample. + const clearDays = daysBetween(last.t, r.latest.date) - (Math.max(1, r.window.strideDays) - 1); + return { peak: Math.max(...alerts.map((x) => x.baa!)), peakDhw: Math.max(0, ...pts.map((x) => x.dhw ?? 0)), lastAlert: last.t, clearDays }; +} + +async function detectBleaching(ctx: RuleContext, p: P): Promise { + const pt = pointOf(ctx, p); + const r = (await shared(ctx, "coral_bleaching", { lat: pt.lat, lon: pt.lon, days: num(p.days, 90) })) as CoralResult; + const s = bleachingRelief(r); + if (!s || s.peak < num(p.minPeakLevel, 3) || s.clearDays < num(p.minClearDays, 14)) return null; + const name = ctx.aoi.name ?? ctx.aoi.id; + const peakLabel = BAA_LABEL[s.peak] ?? `level ${s.peak}`; + const observedAt = dayStart(r.latest.date); + const values = { peak_level: s.peak, peak_dhw: s.peakDhw, dhw_now: r.latest.dhw ?? 0, clear_days: s.clearDays, alert_level_now: 0 }; + return { + title: `Coral heat stress has eased at ${name}: no bleaching alert for ${s.clearDays} days`.slice(0, 200), + summary: + `Good news, if it holds: NOAA Coral Reef Watch put the reef cell near ${pt.lat}, ${pt.lon} at "${peakLabel}" within the last ${num(p.days, 90)} days (last on ${s.lastAlert}); ` + + `since then it has been at "No stress" for ${s.clearDays} days (latest ${r.latest.date}, accumulated heat stress ${r.latest.dhw ?? "n/a"} °C-weeks). ` + + `Relief means the heat has stopped building — corals that already bleached take months to years to recover, and some die. A later day still clear confirms it.`, + observedAt, + evidence: [ + { + id: `crw-baa-${ctx.aoi.id}-${r.latest.date}-relief`, + kind: "series", + source: "noaa-crw-coraltemp", + datetime: observedAt, + href: CRW_HREF, + method: method("bleaching_relief", { lat: pt.lat, lon: pt.lon, days: num(p.days, 90), minPeakLevel: num(p.minPeakLevel, 3), minClearDays: num(p.minClearDays, 14) }), + summary: `CRW Bleaching Alert Area at (${r.gridCell.lat}, ${r.gridCell.lon}): peak "${peakLabel}" (level ${s.peak}) in the window, last alert sample ${s.lastAlert}, "No stress" through ${r.latest.date} (series every ${r.window.strideDays} d).`, + values, + }, + ], + values, + geometry: pointGeom(pt.lat, pt.lon), + notes: [`Case type: improvement — reef heat-stress alert lifted (peak ${peakLabel}, clear ${s.clearDays} days).`], + tags: TAGS, + }; +} + +async function confirmBleaching(ctx: RuleContext, p: P, c0: Pick): Promise { + const pt = pointOf(ctx, p); + const r = (await shared(ctx, "coral_bleaching", { lat: pt.lat, lon: pt.lon, days: num(p.days, 90) })) as CoralResult; + if (dayStart(r.latest.date) <= c0.observedAt || r.latest.alertLevel !== 0) return null; + return { + independence: "revisit", + signal: { + id: `crw-baa-${ctx.aoi.id}-${r.latest.date}-relief-persist`, + kind: "series", + source: "noaa-crw-coraltemp", + datetime: dayStart(r.latest.date), + href: CRW_HREF, + method: method("bleaching_relief", { lat: pt.lat, lon: pt.lon }), + summary: `Still "No stress" on ${r.latest.date} (DHW ${r.latest.dhw ?? "n/a"} °C-weeks).`, + values: { alert_level_now: 0, dhw_now: r.latest.dhw ?? 0 }, + }, + }; +} + +// ---- air_quality_clean --------------------------------------------------------------------- + +interface AirResult { + pm25Daily?: { t: string; v: number; hours: number }[]; +} + +/** Pure: mean of the last `window` full days and how many of the `window` full days before were above the guideline. */ +export function airClean(daily: { t: string; v: number; hours: number }[], guideline: number, window = 7): { last: string; mean: number; priorAbove: number; priorMean: number } | null { + const full = daily.filter((d) => d.hours >= 18); + if (full.length < 2 * window) return null; + const recent = full.slice(-window); + const prior = full.slice(-2 * window, -window); + const avg = (xs: { v: number }[]) => round(xs.reduce((s, d) => s + d.v, 0) / xs.length, 1); + return { last: recent[recent.length - 1]!.t, mean: avg(recent), priorAbove: prior.filter((d) => d.v > guideline).length, priorMean: avg(prior) }; +} + +async function air(ctx: RuleContext, p: P) { + const pt = pointOf(ctx, p); + const w = num(p.window, 7); + const r = (await shared(ctx, "air_quality", { lat: pt.lat, lon: pt.lon, pastDays: Math.min(16, 2 * w + 1) })) as AirResult; + if (!r.pm25Daily) throw new Error("air_quality: result has no pm25Daily (tool too old?)"); + return { pt, s: airClean(r.pm25Daily, num(p.guideline, 15), w) }; +} + +async function detectAir(ctx: RuleContext, p: P): Promise { + const g = num(p.guideline, 15); + const w = num(p.window, 7); + const { pt, s } = await air(ctx, p); + if (!s || s.mean >= g || s.priorAbove < num(p.minDaysAbove, 7)) return null; + const name = ctx.aoi.name ?? ctx.aoi.id; + const observedAt = dayStart(s.last); + const values = { pm25_mean_ugm3: s.mean, pm25_prior_mean_ugm3: s.priorMean, prior_days_above: s.priorAbove, guideline_ugm3: g, windowDays: w }; + return { + title: `Cleaner air in ${name}: a week below the WHO fine-particle guideline`.slice(0, 200), + summary: + `Good news, if it holds: modelled PM2.5 near ${pt.lat}, ${pt.lon} averaged ${s.mean} µg/m³ over the ${w} days to ${s.last}, below the WHO 24-hour guideline of ${g} µg/m³, ` + + `after ${s.priorAbove} of the ${w} days before were above it (mean ${s.priorMean}). Rain and wind often clean the air for a while; a later week still below confirms it.`, + observedAt, + evidence: [ + { + id: `cams-pm25-${ctx.aoi.id}-${s.last}-clean`, + kind: "series", + source: "cams-global", + datetime: observedAt, + href: CAMS_HREF, + method: method("air_quality_clean", { lat: pt.lat, lon: pt.lon, guideline: g, window: w, minDaysAbove: num(p.minDaysAbove, 7) }), + summary: `CAMS PM2.5 daily means (UTC, ≥ 18 h): last ${w} full days mean ${s.mean} µg/m³ < ${g}; the ${w} days before: ${s.priorAbove} above (mean ${s.priorMean}).`, + values, + }, + ], + values, + geometry: pointGeom(pt.lat, pt.lon), + notes: [`Case type: improvement — ${w}-day PM2.5 mean ${s.mean} µg/m³, under the WHO guideline after a week above it.`], + tags: TAGS, + }; +} + +async function confirmAir(ctx: RuleContext, p: P, c0: Pick): Promise { + const g = num(p.guideline, 15); + const { pt, s } = await air(ctx, p); + if (!s || dayStart(s.last) <= c0.observedAt || s.mean >= g) return null; + return { + independence: "revisit", + signal: { + id: `cams-pm25-${ctx.aoi.id}-${s.last}-clean-persist`, + kind: "series", + source: "cams-global", + datetime: dayStart(s.last), + href: CAMS_HREF, + method: method("air_quality_clean", { lat: pt.lat, lon: pt.lon, guideline: g }), + summary: `Still below ${g} µg/m³: ${num(p.window, 7)}-day mean ${s.mean} to ${s.last}.`, + values: { pm25_mean_ugm3: s.mean }, + }, + }; +} + +// ---- fires_absent -------------------------------------------------------------------------- + +interface FiresResult { + count: number; + fires: FireDetection[]; +} + +/** Pure: fire clusters = grid cells (cellDeg) holding ≥ clusterMin detections with FRP ≥ minFrp. */ +export function fireClusters(fires: readonly FireDetection[], o: { minFrp: number; clusterMin: number; cellDeg: number }): { hot: number; clusters: number } { + const cells = new Map(); + let hot = 0; + for (const f of fires) { + if ((f.frp ?? 0) < o.minFrp) continue; + hot++; + const k = `${Math.floor(f.lat / o.cellDeg)}:${Math.floor(f.lon / o.cellDeg)}`; + cells.set(k, (cells.get(k) ?? 0) + 1); + } + return { hot, clusters: [...cells.values()].filter((n) => n >= o.clusterMin).length }; +} + +/** FIRMS window ending `end`, ≤5-day chunks, newest first; stops early once a cluster shows up. */ +async function firesWindow(ctx: RuleContext, p: P, end: string, days: number, stopOnCluster: boolean) { + const all: FireDetection[] = []; + const opts = { minFrp: num(p.minFrp, 20), clusterMin: num(p.clusterMin, 3), cellDeg: num(p.cellDeg, 0.05) }; + for (const c of windowChunks(end, days).reverse()) { + const r = (await ctx.call("fires_in", { bbox: ctx.aoi.bbox, dayRange: c.dayRange, date: c.date, source: String(p.source) })) as FiresResult; + all.push(...r.fires); + if (stopOnCluster && fireClusters(all, opts).clusters > 0) break; + } + return { ...fireClusters(all, opts), all: all.length }; +} + +async function detectFires(ctx: RuleContext, p: P): Promise { + const days = num(p.days, 30); + const end = today(ctx); + const now = await firesWindow(ctx, p, end, days, true); + if (now.clusters > 0) return null; + const endLy = addDays(end, -365); + const ly = await firesWindow(ctx, p, endLy, days, false); + if (ly.clusters < 1 || ly.hot < num(p.minHotLastYear, 10)) return null; // it did not burn last year: nothing to celebrate + // Sensor alive: the wider region has detections in the last days — else absence may be a feed gap. + const ring = ringBBox(ctx.aoi.bbox, num(p.aliveRingKm, 100)); + const alive = (await ctx.call("fires_in", { bbox: ring, dayRange: 5, source: String(p.source) })) as FiresResult; + if (alive.count < 1) return null; + + const name = ctx.aoi.name ?? ctx.aoi.id; + const from = addDays(end, -(days - 1)); + const observedAt = dayStart(end); + const minFrp = num(p.minFrp, 20); + const values = { clusters_now: 0, hot_now: now.hot, detections_now: now.all, clusters_year_ago: ly.clusters, hot_year_ago: ly.hot, windowDays: days, ring_detections: alive.count }; + const sensor = String(p.source).toLowerCase(); + return { + title: `No fire clusters in ${name} so far this season — ${ly.hot} hot fire detections in the same weeks last year`.slice(0, 200), + summary: + `Good news, if it holds: in the ${days} days to ${end} the satellite found no cluster of hot fires (FRP ≥ ${minFrp} MW) in the watch window around ${name}, ` + + `where the same weeks last year held ${ly.clusters} cluster(s) and ${ly.hot} hot detections. The sensor is working nearby (${alive.count} detections within ${num(p.aliveRingKm, 100)} km in the last 5 days). ` + + `Rain, cloud or a later fire season can explain a quiet spell; the next sweep still quiet confirms it.`, + observedAt, + evidence: [ + { + id: `firms-${sensor}-absent-${ctx.aoi.id}-${from}-${end}`, + kind: "alert", + source: `firms-${sensor}`, + datetime: observedAt, + href: FIRMS_HREF, + method: method("fires_absent", { days, minFrp, clusterMin: num(p.clusterMin, 3), cellDeg: num(p.cellDeg, 0.05), source: String(p.source) }), + summary: + `${from}…${end}: ${now.all} detection(s), ${now.hot} with FRP ≥ ${minFrp} MW, 0 clusters (≥ ${num(p.clusterMin, 3)} hot per ${num(p.cellDeg, 0.05)}° cell). ` + + `${addDays(endLy, -(days - 1))}…${endLy}: ${ly.all} detection(s), ${ly.hot} hot, ${ly.clusters} cluster(s). ${String(p.source)} both years.`, + values, + }, + ], + values, + notes: [`Case type: improvement — no fire clusters this season so far where ${ly.clusters} burned in the same weeks last year.`], + tags: TAGS, + }; +} + +async function confirmFires(ctx: RuleContext, p: P, c0: Pick): Promise { + const since = c0.observedAt.slice(0, 10); + const end = today(ctx); + const gap = daysBetween(since, end); + if (gap < num(p.revisitDays, 5)) return null; + const days = Math.min(num(p.days, 30), gap); + const r = await firesWindow(ctx, p, end, days, true); + if (r.clusters > 0) return null; + const sensor = String(p.source).toLowerCase(); + const from = addDays(end, -(days - 1)); + return { + independence: "revisit", + signal: { + id: `firms-${sensor}-absent-${ctx.aoi.id}-${from}-${end}-persist`, + kind: "alert", + source: `firms-${sensor}`, + datetime: dayStart(end), + href: FIRMS_HREF, + method: method("fires_absent", { days, minFrp: num(p.minFrp, 20), source: String(p.source) }), + summary: `Still no fire cluster on later passes (${from}…${end}: ${r.all} detection(s), ${r.hot} hot).`, + values: { clusters_now: 0, hot_now: r.hot }, + }, + }; +} + +// ---- the rule ------------------------------------------------------------------------------ + +const DETECT: Record Promise> = { + forest_recovery: detectForest, + flaring_decline: detectFlaring, + bleaching_relief: detectBleaching, + air_quality_clean: detectAir, + fires_absent: detectFires, +}; + +export const improvement = defineRule({ + name: "improvement", + version: "1.0", + tier: 1, + description: "Good news, held to the same evidence standard: forest loss, gas flaring, reef heat stress, air pollution or fire at a watched place fell clearly below where it was.", + blindSpots: [ + "All: an improvement is a measured drop, not a cause — policy, enforcement, rain, market prices or a data change can all produce it, and the case does not say which.", + "Forest: GFW alerts cover 30°N–30°S only and lag 1–2 weeks; both windows end two weeks before the sweep, but late alerts can still fill in the recent one.", + "Forest: cloud hides optical alerts and RADD (radar) covers only part of the tropics; a cloudy season can look like less clearing.", + "Forest: confirmation is the next 30 days staying low year on year — a case waits at least ~45 days; the optional whole-box NDVI check (off by default) cannot see clearings of this size.", + "Flaring: the two VNF years come from different satellites (S-NPP 2023, NOAA-20 2024); part of a change can be calibration, not gas.", + "Flaring: less flaring can mean less oil produced, gas vented cold (invisible to heat sensors) or re-routed to another flare, not gas put to use.", + "Reefs: one 5 km CRW cell stands for the reef; 'No stress' means the heat stopped building, not that bleached corals recovered or survived.", + "Air: CAMS is a ~40 km model, not a monitor; a clean week is often weather (monsoon rain, wind), not lower emissions.", + "Fires: a quiet spell can be rain, cloud, smoke or a late fire season; the box is a watch window, not the legal boundary; VIIRS misses small, short fires between passes.", + "Fires/flaring: year-on-year FIRMS counts use NOAA-21 only (the one VIIRS feed FIRMS keeps back to 2024); a NOAA-21 outage looks like calm — the fire check requires detections nearby.", + ], + requires: [], + // Only the forest NDVI check spends Copernicus: when that quota is spent, confirmation waits + // (every kind; detection still runs). Missing keys fall back to the persistence check. + confirmRequires: ["CDSE_CLIENT_ID", "CDSE_CLIENT_SECRET"], + ringKm: 25, + defaults: {}, + + async detect(ctx: RuleContext): Promise { + const { kind, p } = improvementParams(ctx.params); + return DETECT[kind](ctx, p); + }, + + async confirm(ctx: RuleContext, c): Promise { + const { kind, p } = improvementParams(ctx.params); + switch (kind) { + case "forest_recovery": + return confirmForest(ctx, p, c); + case "flaring_decline": + return confirmFlaring(ctx, p, c); + case "bleaching_relief": + return confirmBleaching(ctx, p, c); + case "air_quality_clean": + return confirmAir(ctx, p, c); + case "fires_absent": + return confirmFires(ctx, p, c); + } + }, +}); diff --git a/src/watch/rules/index.ts b/src/watch/rules/index.ts index 0f57911..613e070 100644 --- a/src/watch/rules/index.ts +++ b/src/watch/rules/index.ts @@ -1,11 +1,16 @@ import { firesInProtected } from "./firesInProtected.js"; import { flaring, flaringStopped } from "./flaring.js"; import { forestLoss } from "./forestLoss.js"; +import { improvement } from "./improvement.js"; +import { indicatorThreshold } from "./indicatorThreshold.js"; +import { indicatorTrend } from "./indicatorTrend.js"; import { methaneAnomaly } from "./methaneAnomaly.js"; +import { mpaFishing } from "./mpaFishing.js"; import type { Rule } from "./types.js"; +import { weatherExtreme } from "./weatherExtreme.js"; /** Every rule the kernel knows. Adding one = one import here + a plan note on its blind spots. */ -export const RULES: ReadonlyMap = new Map([forestLoss, firesInProtected, flaring, flaringStopped, methaneAnomaly].map((r) => [r.name, r])); +export const RULES: ReadonlyMap = new Map([forestLoss, firesInProtected, flaring, flaringStopped, methaneAnomaly, weatherExtreme, indicatorThreshold, indicatorTrend, improvement, mpaFishing].map((r) => [r.name, r])); export { defineRule, ToolError } from "./types.js"; export type { Rule, RuleContext, Candidate, Confirmation, ToolCall } from "./types.js"; diff --git a/src/watch/rules/indicatorThreshold.ts b/src/watch/rules/indicatorThreshold.ts new file mode 100644 index 0000000..c1e8fae --- /dev/null +++ b/src/watch/rules/indicatorThreshold.ts @@ -0,0 +1,700 @@ +// indicator_threshold@1.0 — one generic rule over the zero-key planetary indicators the repo +// already ingests. The AOI's params pick the indicator; each has its own detector and its own +// second signal: +// +// sea_ice NSIDC extent below the 1981–2010 p10 for the latest day → confirm: still below on a later day (revisit) +// marine_heatwave OISST anomaly ≥ minAnomalyC for ≥ minDays at a point → confirm: still hot on a later day (revisit) +// river_discharge GloFAS discharge ≥ ratio × the period mean at a point → confirm: an EONET flood event within floodKm (provider), else a later day still high (revisit) +// air_quality CAMS PM2.5 daily mean > WHO 15 µg/m³ for ≥ minDays → confirm: a later full day still above (revisit) +// enso ONI meets NOAA's event definition (≥ 5 seasons beyond ±0.5) → confirm: OISST at the Niño3.4 centre has the same-sign anomaly (method) +// quake USGS M ≥ minMagnitude inside the AOI bbox → confirm: USGS marks it "reviewed" with sig ≥ minSig (method — same provider) +// +// Persistence confirmations compare data dates, not sweep times: in the sweep that opens the +// case the data has not moved on, so confirmation always waits for a later observation. +// Every value is a plain number; titles name places (the AOI), never people or companies. + +import type { Evidence, Geometry } from "../../ledger/schema.js"; +import { round } from "../../series.js"; +import { addDays } from "../../util.js"; +import { dayStart, defineRule, num, ringBBox, type Candidate, type Confirmation, type RuleContext, type ToolCall } from "./types.js"; + +export const INDICATOR_KINDS = ["sea_ice", "marine_heatwave", "river_discharge", "air_quality", "enso", "quake"] as const; +export type IndicatorKind = (typeof INDICATOR_KINDS)[number]; + +/** Per-indicator defaults (the rule-level `defaults` stay empty so a case's params show only what applies). */ +export const INDICATOR_DEFAULTS: Record> = { + sea_ice: { hemisphere: "arctic" }, + marine_heatwave: { minAnomalyC: 1.5, minDays: 5, baselineYears: 10 }, + // minSeasonalRatio (optional): also require latest ≥ this × the same calendar month of the + // other years — keeps a monsoon peak that is normal for the season from opening a case. + river_discharge: { ratio: 2.0, years: 10, floodKm: 200 }, + air_quality: { minDays: 3, guideline: 15 }, + enso: { confirmAnomalyC: 0.3, baselineYears: 10 }, + quake: { minMagnitude: 7.0, minSig: 600, days: 7 }, +}; + +const NINO34 = { lat: 0, lon: -145 }; // centre of the Niño3.4 box (5°N–5°S, 170°W–120°W) +const WHO_PM25 = 15; + +// ---- tool result shapes (the fields this rule reads) -------------------------------------- + +interface SeaIceResult { + source: string; + pole: "north" | "south"; + latest: { t: string; v: number }; + anomalyVsAverage: number | null; + belowP10: boolean | null; + climatologyForDay: { doy: number; average: number; p10: number } | null; +} +interface OceanTempResult { + source: string; + gridCell: { lat: number; lon: number }; + window: { from: string; to: string; strideDays: number }; + series: { t: string; v: number | null }[]; +} +interface RiverResult { + source: string; + unit: string; + window: { from: string; to: string }; + latest: { t: string; v: number | null } | null; + stats: { mean: number | null }; + latestVsMean: number | null; + series: { t: string; v: number | null }[]; +} +interface AirResult { + source: string; + pm25Daily?: { t: string; v: number; hours: number }[]; +} +interface EnsoResult { + source: string; + phase: string; + latest: { season: string; year: number; oni: number }; + consecutiveSeasons: number; + meetsEventDefinition: boolean; + series: { t: string; v: number | null }[]; +} +interface QuakeRow { + id: string; + mag: number | null; + place: string; + time: string; + lon: number; + lat: number; + depthKm: number | null; + tsunami: boolean; + alert: string | null; + url: string; + sig?: number | null; + status?: string | null; +} +interface QuakesResult { + source: string; + window: { from: string; to: string }; + quakes: QuakeRow[]; +} +interface EventsResult { + events: { id: string; title: string; category: string; lastDate: string | null; coordinates: [number, number] | null; link: string }[]; +} + +// ---- shared helpers ---------------------------------------------------------------------- + +type P = Record; + +/** The indicator an AOI asks for, with its defaults merged under the AOI's params. */ +export function indicatorParams(params: P): { kind: IndicatorKind; p: P } { + const kind = params.indicator as IndicatorKind; + if (!INDICATOR_KINDS.includes(kind)) throw new Error(`indicator_threshold: params.indicator must be one of ${INDICATOR_KINDS.join(", ")} (got ${JSON.stringify(params.indicator)})`); + const p = { ...INDICATOR_DEFAULTS[kind], ...params }; + if (kind === "sea_ice" && p.hemisphere !== "arctic" && p.hemisphere !== "antarctic") throw new Error(`indicator_threshold: sea_ice hemisphere must be arctic or antarctic (got ${JSON.stringify(p.hemisphere)})`); + return { kind, p }; +} + +/** The point an AOI is about: explicit params.lat/lon, else the bbox centre. */ +function pointOf(ctx: RuleContext, p: P): { lat: number; lon: number } { + const [w, s, e, n] = ctx.aoi.bbox; + return { lat: num(p.lat, round((s + n) / 2, 3)), lon: num(p.lon, round((w + e) / 2, 3)) }; +} + +const pointGeom = (lat: number, lon: number): Geometry => ({ type: "Point", coordinates: [round(lon, 3), round(lat, 3)] }); + +// One pull per tool+args per sweep, shared by detect and confirm. Scoped to the sweep-level +// caller (the kernel exposes it as `base` on its per-rule wrappers) AND the sweep's `now`, so +// a caller reused across sweeps never serves last sweep's data. +const memo = new WeakMap> }>(); +function shared(ctx: RuleContext, tool: string, args: Record): Promise { + const call = ctx.call; + const scope = (call as ToolCall & { base?: ToolCall }).base ?? call; + let slot = memo.get(scope); + if (!slot || slot.now !== ctx.now) memo.set(scope, (slot = { now: ctx.now, m: new Map() })); + const m = slot.m; + const key = `${tool} ${JSON.stringify(args)}`; + let pr = m.get(key); + if (!pr) { + pr = call(tool, args); + m.set(key, pr); + pr.catch(() => m.delete(key)); + } + return pr; +} + +function method(kind: IndicatorKind, params: P): Evidence["method"] { + return { name: "indicator_threshold", version: "1.0", params: { indicator: kind, ...params } }; +} + +const today = (ctx: RuleContext) => ctx.now.slice(0, 10); +const sign = (v: number) => (v >= 0 ? "+" : "−"); +const abs1 = (v: number) => Math.abs(v).toFixed(1); + +function kmBetween(a: { lat: number; lon: number }, b: { lat: number; lon: number }): number { + const rad = Math.PI / 180; + const dLat = (b.lat - a.lat) * rad; + const dLon = (b.lon - a.lon) * rad; + const h = Math.sin(dLat / 2) ** 2 + Math.cos(a.lat * rad) * Math.cos(b.lat * rad) * Math.sin(dLon / 2) ** 2; + return 2 * 6371 * Math.asin(Math.min(1, Math.sqrt(h))); +} + +// ---- sea ice ----------------------------------------------------------------------------- + +async function seaIce(ctx: RuleContext, p: P) { + const pole = p.hemisphere === "antarctic" ? "south" : "north"; + const r = (await shared(ctx, "sea_ice", { pole })) as SeaIceResult; + const c = r.climatologyForDay; + if (!c || r.latest?.v == null) throw new Error("sea_ice: no climatology match for the latest day"); + return { r, c, label: pole === "north" ? "Arctic" : "Antarctic", below: r.latest.v < c.p10 }; +} + +async function detectSeaIce(ctx: RuleContext, p: P): Promise { + const { r, c, label, below } = await seaIce(ctx, p); + if (!below) return null; + const under = round(c.p10 - r.latest.v, 3); + const values = { extent_mkm2: r.latest.v, p10_mkm2: c.p10, anomaly_mkm2: r.anomalyVsAverage ?? round(r.latest.v - c.average, 3), below_p10_mkm2: under }; + const observedAt = dayStart(r.latest.t); + return { + title: `${label} sea ice is below the lowest tenth of past years — ${r.latest.v.toFixed(2)} M km², ${under.toFixed(2)} M km² under the p10 line`, + summary: + `On ${r.latest.t} ${label} sea-ice extent was ${r.latest.v} million km². For this day of the year, 9 in 10 years of 1981–2010 had more ice (the 10th percentile is ${c.p10} M km²); ` + + `the 1981–2010 average is ${c.average} M km², so today is ${Math.abs(values.anomaly_mkm2)} M km² ${values.anomaly_mkm2 < 0 ? "below" : "above"} average. ` + + `A second, later day still below the line confirms it is not a one-day blip.`, + observedAt, + evidence: [ + { + id: `nsidc-${r.pole}-extent-${r.latest.t}`, + kind: "series", + source: "nsidc-g02135-v4", + datetime: observedAt, + href: "https://nsidc.org/data/g02135", + method: method("sea_ice", { hemisphere: p.hemisphere }), + summary: `${label} daily extent ${r.latest.v} M km² on ${r.latest.t}; 1981–2010 p10 for day ${c.doy} = ${c.p10} M km², average ${c.average} M km².`, + values, + }, + ], + values, + notes: [`Dataset: NSIDC Sea Ice Index v4 (G02135), daily extent vs the 1981–2010 day-of-year climatology (5-day trailing mean, passive microwave). Window: ${r.latest.t}.`], + }; +} + +async function confirmSeaIce(ctx: RuleContext, p: P, c0: Pick): Promise { + const { r, c, label, below } = await seaIce(ctx, p); + if (!below || dayStart(r.latest.t) <= c0.observedAt) return null; + return { + independence: "revisit", + signal: { + id: `nsidc-${r.pole}-extent-${r.latest.t}-persist`, + kind: "series", + source: "nsidc-g02135-v4", + datetime: dayStart(r.latest.t), + href: "https://nsidc.org/data/g02135", + method: method("sea_ice", { hemisphere: p.hemisphere }), + summary: `${label} extent still below p10 on a later day: ${r.latest.v} M km² vs p10 ${c.p10} M km² (${r.latest.t}).`, + values: { extent_mkm2: r.latest.v, p10_mkm2: c.p10, below_p10_mkm2: round(c.p10 - r.latest.v, 3) }, + }, + }; +} + +// ---- sea-surface temperature anomaly (marine heatwave + ENSO confirmation) --------------- + +export interface SstAnomaly { + latest: { t: string; sst: number; clim: number; anomaly: number }; + /** Consecutive most-recent days with anomaly ≥ threshold. */ + streak: number; + wholeWindow: boolean; + maxAnomaly: number; + /** Mean anomaly over the whole recent window. */ + meanAnomaly: number; + gridCell: { lat: number; lon: number }; + window: { from: string; to: string }; + baseline: { from: string; to: string; points: number }; + source: string; +} + +function doy(date: string): number { + const d = Date.parse(`${date}T00:00:00Z`); + return Math.floor((d - Date.UTC(Number(date.slice(0, 4)), 0, 1)) / 86_400_000) + 1; +} + +/** + * Pure: SST anomalies of `recent` against a day-of-year climatology built from `base` (±15 + * days, circular), plus the trailing streak at or above `threshold`. Null when the baseline + * is too thin (< 8 points) for the latest day. + */ +export function sstAnomalies(recent: { t: string; v: number | null }[], base: { t: string; v: number | null }[], threshold: number) { + const basePts = base.filter((b): b is { t: string; v: number } => b.v !== null).map((b) => ({ d: doy(b.t), v: b.v })); + const climFor = (date: string): number | null => { + const d = doy(date); + const near = basePts.filter((b) => Math.min(Math.abs(b.d - d), 366 - Math.abs(b.d - d)) <= 15); + return near.length >= 8 ? near.reduce((s, b) => s + b.v, 0) / near.length : null; + }; + const rows = recent + .filter((r): r is { t: string; v: number } => r.v !== null) + .map((r) => { + const c = climFor(r.t); + return c === null ? null : { t: r.t, sst: r.v, clim: round(c, 2), anomaly: round(r.v - c, 2) }; + }) + .filter((r): r is NonNullable => r !== null); + const latest = rows[rows.length - 1]; + if (!latest) return null; + let streak = 0; + for (let i = rows.length - 1; i >= 0 && rows[i]!.anomaly >= threshold; i--) streak++; + return { + latest, + streak, + /** The streak spans every day fetched: the heat started before the window. */ + wholeWindow: streak === rows.length, + maxAnomaly: Math.max(...rows.slice(rows.length - Math.max(1, streak)).map((r) => r.anomaly)), + meanAnomaly: round(rows.reduce((s, r) => s + r.anomaly, 0) / rows.length, 2), + }; +} + +async function sstAnomaly(ctx: RuleContext, pt: { lat: number; lon: number }, recentDays: number, baselineYears: number, threshold: number): Promise { + const t = today(ctx); + const y = Number(t.slice(0, 4)); + const baseArgs = { lat: pt.lat, lon: pt.lon, start: `${y - baselineYears}-01-01`, end: `${y - 1}-12-31` }; + const [recent, base] = (await Promise.all([ + shared(ctx, "ocean_temp", { lat: pt.lat, lon: pt.lon, start: addDays(t, -recentDays) }), + shared(ctx, "ocean_temp", baseArgs), + ])) as [OceanTempResult, OceanTempResult]; + const a = sstAnomalies(recent.series, base.series, threshold); + if (!a) throw new Error(`ocean_temp: baseline too thin for a climatology at ${pt.lat}, ${pt.lon}`); + return { ...a, gridCell: recent.gridCell, window: { from: recent.window.from, to: recent.window.to }, baseline: { from: base.window.from, to: base.window.to, points: base.series.length }, source: recent.source }; +} + +async function detectHeatwave(ctx: RuleContext, p: P): Promise { + const pt = pointOf(ctx, p); + const minA = num(p.minAnomalyC, 1.5); + const minDays = num(p.minDays, 5); + const a = await sstAnomaly(ctx, pt, 60, num(p.baselineYears, 10), minA); + if (a.streak < minDays) return null; + const values = { sst_c: a.latest.sst, climatology_c: a.latest.clim, anomaly_c: a.latest.anomaly, days_over: a.streak, max_anomaly_c: a.maxAnomaly, threshold_c: minA }; + const observedAt = dayStart(a.latest.t); + return { + title: `Marine heatwave at ${ctx.aoi.name}: the sea surface is ${abs1(a.latest.anomaly)} °C warmer than normal, ${a.wholeWindow ? "at least " : ""}${a.streak} days running`.slice(0, 200), + summary: + `Sea-surface temperature at ${a.gridCell.lat}, ${a.gridCell.lon} was ${a.latest.sst} °C on ${a.latest.t}, ${a.latest.anomaly} °C above the same time of year in ${a.baseline.from.slice(0, 4)}–${a.baseline.to.slice(0, 4)} (${a.latest.clim} °C). ` + + `It has been at least ${minA} °C above normal for ${a.wholeWindow ? `all ${a.streak} days fetched (it began earlier)` : `${a.streak} consecutive days`} (peak ${a.maxAnomaly} °C). Heat this persistent stresses corals, kelp and fisheries; a later day still this warm confirms it.`, + observedAt, + evidence: [ + { + id: `oisst-${ctx.aoi.id}-${a.latest.t}`, + kind: "series", + source: "noaa-oisst-v2.1", + datetime: observedAt, + href: "https://www.ncei.noaa.gov/products/optimum-interpolation-sst", + method: method("marine_heatwave", { minAnomalyC: minA, minDays, baselineYears: num(p.baselineYears, 10), lat: pt.lat, lon: pt.lon }), + summary: `OISST ${a.window.from}…${a.window.to} at ${a.gridCell.lat}, ${a.gridCell.lon}: ${a.streak} trailing days ≥ +${minA} °C vs a ±15-day climatology from ${a.baseline.points} points.`, + values, + }, + ], + values, + geometry: pointGeom(a.gridCell.lat, a.gridCell.lon), + notes: [`Dataset: NOAA OISST v2.1 (0.25°, daily, satellite + in-situ) via ERDDAP. Window ${a.window.from}…${a.window.to}; climatology = same ±15 days of ${a.baseline.from.slice(0, 4)}–${a.baseline.to.slice(0, 4)}.`], + }; +} + +async function confirmHeatwave(ctx: RuleContext, p: P, c0: Pick): Promise { + const pt = pointOf(ctx, p); + const minA = num(p.minAnomalyC, 1.5); + const a = await sstAnomaly(ctx, pt, 60, num(p.baselineYears, 10), minA); + if (a.latest.anomaly < minA || dayStart(a.latest.t) <= c0.observedAt) return null; + return { + independence: "revisit", + signal: { + id: `oisst-${ctx.aoi.id}-${a.latest.t}-persist`, + kind: "series", + source: "noaa-oisst-v2.1", + datetime: dayStart(a.latest.t), + href: "https://www.ncei.noaa.gov/products/optimum-interpolation-sst", + method: method("marine_heatwave", { minAnomalyC: minA, lat: pt.lat, lon: pt.lon }), + summary: `Still ${a.latest.anomaly} °C above normal on ${a.latest.t} (${a.streak} days running).`, + values: { anomaly_c: a.latest.anomaly, days_over: a.streak }, + }, + }; +} + +// ---- river discharge --------------------------------------------------------------------- + +async function river(ctx: RuleContext, p: P) { + const pt = pointOf(ctx, p); + const t = today(ctx); + const r = (await shared(ctx, "river_discharge", { lat: pt.lat, lon: pt.lon, start: addDays(t, -Math.round(num(p.years, 10) * 365)) })) as RiverResult; + if (r.latest?.v == null || !r.stats.mean) throw new Error("river_discharge: no latest value or period mean"); + const ratio = r.latestVsMean ?? round(r.latest.v / r.stats.mean, 2); + // Same calendar month in the other years of the window: how unusual is it for the season? + const month = r.latest.t.slice(5, 7); + const year = r.latest.t.slice(0, 4); + const same = r.series.filter((s) => s.v !== null && s.t.slice(5, 7) === month && s.t.slice(0, 4) !== year).map((s) => s.v!); + const seasonalMean = same.length >= 3 ? same.reduce((a, b) => a + b, 0) / same.length : null; + return { pt, r, ratio, seasonalRatio: seasonalMean ? round(r.latest.v / seasonalMean, 2) : null, latest: r.latest as { t: string; v: number }, mean: r.stats.mean }; +} + +async function detectRiver(ctx: RuleContext, p: P): Promise { + const k = num(p.ratio, 2); + const { pt, r, ratio, seasonalRatio, latest, mean } = await river(ctx, p); + if (ratio < k) return null; + const minSeasonal = typeof p.minSeasonalRatio === "number" ? p.minSeasonalRatio : null; + if (minSeasonal !== null && (seasonalRatio === null || seasonalRatio < minSeasonal)) return null; + const values: Record = { discharge_m3s: latest.v, mean_m3s: round(mean, 1), ratio, threshold_ratio: k }; + if (seasonalRatio !== null) values.seasonal_ratio = seasonalRatio; + const observedAt = dayStart(latest.t); + return { + title: `${ctx.aoi.name} is running high: ${Math.round(latest.v).toLocaleString("en-US")} m³/s, ${ratio}× its ${num(p.years, 10)}-year average`.slice(0, 200), + summary: + `Modelled river discharge at ${pt.lat}, ${pt.lon} was ${latest.v} m³/s on ${latest.t} — ${ratio}× the ${r.window.from.slice(0, 4)}–${r.window.to.slice(0, 4)} mean of ${round(mean, 1)} m³/s (threshold ${k}×). ` + + (seasonalRatio !== null ? `Against the same month in other years it is ${seasonalRatio}×${seasonalRatio < 1.2 ? " — high water for the season, not above it" : ""}. ` : "") + + `A flood report nearby (NASA EONET) or a later day still this high confirms it.`, + observedAt, + evidence: [ + { + id: `glofas-${ctx.aoi.id}-${latest.t}`, + kind: "series", + source: "glofas-v4", + datetime: observedAt, + href: "https://open-meteo.com/en/docs/flood-api", + method: method("river_discharge", { ratio: k, years: num(p.years, 10), lat: pt.lat, lon: pt.lon, ...(minSeasonal !== null ? { minSeasonalRatio: minSeasonal } : {}) }), + summary: `GloFAS discharge ${latest.v} m³/s on ${latest.t}; period mean ${round(mean, 1)} m³/s (${r.window.from}…${r.window.to}).`, + values, + }, + ], + values, + geometry: pointGeom(pt.lat, pt.lon), + notes: [`Dataset: GloFAS river discharge (hydrological model, ~5 km) via Open-Meteo. Window ${r.window.from}…${r.window.to}; mean over the whole window, all seasons.`], + tags: ["high-water"], + }; +} + +async function confirmRiver(ctx: RuleContext, p: P, c0: Pick): Promise { + const pt = pointOf(ctx, p); + const km = num(p.floodKm, 200); + const box: [number, number, number, number] = ringBBox([pt.lon - 0.01, pt.lat - 0.01, pt.lon + 0.01, pt.lat + 0.01], km); + const ev = (await shared(ctx, "events", { category: "floods", status: "all", bbox: box, days: 30, limit: 50 })) as EventsResult; + const flood = ev.events.find((e) => e.coordinates && kmBetween(pt, { lon: e.coordinates[0], lat: e.coordinates[1] }) <= km); + if (flood) { + const d = kmBetween(pt, { lon: flood.coordinates![0], lat: flood.coordinates![1] }); + return { + independence: "provider", + signal: { + id: flood.id, + kind: "alert", + source: "nasa-eonet", + datetime: flood.lastDate && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(flood.lastDate) ? flood.lastDate : ctx.now.replace(/\.\d+Z$/, "Z"), + href: flood.link?.startsWith("http") ? flood.link : undefined, + method: method("river_discharge", { floodKm: km }), + summary: `EONET flood event "${flood.title}" ${round(d, 0)} km from the gauge point.`.slice(0, 2000), + values: { flood_km: round(d, 1) }, + }, + }; + } + const { ratio, seasonalRatio, latest } = await river(ctx, p); + const minSeasonal = typeof p.minSeasonalRatio === "number" ? p.minSeasonalRatio : null; + if (ratio < num(p.ratio, 2) || (minSeasonal !== null && (seasonalRatio === null || seasonalRatio < minSeasonal)) || dayStart(latest.t) <= c0.observedAt) return null; + return { + independence: "revisit", + signal: { + id: `glofas-${ctx.aoi.id}-${latest.t}-persist`, + kind: "series", + source: "glofas-v4", + datetime: dayStart(latest.t), + href: "https://open-meteo.com/en/docs/flood-api", + method: method("river_discharge", { ratio: num(p.ratio, 2), lat: pt.lat, lon: pt.lon }), + summary: `Still ${ratio}× the period mean on ${latest.t} (${latest.v} m³/s).`, + values: { discharge_m3s: latest.v, ratio }, + }, + }; +} + +// ---- air quality ------------------------------------------------------------------------- + +/** Pure: trailing run of full days (≥ 18 valid hours) with PM2.5 mean above `guideline`. */ +export function pm25Streak(daily: { t: string; v: number; hours: number }[], guideline: number) { + const full = daily.filter((d) => d.hours >= 18); + const last = full[full.length - 1]; + if (!last) return null; + let n = 0; + for (let i = full.length - 1; i >= 0 && full[i]!.v > guideline; i--) n++; + const run = full.slice(full.length - n); + return { last, days: n, max: run.length ? Math.max(...run.map((d) => d.v)) : last.v, mean: run.length ? round(run.reduce((s, d) => s + d.v, 0) / run.length, 1) : last.v }; +} + +async function air(ctx: RuleContext, p: P) { + const pt = pointOf(ctx, p); + const r = (await shared(ctx, "air_quality", { lat: pt.lat, lon: pt.lon, pastDays: 7 })) as AirResult; + if (!r.pm25Daily) throw new Error("air_quality: result has no pm25Daily (tool too old?)"); + const s = pm25Streak(r.pm25Daily, num(p.guideline, WHO_PM25)); + if (!s) throw new Error("air_quality: no full day of PM2.5 data"); + return { pt, s }; +} + +async function detectAir(ctx: RuleContext, p: P): Promise { + const minDays = num(p.minDays, 3); + const g = num(p.guideline, WHO_PM25); + const { pt, s } = await air(ctx, p); + if (s.days < minDays) return null; + const values = { pm25_daily_ugm3: s.last.v, days_over: s.days, guideline_ugm3: g, pm25_mean_ugm3: s.mean, pm25_max_ugm3: s.max, times_guideline: round(s.last.v / g, 1) }; + const observedAt = dayStart(s.last.t); + return { + title: `${ctx.aoi.name}: fine-particle pollution above the WHO limit ${s.days} days running — ${s.last.v} µg/m³, ${values.times_guideline}× the guideline`.slice(0, 200), + summary: + `Modelled PM2.5 near ${pt.lat}, ${pt.lon} averaged ${s.last.v} µg/m³ on ${s.last.t}; every one of the last ${s.days} full days was above the WHO 24-hour guideline of ${g} µg/m³ ` + + `(mean ${s.mean}, worst day ${s.max}). Fine particles reach deep into the lungs; a later day still above the limit confirms the episode.`, + observedAt, + evidence: [ + { + id: `cams-pm25-${ctx.aoi.id}-${s.last.t}`, + kind: "series", + source: "cams-global", + datetime: observedAt, + href: "https://open-meteo.com/en/docs/air-quality-api", + method: method("air_quality", { minDays, guideline: g, lat: pt.lat, lon: pt.lon }), + summary: `CAMS PM2.5 daily means (UTC, ≥ 18 h): ${s.days} trailing day(s) above ${g} µg/m³, latest ${s.last.t} = ${s.last.v}.`, + values, + }, + ], + values, + geometry: pointGeom(pt.lat, pt.lon), + notes: [`Dataset: Copernicus CAMS global forecast/analysis (~40 km) via Open-Meteo, hourly PM2.5 averaged to UTC days; last 7 days, forecast hours excluded.`], + }; +} + +async function confirmAir(ctx: RuleContext, p: P, c0: Pick): Promise { + const g = num(p.guideline, WHO_PM25); + const { pt, s } = await air(ctx, p); + if (s.days < 1 || dayStart(s.last.t) <= c0.observedAt) return null; + return { + independence: "revisit", + signal: { + id: `cams-pm25-${ctx.aoi.id}-${s.last.t}-persist`, + kind: "series", + source: "cams-global", + datetime: dayStart(s.last.t), + href: "https://open-meteo.com/en/docs/air-quality-api", + method: method("air_quality", { guideline: g, lat: pt.lat, lon: pt.lon }), + summary: `Still above ${g} µg/m³ on ${s.last.t}: ${s.last.v} µg/m³ (${s.days} days running).`, + values: { pm25_daily_ugm3: s.last.v, days_over: s.days }, + }, + }; +} + +// ---- ENSO -------------------------------------------------------------------------------- + +async function detectEnso(ctx: RuleContext, _p: P): Promise { + const r = (await shared(ctx, "enso", { months: 36 })) as EnsoResult; + if (!r.meetsEventDefinition || r.phase === "Neutral") return null; + const dir = r.latest.oni >= 0 ? 1 : -1; + const start = r.series[r.series.length - r.consecutiveSeasons]?.t ?? `${r.latest.year}`; + const end = r.series[r.series.length - 1]?.t ?? `${r.latest.year}`; + const values = { oni_c: r.latest.oni, consecutive_seasons: r.consecutiveSeasons, phase_sign: dir }; + const observedAt = dayStart(`${end.slice(0, 7)}-01`.slice(0, 10)); + return { + title: `${r.phase} is here: the Pacific has been ${dir > 0 ? "warmer" : "cooler"} than normal for ${r.consecutiveSeasons} seasons in a row (ONI ${sign(r.latest.oni)}${Math.abs(r.latest.oni)} °C)`.slice(0, 200), + summary: + `NOAA's Oceanic Niño Index was ${sign(r.latest.oni)}${Math.abs(r.latest.oni)} °C for ${r.latest.season} ${r.latest.year}, making ${r.consecutiveSeasons} overlapping 3-month seasons in a row beyond ${dir > 0 ? "+" : "−"}0.5 °C — ` + + `NOAA's definition of ${r.phase === "El Niño" ? "an El Niño" : "a La Niña"} event. ${r.phase === "El Niño" ? "El Niño years tend to bring drought to Australia, Indonesia and southern Africa, heavier rain to Peru, and coral bleaching." : "La Niña years tend to bring drought to the Horn of Africa and the southern US and floods to Australia and Southeast Asia."} ` + + `Satellite sea-surface temperature in the Niño3.4 region pointing the same way confirms it.`, + observedAt, + evidence: [ + { + // One id per ONI release, so monthly updates keep the one case per event alive. + id: `cpc-oni-${dir > 0 ? "elnino" : "lanina"}-${start}-${end}`, + kind: "series", + source: "noaa-cpc-oni", + datetime: observedAt, + href: "https://origin.cpc.ncep.noaa.gov/products/analysis_monitoring/ensostuff/ONI_v5.php", + method: method("enso", {}), + summary: `ONI ${r.consecutiveSeasons} consecutive seasons beyond ±0.5 °C, ${start}…${end} (season midpoints); latest ${r.latest.season} ${r.latest.year} = ${r.latest.oni} °C.`, + values, + }, + ], + values, + geometry: { type: "Polygon", coordinates: [[[-170, -5], [-120, -5], [-120, 5], [-170, 5], [-170, -5]]] }, + notes: [`Dataset: NOAA CPC ONI (ERSSTv5 Niño3.4, 3-month running means, 1991–2020 base). Event run ${start}…${end}.`], + tags: [dir > 0 ? "el-nino" : "la-nina"], + }; +} + +async function confirmEnso(ctx: RuleContext, p: P, c0: Pick): Promise { + const dir = num(c0.values.phase_sign, 0); + const need = num(p.confirmAnomalyC, 0.3); + const a = await sstAnomaly(ctx, NINO34, 90, num(p.baselineYears, 10), Number.POSITIVE_INFINITY); + if (dir === 0 || a.meanAnomaly * dir < need) return null; + return { + independence: "method", + signal: { + id: `oisst-nino34-${a.window.from}-${a.window.to}`, + kind: "series", + source: "noaa-oisst-v2.1", + datetime: dayStart(a.window.to), + href: "https://www.ncei.noaa.gov/products/optimum-interpolation-sst", + method: method("enso", { confirmAnomalyC: need, lat: NINO34.lat, lon: NINO34.lon }), + summary: `OISST at the Niño3.4 centre (${a.gridCell.lat}, ${a.gridCell.lon}) averaged ${a.meanAnomaly} °C vs the same season of ${a.baseline.from.slice(0, 4)}–${a.baseline.to.slice(0, 4)}, ${a.window.from}…${a.window.to}.`, + values: { nino34_point_anomaly_c: a.meanAnomaly }, + }, + }; +} + +// ---- earthquakes ------------------------------------------------------------------------- + +async function quakes(ctx: RuleContext, p: P) { + // Look back to the last successful sweep (+1 day of overlap), bounded to [1, 30] days. + const sinceDays = ctx.since ? Math.ceil((Date.parse(ctx.now) - Date.parse(ctx.since)) / 86_400_000) + 1 : num(p.days, 7); + const days = Math.max(1, Math.min(30, sinceDays)); + const minMag = num(p.minMagnitude, 7); + const r = (await shared(ctx, "quakes", { bbox: ctx.aoi.bbox, minMagnitude: minMag, days, limit: 50 })) as QuakesResult; + const hits = r.quakes.filter((q) => (q.mag ?? 0) >= minMag).sort((a, b) => (b.mag ?? 0) - (a.mag ?? 0)); + return { r, hits, minMag, days }; +} + +async function detectQuake(ctx: RuleContext, p: P): Promise { + const { hits, minMag, days } = await quakes(ctx, p); + const top = hits[0]; + if (!top || top.mag === null) return null; + const values: Record = { magnitude: top.mag, count: hits.length, tsunami: top.tsunami ? 1 : 0 }; + if (top.depthKm !== null) values.depth_km = top.depthKm; + if (typeof top.sig === "number") values.sig = top.sig; + const observedAt = top.time.replace(/\.\d+Z$/, "Z"); + return { + title: `M${top.mag} earthquake — ${top.place || ctx.aoi.name}`.slice(0, 200), + summary: + `A magnitude ${top.mag} earthquake struck ${top.place || `inside ${ctx.aoi.name}`} at ${observedAt}${top.depthKm !== null ? `, ${top.depthKm} km deep` : ""}` + + `${top.tsunami ? "; USGS flagged tsunami potential" : ""}${top.alert ? `; PAGER alert level ${top.alert}` : ""}. ` + + (hits.length > 1 ? `${hits.length} quakes of M${minMag}+ in the region in the last ${days} days. ` : "") + + `Confirmation is USGS's own human review of the event — same provider, different check.`, + observedAt, + evidence: hits.slice(0, 10).map((q) => ({ + id: q.id, + kind: "record" as const, + source: "usgs-comcat", + datetime: q.time.replace(/\.\d+Z$/, "Z"), + href: q.url.startsWith("http") ? q.url : undefined, + method: method("quake", { minMagnitude: minMag, days }), + summary: `M${q.mag} ${q.place}${q.depthKm !== null ? `, ${q.depthKm} km deep` : ""}; USGS status ${q.status ?? "unknown"}.`, + values: { magnitude: q.mag ?? 0, ...(q.depthKm !== null ? { depth_km: q.depthKm } : {}), ...(typeof q.sig === "number" ? { sig: q.sig } : {}) }, + })), + values, + geometry: pointGeom(top.lat, top.lon), + notes: [`Dataset: USGS ComCat (FDSN event service). Window: last ${days} day(s), M ≥ ${minMag}, inside the AOI box.`], + tags: top.tsunami ? ["tsunami-flag"] : [], + }; +} + +async function confirmQuake(ctx: RuleContext, p: P, c0: Pick): Promise { + const { hits } = await quakes(ctx, p); + const minSig = num(p.minSig, 600); + const ids = new Set(c0.evidence.map((e) => e.id)); + const q = hits.find((h) => ids.has(h.id) && h.status === "reviewed" && (h.sig ?? 0) >= minSig); + if (!q) return null; + return { + independence: "method", + signal: { + id: `${q.id}-reviewed`, + kind: "record", + source: "usgs-comcat-review", + datetime: q.time.replace(/\.\d+Z$/, "Z"), + href: q.url.startsWith("http") ? q.url : undefined, + method: method("quake", { minSig }), + summary: `USGS reviewed event ${q.id} (M${q.mag}); significance ${q.sig} ≥ ${minSig}. Same provider as the detection — a human review, not an independent network.`, + values: { sig: q.sig ?? 0, reviewed: 1 }, + }, + }; +} + +// ---- the rule ------------------------------------------------------------------------------ + +const DETECT: Record Promise> = { + sea_ice: detectSeaIce, + marine_heatwave: detectHeatwave, + river_discharge: detectRiver, + air_quality: detectAir, + enso: detectEnso, + quake: detectQuake, +}; + +/** Blind-spot line prefix per indicator ("All:" lines apply to every indicator). */ +const BLIND_PREFIX: Record = { + sea_ice: "Sea ice:", + marine_heatwave: "Marine heatwave:", + river_discharge: "River:", + air_quality: "Air quality:", + enso: "ENSO:", + quake: "Earthquakes:", +}; + +/** + * Pure: the blind spots that apply to one indicator — its own lines plus the "All:" lines. Also + * used render-side for older ledger entries, which carry the full list for every indicator. + * Unknown/missing indicator → the list unchanged (never hide a caveat we cannot attribute). + */ +export function indicatorBlindSpots(spots: readonly string[], indicator: unknown): string[] { + const own = typeof indicator === "string" ? BLIND_PREFIX[indicator as IndicatorKind] : undefined; + if (!own) return [...spots]; + const known = Object.values(BLIND_PREFIX); + return spots.filter((s) => s.startsWith(own) || !known.some((k) => s.startsWith(k))); +} + +export const indicatorThreshold = defineRule({ + name: "indicator_threshold", + version: "1.0", + tier: 1, + description: "A planetary indicator (sea ice, sea temperature, river flow, air quality, ENSO, earthquakes) crossed a published threshold at a watched place.", + blindSpots: [ + "Sea ice: extent is area with ≥ 15% ice, not volume or thickness — thin new ice counts the same as old multi-year ice.", + "Sea ice: passive microwave misreads melt ponds and coastal cells; the p10 line is 1981–2010, so a warming world crosses it more often.", + "Marine heatwave: one 0.25° cell stands for a whole reef or sea; the baseline is only the previous 10 years (already warm), sampled every ~10 days.", + "Marine heatwave: OISST lags ~2 weeks and sees the surface skin only — heat below a few metres, where corals live, is not measured.", + "River: GloFAS discharge is modelled, not gauged; the cell may miss the main channel, and dams, diversions and levees are poorly represented.", + "River: the 2× line is against the all-season mean, so monsoon and snowmelt rivers cross it every peak season unless minSeasonalRatio also requires it to be high for the month.", + "Air quality: CAMS is a ~40 km model, not a monitor; it smooths city hotspots and can misplace dust and smoke plumes.", + "Air quality: PM2.5 only — ozone, NO₂ and indoor air are not judged, and the WHO guideline is a health line, not a legal limit.", + "ENSO: ONI is a 3-month running mean released monthly, so an event is declared months after it starts; the confirmation is one OISST point, not the Niño3.4 box.", + "Earthquakes: magnitude says nothing about damage — depth, building codes and population decide that; USGS review is the same provider checking its own event.", + "Earthquakes: a sweep more than 30 days late misses older events; only the strongest quake per region per case window leads the case.", + "All: global zero-key feeds can go stale or be revised; a threshold crossing is a signal to look, not a verdict on cause or impact.", + ], + blindSpotsFor(params) { + return indicatorBlindSpots(this.blindSpots, params.indicator); + }, + requires: [], + ringKm: 0, + defaults: {}, + + async detect(ctx: RuleContext): Promise { + const { kind, p } = indicatorParams(ctx.params); + return DETECT[kind](ctx, p); + }, + + async confirm(ctx: RuleContext, c): Promise { + const { kind, p } = indicatorParams(ctx.params); + switch (kind) { + case "sea_ice": + return confirmSeaIce(ctx, p, c); + case "marine_heatwave": + return confirmHeatwave(ctx, p, c); + case "river_discharge": + return confirmRiver(ctx, p, c); + case "air_quality": + return confirmAir(ctx, p, c); + case "enso": + return confirmEnso(ctx, p, c); + case "quake": + return confirmQuake(ctx, p, c); + } + }, +}); diff --git a/src/watch/rules/indicatorTrend.ts b/src/watch/rules/indicatorTrend.ts new file mode 100644 index 0000000..72498e3 --- /dev/null +++ b/src/watch/rules/indicatorTrend.ts @@ -0,0 +1,171 @@ +// indicator_trend@1.0 — the annual world-pulse indicators (Living Planet Index, Red List +// Index, fish stocks, ocean pH, tree cover loss, marine protected areas, …): when a NEW +// year's value appears and the 10-year direction is worsening (or improving → tag +// `improvement`), open one case for that indicator-year. Confirmation: the value reads the +// same on a later sweep (data stability — the source did not revise or retract it); same +// provider, so `independence: "method"`. +// +// Stable case scheme (the kernel keys cases by rule + AOI): +// • one AOI per indicator, id `wp-`, params.indicator = the OWID slug, cooldownDays 1 +// — so each new year's value opens a fresh case instead of piling onto last year's; +// • detect reads this rule's earlier cases for the AOI from the ledger (`ledger_list`) and +// stays quiet when one already has observedAt in the latest year — an indicator-year is +// never re-opened, even after the cooldown or after the case is closed; +// • evidence id `owid--`, observedAt `-01-01T00:00:00Z`. +// If the ledger read fails the pair is a gap (fail closed), never a duplicate case. + +import type { Evidence } from "../../ledger/schema.js"; +import { round } from "../../series.js"; +import { defineRule, type Candidate, type Confirmation, type RuleContext } from "./types.js"; + +interface PulseRow { + slug: string; + label: string; + unit: string; + betterWhen: "up" | "down"; + upstream: string; + status: "ok" | "unavailable"; + error?: string; + latest?: { t: string; v: number | null } | null; + previous?: { t: string; v: number | null } | null; + direction?: "improving" | "worsening" | "flat"; + pctPerDecade?: number | null; +} +interface WorldPulseResult { + indicators: PulseRow[]; +} +interface LedgerListResult { + findings: { observedAt: string; rule: string; aoi?: { id: string } }[]; +} + +/** Plain-language tails for the tracked indicators: [worsening, improving]. */ +const PLAIN: Record = { + "global-living-planet-index": ["wildlife populations keep shrinking", "wildlife populations are recovering"], + "red-list-index": ["more species are sliding towards extinction", "fewer species are heading for extinction"], + "fish-stocks-within-sustainable-levels": ["more of the ocean's fish stocks are overfished", "more fish stocks are fished sustainably"], + "seawater-ph": ["the ocean keeps acidifying as it absorbs CO₂", "ocean acidification is easing"], + "tree-cover-loss": ["the world keeps losing tree cover faster", "tree cover loss is slowing"], + "marine-protected-areas": ["less of the ocean is protected", "more of the ocean is protected"], +}; + +/** Readable number: 29.6 million, 64.5, 0.74, 8.042. */ +export function fmtValue(v: number): string { + const a = Math.abs(v); + if (a >= 1e6) return `${round(v / 1e6, 1)} million`; + if (a >= 1000) return Math.round(v).toLocaleString("en-US"); + if (a >= 10) return String(round(v, 1)); + return String(Number(v.toPrecision(4))); +} + +const obsOf = (year: string) => `${year}-01-01T00:00:00Z`; + +async function row(ctx: RuleContext): Promise { + const slug = ctx.params.indicator; + if (typeof slug !== "string" || !slug) throw new Error("indicator_trend: params.indicator (an OWID slug) is required"); + const r = (await ctx.call("world_pulse", { indicators: [slug] })) as WorldPulseResult; + const x = r.indicators.find((i) => i.slug === slug); + if (!x) throw new Error(`world_pulse: no row for ${slug}`); + if (x.status !== "ok") throw new Error(`world_pulse: ${slug} unavailable (${x.error ?? "no reason"})`); + return x; +} + +export const indicatorTrend = defineRule({ + name: "indicator_trend", + version: "1.0", + tier: 1, + description: "A new annual value of a world indicator (wildlife, species, fish, ocean pH, forests, protected ocean) continues a worsening — or improving — 10-year trend.", + blindSpots: [ + "Annual global indicators lag reality by 1–5 years: a 'new' value can describe a year long past.", + "The direction is the 10-year trend, not the single year: one year can move against the trend, and the title then says so.", + "Global aggregates hide where it happens — a stable global number can mask collapse in one region and recovery in another.", + "Confirmation only proves the source did not revise the number on a later read — same provider, not an independent measurement.", + "Some series are single sites (ocean pH is Station ALOHA, Hawaii) or modelled composites (Living Planet Index) with wide uncertainty bands we do not show.", + "Upstream methods change between releases; a revised back-series can make a year look new or change the trend.", + ], + requires: [], + ringKm: 0, + defaults: {}, + + async detect(ctx: RuleContext): Promise { + const x = await row(ctx); + const v = x.latest?.v; + const year = x.latest?.t?.slice(0, 4); + if (v == null || !year || !x.direction || x.direction === "flat") return null; + + // Never re-open an indicator-year: this rule's earlier cases on this AOI carry their year in observedAt. + const seen = (await ctx.call("ledger_list", { rule: "indicator_trend", aoi: ctx.aoi.id, limit: 500 })) as LedgerListResult; + const years = seen.findings.filter((f) => f.rule.startsWith("indicator_trend") && (!f.aoi || f.aoi.id === ctx.aoi.id)).map((f) => f.observedAt.slice(0, 4)); + if (years.includes(year)) return null; + const lastSeen = years.sort().pop(); + + const prev = x.previous?.v ?? null; + const prevYear = x.previous?.t?.slice(0, 4) ?? null; + const changePct = prev !== null && prev !== 0 ? round(((v - prev) / Math.abs(prev)) * 100, 2) : null; + const verb = prev === null || v === prev ? "stood at" : v > prev ? "rose to" : "fell to"; + const improving = x.direction === "improving"; + // Did this year move with the trend or against it? (For "down is better" series, a rise is bad.) + const yearGood = prev === null || v === prev ? null : (v > prev) === (x.betterWhen === "up"); + const plain = PLAIN[x.slug]?.[improving ? 1 : 0] ?? `the 10-year trend is ${x.direction}`; + const against = yearGood !== null && yearGood !== improving; + const tail = against ? `a ${yearGood ? "better" : "worse"} year, but over ten years ${plain}` : plain; + + const values: Record = { value: v, year: Number(year) }; + if (prev !== null) values.previous = prev; + if (changePct !== null) values.changePct = changePct; + if (typeof x.pctPerDecade === "number") values.pctPerDecade = x.pctPerDecade; + const observedAt = obsOf(year); + const evidence: Evidence[] = [ + { + id: `owid-${x.slug}-${year}`, + kind: "series", + source: "owid-grapher", + collection: x.slug, + datetime: observedAt, + href: `https://ourworldindata.org/grapher/${x.slug}`, + // retrievedAt: when this sweep read the value — confirmation needs a strictly later read. + method: { name: "indicator_trend", version: "1.0", params: { indicator: x.slug, retrievedAt: ctx.now } }, + summary: `${x.label}: ${year} = ${v}${prev !== null ? ` (${prevYear} = ${prev})` : ""} ${x.unit}; 10-year trend ${x.pctPerDecade ?? "?"}% per decade (${x.direction}). Upstream: ${x.upstream}.`.slice(0, 2000), + values, + }, + ]; + return { + title: `${x.label} ${verb} ${fmtValue(v)} (${x.unit}) in ${year} — ${tail}`.slice(0, 200), + summary: + `${x.label} ${verb} ${fmtValue(v)} (${x.unit}) in ${year}` + + (prev !== null && changePct !== null ? `, from ${fmtValue(prev)} in ${prevYear} (${changePct >= 0 ? "+" : ""}${changePct}%)` : "") + + `. Over the last ten years of data it is ${x.direction}` + + (typeof x.pctPerDecade === "number" ? ` (${x.pctPerDecade >= 0 ? "+" : ""}${x.pctPerDecade}% per decade)` : "") + + (against ? ` — this year moved the other way, which one year can do without changing the trend` : "") + + `. Source: ${x.upstream}, via Our World in Data. A later read showing the same value confirms the source has not revised it.`, + observedAt, + evidence, + values, + notes: [`Dataset: ${x.upstream} via Our World in Data (grapher ${x.slug}); annual series, direction = 10-year linear trend.${lastSeen ? ` Last year this watch reported: ${lastSeen}.` : ""}`], + tags: [improving ? "improvement" : "worsening"], + }; + }, + + async confirm(ctx: RuleContext, c): Promise { + const year = String(c.values.year ?? ""); + const first = c.evidence.find((e) => e.id.endsWith(`-${year}`) && typeof e.method.params?.retrievedAt === "string"); + const readAt = first?.method.params?.retrievedAt as string | undefined; + if (!readAt || Date.parse(ctx.now) <= Date.parse(readAt)) return null; // same sweep: not a second read + const x = await row(ctx); + if (x.latest?.t?.slice(0, 4) !== year || x.latest.v == null) return null; + if (Math.abs(x.latest.v - Number(c.values.value)) > 1e-9 * Math.max(1, Math.abs(x.latest.v))) return null; // revised: not stable (yet) + return { + independence: "method", + signal: { + id: `owid-${x.slug}-${year}-reread-${ctx.now.slice(0, 10)}`, + kind: "series", + source: "owid-grapher", + collection: x.slug, + datetime: obsOf(year), + href: `https://ourworldindata.org/grapher/${x.slug}`, + method: { name: "indicator_trend", version: "1.0", params: { indicator: x.slug, retrievedAt: ctx.now } }, + summary: `Re-read on ${ctx.now.slice(0, 10)}: ${year} value unchanged at ${x.latest.v} — the source has not revised it. Same provider (data stability, not an independent measurement).`, + values: { value: x.latest.v, year: Number(year) }, + }, + }; + }, +}); diff --git a/src/watch/rules/mpaFishing.ts b/src/watch/rules/mpaFishing.ts new file mode 100644 index 0000000..2f1082c --- /dev/null +++ b/src/watch/rules/mpaFishing.ts @@ -0,0 +1,185 @@ +// mpa_fishing@1.0 — primary: Global Fishing Watch apparent fishing hours inside a no-take / +// strict marine protected area over the last `days` ≥ `minHours`. With a WDPA `mpaId` (the +// marine watchlist always has one) GFW clips the effort to the reserve's legal polygon +// server-side (region `public-mpa-all/`) and we count the 0.01° cells that also fall +// in this AOI's box — so a tiled reserve is judged per tile, and nothing outside the polygon +// counts. Without an id, the AOI box itself is the (approximate) boundary. +// Confirmation (whichever comes first): +// 1. method — the effort is not a boundary artefact: at least `insetShare` of the bar is +// met in cells well inside the box (box inset by `insetFrac` on every side). +// 2. revisit — ≥ `revisitDays` later, fishing is still there in the new days alone +// (pro-rated bar): persistence across two different temporal windows. +// Aggregated effort only; the title and summary never name a vessel or company. + +import type { Evidence } from "../../ledger/schema.js"; +import type { BBox } from "../../types.js"; +import { addDays } from "../../util.js"; +import { bboxPolygon, dayStart, defineRule, num, type Candidate, type Confirmation, type RuleContext } from "./types.js"; + +interface FishingResult { + dataset: string; + from: string; + to: string; + totalHours: number; + activeDays: number; + lastDataDate: string | null; + byFlag: { flag: string; hours: number }[]; + clip: { hours: number; share: number | null } | null; + provenance?: { attribution?: string }; +} + +const GFW_HREF = "https://globalfishingwatch.org/map"; +const r1 = (v: number) => Math.round(v * 10) / 10; + +/** The box shrunk by `frac` of its width/height on every side. */ +export function insetBBox(b: BBox, frac: number): BBox { + const dx = (b[2] - b[0]) * frac; + const dy = (b[3] - b[1]) * frac; + return [b[0] + dx, b[1] + dy, b[2] - dx, b[3] - dy]; +} + +function mpaIdOf(p: Record): string | null { + return typeof p.mpaId === "string" && p.mpaId ? p.mpaId : null; +} + +function mpaName(ctx: RuleContext): string { + const p = ctx.params.mpaName; + if (typeof p === "string" && p.trim()) return p.trim(); + return (ctx.aoi.name ?? ctx.aoi.id).replace(/\s+—\s+tile.*$/, ""); +} + +export const mpaFishing = defineRule({ + name: "mpa_fishing", + version: "1.0", + tier: 2, + description: "Apparent fishing hours (Global Fishing Watch) inside a no-take / strict marine protected area.", + blindSpots: [ + "Only vessels broadcasting AIS are seen: 'dark' vessels (AIS off, absent or spoofed) are invisible, and most small-scale boats carry no AIS at all.", + "Apparent fishing is inferred by a GFW model from vessel movement, not observed catch — it can be wrong for a given track.", + "Transiting, drifting or waiting vessels can be misread as fishing (and slow fishing as transit).", + "The legal boundary is GFW's copy of the WDPA polygon (0.01° cells, centre-in rule); without a WDPA id the watch box stands in for the boundary. Zoning inside a reserve is not modelled.", + "Some MPAs allow fishing legally in zones or for local/artisanal fleets (e.g. Galápagos, Phoenix Islands since 2021) — effort there may be lawful.", + "Data lag ~4 days, and GFW's effort model is revised between dataset versions.", + "Says nothing about who is responsible; flag state is where a vessel is registered, not who owns or controls it.", + ], + requires: ["GFW_FISHING_TOKEN"], + ringKm: 0, + defaults: { days: 30, minHours: 50, resolution: "HIGH", insetFrac: 0.15, insetShare: 0.5, revisitDays: 7 }, + + async detect(ctx: RuleContext): Promise { + const p = { ...mpaFishing.defaults, ...ctx.params }; + const days = num(p.days, 30); + const minHours = num(p.minHours, 50); + const to = ctx.now.slice(0, 10); + const from = addDays(to, -days); + const mpaId = mpaIdOf(p); + const args = mpaId + ? { mpaId, from, to, resolution: String(p.resolution), byGear: false, clipBBox: ctx.aoi.bbox } + : { bbox: ctx.aoi.bbox, from, to, resolution: String(p.resolution), byGear: false }; + const r = (await ctx.call("fishing_activity", args)) as FishingResult; + const inside = mpaId ? (r.clip?.hours ?? 0) : r.totalHours; + if (!(inside >= minHours)) return null; + + const name = mpaName(ctx); + const hours = Math.round(inside); + const last = r.lastDataDate ?? to; + const flags = r.byFlag.filter((f) => f.hours > 0); + const topFlags = flags.slice(0, 3).map((f) => `${f.flag} ${Math.round(f.hours)} h`).join(", "); + const values = { hours: r1(inside), reserveHours: r1(r.totalHours), activeDays: r.activeDays, flagStates: flags.length, days }; + const where = mpaId ? `inside the legal boundary of MPA ${mpaId} (GFW polygon clip) within this watch box` : "in the watch box (approximate boundary)"; + const evidence: Evidence[] = [ + { + id: `gfw-fishing-${ctx.aoi.id}-${from}-${to}`, + kind: "record", + source: "globalfishingwatch-fishing-effort", + collection: r.dataset, + datetime: dayStart(last), + href: GFW_HREF, + method: { name: "fishing_activity", version: "1.0", params: args }, + summary: + `${r1(inside)} h of apparent fishing ${where}, ${from}..${last}` + + (topFlags ? `; ${mpaId ? "whole reserve " : ""}by flag state: ${topFlags}` : "") + + `. ${r.provenance?.attribution ?? "Global Fishing Watch"}.`, + values, + }, + ]; + return { + title: `Fishing activity inside ${name}: ${hours} hours in ${days} days`, + summary: + `Global Fishing Watch shows ${hours} hours of apparent fishing inside ${name} over the last ${days} days` + + (flags.length ? ` (vessels of ${flags.length} flag state${flags.length === 1 ? "" : "s"})` : "") + + ". The area is a no-take or strictly protected marine reserve. Awaiting an independent check: the effort lying well inside the area rather than along its edge, or still there a week later.", + observedAt: dayStart(last), + evidence, + values, + geometry: bboxPolygon(ctx.aoi.bbox), + notes: ["Apparent fishing is model-inferred from AIS; vessels without AIS are not counted. Flag state ≠ owner.", ...(typeof p.legalNote === "string" ? [p.legalNote] : [])], + tags: ["fishing", "marine-protected-area"], + }; + }, + + async confirm(ctx, candidate): Promise { + const p = { ...mpaFishing.defaults, ...ctx.params }; + const days = num(p.days, 30); + const minHours = num(p.minHours, 50); + const params = candidate.evidence[0]?.method.params as { from?: string; to?: string } | undefined; + const to = params?.to ?? ctx.now.slice(0, 10); + const from = params?.from ?? addDays(to, -days); + const detected = num(candidate.values.hours, 0); + const mpaId = mpaIdOf(p); + + // 1. method: the effort sits well inside the box, not along its edge. + const frac = num(p.insetFrac, 0.15); + const inset = insetBBox(ctx.aoi.bbox, frac); + const args = mpaId ? { mpaId, from, to, resolution: "HIGH", byGear: false, clipBBox: inset } : { bbox: ctx.aoi.bbox, from, to, resolution: "HIGH", byGear: false, clipBBox: inset }; + const r = (await ctx.call("fishing_activity", args)) as FishingResult; + const deep = r.clip?.hours ?? 0; + const bar = minHours * num(p.insetShare, 0.5); + if (deep >= bar) { + const share = detected > 0 ? Math.round((deep / detected) * 100) : null; + return { + independence: "method", + signal: { + id: `gfw-fishing-inset-${ctx.aoi.id}-${from}-${to}`, + kind: "record", + source: "globalfishingwatch-fishing-effort", + collection: r.dataset, + datetime: candidate.observedAt, + href: GFW_HREF, + method: { name: "fishing_activity", version: "1.0", params: args }, + summary: + `${r1(deep)} h${share != null ? ` (${share}% of the ${r1(detected)} h)` : ""} lie in 0.01° cells well inside the area (box inset ${Math.round(frac * 100)}% per side)` + + `${mpaId ? " and inside the legal polygon" : ""} — not a boundary artefact (bar ${r1(bar)} h).`, + values: { insetHours: r1(deep), ...(share != null ? { insetSharePct: share } : {}) }, + }, + }; + } + + // 2. revisit: still there in the days after the first window. + const age = (Date.parse(ctx.now) - Date.parse(candidate.observedAt)) / 86_400_000; + if (age < num(p.revisitDays, 7)) return null; + const from2 = addDays(candidate.observedAt.slice(0, 10), 1); + const to2 = ctx.now.slice(0, 10); + if (from2 >= to2) return null; + const args2 = mpaId ? { mpaId, from: from2, to: to2, resolution: "HIGH", byGear: false, clipBBox: ctx.aoi.bbox } : { bbox: ctx.aoi.bbox, from: from2, to: to2, resolution: "HIGH", byGear: false }; + const r2 = (await ctx.call("fishing_activity", args2)) as FishingResult; + const h2 = mpaId ? (r2.clip?.hours ?? 0) : r2.totalHours; + const newDays = Math.max(1, Math.round((Date.parse(to2) - Date.parse(from2)) / 86_400_000)); + const bar2 = Math.max(5, (minHours * newDays) / days); + if (!(h2 >= bar2) || !r2.lastDataDate) return null; + return { + independence: "revisit", + signal: { + id: `gfw-fishing-${ctx.aoi.id}-${from2}-${to2}-revisit`, + kind: "record", + source: "globalfishingwatch-fishing-effort", + collection: r2.dataset, + datetime: dayStart(r2.lastDataDate), + href: GFW_HREF, + method: { name: "fishing_activity", version: "1.0", params: args2 }, + summary: `Fishing continued: ${r1(h2)} h in the ${newDays} days after the first window (bar ${r1(bar2)} h, pro-rated).`, + values: { hours: r1(h2), days: newDays }, + }, + }; + }, +}); diff --git a/src/watch/rules/types.ts b/src/watch/rules/types.ts index 8676d96..39acee6 100644 --- a/src/watch/rules/types.ts +++ b/src/watch/rules/types.ts @@ -50,7 +50,8 @@ export interface Candidate { export interface Confirmation { signal: Evidence; - independence: "sensor" | "provider" | "revisit" | "human"; + /** `method`: same provider, a different product or check (e.g. USGS review status, a data-stability re-read). */ + independence: "sensor" | "provider" | "revisit" | "method" | "human"; } export interface Rule { @@ -60,6 +61,8 @@ export interface Rule { description: string; /** Required. What this rule cannot see, in plain words. */ blindSpots: string[]; + /** Optional: narrow `blindSpots` to what applies to one case's params (e.g. one indicator). */ + blindSpotsFor?: (params: Record) => string[]; /** Env keys the rule needs (for doctor / graceful skip). */ requires: string[]; /** Subset of `requires` only the confirmation step spends (e.g. optical checks): when that diff --git a/src/watch/rules/weatherExtreme.ts b/src/watch/rules/weatherExtreme.ts new file mode 100644 index 0000000..0aa79f2 --- /dev/null +++ b/src/watch/rules/weatherExtreme.ts @@ -0,0 +1,438 @@ +// weather_extreme@1.0 — three weather hazards at a watched city or region, each with its own +// independent second signal. One rule (so one finding per AOI at a time); `hazards` picks +// which are evaluated, and when several trip at once the most severe leads and the others ride +// along as notes. +// +// heat primary: Open-Meteo forecast-API daily max ≥ absC (42 °C) or ≥ anomalyC (+8 °C) over +// the ERA5 1991–2020 normal, for ≥ minDays (2) consecutive days ending today. +// confirm: ERA5 reanalysis (models=era5 — a different model and provider) agrees on +// ≥ minDays of those days (provider), or a later elapsed day is still hot (revisit). +// cyclone primary: an NHC/CPHC (or GDACS, outside NHC's basins) storm whose current or forecast +// peak category ≥ minCategory (1) and whose forecast cone touches the AOI. +// confirm: a NASA EONET "Severe Storms" event for the same storm (provider). +// rain primary: a day's precipitation ≥ mm (150) yesterday or today. +// confirm: GloFAS discharge at the nearest river cell ≥ dischargeRatio (2×) its 2-year +// mean (provider), or a later elapsed day again ≥ mm (revisit). +// +// Tier 0: a natural hazard names no party. Heat and rain read the AOI's centre point. + +import type { Evidence, Geometry } from "../../ledger/schema.js"; +import { addDays, bboxCenter } from "../../util.js"; +import { bboxPolygon, dayStart, defineRule, num, type Candidate, type Confirmation, type RuleContext } from "./types.js"; + +export const HAZARD_CODE = { heat: 1, cyclone: 2, rain: 3 } as const; +type Hazard = keyof typeof HAZARD_CODE; +/** Lead-hazard order when several trip in one sweep. */ +const SEVERITY: Hazard[] = ["cyclone", "heat", "rain"]; + +interface Day { + date: string; + kind: "past" | "today" | "forecast"; + tmaxC: number | null; + precipMm: number | null; + tmaxNormalC: number | null; + tmaxAnomalyC: number | null; +} +interface WeatherNow { + today: string; + days: Day[]; + era5: { date: string; tmaxC: number | null; precipMm: number | null }[]; + normals?: { period: string }; +} +interface StormOut { + id: string; + name: string; + source: string; + basin: string; + classification: string; + maxWindKt: number | null; + category: number | null; + peakCategory: number | null; + position: { lat: number; lon: number } | null; + advisory: { number: string | null; issued: string | null; url: string | null }; + cone: Geometry | null; +} +interface EventOut { + id: string; + title: string; + category: string; + lastDate: string | null; + coordinates: [number, number] | null; + link: string; +} + +const ORDINALS = ["first", "second", "third", "fourth", "fifth", "sixth", "seventh", "eighth", "ninth", "tenth"]; +const ordinal = (n: number) => ORDINALS[n - 1] ?? `${n}th`; +const fmt = (v: number) => (Math.round(v * 10) / 10).toString(); + +function hazardsOf(p: Record): Hazard[] { + const raw = Array.isArray(p.hazards) ? p.hazards : [p.hazards]; + const hs = raw.filter((h): h is Hazard => typeof h === "string" && h in HAZARD_CODE); + return hs.length ? hs : ["heat", "rain"]; +} + +/** RFC 3339 with whole seconds and Z (the ledger's contract). */ +function rfc3339(s: string | null | undefined, fallback: string): string { + const ms = s ? Date.parse(s) : NaN; + return (Number.isFinite(ms) ? new Date(ms) : new Date(fallback)).toISOString().replace(/\.\d{3}Z$/, "Z"); +} + +function daysBetween(a: string, b: string): number { + return Math.round((Date.parse(`${b}T00:00:00Z`) - Date.parse(`${a}T00:00:00Z`)) / 86_400_000); +} + +function place(ctx: RuleContext): { lat: number; lon: number } { + const [lon, lat] = bboxCenter(ctx.aoi.bbox); + return { lat: Math.round(lat * 1e4) / 1e4, lon: Math.round(lon * 1e4) / 1e4 }; +} + +function weatherArgs(ctx: RuleContext, pastDays: number, normals: boolean) { + return { ...place(ctx), place: ctx.aoi.name, pastDays, forecastDays: 7, normals }; +} + +function forecastHref(lat: number, lon: number, daily: string): string { + return `https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}&daily=${daily}&past_days=7&timezone=auto`; +} + +// ---- heat -------------------------------------------------------------------------------- + +interface HeatParams { + absC: number; + anomalyC: number; + minDays: number; +} +const isHot = (tmax: number | null, anom: number | null, p: HeatParams) => (tmax != null && tmax >= p.absC) || (anom != null && anom >= p.anomalyC); + +function heatCandidate(ctx: RuleContext, w: WeatherNow, p: HeatParams, args: Record): Candidate | null { + const elapsed = w.days.filter((d) => d.kind !== "forecast"); + let run = 0; + for (let i = elapsed.length - 1; i >= 0 && isHot(elapsed[i]!.tmaxC, elapsed[i]!.tmaxAnomalyC, p); i--) run++; + if (run < p.minDays) return null; + const peak = elapsed[elapsed.length - 1]!; + const runStart = elapsed[elapsed.length - run]!.date; + let ahead = 0; + for (const d of w.days.filter((x) => x.kind === "forecast")) { + if (!isHot(d.tmaxC, d.tmaxAnomalyC, p)) break; + ahead++; + } + const a = peak.tmaxAnomalyC; + const anomText = a == null ? "" : `, ${fmt(Math.abs(a))} °C ${a >= 0 ? "above" : "below"} normal`; + const title = `Heatwave in ${ctx.aoi.name}: ${fmt(peak.tmaxC!)} °C${anomText}, ${ordinal(run)} day`; + const { lat, lon } = place(ctx); + const values: Record = { hazardCode: HAZARD_CODE.heat, tmaxC: peak.tmaxC!, runDays: run, forecastHotDaysAhead: ahead, absC: p.absC, anomalyThresholdC: p.anomalyC }; + if (a != null) values.anomalyC = a; + if (peak.tmaxNormalC != null) values.normalC = peak.tmaxNormalC; + const evidence: Evidence[] = [ + { + id: `openmeteo-tmax-${ctx.aoi.id}-${runStart}..${peak.date}`, + kind: "series", + source: "open-meteo-forecast", + collection: "best_match", + datetime: dayStart(peak.date), + href: forecastHref(lat, lon, "temperature_2m_max"), + method: { name: "weather_now", version: "1.0", params: args }, + summary: + `Daily max ${elapsed.slice(-run).map((d) => `${d.date} ${d.tmaxC} °C${d.tmaxAnomalyC != null ? ` (${d.tmaxAnomalyC >= 0 ? "+" : ""}${d.tmaxAnomalyC})` : ""}`).join(", ")} ` + + `at ${lat}, ${lon}; thresholds ≥ ${p.absC} °C or ≥ +${p.anomalyC} °C vs the ERA5 ${w.normals?.period ?? "1991–2020"} normal.` + + (ahead ? ` Forecast: ${ahead} more day(s) over threshold.` : ""), + values, + }, + ]; + return { + title, + summary: + `Model daily maximum at the centre of ${ctx.aoi.name} has been over the heat threshold for ${run} consecutive day(s) ` + + `(${runStart} → ${peak.date}), peaking today at ${fmt(peak.tmaxC!)} °C${anomText}` + + (ahead ? `; the forecast keeps it there ${ahead} more day(s)` : "") + + ". Forecast-model values, not station readings — awaiting ERA5 reanalysis or a further hot day to confirm.", + observedAt: dayStart(peak.date), + evidence, + values, + }; +} + +async function confirmHeat(ctx: RuleContext, c: Pick, p: HeatParams): Promise { + const lastDay = c.observedAt.slice(0, 10); + const runDays = Math.max(1, num(c.values.runDays, p.minDays)); + const today = ctx.now.slice(0, 10); + const pastDays = Math.min(14, Math.max(7, daysBetween(lastDay, today) + runDays)); + const args = weatherArgs(ctx, pastDays, true); + const w = (await ctx.call("weather_now", args)) as WeatherNow; + const normal = new Map(w.days.map((d) => [d.date, d.tmaxNormalC])); + const runFirst = addDays(lastDay, -(runDays - 1)); + + // (1) ERA5 — independent reanalysis — agrees on ≥ minDays of the flagged days. + const era = w.era5.filter((d) => d.date >= runFirst && d.date <= lastDay && d.tmaxC != null); + const eraHot = era.filter((d) => { + const n = normal.get(d.date); + return isHot(d.tmaxC, n != null ? d.tmaxC! - n : null, p); + }); + if (eraHot.length >= Math.min(p.minDays, runDays)) { + const peak = [...eraHot].sort((x, y) => y.tmaxC! - x.tmaxC!)[0]!; + return { + independence: "provider", + signal: { + id: `era5-tmax-${ctx.aoi.id}-${runFirst}..${lastDay}`, + kind: "series", + source: "ecmwf-era5", + collection: "reanalysis-era5-single-levels", + datetime: dayStart(peak.date), + href: `https://archive-api.open-meteo.com/v1/archive?latitude=${args.lat}&longitude=${args.lon}&start_date=${runFirst}&end_date=${lastDay}&daily=temperature_2m_max&models=era5&timezone=auto`, + method: { name: "weather_now", version: "1.0", params: args }, + summary: `ERA5 reanalysis (0.25°) daily max over threshold on ${eraHot.length} of ${era.length} flagged day(s): ${eraHot.map((d) => `${d.date} ${d.tmaxC} °C`).join(", ")}.`, + values: { era5HotDays: eraHot.length, era5PeakTmaxC: peak.tmaxC! }, + }, + }; + } + + // (2) Persistence — a later elapsed day is still over threshold. + const later = w.days.filter((d) => d.kind !== "forecast" && d.date > lastDay && isHot(d.tmaxC, d.tmaxAnomalyC, p)); + if (later.length === 0) return null; + const d = later[later.length - 1]!; + return { + independence: "revisit", + signal: { + id: `openmeteo-tmax-${ctx.aoi.id}-${d.date}`, + kind: "series", + source: "open-meteo-forecast", + collection: "best_match", + datetime: dayStart(d.date), + href: forecastHref(args.lat, args.lon, "temperature_2m_max"), + method: { name: "weather_now", version: "1.0", params: args }, + summary: `Heat persisted after the flagged run: ${later.map((x) => `${x.date} ${x.tmaxC} °C${x.tmaxAnomalyC != null ? ` (${x.tmaxAnomalyC >= 0 ? "+" : ""}${x.tmaxAnomalyC})` : ""}`).join(", ")}.`, + values: { laterHotDays: later.length, tmaxC: d.tmaxC! }, + }, + }; +} + +// ---- rain -------------------------------------------------------------------------------- + +function rainCandidate(ctx: RuleContext, w: WeatherNow, mm: number, args: Record): Candidate | null { + const recent = w.days.filter((d) => d.kind !== "forecast").slice(-2); + const wettest = [...recent].filter((d) => d.precipMm != null).sort((a, b) => b.precipMm! - a.precipMm!)[0]; + if (!wettest || wettest.precipMm! < mm) return null; + const { lat, lon } = place(ctx); + const values = { hazardCode: HAZARD_CODE.rain, precipMm: wettest.precipMm!, thresholdMm: mm }; + return { + title: `Extreme rain in ${ctx.aoi.name}: ${fmt(wettest.precipMm!)} mm in one day`, + summary: + `Model precipitation at the centre of ${ctx.aoi.name} reached ${fmt(wettest.precipMm!)} mm on ${wettest.date} ` + + `(threshold ${mm} mm/day). Local-day total from a forecast model, not a rain gauge — awaiting river response ` + + `(GloFAS) or a further extreme day to confirm.`, + observedAt: dayStart(wettest.date), + evidence: [ + { + id: `openmeteo-precip-${ctx.aoi.id}-${wettest.date}`, + kind: "series", + source: "open-meteo-forecast", + collection: "best_match", + datetime: dayStart(wettest.date), + href: forecastHref(lat, lon, "precipitation_sum"), + method: { name: "weather_now", version: "1.0", params: args }, + summary: `Daily precipitation ${recent.map((d) => `${d.date} ${d.precipMm ?? "?"} mm`).join(", ")} at ${lat}, ${lon}.`, + values, + }, + ], + values, + }; +} + +interface DischargeOut { + latest: { t: string; v: number | null } | null; + latestVsMean: number | null; + stats: { mean: number | null }; +} + +async function confirmRain(ctx: RuleContext, c: Pick, mm: number, ratio: number): Promise { + const day = c.observedAt.slice(0, 10); + const { lat, lon } = place(ctx); + // (1) GloFAS river discharge — a hydrological model, a different product and provider. + try { + const dArgs = { lat, lon }; + const r = (await ctx.call("river_discharge", dArgs)) as DischargeOut; + if (r.latest?.v != null && r.latest.t >= day && r.latestVsMean != null && r.latestVsMean >= ratio) { + return { + independence: "provider", + signal: { + id: `glofas-${ctx.aoi.id}-${r.latest.t}`, + kind: "series", + source: "glofas", + collection: "cems-glofas-historical", + datetime: dayStart(r.latest.t.slice(0, 10)), + href: `https://flood-api.open-meteo.com/v1/flood?latitude=${lat}&longitude=${lon}&daily=river_discharge`, + method: { name: "river_discharge", version: "1.0", params: dArgs }, + summary: `GloFAS discharge at the nearest river cell ${r.latest.v} m³/s on ${r.latest.t}, ${r.latestVsMean}× its 2-year mean (≥ ${ratio}×).`, + values: { dischargeM3s: r.latest.v, dischargeVsMean: r.latestVsMean }, + }, + }; + } + } catch { + /* no river cell nearby, or GloFAS down — fall through to persistence */ + } + // (2) Persistence — another extreme day after the flagged one. + const args = weatherArgs(ctx, 7, false); + const w = (await ctx.call("weather_now", args)) as WeatherNow; + const later = w.days.filter((d) => d.kind !== "forecast" && d.date > day && (d.precipMm ?? 0) >= mm); + if (later.length === 0) return null; + const d = later[later.length - 1]!; + return { + independence: "revisit", + signal: { + id: `openmeteo-precip-${ctx.aoi.id}-${d.date}`, + kind: "series", + source: "open-meteo-forecast", + collection: "best_match", + datetime: dayStart(d.date), + href: forecastHref(lat, lon, "precipitation_sum"), + method: { name: "weather_now", version: "1.0", params: args }, + summary: `Extreme rain again after ${day}: ${later.map((x) => `${x.date} ${x.precipMm} mm`).join(", ")}.`, + values: { laterExtremeDays: later.length, precipMm: d.precipMm! }, + }, + }; +} + +// ---- cyclone ----------------------------------------------------------------------------- + +/** Plain-language storm noun: hurricane (Atlantic/E+C Pacific), typhoon (NW Pacific), cyclone elsewhere. */ +export function stormNoun(s: Pick): string { + const cat = Math.max(s.category ?? 0, 0); + if (cat < 1) return /TD|depression/i.test(s.classification) ? "Tropical depression" : "Tropical storm"; + if (["AL", "EP", "CP"].includes(s.basin)) return "Hurricane"; + const lon = s.position?.lon; + const lat = s.position?.lat ?? 0; + if (lon != null && lat > 0 && lon >= 100) return "Typhoon"; + if (lon != null && lon < -30) return "Hurricane"; + return "Cyclone"; +} + +function validGeometry(g: Geometry | null): g is Geometry { + if (!g) return false; + if (g.type === "Polygon") return (g.coordinates[0]?.length ?? 0) >= 4; + if (g.type === "MultiPolygon") return g.coordinates.length > 0 && g.coordinates.every((p) => (p[0]?.length ?? 0) >= 4); + return false; +} + +async function cycloneCandidate(ctx: RuleContext, minCategory: number): Promise { + const args = { bbox: ctx.aoi.bbox, minCategory, eonet: false }; + const r = (await ctx.call("storms", args)) as { storms: StormOut[] }; + const storms = (r.storms ?? []).filter((s) => Math.max(s.category ?? 0, s.peakCategory ?? 0) >= minCategory); + if (storms.length === 0) return null; + const s = [...storms].sort((a, b) => (b.peakCategory ?? 0) - (a.peakCategory ?? 0) || (b.maxWindKt ?? 0) - (a.maxWindKt ?? 0))[0]!; + const noun = stormNoun(s); + const cat = s.category ?? 0; + const peak = s.peakCategory ?? cat; + const catText = cat >= 1 ? `category ${cat}` : noun.toLowerCase(); + const peakText = peak > cat ? `, forecast to reach category ${peak}` : ""; + const observedAt = rfc3339(s.advisory.issued, ctx.now); + const values: Record = { hazardCode: HAZARD_CODE.cyclone, category: cat, peakCategory: peak }; + if (s.maxWindKt != null) values.maxWindKt = s.maxWindKt; + return { + title: `${noun} ${s.name} (${catText}${peakText}): forecast cone over ${ctx.aoi.name}`, + summary: + `${noun} ${s.name} — ${s.maxWindKt ?? "?"} kt, ${catText}${peakText} — has a forecast cone touching ${ctx.aoi.name} ` + + `(${s.source === "noaa-nhc" ? "NHC/CPHC" : "GDACS"} advisory ${s.advisory.number ?? "?"}, ${observedAt}). The cone is the likely ` + + `path of the centre, not a landfall forecast or the extent of impacts.` + + (storms.length > 1 ? ` ${storms.length - 1} other qualifying storm(s) also touch the region.` : ""), + observedAt, + evidence: [ + { + id: `${s.id}@adv-${s.advisory.number ?? "na"}`, + kind: "record", + source: s.source, + collection: s.source === "noaa-nhc" ? "nhc-tropical-weather-summary" : "gdacs-tc", + datetime: observedAt, + ...(s.advisory.url ? { href: s.advisory.url } : {}), + method: { name: "storms", version: "1.0", params: args }, + summary: `${s.name}: ${s.classification}, ${s.maxWindKt ?? "?"} kt at ${s.position ? `${s.position.lat}, ${s.position.lon}` : "?"}; forecast-peak category ${peak}; cone intersects the AOI.`, + values, + }, + ], + values, + geometry: validGeometry(s.cone) ? s.cone : bboxPolygon(ctx.aoi.bbox), + notes: storms.slice(1, 4).map((o) => `Also touching: ${o.name} (${o.classification}, ${o.maxWindKt ?? "?"} kt)`), + }; +} + +async function confirmCyclone(ctx: RuleContext, c: Pick): Promise { + const stormId = c.evidence.find((e) => e.method.name === "storms")?.id.split("@")[0]; + if (!stormId) return null; + const sr = (await ctx.call("storms", { bbox: ctx.aoi.bbox, minCategory: 0, eonet: false })) as { storms: StormOut[] }; + const storm = (sr.storms ?? []).find((s) => s.id === stormId); + if (!storm) return null; + const args = { category: "severeStorms", status: "open", days: 30, limit: 100 }; + const ev = (await ctx.call("events", args)) as { events: EventOut[] }; + const name = storm.name.toLowerCase(); + const byName = (ev.events ?? []).find((e) => name.length >= 3 && new RegExp(`\\b${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\b`, "i").test(e.title)); + if (!byName) return null; + return { + independence: "provider", + signal: { + id: byName.id, + kind: "record", + source: "nasa-eonet", + collection: "severeStorms", + datetime: rfc3339(byName.lastDate, ctx.now), + ...(byName.link ? { href: byName.link } : {}), + method: { name: "events", version: "1.0", params: args }, + summary: `NASA EONET lists "${byName.title}" as an open severe-storm event${byName.coordinates ? ` (latest ${byName.coordinates[1]}, ${byName.coordinates[0]})` : ""}.`, + values: {}, + }, + }; +} + +// ---- the rule ---------------------------------------------------------------------------- + +export const weatherExtreme = defineRule({ + name: "weather_extreme", + version: "1.0", + tier: 0, + description: + "Extreme weather at a watched place: heat (daily max ≥ 42 °C or ≥ +8 °C over the 1991–2020 normal for ≥ 2 days, confirmed by ERA5 or persistence), " + + "tropical cyclones (category ≥ 1 with a forecast cone over the AOI, confirmed by NASA EONET), extreme rain (≥ 150 mm/day, confirmed by GloFAS river discharge ≥ 2× or persistence).", + blindSpots: [ + "Heat and rain are read from forecast-model analyses at one grid point (the AOI centre, ~2–11 km cell), not station observations: urban heat islands, sea breezes and convective downpours can differ sharply over a few km.", + "Station sparsity: ERA5 and the forecast models are only as good as the observations assimilated into them, which are thin across much of Africa, South Asia and the tropics — exactly where heat risk is highest.", + "Anomalies compare a ~2–11 km forecast grid with a 0.25° ERA5 normal, so they carry ~1–2 °C of grid/elevation bias; ERA5 also smooths extreme daily rainfall, so it is not used to confirm rain.", + "Temperature alone is not heat stress: humidity (wet-bulb), night-time minima and who is exposed decide the harm, and none of these gate this rule.", + "A cyclone cone is the likely path of the storm's centre (~2/3 of past errors), not a landfall forecast or the footprint of wind, surge and rain — impacts extend beyond it, and a cone over the AOI does not mean it will be hit.", + "Outside the Atlantic and eastern/central Pacific, storms come from GDACS, whose winds may be 10-minute averages (reads ~1 category lower than NHC's 1-minute).", + "EONET republishes NHC/JTWC advisories, so the cyclone confirmation is an independent pipeline over largely the same forecast-centre source, not an independent observation.", + "A daily precipitation total is a local-calendar-day sum (today's includes the forecast for the rest of the day), not a rolling 24 h window; GloFAS discharge responds to basin-wide rain, so a city storm on a small catchment may never show at the nearest GloFAS cell.", + ], + requires: [], + ringKm: 0, + defaults: { hazards: ["heat", "rain"], absC: 42, anomalyC: 8, minDays: 2, minCategory: 1, mm: 150, dischargeRatio: 2 }, + + async detect(ctx: RuleContext): Promise { + const p = { ...weatherExtreme.defaults, ...ctx.params }; + const hz = hazardsOf(p); + const heat: HeatParams = { absC: num(p.absC, 42), anomalyC: num(p.anomalyC, 8), minDays: Math.max(1, num(p.minDays, 2)) }; + const found = new Map(); + if (hz.includes("cyclone")) { + const c = await cycloneCandidate(ctx, num(p.minCategory, 1)); + if (c) found.set("cyclone", c); + } + if (hz.includes("heat") || hz.includes("rain")) { + // heat + rain share one weather_now call (normals only when heat is watched). + const args = weatherArgs(ctx, 7, hz.includes("heat")); + const w = (await ctx.call("weather_now", args)) as WeatherNow; + const heatC = hz.includes("heat") ? heatCandidate(ctx, w, heat, args) : null; + const rainC = hz.includes("rain") ? rainCandidate(ctx, w, num(p.mm, 150), args) : null; + if (heatC) found.set("heat", heatC); + if (rainC) found.set("rain", rainC); + } + const [lead, ...rest] = SEVERITY.flatMap((h) => (found.has(h) ? [found.get(h)!] : [])); + if (!lead) return null; + return rest.length ? { ...lead, notes: [...(lead.notes ?? []), ...rest.map((r) => `Also over threshold: ${r.title}`)] } : lead; + }, + + async confirm(ctx, candidate): Promise { + const p = { ...weatherExtreme.defaults, ...ctx.params }; + const code = num(candidate.values.hazardCode, 0); + if (code === HAZARD_CODE.cyclone) return confirmCyclone(ctx, candidate); + if (code === HAZARD_CODE.heat) + return confirmHeat(ctx, candidate, { absC: num(p.absC, 42), anomalyC: num(p.anomalyC, 8), minDays: Math.max(1, num(p.minDays, 2)) }); + if (code === HAZARD_CODE.rain) return confirmRain(ctx, candidate, num(p.mm, 150), num(p.dischargeRatio, 2)); + return null; + }, +}); diff --git a/src/watch/site-render.ts b/src/watch/site-render.ts index b1a8b62..0a74397 100644 --- a/src/watch/site-render.ts +++ b/src/watch/site-render.ts @@ -9,11 +9,15 @@ import { PUBLIC_STATUSES, TERMINAL_STATUSES, type Evidence, type Finding, type FindingEvent } from "../ledger/schema.js"; import { SITE } from "../site.config.js"; +import type { NewsItem } from "../clients/gdelt.js"; import { livingValueOf, type SiteStats, type RateCell } from "./export.js"; +import { indicatorOf, isGlobalCase } from "./map-data.js"; +import { LEVEL_LABEL, type SituationRecord } from "./situation.js"; +import { indicatorBlindSpots } from "./rules/indicatorThreshold.js"; // TODO: import { GLOBAL_NATURE_VALUE } from "../clients/naturalvalue.js" once natural_value // (a3ab7a9) is on main — these are its figures (2007 US$, 2011 vs 1997 biome areas). -const GLOBAL_NATURE_VALUE = { +export const GLOBAL_NATURE_VALUE = { usdPerYear: { low: 1.25e14, high: 1.45e14 }, source: "Costanza et al. 2014, “Changes in the global value of ecosystem services”, Global Environmental Change 26:152–158 (2007 US$)", } as const; @@ -141,7 +145,26 @@ function plainActor(a: string): string { } const REPLY_TEXT = - "If a case names or affects you, you can reply. A reply channel that keeps both sides on record is being set up; until then, every case page carries its ledger id so a reply can be attached to it."; + "If a case names or affects you, or you know the place, reply under the case itself. Replies are public and anonymous: no account, no email. A second AI model reads each one before it appears, and turns away spam, abuse and anything that names a private person."; +const REPLY_LEDE = "Know this place? Say what you see. Replies are checked before they appear. No account, no email."; +const REPLY_NOJS = "Replies are open on the interactive site (it needs JavaScript)."; +const REPLY_NOTE = "Every reply here was read and accepted by a second AI model before it appeared. They are the writers’ own words, not checked facts."; +export const ROLE_LABEL: Record = { + resident: "Lives nearby", + operator: "Works on site", + company: "From a company", + official: "Public official", + researcher: "Researcher", + other: "Someone who knows the place", +}; + +/** A reviewed public reply, as the export reads it from the reply wall (src/replies/review.ts). */ +export interface ShownReply { + id: string; + text: string; + role: string; + receivedAt: string; +} // ---- page context --------------------------------------------------------------------------------- @@ -192,6 +215,10 @@ export function head(c: Ctx, h: HeadSpec): string { ``, ``, image ? `` : "", + ``, + ``, + ``, + ``, ``, ...(h.jsonld ?? []).map(jsonLd), ]; @@ -200,7 +227,8 @@ export function head(c: Ctx, h: HeadSpec): string { // ---- chrome ----------------------------------------------------------------------------------------- -const BRAND_MARK = ``; +/** The mark (a ring — the limits — with a horizon across it); same drawing as web/site/public/favicon.svg. */ +const BRAND_MARK = ``; /** The shared header. On the landing, `line` (the one sentence) sits beside the wordmark as the page's h1. */ export function siteTop(c: Ctx, current: "landing" | "cases" | "trust" | "developers" | null, line?: string): string { @@ -212,7 +240,6 @@ export function siteTop(c: Ctx, current: "landing" | "cases" | "trust" | "develo ${line ? `

${esc(line)}

` : ""}
@@ -227,7 +254,9 @@ export function siteFoot(c: Ctx): string {
  • Global Forest Watch — integrated deforestation alerts, World Resources Institute. CC BY 4.0.
  • Copernicus — contains modified Copernicus Sentinel data, processed via the Copernicus Data Space Ecosystem; CAMS, ERA5 and GloFAS information from the Copernicus services.
  • -
  • NASA FIRMS — we acknowledge the use of data and imagery from LANCE FIRMS operated by NASA’s Earth Science Data and Information System (ESDIS). Imagery: NASA GIBS (Blue Marble, Black Marble).
  • +
  • NASA FIRMS — we acknowledge the use of data and imagery from LANCE FIRMS operated by NASA’s Earth Science Data and Information System (ESDIS). Imagery: NASA GIBS (Blue Marble, Black Marble, VIIRS daily true colour).
  • +
  • EOX — map imagery when zoomed in: EOxCloudless https://cloudless.eox.at by EOX IT Services GmbH (Contains modified Copernicus Sentinel data 2025). CC BY-NC-SA 4.0.
  • +
  • OpenStreetMap — map place names and roads: © OpenStreetMap contributors, ODbL; tiles by OpenFreeMap, OpenMapTiles schema.
  • Climate TRACE — asset-level emissions inventory. CC BY 4.0.
  • Our World in Data — world pulse indicators. CC BY 4.0; upstream licences per indicator.
  • GBIF — GBIF.org occurrence data; licence per dataset (CC0, CC BY or CC BY-NC).
  • @@ -330,26 +359,18 @@ export function renderMarkdown(md: string, headingOffset = 0): string { return html.join("\n"); } -// ---- landing ------------------------------------------------------------------------------------------------- +// ---- the world map (static first paint; web/src/site/map upgrades it to MapLibre in place) -------------- -export function landingPage(c: Ctx, findings: Finding[]): { head: string; body: string } { - const s = c.stats; - const site = c.baseUrl ?? SITE.organization.url; - const orgId = `${site}#org`; - const ld = [ - { "@context": "https://schema.org", "@type": "Organization", "@id": orgId, name: SITE.organization.name, url: c.baseUrl ?? SITE.organization.url }, - { "@context": "https://schema.org", "@type": "WebSite", name: SITE.fullName, alternateName: SITE.name, url: abs(c, "") ?? undefined, description: SITE.description, publisher: { "@id": orgId } }, - datasetLd(c, orgId), - ]; +/** + * Plain links positioned over an equirectangular NASA image, so lon/lat → % is linear. It is the + * map for crawlers, no-JS readers and the first paint; `data-map` tells the site bundle it may + * swap in the interactive globe once the reader touches it (or the page goes idle). + */ +function worldFigure(all: Finding[], caseBase: string, nPub: number): string { const isPub = (f: Finding) => PUBLIC_STATUSES.includes(f.status); - // What's live: published cases plus the open ones still being checked or reviewed. - const live = findings.filter((f) => isPub(f) || f.status === "candidate" || f.status === "confirmed"); - const latest = [...live].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, 6); - const nPub = live.filter(isPub).length; - - // Markers: plain links positioned over an equirectangular image, so lon/lat → % is linear. + const cases = all.filter((f) => !isGlobalCase({ bbox: f.bbox, aoiId: f.aoi?.id, indicator: indicatorOf(f) })); // planet-wide cases are not a place const pct = (v: number) => Math.min(100, Math.max(0, v)).toFixed(2); - const pins = [...live] + const pins = [...cases] .sort((a, b) => Number(isPub(a)) - Number(isPub(b))) // published drawn last, on top .map((f) => { const [w, so, e, n] = f.bbox; @@ -357,15 +378,84 @@ export function landingPage(c: Ctx, findings: Finding[]): { head: string; body: const y = ((90 - (so + n) / 2) / 180) * 100; const cls = ["pin", isPub(f) ? "pin--pub" : "pin--open", y < 18 ? "pin--below" : "", x < 14 ? "pin--l" : x > 86 ? "pin--r" : ""].filter(Boolean).join(" "); const title = plainTitle(f); - return ``; + return ``; }) .join(""); - const rows = latest.length - ? latest.map((f) => `
  • ${caseRow(f, `watch/case/${f.findingId}/`, `live-row${isPub(f) ? "" : " is-unpublished"}`)}
  • `).join("") - : `
  • No cases yet — the first check hasn’t found anything.
  • `; + return `
    +
    +
    + The Earth at night with the places of ${nPub} published case${nPub === 1 ? +
    ${pins}
    +
    +
    +
    PublishedBeing checkedEarth at night · NASA
    +
    `; +} + +// ---- landing ------------------------------------------------------------------------------------------------- + +const SIT_ID = /^[A-Za-z0-9_-]{1,64}$/; +/** One briefing item: a case opens in the map (`#case=`), an indicator scrolls to its Planet row. */ +function situationItem(i: SituationRecord["text"]["items"][number]): string { + if (i.caseId && SIT_ID.test(i.caseId)) return `
  • ${esc(i.line)}
  • `; + if (i.indicator && SIT_ID.test(i.indicator)) return `
  • ${esc(i.line)}
  • `; + return `
  • ${esc(i.line)}
  • `; +} +const sitWhy = (r: SituationRecord) => + r.reasons.length ? `
      ${r.reasons.map((x) => `
    • ${esc(LEVEL_LABEL[x.level])} ${esc(x.text)}
    • `).join("")}
    ` : `

    No rule fired: no newly confirmed case in 7 days, no watched indicator outside its usual range.

    `; +const sitBy = (r: SituationRecord) => + r.source === "model" ? "Level set by fixed rules. Briefing written by AI and checked by a second, separate AI against the facts before it went up." : "Level set by fixed rules. This text comes straight from those rules — no AI wording today."; + +/** The slim strip at the top of the map. */ +export function situationStrip(r: SituationRecord | null | undefined): string { + if (!r) return ""; + return `Situation · ${esc(LEVEL_LABEL[r.level])}${esc(r.text.headline)}`; +} + +/** The full briefing at the top of Planet mode. */ +export function situationBrief(r: SituationRecord | null | undefined): string { + if (!r) return ""; + return `
    +

    Situation · ${esc(LEVEL_LABEL[r.level])} ·

    +

    ${esc(r.text.headline)}

    +

    ${esc(r.text.summary)}

    + ${r.text.items.length ? `
      ${r.text.items.map(situationItem).join("")}
    ` : ""} +
    Why this level${sitWhy(r)}
    +

    ${esc(sitBy(r))}

    +
    `; +} + +/** Below the fold: the same briefing as plain text, for crawlers and readers without JavaScript. */ +export function situationStatic(r: SituationRecord | null | undefined): string { + if (!r) return ""; + return `

    Situation · ${esc(LEVEL_LABEL[r.level])} (${esc(r.date)})

    ${esc(r.text.headline)} ${esc(r.text.summary)}

    ${sitWhy(r)}

    ${esc(sitBy(r))}

    `; +} + +export function landingPage(c: Ctx, findings: Finding[], situation: SituationRecord | null = null): { head: string; body: string } { + const s = c.stats; + const site = c.baseUrl ?? SITE.organization.url; + const orgId = `${site}#org`; + const ld = [ + { "@context": "https://schema.org", "@type": "Organization", "@id": orgId, name: SITE.organization.name, url: c.baseUrl ?? SITE.organization.url, ...(abs(c, SITE.logo) ? { logo: abs(c, SITE.logo) } : {}) }, + { "@context": "https://schema.org", "@type": "WebSite", name: SITE.fullName, alternateName: SITE.name, url: abs(c, "") ?? undefined, description: SITE.description, publisher: { "@id": orgId } }, + datasetLd(c, orgId), + ]; + const isPub = (f: Finding) => PUBLIC_STATUSES.includes(f.status); + const global = (f: Finding) => isGlobalCase({ bbox: f.bbox, aoiId: f.aoi?.id, indicator: indicatorOf(f) }); + // What's live: published cases plus the open ones still being checked or reviewed. Places go on + // the map and in the Cases list; planet-wide cases (world trends, sea ice) live in Planet. + const live = findings.filter((f) => isPub(f) || f.status === "candidate" || f.status === "confirmed"); + const local = live.filter((f) => !global(f)); + const planet = live.filter(global).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); + const latest = [...local].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)).slice(0, 12); + const nPub = local.filter(isPub).length; + const row = (f: Finding) => `
  • ${caseRow(f, `watch/case/${f.findingId}/`, `live-row${isPub(f) ? "" : " is-unpublished"}`)}
  • `; + + const rows = latest.length ? latest.map(row).join("") : `
  • No cases yet — the first check hasn’t found anything.
  • `; const fp = s.falsePositiveRate.overall; - const num = (v: string, k: string, title = "") => `
    ${esc(k)}
    ${v}
    `; + const num = (v: string, k: string, title = "", stat = "") => + `
    ${esc(k)}
    ${v}
    `; const wrongTitle = fp.decided ? `${fp.falsePositives} of the ${fp.decided} cases we could settle were false alarms — caught by our own checks before anything was published. We keep them on the site.` : "No case has been settled yet."; const flow: [string, string][] = [ ["Spot", "satellites flag a change"], @@ -374,42 +464,87 @@ export function landingPage(c: Ctx, findings: Finding[]): { head: string; body: ["Warn first", "the people named hear first"], ["Keep the record", "nothing is edited or deleted"], ]; + const modes: [string, string][] = [ + ["cases", "Cases"], + ["planet", "Planet"], + ["live", "Live"], + ["metrics", "Metrics"], + ["about", "About"], + ]; + const pane = (id: string, inner: string) => `
    ${inner}
    `; + const fpLine = fp.decided + ? `Of the ${fp.decided} cases we could settle so far, ${fp.falsePositives} turned out to be false alarms. Our own second check caught them before anything went public — and they stay on this site, counted, not hidden.` + : "No case has been settled yet, so there is no false-alarm rate to show. When there is, it is shown here — counted, not hidden."; const body = `${siteTop(c, "landing", SITE.oneLine)}
    -
    -
    -
    -
    -
    - The Earth at night with the places of ${nPub} published case${nPub === 1 ? -
    ${pins}
    -
    -
    -
    PublishedBeing checkedEarth at night · NASA
    -
    +
    + ${situationStrip(situation)} +
    + ${worldFigure(local, "watch/", nPub)}
    - ${num(String(s.cases.public), "Cases published")} - ${num(fp.decided ? `${fp.falsePositives} of ${fp.decided}` : "0", "False alarms we caught", wrongTitle)} + ${num(String(s.cases.public), "Cases published", "", "published")} + ${num(fp.decided ? `${fp.falsePositives} of ${fp.decided}` : "0", "False alarms we caught", wrongTitle, "fp")} ${num(s.lastSweep ? time(s.lastSweep.at, plainDate(s.lastSweep.at), "ago") : "—", "Last check", s.lastSweep ? `${s.lastSweep.at.replace("T", " ").slice(0, 16)} UTC` : "")}
    -
    -

    Latest cases

    All cases →
    -
      ${rows}
    -
    -
    -
    -

    How a case is made

    -
      ${flow.map(([k, v], i) => `
    1. ${i + 1}${esc(k)}${esc(v)}
    2. `).join("")}
    +
    - -
    -

    Named in a case? Think it’s wrong?

    -

    ${esc(REPLY_TEXT)}

    If a case turns out wrong, it is marked “Turned out wrong” — in public — and it stays on this site.

    +
    + ${situationStatic(situation)} +

    What the watch has found

    ${nPub} published case${nPub === 1 ? "" : "s"} and ${local.length - nPub} still being checked, in forests, fire, gas flaring, methane, oceans, ice, air and weather. See every case.

    +

    How a case is made

    ${flow.map(([k, v]) => `${esc(k)}: ${esc(v)}.`).join(" ")}

    +

    World pulse

    How the planet is doing — good news and bad: wildlife, forests, oceans, air and the energy we use, as long-running open indicators.

    ${siteFoot(c)}`; @@ -493,6 +628,7 @@ export function watchIndexPage(c: Ctx, findings: Finding[]): { head: string; bod const s = c.stats; const isPublic = (f: Finding) => PUBLIC_STATUSES.includes(f.status); const pub = findings.filter(isPublic); + const live = findings.filter((f) => isPublic(f) || f.status === "candidate" || f.status === "confirmed"); const rows = findings.map((f) => `
  • ${caseRow(f, `case/${f.findingId}/`)}
  • `).join(""); const orgId = `${c.baseUrl ?? SITE.organization.url}#org`; const crumbs = c.baseUrl @@ -512,9 +648,10 @@ export function watchIndexPage(c: Ctx, findings: Finding[]): { head: string; bod

    Cases

    Every published finding with its evidence, independent confirmation, review trail and a proof against the signed ledger. Unpublished findings — candidates, false positives, expired — stay in the ledger too.

    +
    ${worldFigure(live, "", live.filter(isPublic).length)}
    -
    ${pub.length} published${findings.length} in ledger${s.ledger.size} entries
    +
    ${pub.length} published${findings.length} in ledger${s.ledger.size} entries
    ${s.ledger.root ? `
    Root${esc(s.ledger.root.slice(0, 10))}…${copyBtn(s.ledger.root)}
    ` : ""}
    ${unpublished ? `` : ""} @@ -559,7 +696,22 @@ const CHANGE_MIND = const NOT_SURE_DEFAULT = "Satellite signals can be wrong: clouds, smoke, the seasons and sensor glitches can all look like change. That is why every case needs a second, separate source before it is published."; -export function casePage(c: Ctx, d: CaseData): { head: string; body: string } { +export const NEWS_NOTE = "News found by place and topic. It is context, not evidence: our checks don't use it."; + +/** "In the news" — headline links only (no bodies, no images); "" when there is nothing. */ +export function newsHtml(items: readonly NewsItem[] | undefined): string { + const li = (items ?? []) + .map((n) => { + const href = safeUrl(n.url); + if (!href || !n.title) return ""; + const when = n.seendate ? ` (${esc(plainDate(n.seendate))})` : ""; + return `
  • ${esc(n.title)} ${esc(n.domain)}${when}
  • `; + }) + .filter(Boolean); + return li.length ? section("In the news", `
      ${li.join("")}

    ${esc(NEWS_NOTE)}

    `) : ""; +} + +export function casePage(c: Ctx, d: CaseData, wall: { replies?: ShownReply[]; replyEndpoint?: string | null; news?: readonly NewsItem[] } = {}): { head: string; body: string } { const f = d.finding; const s = c.stats; const isPublic = PUBLIC_STATUSES.includes(f.status); @@ -582,7 +734,9 @@ export function casePage(c: Ctx, d: CaseData): { head: string; body: string } { return `
  • ${esc(sourceName(x.source))}${x.summary ? ` — ${esc(x.summary)}` : ""} (${esc(plainDate(x.datetime))})${href ? ` See the source ↗` : ""}
  • `; }), ]; - const doubts = [...(nar?.caveats ?? []), ...(f.blindSpots ?? [])]; + // Older indicator_threshold entries carry every indicator's blind spots; show only this case's. + const spots = f.rule.name === "indicator_threshold" ? indicatorBlindSpots(f.blindSpots ?? [], indicatorOf(f)) : (f.blindSpots ?? []); + const doubts = [...(nar?.caveats ?? []), ...spots]; const replies = rightOfReplyHtml(f); // Technical details (collapsed). @@ -602,10 +756,14 @@ export function casePage(c: Ctx, d: CaseData): { head: string; body: string } { const ctxHtml = contextHtml(f); const hist = [...f.history].reverse().map((h) => tl(h.at, `${words(h.kind)} → ${words(h.status)}`, plainActor(h.actor))).join(""); + // Map first (at least half the screen, the case area outlined), the words below. Readers with + // JavaScript are taken into the same case on the live map (web/src/site/main.ts); this page is + // what crawlers and no-JS readers get. const body = `${siteTop(c, "cases")} +
    ${heroHtml(f)}
    -
    +
    ${plainStatus(f.status)}

    ${esc(title)}

    @@ -614,12 +772,12 @@ export function casePage(c: Ctx, d: CaseData): { head: string; body: string } { ${nar ? `
    ${renderMarkdown(nar.body, 1)}

    Written by AI, then checked by a separate reviewer before publication. Every claim points at the evidence below.

    ` : `

    ${esc(f.summary)}

    `} ${isPublic ? "" : ``} ${f.retracted ? `` : ""} - ${heroHtml(f)} ${section("What we saw", `
      ${seen.join("")}
    `)} + ${newsHtml(wall.news)} ${section("What it might not be", doubts.length ? `
      ${doubts.map((b) => `
    • ${esc(b)}
    • `).join("")}
    ` : `

    ${esc(NOT_SURE_DEFAULT)}

    `)} ${section("What would change our mind", `

    ${esc(CHANGE_MIND)}

    `)} ${section(isPublic ? "Why this was published" : "Why this is not published", `

    ${esc(whySentence(f, pubEv))}

    `)} - ${section("Right of reply", `${replies}

    ${esc(REPLY_TEXT)}

    Ledger id ${esc(f.findingId)}${copyBtn(f.findingId)}

    `, undefined, "challenge")} + ${section("Replies", `${replies}${replyWallHtml(f.findingId, wall.replies ?? [], wall.replyEndpoint ?? null)}

    Ledger id ${esc(f.findingId)}${copyBtn(f.findingId)}

    `, wall.replies?.length || undefined, "challenge")}
    Technical details rule, evidence ids, history, proof
    ${facts.map(([k, v]) => `
    ${esc(k)}
    ${esc(v)}`).join("")}
    @@ -702,7 +860,7 @@ function heroHtml(f: Finding): string { } const q = `SERVICE=WMS&REQUEST=GetMap&VERSION=1.1.1&LAYERS=BlueMarble_NextGeneration&STYLES=&SRS=EPSG:4326&BBOX=${[W, S, E, N].map((v) => v.toFixed(4)).join(",")}&WIDTH=800&HEIGHT=450&FORMAT=image/jpeg`; const where = f.aoi?.name ?? "the finding"; - return `
    ${esc(`Cloud-free satellite view around ${where}, with the finding area outlined`)}
    ${esc(`${fmtLat(cy)} ${fmtLon(cx)}`)}NASA Blue Marble via GIBS · outline = finding area
    `; + return `
    ${esc(`Cloud-free satellite view around ${where}, with the finding area outlined`)}
    ${esc(`${fmtLat(cy)} ${fmtLon(cx)}`)}NASA Blue Marble via GIBS · outline = finding area
    `; } function stepperHtml(f: Finding): string { @@ -750,6 +908,19 @@ function tl(at: string | null, what: string, sub: string, cls = ""): string { return `
  • ${at ? time(at, dateOf(at), "tl-when") : ''}${esc(what)}${sub ? `${esc(sub)}` : ""}
  • `; } +/** The public reply wall under a case: reviewed replies, then the form's mount point (built by web/src/site/reply.ts). */ +export function replyWallHtml(caseId: string, list: ShownReply[], endpoint: string | null): string { + const items = list.map( + (r) => + `
  • ${esc(ROLE_LABEL[r.role] ?? ROLE_LABEL.other)} · ${time(r.receivedAt, plainDate(r.receivedAt))}

    ${esc(r.text).replace(/\n/g, "
    ")}

  • `, + ); + const listHtml = items.length ? `
      ${items.join("")}

    ${esc(REPLY_NOTE)}

    ` : ""; + const box = endpoint + ? `

    ${esc(REPLY_LEDE)}

    ${esc(REPLY_NOJS)}

    ` + : ""; + return `${listHtml}${box}${!items.length && !endpoint ? `

    No replies yet.

    ` : ""}`; +} + function rightOfReplyHtml(f: Finding): string { if (!f.notifications.length && !f.replies.length) return ""; const items = f.notifications.map((x) => tl(x.at, `Told ${x.to.name} first`, `Public from ${plainDate(x.publicAt)}`)); @@ -857,6 +1028,30 @@ export function trustPage(c: Ctx, md: string): { head: string; body: string } { }; } +// ---- web app manifest (icons for home screens; names from SITE) ------------------------------------------ + +export function webManifest(): string { + return `${JSON.stringify( + { + name: SITE.fullName, + short_name: SITE.name, + description: SITE.byline, + start_url: "./", + scope: "./", + display: "browser", + background_color: SITE.themeColor, + theme_color: SITE.themeColor, + icons: [ + { src: "icon-192.png", sizes: "192x192", type: "image/png" }, + { src: "icon-512.png", sizes: "512x512", type: "image/png" }, + { src: "favicon.svg", sizes: "any", type: "image/svg+xml" }, + ], + }, + null, + 2, + )}\n`; +} + // ---- sitemap / robots --------------------------------------------------------------------------------------------------- export function sitemap(baseUrl: string, pages: { path: string; lastmod?: string }[]): string { diff --git a/src/watch/situation.ts b/src/watch/situation.ts new file mode 100644 index 0000000..b63013c --- /dev/null +++ b/src/watch/situation.ts @@ -0,0 +1,362 @@ +// The daily Situation: one level for the whole watch — quiet, watch or urgent — decided by +// explicit rules over the ledger (last 7 days) and the planet indicators, never by a model. +// A model may write the briefing around it (src/analyst/situation.ts); if it can't, the +// rules-only text below is what goes out. Criteria in plain words: TRUST.md "Situation". +// +// Stored as /situation/.json (last 30 days). The Merkle ledger only +// holds per-finding events (every event needs a findingId), so a situation is kept beside it, +// not in it: its inputs are ledger facts, but the briefing itself is not signed. + +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { ensoPhase, type OniRow, type SeaIceClimatologyRow } from "../clients/indicators.js"; +import { PUBLIC_STATUSES, type Finding, type Status } from "../ledger/schema.js"; +import type { SeriesPoint } from "../series.js"; +import type { PulseRow } from "../tools/worldpulse.js"; +import { canonicalize } from "../ledger/jcs.js"; +import { indicatorOf, topicOf } from "./map-data.js"; + +export type Level = "quiet" | "watch" | "urgent"; +export const LEVELS: readonly Level[] = ["quiet", "watch", "urgent"]; + +export interface Reason { + /** Which criterion fired (stable, testable). */ + code: "enso_change" | "quake_m7" | "weather_published" | "sea_ice_record" | "regional_cluster" | "new_confirmed" | "indicator_crossing" | "sea_ice_p10"; + level: Exclude; + /** One plain sentence a general reader can follow. */ + text: string; + caseIds: string[]; + indicator?: string; +} + +export interface SeaIceInput { + pole: "north" | "south"; + daily: SeriesPoint[]; + clim: SeaIceClimatologyRow[]; +} + +/** Indicator data the rules read. Anything missing just can't trigger its criterion. */ +export interface IndicatorInputs { + oni?: OniRow[] | null; + seaIce?: SeaIceInput[]; + pulse?: PulseRow[] | null; +} + +const H = 3_600_000; +/** Statuses that take a case out of the picture: ruled out, lapsed or withdrawn. */ +const DROPPED: readonly Status[] = ["false_positive", "expired", "retracted"]; +const live = (f: Finding) => !DROPPED.includes(f.status); +const within = (iso: string | null | undefined, now: Date, hours: number) => { + const t = iso ? Date.parse(iso) : NaN; + return Number.isFinite(t) && t <= now.getTime() + H && now.getTime() - t <= hours * H; +}; +const values = (f: Finding) => [...f.evidence, ...(f.confirmed ? [f.confirmed.signal] : [])].map((e) => e.values ?? {}); +const valueOf = (f: Finding, key: string): number | null => { + for (const v of values(f)) if (typeof v[key] === "number" && Number.isFinite(v[key])) return v[key]!; + return null; +}; +/** Rules about something happening now (not chronic sources like flaring, not good news). */ +const ACUTE_RULES = new Set(["forest_loss", "fires_in_protected", "weather_extreme", "methane_anomaly", "mpa_fishing"]); +const ACUTE_INDICATORS = new Set(["quake", "marine_heatwave", "river_discharge", "air_quality"]); +/** Pure: may this case count toward the regional-cluster criterion? */ +export function isAcute(f: Finding): boolean { + if (f.aoi?.tags?.includes("improvement")) return false; + if (f.rule.name === "indicator_threshold") return ACUTE_INDICATORS.has(indicatorOf(f) ?? ""); + return ACUTE_RULES.has(f.rule.name); +} + +/** When a case went public (first move into a public status), or null. */ +export function publishedAt(f: Finding): string | null { + return f.history.find((h) => PUBLIC_STATUSES.includes(h.status) && h.status !== "retracted")?.at ?? null; +} +/** A 5° × 5° box around a case's centre — "one region" for the cluster criterion. */ +export function regionOf(f: Pick): string { + const [w, s, e, n] = f.bbox; + const lon = (w + e) / 2; + const lat = (s + n) / 2; + const cell = (v: number) => Math.floor(v / 5) * 5; + return `${cell(lat)},${cell(lon)}`; +} +const place = (f: Finding) => f.aoi?.name ?? f.title; +/** "A; B; C and 7 more" — reasons stay one readable line however many cases are behind them. */ +const places = (fs: readonly Finding[], max = 3) => { + const names = [...new Set(fs.map(place))]; + return names.length > max ? `${names.slice(0, max).join("; ")} and ${names.length - max} more` : names.join("; "); +}; +const hemisphereOf = (f: Finding) => f.evidence.map((e) => e.method.params?.hemisphere).find((h) => typeof h === "string"); + +/** ENSO phase by NOAA's event definition (≥ 5 seasons), else Neutral. */ +const declared = (rows: OniRow[]) => { + if (!rows.length) return "Neutral"; + const p = ensoPhase(rows); + return p.meetsEventDefinition ? p.phase : "Neutral"; +}; + +/** Lowest extent on the same month-day in earlier years of the series (the record for the date), or null. */ +export function seaIceRecordFor(daily: SeriesPoint[], date: string): number | null { + const md = date.slice(5, 10); + const year = date.slice(0, 4); + let min: number | null = null; + for (const p of daily) if (p.v !== null && p.t.slice(5, 10) === md && p.t.slice(0, 4) < year && (min === null || p.v < min)) min = p.v; + return min; +} + +const pct = (sorted: number[], q: number) => { + const i = (sorted.length - 1) * q; + const lo = Math.floor(i); + const hi = Math.ceil(i); + return sorted[lo]! + (sorted[hi]! - sorted[lo]!) * (i - lo); +}; +/** A world-pulse row whose latest value just left its own p10–p90 band (the previous value was inside). */ +export function pulseCrossing(r: PulseRow): "above_p90" | "below_p10" | null { + if (r.status !== "ok" || !r.latest || r.latest.v === null) return null; + const hist = (r.sparkline ?? []).map((p) => p.v).filter((v): v is number => typeof v === "number" && Number.isFinite(v)); + if (hist.at(-1) === r.latest.v) hist.pop(); + if (hist.length < 10) return null; + const prev = r.previous?.v ?? hist.at(-1)!; + const s = [...hist].sort((a, b) => a - b); + const p10 = pct(s, 0.1); + const p90 = pct(s, 0.9); + if (prev === null || prev < p10 || prev > p90) return null; + if (r.latest.v > p90) return "above_p90"; + if (r.latest.v < p10) return "below_p10"; + return null; +} + +/** Pure: the level and every criterion that fired. The highest level among the reasons wins. */ +export function computeLevel(findings: readonly Finding[], ind: IndicatorInputs, now = new Date()): { level: Level; reasons: Reason[] } { + const reasons: Reason[] = []; + const month = now.toISOString().slice(0, 7); + + // U1 — ENSO phase newly declared or changed this month. + const ensoCases = findings.filter((f) => live(f) && indicatorOf(f) === "enso" && f.createdAt.slice(0, 7) === month); + const oni = ind.oni ?? []; + const nowPhase = oni.length ? declared(oni) : null; + const wasPhase = oni.length > 1 ? declared(oni.slice(0, -1)) : null; + if ((nowPhase && wasPhase && nowPhase !== wasPhase) || ensoCases.length) { + const phase = nowPhase ?? "an ENSO phase"; + const text = nowPhase && wasPhase && nowPhase !== wasPhase ? `ENSO changed this month: ${wasPhase} → ${nowPhase} by NOAA's definition.` : `A new ${phase === "Neutral" ? "ENSO" : phase} case was opened this month.`; + reasons.push({ code: "enso_change", level: "urgent", text, caseIds: ensoCases.map((f) => f.findingId), indicator: "enso" }); + } + + // U2 — an M7+ earthquake case in the last 48 h. + const quakes = findings.filter((f) => live(f) && indicatorOf(f) === "quake" && (valueOf(f, "magnitude") ?? 0) >= 7 && (within(f.observedAt, now, 48) || within(f.createdAt, now, 48))); + if (quakes.length) reasons.push({ code: "quake_m7", level: "urgent", text: `Magnitude 7 or stronger earthquake: ${places(quakes)}.`, caseIds: quakes.map((f) => f.findingId), indicator: "quake" }); + + // U3 — a published tropical-cyclone or extreme-heat case in the last 48 h. + const weather = findings.filter((f) => { + if (f.rule.name !== "weather_extreme" || !PUBLIC_STATUSES.includes(f.status) || f.status === "retracted") return false; + const code = valueOf(f, "hazardCode"); + return (code === 1 || code === 2) && (within(publishedAt(f), now, 48) || within(f.observedAt, now, 48)); + }); + if (weather.length) reasons.push({ code: "weather_published", level: "urgent", text: `Published extreme heat or tropical cyclone: ${places(weather)}.`, caseIds: weather.map((f) => f.findingId) }); + + // U4 / W3 — sea ice below the record for the date (urgent) or below the 1981–2010 p10 (watch). + for (const s of ind.seaIce ?? []) { + const latest = [...s.daily].reverse().find((p) => p.v !== null); + if (!latest || latest.v === null) continue; + const label = s.pole === "north" ? "Arctic" : "Antarctic"; + const hemi = s.pole === "north" ? "arctic" : "antarctic"; + const cases = findings.filter((f) => live(f) && indicatorOf(f) === "sea_ice" && (hemisphereOf(f) ?? "arctic") === hemi).map((f) => f.findingId); + const record = seaIceRecordFor(s.daily, latest.t); + if (record !== null && latest.v < record) { + reasons.push({ code: "sea_ice_record", level: "urgent", text: `${label} sea ice is at a record low for ${latest.t.slice(5)}: ${latest.v} million km², below the previous lowest of ${record}.`, caseIds: cases, indicator: `sea_ice_${s.pole}` }); + continue; + } + const doy = dayOfYearUtc(latest.t); + const c = s.clim.find((r) => r.doy === doy); + if (c && latest.v < c.p10) reasons.push({ code: "sea_ice_p10", level: "watch", text: `${label} sea ice is in the lowest tenth for the date: ${latest.v} million km² (1981–2010 p10 ${c.p10}).`, caseIds: cases, indicator: `sea_ice_${s.pole}` }); + } + + // U5 — acute cases newly confirmed in the last 24 h at ≥ 3 distinct places (AOI ids) in one 5° box. + const fresh = findings.filter((f) => live(f) && isAcute(f) && f.confirmed && within(f.confirmed.at, now, 24)); + const byRegion = new Map(); + for (const f of fresh) byRegion.set(regionOf(f), [...(byRegion.get(regionOf(f)) ?? []), f]); + for (const [, fs] of byRegion) { + if (new Set(fs.map((f) => f.aoi?.id ?? f.findingId)).size >= 3) reasons.push({ code: "regional_cluster", level: "urgent", text: `${fs.length} urgent cases confirmed in one region within a day: ${places(fs)}.`, caseIds: fs.map((f) => f.findingId) }); + } + + // W1 — any newly confirmed case in the last 7 days. + const week = findings.filter((f) => live(f) && f.confirmed && within(f.confirmed.at, now, 7 * 24)); + if (week.length) reasons.push({ code: "new_confirmed", level: "watch", text: `${week.length} case${week.length === 1 ? "" : "s"} confirmed by a second, independent signal in the last 7 days.`, caseIds: week.map((f) => f.findingId) }); + + // W2 — a world-pulse indicator leaving its own p10–p90 band. + for (const r of ind.pulse ?? []) { + const x = pulseCrossing(r); + if (x) reasons.push({ code: "indicator_crossing", level: "watch", text: `${r.label} moved ${x === "above_p90" ? "above its usual range (p90)" : "below its usual range (p10)"}: ${r.latest!.v} ${r.unit}.`, caseIds: [], indicator: r.slug }); + } + + const level: Level = reasons.some((r) => r.level === "urgent") ? "urgent" : reasons.length ? "watch" : "quiet"; + return { level, reasons }; +} + +function dayOfYearUtc(date: string): number { + const d = Date.parse(`${date.slice(0, 10)}T00:00:00Z`); + return Math.round((d - Date.UTC(Number(date.slice(0, 4)), 0, 0)) / 86_400_000); +} + +// ---- Dossier: everything the briefing model may know ---------------------------------------- + +export interface DossierCase { + caseId: string; + headline: string; + topic: string; + place: string | null; + status: Status; +} +export interface DossierIndicator { + indicator: string; + label: string; + unit: string; + latest: number; + latestDate: string; + normal: number | null; + normalMeans: string; +} +export interface Dossier { + date: string; + level: Level; + reasons: Reason[]; + sinceYesterday: { byStatus: Partial>; byTopic: Record }; + newPublished: DossierCase[]; + goodNews: DossierCase[]; + indicators: DossierIndicator[]; + falseAlarmsCaught: { last7Days: number; caseIds: string[] }; +} + +const headlineOf = (f: Finding) => (f.narration?.text.split("\n")[0]?.trim() || f.title).slice(0, 200); +const dcase = (f: Finding): DossierCase => ({ caseId: f.findingId, headline: headlineOf(f), topic: topicOf(f.rule.name, indicatorOf(f), f.aoi?.tags ?? []), place: f.aoi?.name ?? null, status: f.status }); +const r3 = (v: number) => Number(v.toPrecision(3)); + +/** Pure: the facts behind one day's briefing. */ +export function buildDossier(findings: readonly Finding[], ind: IndicatorInputs, now = new Date()): Dossier { + const { level, reasons } = computeLevel(findings, ind, now); + const byStatus: Partial> = {}; + const byTopic: Record = {}; + for (const f of findings) { + if (!within(f.updatedAt, now, 24)) continue; + byStatus[f.status] = (byStatus[f.status] ?? 0) + 1; + const t = topicOf(f.rule.name, indicatorOf(f), f.aoi?.tags ?? []); + byTopic[t] = (byTopic[t] ?? 0) + 1; + } + const pub = findings.filter((f) => PUBLIC_STATUSES.includes(f.status) && f.status !== "retracted"); + const newPublished = pub.filter((f) => within(publishedAt(f), now, 24)).map(dcase); + const goodNews = pub.filter((f) => f.aoi?.tags?.includes("improvement") || f.rule.name === "flaring_stopped").filter((f) => within(publishedAt(f), now, 7 * 24)).map(dcase); + const fps = findings.filter((f) => f.status === "false_positive" && within(f.updatedAt, now, 7 * 24)); + + const indicators: DossierIndicator[] = []; + const oni = ind.oni ?? []; + if (oni.length) { + const p = ensoPhase(oni); + indicators.push({ indicator: "enso", label: `ENSO (ONI), current phase ${declared(oni)}`, unit: "°C", latest: p.latest.anom, latestDate: `${p.latest.season} ${p.latest.year}`, normal: 0, normalMeans: "ONI 0 = neutral; El Niño at +0.5 or above for 5 seasons, La Niña at −0.5 or below" }); + } + for (const s of ind.seaIce ?? []) { + const latest = [...s.daily].reverse().find((p) => p.v !== null); + if (!latest || latest.v === null) continue; + const c = s.clim.find((r) => r.doy === dayOfYearUtc(latest.t)); + indicators.push({ indicator: `sea_ice_${s.pole}`, label: `${s.pole === "north" ? "Arctic" : "Antarctic"} sea-ice extent`, unit: "million km²", latest: latest.v, latestDate: latest.t, normal: c ? c.average : null, normalMeans: "1981–2010 average for this day of the year" }); + } + for (const r of ind.pulse ?? []) { + if (r.status !== "ok" || !r.latest || r.latest.v === null) continue; + indicators.push({ indicator: r.slug, label: r.label, unit: r.unit, latest: r3(r.latest.v), latestDate: r.latest.t, normal: r.previous?.v != null ? r3(r.previous.v) : null, normalMeans: `previous reading (${r.previous?.t ?? "n/a"}); trend ${r.direction ?? "flat"}` }); + } + return { + date: now.toISOString().slice(0, 10), + level, + reasons, + sinceYesterday: { byStatus, byTopic }, + newPublished, + goodNews, + indicators, + falseAlarmsCaught: { last7Days: fps.length, caseIds: fps.map((f) => f.findingId) }, + }; +} + +export const dossierHash = (d: Dossier) => createHash("sha256").update(canonicalize(d)).digest("hex"); + +// ---- The briefing text and its record ------------------------------------------------------ + +export interface BriefingItem { + caseId?: string; + indicator?: string; + line: string; +} +export interface Briefing { + headline: string; + summary: string; + items: BriefingItem[]; +} + +export interface SituationRecord { + v: 1; + date: string; + generatedAt: string; + level: Level; + reasons: Reason[]; + dossierHash: string; + dossier: Dossier; + text: Briefing; + /** "model": written by the narrator and accepted by the reviewer; "rules": the plain fallback. */ + source: "model" | "rules"; + models: null | { narrator: string; reviewer: string }; + verdict: null | { accept: boolean; reason: string }; + /** The model's draft when it was not used (failed the checks or the reviewer) — kept for the record, never shown. */ + draft?: Briefing | null; + /** Deterministic check failures (faithfulness, no persons, JSON), when the model text was dropped. */ + problems: string[]; + /** Model calls spent on today's briefing so far (cap: one briefing a day). */ + modelBriefings: number; + costUsd: number; + note: string; +} + +export const LEVEL_LABEL: Record = { quiet: "Quiet", watch: "Watch", urgent: "Urgent" }; +export const SITUATION_NOTE = "Level decided by fixed rules, not by AI. Kept beside the signed ledger, not in it: the ledger records only per-case events."; + +/** Pure: the rules-only briefing — level and reasons as plain sentences, no model text. */ +export function fallbackBriefing(level: Level, reasons: readonly Reason[]): Briefing { + if (!reasons.length) return { headline: "Quiet: nothing urgent in the watch today", summary: "No rule for urgent or watch fired today. No newly confirmed cases in the last 7 days and no watched indicator left its usual range.", items: [] }; + const top = reasons.find((r) => r.level === level) ?? reasons[0]!; + const headline = `${LEVEL_LABEL[level]}: ${top.text.replace(/\.$/, "")}`; + return { + headline: headline.length > 90 ? `${headline.slice(0, 89).trimEnd()}…` : headline, + summary: reasons.map((r) => r.text).join(" "), + items: reasons.slice(0, 6).map((r) => ({ ...(r.caseIds[0] ? { caseId: r.caseIds[0] } : r.indicator ? { indicator: r.indicator } : {}), line: r.text })), + }; +} + +export const situationDir = (ledgerDir: string) => join(ledgerDir, "situation"); +const DATE_FILE = /^\d{4}-\d{2}-\d{2}\.json$/; + +export function readSituation(ledgerDir: string, date: string): SituationRecord | null { + const p = join(situationDir(ledgerDir), `${date}.json`); + if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || !existsSync(p)) return null; + try { + const r = JSON.parse(readFileSync(p, "utf8")) as SituationRecord; + return r && r.v === 1 && LEVELS.includes(r.level) ? r : null; + } catch { + return null; + } +} + +/** Every stored day, newest first. */ +export function listSituations(ledgerDir: string): SituationRecord[] { + const dir = situationDir(ledgerDir); + if (!existsSync(dir)) return []; + return readdirSync(dir) + .filter((f) => DATE_FILE.test(f)) + .sort() + .reverse() + .map((f) => readSituation(ledgerDir, f.slice(0, 10))) + .filter((r): r is SituationRecord => r !== null); +} + +/** Write today's record and drop days older than `keepDays`. */ +export function writeSituation(ledgerDir: string, rec: SituationRecord, keepDays = 30): void { + const dir = situationDir(ledgerDir); + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, `${rec.date}.json`), `${JSON.stringify(rec, null, 2)}\n`); + const cutoff = new Date(Date.parse(`${rec.date}T00:00:00Z`) - keepDays * 86_400_000).toISOString().slice(0, 10); + for (const f of readdirSync(dir)) if (DATE_FILE.test(f) && f.slice(0, 10) <= cutoff) rmSync(join(dir, f), { force: true }); +} diff --git a/test/basemap.test.ts b/test/basemap.test.ts new file mode 100644 index 0000000..833b9b5 --- /dev/null +++ b/test/basemap.test.ts @@ -0,0 +1,64 @@ +// The shared zoom-dependent basemap (web/src/layers/basemap.ts), pure parts: which layers are +// usable with the keys at hand, the zoom crossfade, the "what imagery is this" caption, the GIBS day. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { activeAt, availableBasemaps, basemaps, basemapStyle, captionAt, gibsDay, opacityFor } from "../web/src/layers/basemap.js"; + +const NOW = new Date("2026-09-27T12:00:00Z"); + +test("basemap config: keyed layers are skipped without their key, filled in with it", () => { + const all = basemaps(NOW); + assert.deepEqual(all.map((b) => b.id), ["bm-gibs", "bm-eox", "bm-esri"]); + assert.equal(all[2]!.requiresKey, "ARCGIS_API_KEY"); + assert.deepEqual(availableBasemaps(all).map((b) => b.id), ["bm-gibs", "bm-eox"], "keyless by default"); + assert.deepEqual(availableBasemaps(all, { ARCGIS_API_KEY: " " }).map((b) => b.id), ["bm-gibs", "bm-eox"], "a blank key is no key"); + const withKey = availableBasemaps(all, { ARCGIS_API_KEY: "a b&c" }); + assert.deepEqual(withKey.map((b) => b.id), ["bm-gibs", "bm-eox", "bm-esri"]); + assert.match(withKey[2]!.tiles[0]!, /token=a%20b%26c$/, "the key is URL-encoded into the template"); + assert.ok(!all.some((b) => b.tiles.some((t) => t.includes("token=a"))), "the config itself is never mutated"); +}); + +test("basemap config: tile URLs, native max zooms and the EOX attribution", () => { + const [gibs, eox] = basemaps(NOW); + assert.equal(gibs!.tiles[0], "https://gibs.earthdata.nasa.gov/wmts/epsg3857/best/VIIRS_SNPP_CorrectedReflectance_TrueColor/default/2026-09-26/GoogleMapsCompatible_Level9/{z}/{y}/{x}.jpg"); + assert.equal(gibs!.maxzoom, 9, "Level9 tile matrix — overzoom past it, no 404s"); + assert.equal(eox!.tiles[0], "https://tiles.maps.eox.at/wmts/1.0.0/s2cloudless-2025_3857/default/g/{z}/{y}/{x}.jpg"); + assert.equal(eox!.maxzoom, 14, "10 m Sentinel-2 ≈ z14"); + assert.match(eox!.attribution, /EOxCloudless https:\/\/cloudless\.eox\.at by EOX IT Services GmbH \(Contains modified Copernicus Sentinel data 2025\)/); +}); + +test("crossfade: opacity ramps over the fade span; the base is always opaque", () => { + const [gibs, eox] = basemaps(NOW); + assert.equal(opacityFor(gibs!), 1); + assert.deepEqual(opacityFor(eox!), ["interpolate", ["linear"], ["zoom"], 6, 0, 8, 1]); + const style = basemapStyle({ now: NOW }); + const layer = (id: string) => style.layers.find((l) => l.id === id)!; + assert.equal(layer("bm-eox").minzoom, 6, "EOX is not fetched before its fade starts"); + assert.equal(layer("bm-gibs").maxzoom, 9, "GIBS stops drawing once EOX is fully opaque"); + assert.equal(layer("bm-eox").maxzoom, undefined, "no keyed layer above: EOX runs to the deepest zoom (overzoomed)"); + const keyed = basemapStyle({ now: NOW, keys: { ARCGIS_API_KEY: "k" } }); + assert.equal(keyed.layers.find((l) => l.id === "bm-eox")!.maxzoom, 16, "…or hands over to the keyed layer"); + // Imagery first, then roads, then place names on top. + const ids = style.layers.map((l) => l.id); + assert.ok(ids.indexOf("bm-eox") < ids.indexOf("bm-roads") && ids.indexOf("bm-roads") < ids.indexOf("bm-city")); + assert.equal((style.sources["bm-ofm"] as { url?: string }).url, "https://tiles.openfreemap.org/planet"); + assert.equal(style.glyphs, "https://tiles.openfreemap.org/fonts/{fontstack}/{range}.pbf"); +}); + +test("caption by zoom: today-ish NASA view zoomed out, the dated mosaic zoomed in", () => { + const list = availableBasemaps(basemaps(NOW)); + assert.equal(captionAt(2, list), "Daily satellite view, Sep 26 (NASA)"); + assert.equal(captionAt(6.9, list), "Daily satellite view, Sep 26 (NASA)"); + assert.equal(captionAt(7, list), "Cloud-free mosaic, Sentinel-2 2025 (EOX)", "switches at the middle of the fade"); + assert.equal(captionAt(13, list), "Cloud-free mosaic, Sentinel-2 2025 (EOX)"); + const keyed = availableBasemaps(basemaps(NOW), { ARCGIS_API_KEY: "k" }); + assert.equal(activeAt(15, keyed)!.id, "bm-esri"); + assert.equal(captionAt(3, []), ""); +}); + +test("GIBS day: the last complete UTC day", () => { + assert.equal(gibsDay(new Date("2026-09-27T12:00:00Z")), "2026-09-26"); + assert.equal(gibsDay(new Date("2026-09-27T03:00:00Z")), "2026-09-25", "early UTC: yesterday's last passes may still be processing"); + assert.equal(gibsDay(new Date("2026-03-01T08:00:00Z")), "2026-02-28"); +}); diff --git a/test/e2e/marker-click.e2e.mjs b/test/e2e/marker-click.e2e.mjs new file mode 100644 index 0000000..5aadf51 --- /dev/null +++ b/test/e2e/marker-click.e2e.mjs @@ -0,0 +1,64 @@ +// Browser test (not part of the offline `pnpm test`): every single-case dot on the landing map +// opens its case when clicked — dead centre and 11 px off (dots take clicks within 12 px, picked in screen space) — at +// zoom 2, 4, 6 and 9. Needs a served export and a Playwright browser: +// node dist/cli.js watch export --out /tmp/site --base-url http://localhost:8080 +// npx -y serve -l 8080 /tmp/site (or any static server) +// npx playwright install chromium (once) +// E2E_BASE=http://127.0.0.1:8080 pnpm test:e2e + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { chromium } from "playwright"; + +const BASE = process.env.E2E_BASE ?? "http://127.0.0.1:8080"; +const CENTRES = [[-55, -8], [47.5, 32], [-100, 35]]; + +test("map dots are clickable at zoom 2, 4, 6, 9", { timeout: 600_000 }, async () => { + const browser = await chromium.launch({ args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader", "--ignore-gpu-blocklist"] }); + try { + const page = await (await browser.newContext({ viewport: { width: 1440, height: 860 } })).newPage(); + await page.goto(`${BASE}/`, { waitUntil: "load" }); + await page.waitForSelector(".xp .maplibregl-canvas", { timeout: 30_000 }); + await page.waitForFunction(() => document.querySelector(".xp")?.xpMap?.getLayer("pt"), null, { timeout: 30_000 }); + let clicked = 0; + const misses = []; + for (const z of [2, 4, 6, 9]) { + for (const centre of CENTRES) { + // Dots in view, not under the panel/time bar/chips (those are on top by design). + const dots = await page.evaluate(async ({ centre, z }) => { + const m = document.querySelector(".xp").xpMap; + m.jumpTo({ center: centre, zoom: z }); + await new Promise((r) => { m.once("idle", r); setTimeout(r, 3000); }); + const cv = m.getCanvas().getBoundingClientRect(); + return m.queryRenderedFeatures({ layers: ["pt"] }).map((f) => { + const p = m.project(f.geometry.coordinates); + // On the globe, tiles also hold dots behind the horizon; project() still returns a + // pixel for them. Keep only dots whose pixel maps back to them (the visible side). + const back = m.unproject(p); + const [lon, lat] = f.geometry.coordinates; + const front = Math.abs(back.lat - lat) < 0.5 && Math.abs(((back.lng - lon + 540) % 360) - 180) < 0.5; + return { id: f.properties.id, x: cv.x + p.x, y: cv.y + p.y, front }; + }).filter((d) => d.front && document.elementFromPoint(d.x, d.y) === m.getCanvas() && document.elementFromPoint(d.x + 11, d.y) === m.getCanvas()).slice(0, 2); + }, { centre, z }); + for (const d of dots) { + for (const dx of [0, 11]) { + await page.evaluate(() => history.replaceState(null, "", `${location.pathname}#map:v=1`)); + await page.mouse.move(d.x + dx, d.y); + await page.mouse.click(d.x + dx, d.y); + await page.waitForTimeout(800); + const hash = decodeURIComponent(await page.evaluate(() => location.hash)); + clicked++; + if (!hash.includes(d.id)) misses.push(`z=${z} dx=${dx} ${d.id} → ${hash}`); + await page.keyboard.press("Escape"); + await page.evaluate(({ centre, z }) => document.querySelector(".xp").xpMap.jumpTo({ center: centre, zoom: z }), { centre, z }); + await page.waitForTimeout(400); + } + } + } + } + assert.ok(clicked >= 8, `only ${clicked} dots were in view to click`); + assert.deepEqual(misses, []); + } finally { + await browser.close(); + } +}); diff --git a/test/fixtures/aisstream-gibraltar-2026-09-27.json b/test/fixtures/aisstream-gibraltar-2026-09-27.json new file mode 100644 index 0000000..e676937 --- /dev/null +++ b/test/fixtures/aisstream-gibraltar-2026-09-27.json @@ -0,0 +1,610 @@ +{ + "note": "One live 20 s aisstream.io sample over the Strait of Gibraltar (box [[35.6,-6.6],[36.4,-4.8]]), 2026-09-27. Identities pseudonymised before commit: MMSI → 99000000n, names → TEST VESSEL n, call sign/IMO/destination blanked. Positions, types and timestamps are as received.", + "messages": [ + { + "Message": { + "CompressionEnabled": true + }, + "MessageType": "SubscriptionConfirmation" + }, + { + "MetaData": { + "MMSI": 990000001, + "MMSI_String": "990000001", + "ShipName": "TEST VESSEL 1", + "latitude": 35.9981, + "longitude": -5.4854, + "time_utc": "2026-09-27 08:42:39.511916917 +0000 UTC" + }, + "MessageType": "PositionReport", + "Message": { + "PositionReport": { + "MessageID": 1, + "RepeatIndicator": 0, + "UserID": 990000001, + "Valid": true, + "NavigationalStatus": 0, + "RateOfTurn": 0, + "Sog": 11.1, + "PositionAccuracy": false, + "Longitude": -5.4854, + "Latitude": 35.9981, + "Cog": 254, + "TrueHeading": 254, + "Timestamp": 36, + "SpecialManoeuvreIndicator": 0, + "Spare": 0, + "Raim": false, + "CommunicationState": 66999 + } + } + }, + { + "MetaData": { + "MMSI": 990000002, + "MMSI_String": "990000002", + "ShipName": "TEST VESSEL 2", + "latitude": 35.90895, + "longitude": -5.70582, + "time_utc": "2026-09-27 08:42:41.963104249 +0000 UTC" + }, + "MessageType": "ShipStaticData", + "Message": { + "ShipStaticData": { + "AisVersion": 1, + "CallSign": "TEST", + "Destination": "REDACTED", + "Dimension": { + "A": 144, + "B": 35, + "C": 17, + "D": 9 + }, + "Dte": false, + "Eta": { + "Day": 0, + "Hour": 0, + "Minute": 0, + "Month": 0 + }, + "FixType": 0, + "ImoNumber": 0, + "MaximumStaticDraught": 11.1, + "MessageID": 5, + "Name": "TEST VESSEL 2", + "RepeatIndicator": 0, + "Spare": false, + "Type": 80, + "UserID": 990000002, + "Valid": true + } + } + }, + { + "MetaData": { + "MMSI": 990000003, + "MMSI_String": "990000003", + "ShipName": "TEST VESSEL 3", + "latitude": 36.12985, + "longitude": -5.37125, + "time_utc": "2026-09-27 08:42:42.264468736 +0000 UTC" + }, + "MessageType": "StandardClassBPositionReport", + "Message": { + "StandardClassBPositionReport": { + "AssignedMode": false, + "ClassBBand": true, + "ClassBDisplay": true, + "ClassBDsc": true, + "ClassBMsg22": true, + "ClassBUnit": false, + "Cog": 104.8, + "CommunicationState": 26769, + "CommunicationStateIsItdma": true, + "Latitude": 36.129850000000005, + "Longitude": -5.371251666666667, + "MessageID": 18, + "PositionAccuracy": true, + "Raim": true, + "RepeatIndicator": 0, + "Sog": 3.6, + "Spare1": 0, + "Spare2": 0, + "Timestamp": 41, + "TrueHeading": 511, + "UserID": 990000003, + "Valid": true + } + } + }, + { + "MetaData": { + "MMSI": 990000004, + "MMSI_String": "990000004", + "ShipName": "TEST VESSEL 4", + "latitude": 35.89423, + "longitude": -5.49254, + "time_utc": "2026-09-27 08:42:42.429440668 +0000 UTC" + }, + "MessageType": "PositionReport", + "Message": { + "PositionReport": { + "MessageID": 1, + "RepeatIndicator": 0, + "UserID": 990000004, + "Valid": true, + "NavigationalStatus": 0, + "RateOfTurn": 0, + "Sog": 0, + "PositionAccuracy": false, + "Longitude": -5.492538333333333, + "Latitude": 35.89423, + "Cog": 67.8, + "TrueHeading": 45, + "Timestamp": 40, + "SpecialManoeuvreIndicator": 0, + "Spare": 0, + "Raim": false, + "CommunicationState": 34354 + } + } + }, + { + "MetaData": { + "MMSI": 990000005, + "MMSI_String": "990000005", + "ShipName": "TEST VESSEL 5", + "latitude": 35.793, + "longitude": -5.80677, + "time_utc": "2026-09-27 08:42:42.961808354 +0000 UTC" + }, + "MessageType": "PositionReport", + "Message": { + "PositionReport": { + "MessageID": 3, + "RepeatIndicator": 0, + "UserID": 990000005, + "Valid": true, + "NavigationalStatus": 7, + "RateOfTurn": 127, + "Sog": 0, + "PositionAccuracy": false, + "Longitude": -5.806768333333333, + "Latitude": 35.793, + "Cog": 0, + "TrueHeading": 0, + "Timestamp": 60, + "SpecialManoeuvreIndicator": 0, + "Spare": 0, + "Raim": false, + "CommunicationState": 0 + } + } + }, + { + "MetaData": { + "MMSI": 990000006, + "MMSI_String": "990000006", + "ShipName": "TEST VESSEL 6", + "latitude": 35.79108, + "longitude": -5.80203, + "time_utc": "2026-09-27 08:42:43.890090829 +0000 UTC" + }, + "MessageType": "PositionReport", + "Message": { + "PositionReport": { + "MessageID": 3, + "RepeatIndicator": 0, + "UserID": 990000006, + "Valid": true, + "NavigationalStatus": 0, + "RateOfTurn": 0, + "Sog": 0, + "PositionAccuracy": false, + "Longitude": -5.802026666666666, + "Latitude": 35.79108, + "Cog": 199, + "TrueHeading": 84, + "Timestamp": 60, + "SpecialManoeuvreIndicator": 0, + "Spare": 0, + "Raim": false, + "CommunicationState": 0 + } + } + }, + { + "MetaData": { + "MMSI": 990000007, + "MMSI_String": "990000007", + "ShipName": "TEST VESSEL 7", + "latitude": 36.14948, + "longitude": -5.42385, + "time_utc": "2026-09-27 08:42:44.263979486 +0000 UTC" + }, + "MessageType": "PositionReport", + "Message": { + "PositionReport": { + "MessageID": 1, + "RepeatIndicator": 0, + "UserID": 990000007, + "Valid": true, + "NavigationalStatus": 0, + "RateOfTurn": 0, + "Sog": 10.1, + "PositionAccuracy": false, + "Longitude": -5.423853333333333, + "Latitude": 36.149478333333334, + "Cog": 287.4, + "TrueHeading": 285, + "Timestamp": 42, + "SpecialManoeuvreIndicator": 0, + "Spare": 0, + "Raim": false, + "CommunicationState": 0 + } + } + }, + { + "MetaData": { + "MMSI": 990000008, + "MMSI_String": "990000008", + "ShipName": "TEST VESSEL 8", + "latitude": 36.12772, + "longitude": -5.44057, + "time_utc": "2026-09-27 08:42:45.513105047 +0000 UTC" + }, + "MessageType": "PositionReport", + "Message": { + "PositionReport": { + "MessageID": 1, + "RepeatIndicator": 0, + "UserID": 990000008, + "Valid": true, + "NavigationalStatus": 3, + "RateOfTurn": 0, + "Sog": 0, + "PositionAccuracy": false, + "Longitude": -5.440566666666667, + "Latitude": 36.12772, + "Cog": 65, + "TrueHeading": 162, + "Timestamp": 42, + "SpecialManoeuvreIndicator": 0, + "Spare": 0, + "Raim": false, + "CommunicationState": 50620 + } + } + }, + { + "MetaData": { + "MMSI": 990000009, + "MMSI_String": "990000009", + "ShipName": "TEST VESSEL 9", + "latitude": 35.89451, + "longitude": -5.30603, + "time_utc": "2026-09-27 08:42:46.608926495 +0000 UTC" + }, + "MessageType": "PositionReport", + "Message": { + "PositionReport": { + "MessageID": 1, + "RepeatIndicator": 0, + "UserID": 990000009, + "Valid": true, + "NavigationalStatus": 0, + "RateOfTurn": -127, + "Sog": 0.5, + "PositionAccuracy": true, + "Longitude": -5.306030000000001, + "Latitude": 35.894511666666666, + "Cog": 162, + "TrueHeading": 210, + "Timestamp": 36, + "SpecialManoeuvreIndicator": 0, + "Spare": 0, + "Raim": false, + "CommunicationState": 100046 + } + } + }, + { + "MetaData": { + "MMSI": 990000010, + "MMSI_String": "990000010", + "ShipName": "TEST VESSEL 10", + "latitude": 35.91009, + "longitude": -5.51743, + "time_utc": "2026-09-27 08:42:47.099476413 +0000 UTC" + }, + "MessageType": "PositionReport", + "Message": { + "PositionReport": { + "MessageID": 3, + "RepeatIndicator": 0, + "UserID": 990000010, + "Valid": true, + "NavigationalStatus": 0, + "RateOfTurn": 127, + "Sog": 0.7, + "PositionAccuracy": false, + "Longitude": -5.51743, + "Latitude": 35.910085, + "Cog": 13.1, + "TrueHeading": 1, + "Timestamp": 46, + "SpecialManoeuvreIndicator": 0, + "Spare": 0, + "Raim": false, + "CommunicationState": 4048 + } + } + }, + { + "MetaData": { + "MMSI": 990000011, + "MMSI_String": "990000011", + "ShipName": "TEST VESSEL 11", + "latitude": 35.8923, + "longitude": -5.50287, + "time_utc": "2026-09-27 08:42:49.798311876 +0000 UTC" + }, + "MessageType": "PositionReport", + "Message": { + "PositionReport": { + "MessageID": 1, + "RepeatIndicator": 0, + "UserID": 990000011, + "Valid": true, + "NavigationalStatus": 0, + "RateOfTurn": 0, + "Sog": 0, + "PositionAccuracy": false, + "Longitude": -5.502871666666667, + "Latitude": 35.89229666666667, + "Cog": 272.6, + "TrueHeading": 38, + "Timestamp": 48, + "SpecialManoeuvreIndicator": 0, + "Spare": 0, + "Raim": false, + "CommunicationState": 20648 + } + } + }, + { + "MetaData": { + "MMSI": 990000012, + "MMSI_String": "990000012", + "ShipName": "TEST VESSEL 12", + "latitude": 36.12754, + "longitude": -5.43715, + "time_utc": "2026-09-27 08:42:51.516935728 +0000 UTC" + }, + "MessageType": "PositionReport", + "Message": { + "PositionReport": { + "MessageID": 3, + "RepeatIndicator": 0, + "UserID": 990000012, + "Valid": true, + "NavigationalStatus": 5, + "RateOfTurn": 0, + "Sog": 0, + "PositionAccuracy": false, + "Longitude": -5.437148333333334, + "Latitude": 36.127541666666666, + "Cog": 223, + "TrueHeading": 264, + "Timestamp": 50, + "SpecialManoeuvreIndicator": 0, + "Spare": 0, + "Raim": false, + "CommunicationState": 85610 + } + } + }, + { + "MetaData": { + "MMSI": 990000013, + "MMSI_String": "990000013", + "ShipName": "TEST VESSEL 13", + "latitude": 36.14713, + "longitude": -5.36642, + "time_utc": "2026-09-27 08:42:52.454844316 +0000 UTC" + }, + "MessageType": "PositionReport", + "Message": { + "PositionReport": { + "MessageID": 3, + "RepeatIndicator": 0, + "UserID": 990000013, + "Valid": true, + "NavigationalStatus": 0, + "RateOfTurn": 0, + "Sog": 0, + "PositionAccuracy": false, + "Longitude": -5.3664233333333335, + "Latitude": 36.147131666666674, + "Cog": 235, + "TrueHeading": 179, + "Timestamp": 60, + "SpecialManoeuvreIndicator": 0, + "Spare": 0, + "Raim": false, + "CommunicationState": 0 + } + } + }, + { + "MetaData": { + "MMSI": 990000014, + "MMSI_String": "990000014", + "ShipName": "TEST VESSEL 14", + "latitude": 36.12127, + "longitude": -5.41787, + "time_utc": "2026-09-27 08:42:53.018247148 +0000 UTC" + }, + "MessageType": "ShipStaticData", + "Message": { + "ShipStaticData": { + "AisVersion": 0, + "CallSign": "TEST", + "Destination": "REDACTED", + "Dimension": { + "A": 130, + "B": 42, + "C": 18, + "D": 9 + }, + "Dte": false, + "Eta": { + "Day": 24, + "Hour": 15, + "Minute": 0, + "Month": 9 + }, + "FixType": 1, + "ImoNumber": 0, + "MaximumStaticDraught": 6.8, + "MessageID": 5, + "Name": "TEST VESSEL 14", + "RepeatIndicator": 0, + "Spare": false, + "Type": 73, + "UserID": 990000014, + "Valid": true + } + } + }, + { + "MetaData": { + "MMSI": 990000015, + "MMSI_String": "990000015", + "ShipName": "TEST VESSEL 15", + "latitude": 35.89802, + "longitude": -5.49024, + "time_utc": "2026-09-27 08:42:53.245780149 +0000 UTC" + }, + "MessageType": "PositionReport", + "Message": { + "PositionReport": { + "MessageID": 3, + "RepeatIndicator": 0, + "UserID": 990000015, + "Valid": true, + "NavigationalStatus": 15, + "RateOfTurn": -127, + "Sog": 0, + "PositionAccuracy": true, + "Longitude": -5.490241666666666, + "Latitude": 35.898019999999995, + "Cog": 115.5, + "TrueHeading": 254, + "Timestamp": 52, + "SpecialManoeuvreIndicator": 0, + "Spare": 0, + "Raim": false, + "CommunicationState": 3616 + } + } + }, + { + "MetaData": { + "MMSI": 990000016, + "MMSI_String": "990000016", + "ShipName": "TEST VESSEL 16", + "latitude": 35.90646, + "longitude": -5.58038, + "time_utc": "2026-09-27 08:42:54.680150662 +0000 UTC" + }, + "MessageType": "PositionReport", + "Message": { + "PositionReport": { + "MessageID": 3, + "RepeatIndicator": 0, + "UserID": 990000016, + "Valid": true, + "NavigationalStatus": 0, + "RateOfTurn": 0, + "Sog": 4.6, + "PositionAccuracy": false, + "Longitude": -5.580383333333333, + "Latitude": 35.90645666666667, + "Cog": 73, + "TrueHeading": 71, + "Timestamp": 60, + "SpecialManoeuvreIndicator": 0, + "Spare": 0, + "Raim": false, + "CommunicationState": 0 + } + } + }, + { + "MetaData": { + "MMSI": 990000017, + "MMSI_String": "990000017", + "ShipName": "TEST VESSEL 17", + "latitude": 36.1012, + "longitude": -5.40742, + "time_utc": "2026-09-27 08:42:58.51407661 +0000 UTC" + }, + "MessageType": "PositionReport", + "Message": { + "PositionReport": { + "MessageID": 3, + "RepeatIndicator": 0, + "UserID": 990000017, + "Valid": true, + "NavigationalStatus": 5, + "RateOfTurn": 0, + "Sog": 0, + "PositionAccuracy": true, + "Longitude": -5.407415, + "Latitude": 36.10119666666667, + "Cog": 56, + "TrueHeading": 125, + "Timestamp": 57, + "SpecialManoeuvreIndicator": 0, + "Spare": 0, + "Raim": false, + "CommunicationState": 83498 + } + } + }, + { + "MetaData": { + "MMSI": 990000018, + "MMSI_String": "990000018", + "ShipName": "TEST VESSEL 18", + "latitude": 36.00163, + "longitude": -5.41954, + "time_utc": "2026-09-27 08:42:59.058766285 +0000 UTC" + }, + "MessageType": "PositionReport", + "Message": { + "PositionReport": { + "MessageID": 1, + "RepeatIndicator": 0, + "UserID": 990000018, + "Valid": true, + "NavigationalStatus": 0, + "RateOfTurn": 0, + "Sog": 10.1, + "PositionAccuracy": true, + "Longitude": -5.419535, + "Latitude": 36.00162833333333, + "Cog": 254.8, + "TrueHeading": 256, + "Timestamp": 58, + "SpecialManoeuvreIndicator": 0, + "Spare": 0, + "Raim": false, + "CommunicationState": 2269 + } + } + } + ] +} \ No newline at end of file diff --git a/test/fixtures/eonet-severe-storms-2026-09-27.json b/test/fixtures/eonet-severe-storms-2026-09-27.json new file mode 100644 index 0000000..c3b248e --- /dev/null +++ b/test/fixtures/eonet-severe-storms-2026-09-27.json @@ -0,0 +1,1281 @@ +{ + "title": "EONET Events", + "description": "Natural events from EONET.", + "link": "https://eonet.gsfc.nasa.gov/api/v3/events", + "events": [ + { + "id": "EONET_24811", + "title": "Tropical Storm Gonzalo", + "description": null, + "link": "https://eonet.gsfc.nasa.gov/api/v3/events/EONET_24811", + "closed": null, + "categories": [ + { + "id": "severeStorms", + "title": "Severe Storms" + } + + ], + "sources": [ + { + "id": "NOAA_NHC", + "url": "https://www.nhc.noaa.gov/archive/2026/GONZALO.shtml" + } + + + ], + "geometry": [ + { + "magnitudeValue": 40.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T03:00:00Z", + "type": "Point", + "coordinates": [ -22.1, 13.2 ] + }, + + { + "magnitudeValue": 40.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T09:00:00Z", + "type": "Point", + "coordinates": [ -22.4, 14.2 ] + } + + + ] + }, + + { + "id": "EONET_24786", + "title": "Hurricane Nolo", + "description": null, + "link": "https://eonet.gsfc.nasa.gov/api/v3/events/EONET_24786", + "closed": null, + "categories": [ + { + "id": "severeStorms", + "title": "Severe Storms" + } + + ], + "sources": [ + { + "id": "JTWC", + "url": "https://www.metoc.navy.mil/jtwc/products/ep1526.tcw" + } + + + ], + "geometry": [ + { + "magnitudeValue": 40.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T00:00:00Z", + "type": "Point", + "coordinates": [ -155.8, 14.6 ] + }, + + { + "magnitudeValue": 40.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T06:00:00Z", + "type": "Point", + "coordinates": [ -156, 14.8 ] + }, + + { + "magnitudeValue": 50.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T12:00:00Z", + "type": "Point", + "coordinates": [ -156.2, 14.6 ] + }, + + { + "magnitudeValue": 55.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T18:00:00Z", + "type": "Point", + "coordinates": [ -156.2, 14.7 ] + }, + + { + "magnitudeValue": 60.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T00:00:00Z", + "type": "Point", + "coordinates": [ -156, 14.9 ] + }, + + { + "magnitudeValue": 70.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T06:00:00Z", + "type": "Point", + "coordinates": [ -155.8, 15.2 ] + }, + + { + "magnitudeValue": 75.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T12:00:00Z", + "type": "Point", + "coordinates": [ -155.6, 15.8 ] + }, + + { + "magnitudeValue": 90.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T18:00:00Z", + "type": "Point", + "coordinates": [ -155.4, 16.3 ] + }, + + { + "magnitudeValue": 90.00, + "magnitudeUnit": "kts", + "date": "2026-09-26T00:00:00Z", + "type": "Point", + "coordinates": [ -155.4, 16.7 ] + }, + + { + "magnitudeValue": 90.00, + "magnitudeUnit": "kts", + "date": "2026-09-26T06:00:00Z", + "type": "Point", + "coordinates": [ -155.2, 16.9 ] + }, + + { + "magnitudeValue": 90.00, + "magnitudeUnit": "kts", + "date": "2026-09-26T12:00:00Z", + "type": "Point", + "coordinates": [ -155.3, 16.9 ] + }, + + { + "magnitudeValue": 85.00, + "magnitudeUnit": "kts", + "date": "2026-09-26T18:00:00Z", + "type": "Point", + "coordinates": [ -155.7, 16.8 ] + }, + + { + "magnitudeValue": 80.00, + "magnitudeUnit": "kts", + "date": "2026-09-27T00:00:00Z", + "type": "Point", + "coordinates": [ -156.1, 16.7 ] + } + + + ] + }, + + { + "id": "EONET_24787", + "title": "Typhoon Surigae", + "description": null, + "link": "https://eonet.gsfc.nasa.gov/api/v3/events/EONET_24787", + "closed": null, + "categories": [ + { + "id": "severeStorms", + "title": "Severe Storms" + } + + ], + "sources": [ + { + "id": "JTWC", + "url": "https://www.metoc.navy.mil/jtwc/products/wp2526.tcw" + } + + + ], + "geometry": [ + { + "magnitudeValue": 35.00, + "magnitudeUnit": "kts", + "date": "2026-09-23T18:00:00Z", + "type": "Point", + "coordinates": [ 135.8, 17.3 ] + }, + + { + "magnitudeValue": 35.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T00:00:00Z", + "type": "Point", + "coordinates": [ 134.4, 18.1 ] + }, + + { + "magnitudeValue": 45.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T06:00:00Z", + "type": "Point", + "coordinates": [ 133.5, 18.4 ] + }, + + { + "magnitudeValue": 40.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T12:00:00Z", + "type": "Point", + "coordinates": [ 132.5, 18.6 ] + }, + + { + "magnitudeValue": 35.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T18:00:00Z", + "type": "Point", + "coordinates": [ 131.7, 19.3 ] + }, + + { + "magnitudeValue": 40.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T00:00:00Z", + "type": "Point", + "coordinates": [ 130.7, 19.9 ] + }, + + { + "magnitudeValue": 45.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T06:00:00Z", + "type": "Point", + "coordinates": [ 129.3, 20.7 ] + }, + + { + "magnitudeValue": 50.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T12:00:00Z", + "type": "Point", + "coordinates": [ 128.2, 21.4 ] + }, + + { + "magnitudeValue": 55.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T18:00:00Z", + "type": "Point", + "coordinates": [ 127.8, 21.9 ] + }, + + { + "magnitudeValue": 60.00, + "magnitudeUnit": "kts", + "date": "2026-09-26T00:00:00Z", + "type": "Point", + "coordinates": [ 127, 22.4 ] + }, + + { + "magnitudeValue": 70.00, + "magnitudeUnit": "kts", + "date": "2026-09-26T06:00:00Z", + "type": "Point", + "coordinates": [ 126.8, 22.9 ] + }, + + { + "magnitudeValue": 70.00, + "magnitudeUnit": "kts", + "date": "2026-09-26T12:00:00Z", + "type": "Point", + "coordinates": [ 126.9, 23.3 ] + }, + + { + "magnitudeValue": 75.00, + "magnitudeUnit": "kts", + "date": "2026-09-26T18:00:00Z", + "type": "Point", + "coordinates": [ 127.2, 24 ] + }, + + { + "magnitudeValue": 90.00, + "magnitudeUnit": "kts", + "date": "2026-09-27T00:00:00Z", + "type": "Point", + "coordinates": [ 127.6, 24.6 ] + } + + + ] + }, + + { + "id": "EONET_24785", + "title": "Tropical Cyclone 01B", + "description": null, + "link": "https://eonet.gsfc.nasa.gov/api/v3/events/EONET_24785", + "closed": null, + "categories": [ + { + "id": "severeStorms", + "title": "Severe Storms" + } + + ], + "sources": [ + { + "id": "JTWC", + "url": "https://www.metoc.navy.mil/jtwc/products/io0126.tcw" + } + + + ], + "geometry": [ + { + "magnitudeValue": 35.00, + "magnitudeUnit": "kts", + "date": "2026-09-22T06:00:00Z", + "type": "Point", + "coordinates": [ 85, 17.5 ] + }, + + { + "magnitudeValue": 30.00, + "magnitudeUnit": "kts", + "date": "2026-09-22T12:00:00Z", + "type": "Point", + "coordinates": [ 85.2, 17.5 ] + }, + + { + "magnitudeValue": 35.00, + "magnitudeUnit": "kts", + "date": "2026-09-22T18:00:00Z", + "type": "Point", + "coordinates": [ 85, 17.5 ] + }, + + { + "magnitudeValue": 40.00, + "magnitudeUnit": "kts", + "date": "2026-09-23T00:00:00Z", + "type": "Point", + "coordinates": [ 84.8, 17.7 ] + }, + + { + "magnitudeValue": 45.00, + "magnitudeUnit": "kts", + "date": "2026-09-23T06:00:00Z", + "type": "Point", + "coordinates": [ 84.6, 17.8 ] + }, + + { + "magnitudeValue": 45.00, + "magnitudeUnit": "kts", + "date": "2026-09-23T12:00:00Z", + "type": "Point", + "coordinates": [ 84, 17.8 ] + }, + + { + "magnitudeValue": 40.00, + "magnitudeUnit": "kts", + "date": "2026-09-23T18:00:00Z", + "type": "Point", + "coordinates": [ 83.7, 17.8 ] + }, + + { + "magnitudeValue": 35.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T00:00:00Z", + "type": "Point", + "coordinates": [ 83.7, 18.1 ] + } + + + ] + }, + + { + "id": "EONET_24721", + "title": "Hurricane Polo", + "description": null, + "link": "https://eonet.gsfc.nasa.gov/api/v3/events/EONET_24721", + "closed": null, + "categories": [ + { + "id": "severeStorms", + "title": "Severe Storms" + } + + ], + "sources": [ + { + "id": "JTWC", + "url": "https://www.metoc.navy.mil/jtwc/products/ep1726.tcw" + }, + + { + "id": "NOAA_NHC", + "url": "https://www.nhc.noaa.gov/archive/2026/POLO.shtml" + } + + + ], + "geometry": [ + { + "magnitudeValue": 35.00, + "magnitudeUnit": "kts", + "date": "2026-09-21T00:00:00Z", + "type": "Point", + "coordinates": [ -104.8, 15.1 ] + }, + + { + "magnitudeValue": 40.00, + "magnitudeUnit": "kts", + "date": "2026-09-21T06:00:00Z", + "type": "Point", + "coordinates": [ -104.1, 15.5 ] + }, + + { + "magnitudeValue": 55.00, + "magnitudeUnit": "kts", + "date": "2026-09-21T12:00:00Z", + "type": "Point", + "coordinates": [ -103.6, 15.4 ] + }, + + { + "magnitudeValue": 70.00, + "magnitudeUnit": "kts", + "date": "2026-09-21T18:00:00Z", + "type": "Point", + "coordinates": [ -103, 15.2 ] + }, + + { + "magnitudeValue": 90.00, + "magnitudeUnit": "kts", + "date": "2026-09-22T00:00:00Z", + "type": "Point", + "coordinates": [ -102.5, 15.1 ] + }, + + { + "magnitudeValue": 120.00, + "magnitudeUnit": "kts", + "date": "2026-09-22T06:00:00Z", + "type": "Point", + "coordinates": [ -102, 14.7 ] + }, + + { + "magnitudeValue": 140.00, + "magnitudeUnit": "kts", + "date": "2026-09-22T12:00:00Z", + "type": "Point", + "coordinates": [ -101.6, 14.7 ] + }, + + { + "magnitudeValue": 155.00, + "magnitudeUnit": "kts", + "date": "2026-09-22T18:00:00Z", + "type": "Point", + "coordinates": [ -101.5, 14.6 ] + }, + + { + "magnitudeValue": 145.00, + "magnitudeUnit": "kts", + "date": "2026-09-23T00:00:00Z", + "type": "Point", + "coordinates": [ -101.4, 14.6 ] + }, + + { + "magnitudeValue": 140.00, + "magnitudeUnit": "kts", + "date": "2026-09-23T06:00:00Z", + "type": "Point", + "coordinates": [ -101.3, 14.8 ] + }, + + { + "magnitudeValue": 130.00, + "magnitudeUnit": "kts", + "date": "2026-09-23T12:00:00Z", + "type": "Point", + "coordinates": [ -101.5, 15.2 ] + }, + + { + "magnitudeValue": 125.00, + "magnitudeUnit": "kts", + "date": "2026-09-23T18:00:00Z", + "type": "Point", + "coordinates": [ -102.1, 15.5 ] + }, + + { + "magnitudeValue": 140.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T00:00:00Z", + "type": "Point", + "coordinates": [ -102.3, 15.8 ] + }, + + { + "magnitudeValue": 140.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T06:00:00Z", + "type": "Point", + "coordinates": [ -103, 16.4 ] + }, + + { + "magnitudeValue": 135.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T12:00:00Z", + "type": "Point", + "coordinates": [ -103.9, 16.7 ] + }, + + { + "magnitudeValue": 130.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T18:00:00Z", + "type": "Point", + "coordinates": [ -104.9, 16.9 ] + }, + + { + "magnitudeValue": 130.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T00:00:00Z", + "type": "Point", + "coordinates": [ -106.1, 17.1 ] + }, + + { + "magnitudeValue": 135.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T06:00:00Z", + "type": "Point", + "coordinates": [ -107, 17.1 ] + }, + + { + "magnitudeValue": 155.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T12:00:00Z", + "type": "Point", + "coordinates": [ -108, 17.1 ] + }, + + { + "magnitudeValue": 150.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T18:00:00Z", + "type": "Point", + "coordinates": [ -108.8, 17.1 ] + }, + + { + "magnitudeValue": 150.00, + "magnitudeUnit": "kts", + "date": "2026-09-26T00:00:00Z", + "type": "Point", + "coordinates": [ -109.7, 17.2 ] + }, + + { + "magnitudeValue": 150.00, + "magnitudeUnit": "kts", + "date": "2026-09-26T06:00:00Z", + "type": "Point", + "coordinates": [ -110.5, 17.5 ] + }, + + { + "magnitudeValue": 140.00, + "magnitudeUnit": "kts", + "date": "2026-09-26T12:00:00Z", + "type": "Point", + "coordinates": [ -111.4, 17.7 ] + }, + + { + "magnitudeValue": 125.00, + "magnitudeUnit": "kts", + "date": "2026-09-26T18:00:00Z", + "type": "Point", + "coordinates": [ -112.2, 18.3 ] + }, + + { + "magnitudeValue": 110.00, + "magnitudeUnit": "kts", + "date": "2026-09-27T00:00:00Z", + "type": "Point", + "coordinates": [ -112.9, 19 ] + } + + + ] + }, + + { + "id": "EONET_24722", + "title": "Tropical Storm Fay", + "description": null, + "link": "https://eonet.gsfc.nasa.gov/api/v3/events/EONET_24722", + "closed": null, + "categories": [ + { + "id": "severeStorms", + "title": "Severe Storms" + } + + ], + "sources": [ + { + "id": "NOAA_NHC", + "url": "https://www.nhc.noaa.gov/archive/2026/FAY.shtml" + } + + + ], + "geometry": [ + { + "magnitudeValue": 40.00, + "magnitudeUnit": "kts", + "date": "2026-09-20T09:00:00Z", + "type": "Point", + "coordinates": [ -33.1, 33.7 ] + }, + + { + "magnitudeValue": 50.00, + "magnitudeUnit": "kts", + "date": "2026-09-20T15:00:00Z", + "type": "Point", + "coordinates": [ -33, 34.1 ] + }, + + { + "magnitudeValue": 55.00, + "magnitudeUnit": "kts", + "date": "2026-09-20T21:00:00Z", + "type": "Point", + "coordinates": [ -32.7, 34.4 ] + }, + + { + "magnitudeValue": 60.00, + "magnitudeUnit": "kts", + "date": "2026-09-21T03:00:00Z", + "type": "Point", + "coordinates": [ -31.9, 34.1 ] + }, + + { + "magnitudeValue": 55.00, + "magnitudeUnit": "kts", + "date": "2026-09-21T09:00:00Z", + "type": "Point", + "coordinates": [ -32.1, 33.8 ] + }, + + { + "magnitudeValue": 45.00, + "magnitudeUnit": "kts", + "date": "2026-09-21T15:00:00Z", + "type": "Point", + "coordinates": [ -32, 33.3 ] + }, + + { + "magnitudeValue": 40.00, + "magnitudeUnit": "kts", + "date": "2026-09-21T21:00:00Z", + "type": "Point", + "coordinates": [ -32.2, 33.1 ] + }, + + { + "magnitudeValue": 35.00, + "magnitudeUnit": "kts", + "date": "2026-09-22T03:00:00Z", + "type": "Point", + "coordinates": [ -33.1, 32.3 ] + }, + + { + "magnitudeValue": 35.00, + "magnitudeUnit": "kts", + "date": "2026-09-22T09:00:00Z", + "type": "Point", + "coordinates": [ -33.7, 31.8 ] + }, + + { + "magnitudeValue": 30.00, + "magnitudeUnit": "kts", + "date": "2026-09-22T15:00:00Z", + "type": "Point", + "coordinates": [ -34.6, 31.1 ] + }, + + { + "magnitudeValue": 30.00, + "magnitudeUnit": "kts", + "date": "2026-09-22T21:00:00Z", + "type": "Point", + "coordinates": [ -35.3, 30.8 ] + }, + + { + "magnitudeValue": 30.00, + "magnitudeUnit": "kts", + "date": "2026-09-23T21:00:00Z", + "type": "Point", + "coordinates": [ -39.2, 30.1 ] + }, + + { + "magnitudeValue": 35.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T03:00:00Z", + "type": "Point", + "coordinates": [ -40, 29.8 ] + }, + + { + "magnitudeValue": 35.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T09:00:00Z", + "type": "Point", + "coordinates": [ -40.5, 29.8 ] + }, + + { + "magnitudeValue": 45.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T15:00:00Z", + "type": "Point", + "coordinates": [ -41.2, 29.8 ] + }, + + { + "magnitudeValue": 45.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T21:00:00Z", + "type": "Point", + "coordinates": [ -41.8, 29.8 ] + }, + + { + "magnitudeValue": 45.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T03:00:00Z", + "type": "Point", + "coordinates": [ -42.3, 29.8 ] + }, + + { + "magnitudeValue": 45.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T09:00:00Z", + "type": "Point", + "coordinates": [ -42.8, 29.8 ] + } + + + ] + }, + + { + "id": "EONET_24720", + "title": "Hurricane Odalys", + "description": null, + "link": "https://eonet.gsfc.nasa.gov/api/v3/events/EONET_24720", + "closed": null, + "categories": [ + { + "id": "severeStorms", + "title": "Severe Storms" + } + + ], + "sources": [ + { + "id": "JTWC", + "url": "https://www.metoc.navy.mil/jtwc/products/ep1626.tcw" + }, + + { + "id": "NOAA_NHC", + "url": "https://www.nhc.noaa.gov/archive/2026/ODALYS.shtml" + } + + + ], + "geometry": [ + { + "magnitudeValue": 35.00, + "magnitudeUnit": "kts", + "date": "2026-09-20T06:00:00Z", + "type": "Point", + "coordinates": [ -124.3, 11.1 ] + }, + + { + "magnitudeValue": 40.00, + "magnitudeUnit": "kts", + "date": "2026-09-20T12:00:00Z", + "type": "Point", + "coordinates": [ -125.2, 11.1 ] + }, + + { + "magnitudeValue": 45.00, + "magnitudeUnit": "kts", + "date": "2026-09-20T18:00:00Z", + "type": "Point", + "coordinates": [ -126.3, 11.6 ] + }, + + { + "magnitudeValue": 45.00, + "magnitudeUnit": "kts", + "date": "2026-09-21T00:00:00Z", + "type": "Point", + "coordinates": [ -127.3, 12.8 ] + }, + + { + "magnitudeValue": 40.00, + "magnitudeUnit": "kts", + "date": "2026-09-21T06:00:00Z", + "type": "Point", + "coordinates": [ -128.3, 13.3 ] + }, + + { + "magnitudeValue": 40.00, + "magnitudeUnit": "kts", + "date": "2026-09-21T12:00:00Z", + "type": "Point", + "coordinates": [ -129, 13.6 ] + }, + + { + "magnitudeValue": 45.00, + "magnitudeUnit": "kts", + "date": "2026-09-21T18:00:00Z", + "type": "Point", + "coordinates": [ -129.7, 13.8 ] + }, + + { + "magnitudeValue": 45.00, + "magnitudeUnit": "kts", + "date": "2026-09-22T00:00:00Z", + "type": "Point", + "coordinates": [ -130.2, 14.1 ] + }, + + { + "magnitudeValue": 50.00, + "magnitudeUnit": "kts", + "date": "2026-09-22T06:00:00Z", + "type": "Point", + "coordinates": [ -130.5, 14.5 ] + }, + + { + "magnitudeValue": 55.00, + "magnitudeUnit": "kts", + "date": "2026-09-22T12:00:00Z", + "type": "Point", + "coordinates": [ -130.7, 14.8 ] + }, + + { + "magnitudeValue": 60.00, + "magnitudeUnit": "kts", + "date": "2026-09-22T18:00:00Z", + "type": "Point", + "coordinates": [ -130.4, 15 ] + }, + + { + "magnitudeValue": 60.00, + "magnitudeUnit": "kts", + "date": "2026-09-23T00:00:00Z", + "type": "Point", + "coordinates": [ -129.4, 15.3 ] + }, + + { + "magnitudeValue": 65.00, + "magnitudeUnit": "kts", + "date": "2026-09-23T06:00:00Z", + "type": "Point", + "coordinates": [ -128.7, 15.8 ] + }, + + { + "magnitudeValue": 65.00, + "magnitudeUnit": "kts", + "date": "2026-09-23T12:00:00Z", + "type": "Point", + "coordinates": [ -128.2, 15.9 ] + }, + + { + "magnitudeValue": 70.00, + "magnitudeUnit": "kts", + "date": "2026-09-23T18:00:00Z", + "type": "Point", + "coordinates": [ -127.5, 15.5 ] + }, + + { + "magnitudeValue": 75.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T00:00:00Z", + "type": "Point", + "coordinates": [ -126.9, 15.6 ] + }, + + { + "magnitudeValue": 75.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T06:00:00Z", + "type": "Point", + "coordinates": [ -126.3, 15.9 ] + }, + + { + "magnitudeValue": 80.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T12:00:00Z", + "type": "Point", + "coordinates": [ -125.8, 16.2 ] + }, + + { + "magnitudeValue": 80.00, + "magnitudeUnit": "kts", + "date": "2026-09-24T18:00:00Z", + "type": "Point", + "coordinates": [ -125.1, 16.6 ] + }, + + { + "magnitudeValue": 90.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T00:00:00Z", + "type": "Point", + "coordinates": [ -124.4, 16.9 ] + }, + + { + "magnitudeValue": 100.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T06:00:00Z", + "type": "Point", + "coordinates": [ -124.1, 17.3 ] + }, + + { + "magnitudeValue": 115.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T12:00:00Z", + "type": "Point", + "coordinates": [ -123.8, 17.7 ] + }, + + { + "magnitudeValue": 115.00, + "magnitudeUnit": "kts", + "date": "2026-09-25T18:00:00Z", + "type": "Point", + "coordinates": [ -123.6, 18 ] + }, + + { + "magnitudeValue": 110.00, + "magnitudeUnit": "kts", + "date": "2026-09-26T00:00:00Z", + "type": "Point", + "coordinates": [ -123.7, 18.6 ] + }, + + { + "magnitudeValue": 105.00, + "magnitudeUnit": "kts", + "date": "2026-09-26T06:00:00Z", + "type": "Point", + "coordinates": [ -123.8, 18.8 ] + }, + + { + "magnitudeValue": 90.00, + "magnitudeUnit": "kts", + "date": "2026-09-26T12:00:00Z", + "type": "Point", + "coordinates": [ -123.7, 19.5 ] + }, + + { + "magnitudeValue": 80.00, + "magnitudeUnit": "kts", + "date": "2026-09-26T18:00:00Z", + "type": "Point", + "coordinates": [ -123.6, 20.2 ] + }, + + { + "magnitudeValue": 75.00, + "magnitudeUnit": "kts", + "date": "2026-09-27T00:00:00Z", + "type": "Point", + "coordinates": [ -123.6, 20.8 ] + } + + + ] + }, + + { + "id": "EONET_24317", + "title": "Typhoon Dujuan", + "description": null, + "link": "https://eonet.gsfc.nasa.gov/api/v3/events/EONET_24317", + "closed": null, + "categories": [ + { + "id": "severeStorms", + "title": "Severe Storms" + } + + ], + "sources": [ + { + "id": "JTWC", + "url": "https://www.metoc.navy.mil/jtwc/products/wp2426.tcw" + } + + + ], + "geometry": [ + { + "magnitudeValue": 35.00, + "magnitudeUnit": "kts", + "date": "2026-09-16T12:00:00Z", + "type": "Point", + "coordinates": [ 149.5, 16.5 ] + }, + + { + "magnitudeValue": 40.00, + "magnitudeUnit": "kts", + "date": "2026-09-16T18:00:00Z", + "type": "Point", + "coordinates": [ 149.9, 17.6 ] + }, + + { + "magnitudeValue": 50.00, + "magnitudeUnit": "kts", + "date": "2026-09-17T00:00:00Z", + "type": "Point", + "coordinates": [ 150.4, 19 ] + }, + + { + "magnitudeValue": 50.00, + "magnitudeUnit": "kts", + "date": "2026-09-17T06:00:00Z", + "type": "Point", + "coordinates": [ 150.3, 21.6 ] + }, + + { + "magnitudeValue": 55.00, + "magnitudeUnit": "kts", + "date": "2026-09-17T12:00:00Z", + "type": "Point", + "coordinates": [ 148.6, 22.8 ] + }, + + { + "magnitudeValue": 65.00, + "magnitudeUnit": "kts", + "date": "2026-09-17T18:00:00Z", + "type": "Point", + "coordinates": [ 146, 25.2 ] + }, + + { + "magnitudeValue": 60.00, + "magnitudeUnit": "kts", + "date": "2026-09-18T00:00:00Z", + "type": "Point", + "coordinates": [ 144.5, 25.1 ] + }, + + { + "magnitudeValue": 60.00, + "magnitudeUnit": "kts", + "date": "2026-09-18T06:00:00Z", + "type": "Point", + "coordinates": [ 142.9, 25.9 ] + }, + + { + "magnitudeValue": 60.00, + "magnitudeUnit": "kts", + "date": "2026-09-18T12:00:00Z", + "type": "Point", + "coordinates": [ 141.7, 25.4 ] + }, + + { + "magnitudeValue": 65.00, + "magnitudeUnit": "kts", + "date": "2026-09-18T18:00:00Z", + "type": "Point", + "coordinates": [ 140.7, 26.2 ] + }, + + { + "magnitudeValue": 65.00, + "magnitudeUnit": "kts", + "date": "2026-09-19T00:00:00Z", + "type": "Point", + "coordinates": [ 139.7, 26.2 ] + }, + + { + "magnitudeValue": 65.00, + "magnitudeUnit": "kts", + "date": "2026-09-19T06:00:00Z", + "type": "Point", + "coordinates": [ 139.1, 27 ] + }, + + { + "magnitudeValue": 65.00, + "magnitudeUnit": "kts", + "date": "2026-09-19T12:00:00Z", + "type": "Point", + "coordinates": [ 138.2, 27.8 ] + }, + + { + "magnitudeValue": 65.00, + "magnitudeUnit": "kts", + "date": "2026-09-19T18:00:00Z", + "type": "Point", + "coordinates": [ 137.7, 28.5 ] + }, + + { + "magnitudeValue": 60.00, + "magnitudeUnit": "kts", + "date": "2026-09-20T00:00:00Z", + "type": "Point", + "coordinates": [ 137.5, 28.7 ] + }, + + { + "magnitudeValue": 60.00, + "magnitudeUnit": "kts", + "date": "2026-09-20T06:00:00Z", + "type": "Point", + "coordinates": [ 137.5, 29.8 ] + }, + + { + "magnitudeValue": 60.00, + "magnitudeUnit": "kts", + "date": "2026-09-20T12:00:00Z", + "type": "Point", + "coordinates": [ 137.6, 30.4 ] + }, + + { + "magnitudeValue": 60.00, + "magnitudeUnit": "kts", + "date": "2026-09-20T18:00:00Z", + "type": "Point", + "coordinates": [ 137.9, 31.3 ] + }, + + { + "magnitudeValue": 65.00, + "magnitudeUnit": "kts", + "date": "2026-09-21T00:00:00Z", + "type": "Point", + "coordinates": [ 138.7, 32.4 ] + }, + + { + "magnitudeValue": 70.00, + "magnitudeUnit": "kts", + "date": "2026-09-21T06:00:00Z", + "type": "Point", + "coordinates": [ 139.8, 33.7 ] + }, + + { + "magnitudeValue": 70.00, + "magnitudeUnit": "kts", + "date": "2026-09-21T12:00:00Z", + "type": "Point", + "coordinates": [ 141.8, 34.9 ] + }, + + { + "magnitudeValue": 70.00, + "magnitudeUnit": "kts", + "date": "2026-09-21T18:00:00Z", + "type": "Point", + "coordinates": [ 144.1, 36.9 ] + }, + + { + "magnitudeValue": 65.00, + "magnitudeUnit": "kts", + "date": "2026-09-22T00:00:00Z", + "type": "Point", + "coordinates": [ 147.4, 38.1 ] + }, + + { + "magnitudeValue": 60.00, + "magnitudeUnit": "kts", + "date": "2026-09-22T06:00:00Z", + "type": "Point", + "coordinates": [ 150.2, 39 ] + } + + + ] + } + + ] +} \ No newline at end of file diff --git a/test/fixtures/gdacs-geometry-one-26.json b/test/fixtures/gdacs-geometry-one-26.json new file mode 100644 index 0000000..7d59fd0 --- /dev/null +++ b/test/fixtures/gdacs-geometry-one-26.json @@ -0,0 +1 @@ +{"type": "FeatureCollection", "features": [{"type": "Feature", "bbox": [83.7, 18.1, 83.7, 18.1], "geometry": {"type": "Point", "coordinates": [83.7, 18.1]}, "properties": {"eventtype": "TC", "eventid": 1001326, "episodeid": 6, "eventname": "ONE-26", "glide": "", "name": "Tropical Cyclone ONE-26", "description": "Tropical Cyclone ONE-26", "htmldescription": "Orange Tropical Cyclone ONE-26 in India from: 22 Sep 2026 to: 24 Sep 2026 .", "icon": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "iconoverall": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "url": {"geometry": "https://www.gdacs.org/gdacsapi/api/polygons/getgeometry?eventtype=TC&eventid=1001326&episodeid=6", "report": "https://www.gdacs.org/report.aspx?eventid=1001326&episodeid=6&eventtype=TC", "details": "https://www.gdacs.org/gdacsapi/api/events/geteventdata?eventtype=TC&eventid=1001326"}, "alertlevel": "Orange", "alertscore": 2, "episodealertlevel": "Orange", "episodealertscore": 2.0, "istemporary": "false", "iscurrent": "true", "country": "India", "fromdate": "2026-09-22T18:00:00", "todate": "2026-09-24T00:00:00", "datemodified": "2026-09-27T08:00:13", "iso3": "IND", "source": "JTWC", "sourceid": "", "polygonlabel": "Centroid", "Class": "Point_Centroid", "countryonland": "India", "affectedcountries": [{"iso2": "IN", "iso3": "IND", "countryname": "India"}], "severitydata": {"severity": 83.3328, "severitytext": "Tropical Storm (maximum wind speed of 83 km/h)", "severityunit": "km/h"}}}, {"type": "Feature", "bbox": [82.7, 19.1, 83.1, 20.1], "geometry": {"type": "LineString", "coordinates": [[83.1, 19.1], [82.7, 20.1]]}, "properties": {"eventtype": "TC", "eventid": 1001326, "episodeid": 6, "eventname": "ONE-26", "glide": "", "name": "Tropical Cyclone ONE-26", "description": "Tropical Cyclone ONE-26", "htmldescription": "Orange Tropical Cyclone ONE-26 in India from: 22 Sep 2026 to: 24 Sep 2026 .", "icon": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "iconoverall": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "url": {"geometry": "https://www.gdacs.org/gdacsapi/api/polygons/getgeometry?eventtype=TC&eventid=1001326&episodeid=6", "report": "https://www.gdacs.org/report.aspx?eventid=1001326&episodeid=6&eventtype=TC", "details": "https://www.gdacs.org/gdacsapi/api/events/geteventdata?eventtype=TC&eventid=1001326"}, "alertlevel": "Orange", "alertscore": 2, "episodealertlevel": "Orange", "episodealertscore": 2.0, "istemporary": "false", "iscurrent": "true", "country": "India", "fromdate": "2026-09-22T18:00:00", "todate": "2026-09-24T00:00:00", "datemodified": "2026-09-27T08:00:13", "iso3": "IND", "source": "JTWC", "sourceid": "", "polygondate": "2026-09-24T00:00:00", "polygonlabel": "TD", "countryonland": "India", "affectedcountries": [{"iso2": "IN", "iso3": "IND", "countryname": "India"}], "severitydata": {"severity": 83.3328, "severitytext": "Tropical Storm (maximum wind speed of 83 km/h)", "severityunit": "km/h"}, "forecast": true, "Class": "Line_Line_0", "iconeventlink": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "iconitemlink": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png"}}, {"type": "Feature", "bbox": [83.1, 18.1, 83.7, 19.1], "geometry": {"type": "LineString", "coordinates": [[83.7, 18.1], [83.1, 19.1]]}, "properties": {"eventtype": "TC", "eventid": 1001326, "episodeid": 6, "eventname": "ONE-26", "glide": "", "name": "Tropical Cyclone ONE-26", "description": "Tropical Cyclone ONE-26", "htmldescription": "Orange Tropical Cyclone ONE-26 in India from: 22 Sep 2026 to: 24 Sep 2026 .", "icon": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "iconoverall": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "url": {"geometry": "https://www.gdacs.org/gdacsapi/api/polygons/getgeometry?eventtype=TC&eventid=1001326&episodeid=6", "report": "https://www.gdacs.org/report.aspx?eventid=1001326&episodeid=6&eventtype=TC", "details": "https://www.gdacs.org/gdacsapi/api/events/geteventdata?eventtype=TC&eventid=1001326"}, "alertlevel": "Orange", "alertscore": 2, "episodealertlevel": "Orange", "episodealertscore": 2.0, "istemporary": "false", "iscurrent": "true", "country": "India", "fromdate": "2026-09-22T18:00:00", "todate": "2026-09-24T00:00:00", "datemodified": "2026-09-27T08:00:13", "iso3": "IND", "source": "JTWC", "sourceid": "", "polygondate": "2026-09-24T00:00:00", "polygonlabel": "TD", "countryonland": "India", "affectedcountries": [{"iso2": "IN", "iso3": "IND", "countryname": "India"}], "severitydata": {"severity": 83.3328, "severitytext": "Tropical Storm (maximum wind speed of 83 km/h)", "severityunit": "km/h"}, "forecast": true, "Class": "Line_Line_1", "iconeventlink": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "iconitemlink": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png"}}, {"type": "Feature", "bbox": [83.7, 17.8, 83.7, 18.1], "geometry": {"type": "LineString", "coordinates": [[83.7, 17.8], [83.7, 18.1]]}, "properties": {"eventtype": "TC", "eventid": 1001326, "episodeid": 6, "eventname": "ONE-26", "glide": "", "name": "Tropical Cyclone ONE-26", "description": "Tropical Cyclone ONE-26", "htmldescription": "Orange Tropical Cyclone ONE-26 in India from: 22 Sep 2026 to: 24 Sep 2026 .", "icon": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "iconoverall": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "url": {"geometry": "https://www.gdacs.org/gdacsapi/api/polygons/getgeometry?eventtype=TC&eventid=1001326&episodeid=6", "report": "https://www.gdacs.org/report.aspx?eventid=1001326&episodeid=6&eventtype=TC", "details": "https://www.gdacs.org/gdacsapi/api/events/geteventdata?eventtype=TC&eventid=1001326"}, "alertlevel": "Orange", "alertscore": 2, "episodealertlevel": "Orange", "episodealertscore": 2.0, "istemporary": "false", "iscurrent": "true", "country": "India", "fromdate": "2026-09-22T18:00:00", "todate": "2026-09-24T00:00:00", "datemodified": "2026-09-27T08:00:13", "iso3": "IND", "source": "JTWC", "sourceid": "", "polygondate": "2026-09-24T00:00:00", "polygonlabel": "TS", "countryonland": "India", "affectedcountries": [{"iso2": "IN", "iso3": "IND", "countryname": "India"}], "severitydata": {"severity": 83.3328, "severitytext": "Tropical Storm (maximum wind speed of 83 km/h)", "severityunit": "km/h"}, "forecast": false, "Class": "Line_Line_2", "iconeventlink": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "iconitemlink": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png"}}, {"type": "Feature", "bbox": [83.7, 17.8, 84.0, 17.8], "geometry": {"type": "LineString", "coordinates": [[84.0, 17.8], [83.7, 17.8]]}, "properties": {"eventtype": "TC", "eventid": 1001326, "episodeid": 6, "eventname": "ONE-26", "glide": "", "name": "Tropical Cyclone ONE-26", "description": "Tropical Cyclone ONE-26", "htmldescription": "Orange Tropical Cyclone ONE-26 in India from: 22 Sep 2026 to: 24 Sep 2026 .", "icon": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "iconoverall": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "url": {"geometry": "https://www.gdacs.org/gdacsapi/api/polygons/getgeometry?eventtype=TC&eventid=1001326&episodeid=6", "report": "https://www.gdacs.org/report.aspx?eventid=1001326&episodeid=6&eventtype=TC", "details": "https://www.gdacs.org/gdacsapi/api/events/geteventdata?eventtype=TC&eventid=1001326"}, "alertlevel": "Orange", "alertscore": 2, "episodealertlevel": "Orange", "episodealertscore": 2.0, "istemporary": "false", "iscurrent": "true", "country": "India", "fromdate": "2026-09-22T18:00:00", "todate": "2026-09-24T00:00:00", "datemodified": "2026-09-27T08:00:13", "iso3": "IND", "source": "JTWC", "sourceid": "", "polygondate": "2026-09-24T00:00:00", "polygonlabel": "TS", "countryonland": "India", "affectedcountries": [{"iso2": "IN", "iso3": "IND", "countryname": "India"}], "severitydata": {"severity": 83.3328, "severitytext": "Tropical Storm (maximum wind speed of 83 km/h)", "severityunit": "km/h"}, "forecast": false, "Class": "Line_Line_3", "iconeventlink": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "iconitemlink": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png"}}, {"type": "Feature", "bbox": [84.0, 17.8, 84.6, 17.8], "geometry": {"type": "LineString", "coordinates": [[84.6, 17.8], [84.0, 17.8]]}, "properties": {"eventtype": "TC", "eventid": 1001326, "episodeid": 6, "eventname": "ONE-26", "glide": "", "name": "Tropical Cyclone ONE-26", "description": "Tropical Cyclone ONE-26", "htmldescription": "Orange Tropical Cyclone ONE-26 in India from: 22 Sep 2026 to: 24 Sep 2026 .", "icon": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "iconoverall": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "url": {"geometry": "https://www.gdacs.org/gdacsapi/api/polygons/getgeometry?eventtype=TC&eventid=1001326&episodeid=6", "report": "https://www.gdacs.org/report.aspx?eventid=1001326&episodeid=6&eventtype=TC", "details": "https://www.gdacs.org/gdacsapi/api/events/geteventdata?eventtype=TC&eventid=1001326"}, "alertlevel": "Orange", "alertscore": 2, "episodealertlevel": "Orange", "episodealertscore": 2.0, "istemporary": "false", "iscurrent": "true", "country": "India", "fromdate": "2026-09-22T18:00:00", "todate": "2026-09-24T00:00:00", "datemodified": "2026-09-27T08:00:13", "iso3": "IND", "source": "JTWC", "sourceid": "", "polygondate": "2026-09-24T00:00:00", "polygonlabel": "TS", "countryonland": "India", "affectedcountries": [{"iso2": "IN", "iso3": "IND", "countryname": "India"}], "severitydata": {"severity": 83.3328, "severitytext": "Tropical Storm (maximum wind speed of 83 km/h)", "severityunit": "km/h"}, "forecast": false, "Class": "Line_Line_4", "iconeventlink": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "iconitemlink": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png"}}, {"type": "Feature", "bbox": [84.8, 17.6, 84.9, 17.6], "geometry": {"type": "LineString", "coordinates": [[84.8, 17.6], [84.9, 17.6]]}, "properties": {"eventtype": "TC", "eventid": 1001326, "episodeid": 6, "eventname": "ONE-26", "glide": "", "name": "Tropical Cyclone ONE-26", "description": "Tropical Cyclone ONE-26", "htmldescription": "Orange Tropical Cyclone ONE-26 in India from: 22 Sep 2026 to: 24 Sep 2026 .", "icon": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "iconoverall": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "url": {"geometry": "https://www.gdacs.org/gdacsapi/api/polygons/getgeometry?eventtype=TC&eventid=1001326&episodeid=6", "report": "https://www.gdacs.org/report.aspx?eventid=1001326&episodeid=6&eventtype=TC", "details": "https://www.gdacs.org/gdacsapi/api/events/geteventdata?eventtype=TC&eventid=1001326"}, "alertlevel": "Orange", "alertscore": 2, "episodealertlevel": "Orange", "episodealertscore": 2.0, "istemporary": "false", "iscurrent": "true", "country": "India", "fromdate": "2026-09-22T18:00:00", "todate": "2026-09-24T00:00:00", "datemodified": "2026-09-27T08:00:13", "iso3": "IND", "source": "JTWC", "sourceid": "", "polygondate": "2026-09-24T00:00:00", "polygonlabel": "TS", "countryonland": "India", "affectedcountries": [{"iso2": "IN", "iso3": "IND", "countryname": "India"}], "severitydata": {"severity": 83.3328, "severitytext": "Tropical Storm (maximum wind speed of 83 km/h)", "severityunit": "km/h"}, "forecast": false, "Class": "Line_Line_5", "iconeventlink": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "iconitemlink": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png"}}, {"type": "Feature", "bbox": [84.6, 17.6, 84.9, 17.8], "geometry": {"type": "LineString", "coordinates": [[84.9, 17.6], [84.6, 17.8]]}, "properties": {"eventtype": "TC", "eventid": 1001326, "episodeid": 6, "eventname": "ONE-26", "glide": "", "name": "Tropical Cyclone ONE-26", "description": "Tropical Cyclone ONE-26", "htmldescription": "Orange Tropical Cyclone ONE-26 in India from: 22 Sep 2026 to: 24 Sep 2026 .", "icon": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "iconoverall": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "url": {"geometry": "https://www.gdacs.org/gdacsapi/api/polygons/getgeometry?eventtype=TC&eventid=1001326&episodeid=6", "report": "https://www.gdacs.org/report.aspx?eventid=1001326&episodeid=6&eventtype=TC", "details": "https://www.gdacs.org/gdacsapi/api/events/geteventdata?eventtype=TC&eventid=1001326"}, "alertlevel": "Orange", "alertscore": 2, "episodealertlevel": "Orange", "episodealertscore": 2.0, "istemporary": "false", "iscurrent": "true", "country": "India", "fromdate": "2026-09-22T18:00:00", "todate": "2026-09-24T00:00:00", "datemodified": "2026-09-27T08:00:13", "iso3": "IND", "source": "JTWC", "sourceid": "", "polygondate": "2026-09-24T00:00:00", "polygonlabel": "TS", "countryonland": "India", "affectedcountries": [{"iso2": "IN", "iso3": "IND", "countryname": "India"}], "severitydata": {"severity": 83.3328, "severitytext": "Tropical Storm (maximum wind speed of 83 km/h)", "severityunit": "km/h"}, "forecast": false, "Class": "Line_Line_6", "iconeventlink": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "iconitemlink": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png"}}, {"type": "Feature", "bbox": [82.0249, 17.85, 83.963, 20.734], "geometry": {"type": "Polygon", "coordinates": [[[83.7, 17.85], [83.7092, 17.8502], [83.7183, 17.8506], [83.7275, 17.8514], [83.7366, 17.8524], [83.7457, 17.8538], [83.7547, 17.8555], [83.7636, 17.8574], [83.7725, 17.8597], [83.7813, 17.8622], [83.79, 17.8651], [83.7985, 17.8682], [83.807, 17.8716], [83.8153, 17.8753], [83.8235, 17.8793], [83.8315, 17.8835], [83.8394, 17.888], [83.8471, 17.8927], [83.8546, 17.8977], [83.8619, 17.903], [83.8691, 17.9085], [83.876, 17.9142], [83.8827, 17.9202], [83.8892, 17.9263], [83.8955, 17.9327], [83.9015, 17.9393], [83.9073, 17.9461], [83.9128, 17.9531], [83.918, 17.9602], [83.923, 17.9675], [83.9278, 17.975], [83.9322, 17.9826], [83.9364, 17.9904], [83.9403, 17.9983], [83.9439, 18.0063], [83.9472, 18.0145], [83.9501, 18.0227], [83.9528, 18.0311], [83.9552, 18.0395], [83.9573, 18.048], [83.959, 18.0566], [83.9605, 18.0652], [83.9616, 18.0739], [83.9624, 18.0826], [83.9629, 18.0913], [83.963, 18.1], [83.9629, 18.1087], [83.9624, 18.1174], [83.9616, 18.1261], [83.9605, 18.1348], [83.959, 18.1434], [83.9573, 18.152], [83.9552, 18.1605], [83.9528, 18.1689], [83.9501, 18.1773], [83.9472, 18.1855], [83.9439, 18.1937], [83.5288, 19.2082], [83.3685, 20.1882], [83.3649, 20.2101], [83.3604, 20.2318], [83.3551, 20.2534], [83.349, 20.2748], [83.3421, 20.2959], [83.3344, 20.3168], [83.326, 20.3375], [83.3168, 20.3579], [83.3068, 20.3779], [83.2961, 20.3976], [83.2847, 20.417], [83.2725, 20.436], [83.2597, 20.4545], [83.2462, 20.4727], [83.232, 20.4903], [83.2172, 20.5075], [83.2017, 20.5242], [83.1856, 20.5404], [83.169, 20.5561], [83.1517, 20.5712], [83.134, 20.5857], [83.1156, 20.5996], [83.0968, 20.6129], [83.0775, 20.6256], [83.0578, 20.6377], [83.0376, 20.6491], [83.0169, 20.6598], [82.996, 20.6698], [82.9746, 20.6792], [82.9529, 20.6878], [82.9309, 20.6958], [82.9086, 20.703], [82.8861, 20.7094], [82.8633, 20.7152], [82.8404, 20.7201], [82.8172, 20.7244], [82.794, 20.7278], [82.7706, 20.7305], [82.7471, 20.7325], [82.7236, 20.7336], [82.7, 20.734], [82.6764, 20.7336], [82.6529, 20.7325], [82.6294, 20.7305], [82.606, 20.7278], [82.5828, 20.7244], [82.5596, 20.7201], [82.5367, 20.7152], [82.5139, 20.7094], [82.4914, 20.703], [82.4691, 20.6958], [82.4471, 20.6878], [82.4254, 20.6792], [82.404, 20.6698], [82.3831, 20.6598], [82.3624, 20.6491], [82.3422, 20.6377], [82.3225, 20.6256], [82.3032, 20.6129], [82.2844, 20.5996], [82.266, 20.5857], [82.2483, 20.5712], [82.231, 20.5561], [82.2144, 20.5404], [82.1983, 20.5242], [82.1828, 20.5075], [82.168, 20.4903], [82.1538, 20.4727], [82.1403, 20.4545], [82.1275, 20.436], [82.1153, 20.417], [82.1039, 20.3976], [82.0932, 20.3779], [82.0832, 20.3579], [82.074, 20.3375], [82.0656, 20.3168], [82.0579, 20.2959], [82.051, 20.2748], [82.0449, 20.2534], [82.0396, 20.2318], [82.0351, 20.2101], [82.0315, 20.1882], [82.0286, 20.1663], [82.0265, 20.1442], [82.0253, 20.1221], [82.0249, 20.1], [82.0253, 20.0779], [82.0265, 20.0558], [82.0286, 20.0337], [82.0315, 20.0118], [82.0351, 19.9899], [82.0396, 19.9682], [82.0449, 19.9466], [82.051, 19.9252], [82.0579, 19.9041], [82.0656, 19.8832], [82.074, 19.8625], [82.0832, 19.8421], [82.0932, 19.8221], [82.1039, 19.8024], [82.1153, 19.783], [82.1275, 19.764], [82.7258, 18.879], [82.7342, 18.8668], [82.743, 18.8549], [82.7523, 18.8433], [83.4927, 17.9461], [83.4985, 17.9393], [83.5045, 17.9327], [83.5108, 17.9263], [83.5173, 17.9202], [83.524, 17.9142], [83.5309, 17.9085], [83.5381, 17.903], [83.5454, 17.8977], [83.5529, 17.8927], [83.5606, 17.888], [83.5685, 17.8835], [83.5765, 17.8793], [83.5847, 17.8753], [83.593, 17.8716], [83.6015, 17.8682], [83.61, 17.8651], [83.6187, 17.8622], [83.6275, 17.8597], [83.6364, 17.8574], [83.6453, 17.8555], [83.6543, 17.8538], [83.6634, 17.8524], [83.6725, 17.8514], [83.6817, 17.8506], [83.6908, 17.8502], [83.7, 17.85]]]}, "properties": {"eventtype": "TC", "eventid": 1001326, "episodeid": 6, "eventname": "ONE-26", "glide": "", "name": "Tropical Cyclone ONE-26", "description": "Tropical Cyclone ONE-26", "htmldescription": "Orange Tropical Cyclone ONE-26 in India from: 22 Sep 2026 to: 24 Sep 2026 .", "icon": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "iconoverall": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "url": {"geometry": "https://www.gdacs.org/gdacsapi/api/polygons/getgeometry?eventtype=TC&eventid=1001326&episodeid=6", "report": "https://www.gdacs.org/report.aspx?eventid=1001326&episodeid=6&eventtype=TC", "details": "https://www.gdacs.org/gdacsapi/api/events/geteventdata?eventtype=TC&eventid=1001326"}, "alertlevel": "Orange", "alertscore": 2, "episodealertlevel": "Orange", "episodealertscore": 2.0, "istemporary": "false", "iscurrent": "true", "country": "India", "fromdate": "2026-09-22T18:00:00", "todate": "2026-09-24T00:00:00", "datemodified": "2026-09-27T08:00:13", "iso3": "IND", "source": "JTWC", "sourceid": "", "polygondate": "2026-09-24T00:00:00", "polygonlabel": "Uncertainty Cones", "countryonland": "India", "affectedcountries": [{"iso2": "IN", "iso3": "IND", "countryname": "India"}], "severitydata": {"severity": 83.3328, "severitytext": "Tropical Storm (maximum wind speed of 83 km/h)", "severityunit": "km/h"}, "Class": "Poly_Cones", "iconeventlink": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png", "iconitemlink": "https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png"}}], "bbox": null} \ No newline at end of file diff --git a/test/fixtures/gdacs-tc-list-2026-09-27.json b/test/fixtures/gdacs-tc-list-2026-09-27.json new file mode 100644 index 0000000..99b9408 --- /dev/null +++ b/test/fixtures/gdacs-tc-list-2026-09-27.json @@ -0,0 +1 @@ +{"type":"FeatureCollection","features":[{"type":"Feature","bbox":[-43.9,29.6,-43.9,29.6],"geometry":{"type":"Point","coordinates":[-43.9,29.6]},"properties":{"eventtype":"TC","eventid":1001323,"episodeid":28,"eventname":"FAY-26","glide":"","name":"Tropical Cyclone FAY-26","description":"Tropical Cyclone FAY-26","htmldescription":"Green Tropical Cyclone FAY-26 off-shore from: 19 Sep 2026 to: 27 Sep 2026 .","icon":"https://www.gdacs.org/images/gdacs_icons/maps/Green/TC.png","iconoverall":"https://www.gdacs.org/images/gdacs_icons/maps/Green/TC.png","url":{"geometry":"https://www.gdacs.org/gdacsapi/api/polygons/getgeometry?eventtype=TC&eventid=1001323&episodeid=28","report":"https://www.gdacs.org/report.aspx?eventid=1001323&episodeid=28&eventtype=TC","details":"https://www.gdacs.org/gdacsapi/api/events/geteventdata?eventtype=TC&eventid=1001323"},"alertlevel":"Green","alertscore":1,"episodealertlevel":"Green","episodealertscore":1.0,"istemporary":"false","iscurrent":"true","country":"","fromdate":"2026-09-19T15:00:00","todate":"2026-09-27T03:00:00","datemodified":"2026-09-27T02:51:45","iso3":"","source":"NOAA","sourceid":"","polygonlabel":"Centroid","Class":"Point_Centroid","countryonland":"","affectedcountries":[],"severitydata":{"severity":111.1104,"severitytext":"Tropical Depression (maximum wind speed of 111 km/h)","severityunit":"km/h"}}},{"type":"Feature","bbox":[-123.6,21.1,-123.6,21.1],"geometry":{"type":"Point","coordinates":[-123.6,21.1]},"properties":{"eventtype":"TC","eventid":1001324,"episodeid":29,"eventname":"ODALYS-26","glide":"","name":"Tropical Cyclone ODALYS-26","description":"Tropical Cyclone ODALYS-26","htmldescription":"Green Tropical Cyclone ODALYS-26 off-shore from: 20 Sep 2026 to: 27 Sep 2026 .","icon":"https://www.gdacs.org/images/gdacs_icons/maps/Green/TC.png","iconoverall":"https://www.gdacs.org/images/gdacs_icons/maps/Green/TC.png","url":{"geometry":"https://www.gdacs.org/gdacsapi/api/polygons/getgeometry?eventtype=TC&eventid=1001324&episodeid=29","report":"https://www.gdacs.org/report.aspx?eventid=1001324&episodeid=29&eventtype=TC","details":"https://www.gdacs.org/gdacsapi/api/events/geteventdata?eventtype=TC&eventid=1001324"},"alertlevel":"Green","alertscore":1,"episodealertlevel":"Green","episodealertscore":1.0,"istemporary":"false","iscurrent":"true","country":"","fromdate":"2026-09-20T09:00:00","todate":"2026-09-27T03:00:00","datemodified":"2026-09-27T03:08:14","iso3":"","source":"NOAA","sourceid":"","polygonlabel":"Centroid","Class":"Point_Centroid","countryonland":"","affectedcountries":[],"severitydata":{"severity":212.9616,"severitytext":"Hurricane/Typhoon > 74 mph (maximum wind speed of 213 km/h)","severityunit":"km/h"}}},{"type":"Feature","bbox":[-156.5,16.7,-156.5,16.7],"geometry":{"type":"Point","coordinates":[-156.5,16.7]},"properties":{"eventtype":"TC","eventid":1001321,"episodeid":26,"eventname":"NOLO-26","glide":"","name":"Tropical Cyclone NOLO-26","description":"Tropical Cyclone NOLO-26","htmldescription":"Green Tropical Cyclone NOLO-26 in United States from: 13 Sep 2026 to: 27 Sep 2026 .","icon":"https://www.gdacs.org/images/gdacs_icons/maps/Green/TC.png","iconoverall":"https://www.gdacs.org/images/gdacs_icons/maps/Green/TC.png","url":{"geometry":"https://www.gdacs.org/gdacsapi/api/polygons/getgeometry?eventtype=TC&eventid=1001321&episodeid=26","report":"https://www.gdacs.org/report.aspx?eventid=1001321&episodeid=26&eventtype=TC","details":"https://www.gdacs.org/gdacsapi/api/events/geteventdata?eventtype=TC&eventid=1001321"},"alertlevel":"Green","alertscore":1,"episodealertlevel":"Green","episodealertscore":1.0,"istemporary":"false","iscurrent":"true","country":"United States","fromdate":"2026-09-13T21:00:00","todate":"2026-09-27T03:00:00","datemodified":"2026-09-27T05:21:31","iso3":"","source":"NOAA","sourceid":"","polygonlabel":"Centroid","Class":"Point_Centroid","countryonland":"","affectedcountries":[{"iso2":"US","iso3":"USA","countryname":"United States"}],"severitydata":{"severity":212.9616,"severitytext":"Hurricane/Typhoon > 74 mph (maximum wind speed of 213 km/h)","severityunit":"km/h"}}},{"type":"Feature","bbox":[-113.1,19.3,-113.1,19.3],"geometry":{"type":"Point","coordinates":[-113.1,19.3]},"properties":{"eventtype":"TC","eventid":1001325,"episodeid":26,"eventname":"POLO-26","glide":"","name":"Tropical Cyclone POLO-26","description":"Tropical Cyclone POLO-26","htmldescription":"Orange Tropical Cyclone POLO-26 in Mexico from: 21 Sep 2026 to: 27 Sep 2026 .","icon":"https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png","iconoverall":"https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png","url":{"geometry":"https://www.gdacs.org/gdacsapi/api/polygons/getgeometry?eventtype=TC&eventid=1001325&episodeid=26","report":"https://www.gdacs.org/report.aspx?eventid=1001325&episodeid=26&eventtype=TC","details":"https://www.gdacs.org/gdacsapi/api/events/geteventdata?eventtype=TC&eventid=1001325"},"alertlevel":"Orange","alertscore":2,"episodealertlevel":"Orange","episodealertscore":2.0,"istemporary":"false","iscurrent":"true","country":"Mexico","fromdate":"2026-09-21T03:00:00","todate":"2026-09-27T03:00:00","datemodified":"2026-09-27T05:38:34","iso3":"MEX","source":"NOAA","sourceid":"","polygonlabel":"Centroid","Class":"Point_Centroid","countryonland":"","affectedcountries":[{"iso2":"MX","iso3":"MEX","countryname":"Mexico"}],"severitydata":{"severity":287.0352,"severitytext":"Hurricane/Typhoon > 74 mph (maximum wind speed of 287 km/h)","severityunit":"km/h"}}},{"type":"Feature","bbox":[127.6,24.6,127.6,24.6],"geometry":{"type":"Point","coordinates":[127.6,24.6]},"properties":{"eventtype":"TC","eventid":1001327,"episodeid":16,"eventname":"SURIGAE-26","glide":"","name":"Tropical Cyclone SURIGAE-26","description":"Tropical Cyclone SURIGAE-26","htmldescription":"Green Tropical Cyclone SURIGAE-26 in Japan from: 23 Sep 2026 to: 27 Sep 2026 .","icon":"https://www.gdacs.org/images/gdacs_icons/maps/Green/TC.png","iconoverall":"https://www.gdacs.org/images/gdacs_icons/maps/Green/TC.png","url":{"geometry":"https://www.gdacs.org/gdacsapi/api/polygons/getgeometry?eventtype=TC&eventid=1001327&episodeid=16","report":"https://www.gdacs.org/report.aspx?eventid=1001327&episodeid=16&eventtype=TC","details":"https://www.gdacs.org/gdacsapi/api/events/geteventdata?eventtype=TC&eventid=1001327"},"alertlevel":"Green","alertscore":1,"episodealertlevel":"Green","episodealertscore":1.0,"istemporary":"false","iscurrent":"true","country":"Japan","fromdate":"2026-09-23T06:00:00","todate":"2026-09-27T00:00:00","datemodified":"2026-09-27T05:53:41","iso3":"JPN","source":"JTWC","sourceid":"","polygonlabel":"Centroid","Class":"Point_Centroid","countryonland":"","affectedcountries":[{"iso2":"JP","iso3":"JPN","countryname":"Japan"}],"severitydata":{"severity":185.184,"severitytext":"Hurricane/Typhoon > 74 mph (maximum wind speed of 185 km/h)","severityunit":"km/h"}}},{"type":"Feature","bbox":[-23.3,19.3,-23.3,19.3],"geometry":{"type":"Point","coordinates":[-23.3,19.3]},"properties":{"eventtype":"TC","eventid":1001328,"episodeid":8,"eventname":"GONZALO-26","glide":"","name":"Tropical Cyclone GONZALO-26","description":"Tropical Cyclone GONZALO-26","htmldescription":"Green Tropical Cyclone GONZALO-26 in Cape Verde from: 25 Sep 2026 to: 26 Sep 2026 .","icon":"https://www.gdacs.org/images/gdacs_icons/maps/Green/TC.png","iconoverall":"https://www.gdacs.org/images/gdacs_icons/maps/Green/TC.png","url":{"geometry":"https://www.gdacs.org/gdacsapi/api/polygons/getgeometry?eventtype=TC&eventid=1001328&episodeid=8","report":"https://www.gdacs.org/report.aspx?eventid=1001328&episodeid=8&eventtype=TC","details":"https://www.gdacs.org/gdacsapi/api/events/geteventdata?eventtype=TC&eventid=1001328"},"alertlevel":"Green","alertscore":1,"episodealertlevel":"Green","episodealertscore":1.0,"istemporary":"false","iscurrent":"true","country":"Cape Verde","fromdate":"2026-09-25T03:00:00","todate":"2026-09-26T21:00:00","datemodified":"2026-09-27T06:23:18","iso3":"CPV","source":"NOAA","sourceid":"","polygonlabel":"Centroid","Class":"Point_Centroid","countryonland":"","affectedcountries":[{"iso2":"CV","iso3":"CPV","countryname":"Cape Verde"}],"severitydata":{"severity":83.3328,"severitytext":"Tropical Storm (maximum wind speed of 83 km/h)","severityunit":"km/h"}}},{"type":"Feature","bbox":[83.7,18.1,83.7,18.1],"geometry":{"type":"Point","coordinates":[83.7,18.1]},"properties":{"eventtype":"TC","eventid":1001326,"episodeid":6,"eventname":"ONE-26","glide":"","name":"Tropical Cyclone ONE-26","description":"Tropical Cyclone ONE-26","htmldescription":"Orange Tropical Cyclone ONE-26 in India from: 22 Sep 2026 to: 24 Sep 2026 .","icon":"https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png","iconoverall":"https://www.gdacs.org/images/gdacs_icons/maps/Orange/TC.png","url":{"geometry":"https://www.gdacs.org/gdacsapi/api/polygons/getgeometry?eventtype=TC&eventid=1001326&episodeid=6","report":"https://www.gdacs.org/report.aspx?eventid=1001326&episodeid=6&eventtype=TC","details":"https://www.gdacs.org/gdacsapi/api/events/geteventdata?eventtype=TC&eventid=1001326"},"alertlevel":"Orange","alertscore":2,"episodealertlevel":"Orange","episodealertscore":2.0,"istemporary":"false","iscurrent":"true","country":"India","fromdate":"2026-09-22T18:00:00","todate":"2026-09-24T00:00:00","datemodified":"2026-09-27T08:00:13","iso3":"IND","source":"JTWC","sourceid":"","polygonlabel":"Centroid","Class":"Point_Centroid","countryonland":"","affectedcountries":[{"iso2":"IN","iso3":"IND","countryname":"India"}],"severitydata":{"severity":83.3328,"severitytext":"Tropical Storm (maximum wind speed of 83 km/h)","severityunit":"km/h"}}},{"type":"Feature","bbox":[150.2,39.0,150.2,39.0],"geometry":{"type":"Point","coordinates":[150.2,39.0]},"properties":{"eventtype":"TC","eventid":1001322,"episodeid":28,"eventname":"DUJUAN-26","glide":"","name":"Tropical Cyclone DUJUAN-26","description":"Tropical Cyclone DUJUAN-26","htmldescription":"Green Tropical Cyclone DUJUAN-26 in Japan from: 15 Sep 2026 to: 22 Sep 2026 .","icon":"https://www.gdacs.org/images/gdacs_icons/maps/Green/TC.png","iconoverall":"https://www.gdacs.org/images/gdacs_icons/maps/Green/TC.png","url":{"geometry":"https://www.gdacs.org/gdacsapi/api/polygons/getgeometry?eventtype=TC&eventid=1001322&episodeid=28","report":"https://www.gdacs.org/report.aspx?eventid=1001322&episodeid=28&eventtype=TC","details":"https://www.gdacs.org/gdacsapi/api/events/geteventdata?eventtype=TC&eventid=1001322"},"alertlevel":"Green","alertscore":1,"episodealertlevel":"Green","episodealertscore":1.0,"istemporary":"false","iscurrent":"false","country":"Japan","fromdate":"2026-09-15T12:00:00","todate":"2026-09-22T06:00:00","datemodified":"2026-09-23T08:20:07","iso3":"JPN","source":"JTWC","sourceid":"","polygonlabel":"Centroid","Class":"Point_Centroid","countryonland":"","affectedcountries":[{"iso2":"JP","iso3":"JPN","countryname":"Japan"}],"severitydata":{"severity":129.6288,"severitytext":"Tropical Storm (maximum wind speed of 130 km/h)","severityunit":"km/h"}}}],"bbox":null} \ No newline at end of file diff --git a/test/fixtures/gdelt-doc-california-fire-2026-09-27.json b/test/fixtures/gdelt-doc-california-fire-2026-09-27.json new file mode 100644 index 0000000..5646f79 --- /dev/null +++ b/test/fixtures/gdelt-doc-california-fire-2026-09-27.json @@ -0,0 +1 @@ +{"articles": [ { "url": "https://www.topky.sk/cl/11/9503843/Hrozba-gigantickych-rozmerov--Blizi-sa-super-El-Ni-o--Vedci-varuju-pred-zaplavami--suchom-aj-nedostatkom-potravin", "url_mobile": "", "title": "Blíži sa super El Niño , vedci varujú pred záplavami , suchom aj nedostatkom potravín", "seendate": "20260927T093000Z", "socialimage": "https://static-images.zoznam.sk/image/fetch/q_92,w_1200,h_630,c_fill/h_108,g_north_east,x_0,y_30,l_topky_watermark/https://img.topky.sk/1280px/9041917.jpg", "domain": "topky.sk", "language": "Slovak", "sourcecountry": "Slovak Republic" },{ "url": "https://www.newstribune.com/news/2026/sep/27/californias-oldest-family-owned-winery-declares/", "url_mobile": "", "title": "California oldest family - owned winery declares bankruptcy as wine industry struggles", "seendate": "20260927T093000Z", "socialimage": "https://faughnmedia.media.clients.ellingtoncms.com/imports/nt/img/2026/09/27/217547362_BIZ-CALIF-WINERY-BANKRUPTCY-FILEPIC-DMT_t1200.jpg?57a0c2296240c280e9492005c3cad63e7cbe80f4", "domain": "newstribune.com", "language": "English", "sourcecountry": "United States" },{ "url": "https://www.kcur.org/news/2026-09-27/missouri-vehicle-sales-boosted-by-strong-purchasing-of-commercial-vehicles-in-jackson-county", "url_mobile": "", "title": "Missouri vehicle sales boosted by strong purchasing of commercial vehicles in Jackson County", "seendate": "20260927T093000Z", "socialimage": "", "domain": "kcur.org", "language": "English", "sourcecountry": "United States" },{ "url": "https://www.orientaldaily.com.my/news/health/2026/09/27/850785", "url_mobile": "", "title": "手机放床头恐伤脑兼致癌 研究揭1习惯增67 % 糖尿病率 | 健康 | 生活", "seendate": "20260927T074500Z", "socialimage": "https://www.orientaldaily.com.my/storage/resize_cache/images/uploads/news-cover/2026/SEP_2026/20260927/istockphoto-1441017324-612x612.jpg/67232963116a0b8873da8e85bbed8fde.jpg", "domain": "orientaldaily.com.my", "language": "Chinese", "sourcecountry": "Malaysia" },{ "url": "https://www.turnto23.com/news/in-your-neighborhood/bakersfield/friends-and-family-gather-to-celebrate-lives-of-vanessa-kylie-and-kloie-wetmore", "url_mobile": "", "title": "Bakersfield community celebrates lives of Wetmore family", "seendate": "20260927T070000Z", "socialimage": "https://cf.cdn.uplynk.com/ause1/slices/be6/3870ad0511fa47a79b3577075088ec91/be6e9b2fc4c946efa00cf12b71e5c88e/poster_280cdaa13ee44e589d137c2d556f2e5e.jpg", "domain": "turnto23.com", "language": "English", "sourcecountry": "United States" }] } \ No newline at end of file diff --git a/test/fixtures/gee-landcover-live-2026-09-27.json b/test/fixtures/gee-landcover-live-2026-09-27.json new file mode 100644 index 0000000..50735d2 --- /dev/null +++ b/test/fixtures/gee-landcover-live-2026-09-27.json @@ -0,0 +1,48 @@ +{ + "recorded": "2026-09-27T08:08:53.360Z", + "note": "Raw Earth Engine value:compute results (reduceRegion frequencyHistogram), one live call each.", + "mapbiomas": { + "bbox": [ + -52.4, + -6.9, + -51.9, + -6.4 + ], + "year": 2024, + "scaleM": 30, + "result": { + "classification": { + "0": 149, + "3": 1130471.0980392094, + "4": 9553.694117647061, + "6": 147705.8941176471, + "11": 8549.494117647058, + "12": 8938.709803921567, + "15": 1926006.5999999563, + "24": 15866, + "25": 5220.549019607843, + "29": 7571.603921568621, + "30": 22765.027450980404, + "33": 158110.54509803923, + "39": 443, + "41": 961.4941176470588 + } + } + }, + "dynamicWorld": { + "bbox": [ + 113.8, + -2.5, + 113.9, + -2.4 + ], + "dateFrom": "2026-03-29", + "dateTo": "2026-09-27", + "scaleM": 10, + "result": { + "label": { + "1": 1239262.2549019426 + } + } + } +} diff --git a/test/fixtures/gfw-fishing-galapagos-bbox-2026-09-27.json b/test/fixtures/gfw-fishing-galapagos-bbox-2026-09-27.json new file mode 100644 index 0000000..44e0f26 --- /dev/null +++ b/test/fixtures/gfw-fishing-galapagos-bbox-2026-09-27.json @@ -0,0 +1 @@ +{"total":1,"limit":null,"offset":null,"nextOffset":null,"metadata":{},"entries":[{"public-global-fishing-effort:v4.0":[{"date":"2026-09-17","flag":"ECU","hours":0.1502777777777778,"lat":-1.69,"lon":-92.32,"vesselIDs":1},{"date":"2026-09-10","flag":"ECU","hours":3.833611111111111,"lat":-0.7,"lon":-89.42,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":0.9530555555555555,"lat":1.99,"lon":-88.78,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.3880555555555556,"lat":1.38,"lon":-91.81,"vesselIDs":1},{"date":"2026-09-03","flag":"ECU","hours":1.1669444444444443,"lat":-1.02,"lon":-90.87,"vesselIDs":1},{"date":"2026-09-03","flag":"ECU","hours":1.083611111111111,"lat":-1.03,"lon":-90.88,"vesselIDs":1},{"date":"2026-09-05","flag":"ECU","hours":0.7649999999999999,"lat":0.76,"lon":-90.74,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.7055555555555555,"lat":-0.32,"lon":-90.34,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":1.7738888888888888,"lat":-1.45,"lon":-92.47,"vesselIDs":1},{"date":"2026-09-06","flag":"ECU","hours":0.4822222222222222,"lat":-0.23,"lon":-90.59,"vesselIDs":1},{"date":"2026-09-05","flag":"ECU","hours":0.5663888888888888,"lat":-0.29,"lon":-90.55,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":1.0000000000000002,"lat":-0.39,"lon":-90.56,"vesselIDs":1},{"date":"2026-09-19","flag":"ECU","hours":0.16722222222222222,"lat":-0.75,"lon":-90.27,"vesselIDs":1},{"date":"2026-09-07","flag":"ECU","hours":1.9919444444444445,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-01","flag":"ECU","hours":0.1661111111111111,"lat":-0.77,"lon":-90.31,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.6152777777777778,"lat":-1.72,"lon":-92.26,"vesselIDs":1},{"date":"2026-09-07","flag":"ECU","hours":1.0758333333333336,"lat":0.75,"lon":-90.76,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":1.2844444444444445,"lat":-2.08,"lon":-92.2,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":1.1130555555555555,"lat":-0.32,"lon":-90.31,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":1.208611111111111,"lat":-1.58,"lon":-92.44,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":0.1661111111111111,"lat":-0.78,"lon":-89.53,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":0.9977777777777779,"lat":-1.16,"lon":-92.51,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":0.043055555555555555,"lat":-0.39,"lon":-90.52,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":1.2347222222222223,"lat":-1.25,"lon":-92.46,"vesselIDs":1},{"date":"2026-09-15","flag":"ECU","hours":0.3577777777777778,"lat":-0.55,"lon":-90.86,"vesselIDs":1},{"date":"2026-08-31","flag":"ECU","hours":0.13527777777777777,"lat":-1.03,"lon":-90.73,"vesselIDs":1},{"date":"2026-09-21","flag":"ECU","hours":0.20333333333333337,"lat":-0.04,"lon":-91.19,"vesselIDs":1},{"date":"2026-09-15","flag":"ECU","hours":1.5480555555555555,"lat":-1.79,"lon":-92.12,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":0.7105555555555556,"lat":-0.37,"lon":-90.28,"vesselIDs":1},{"date":"2026-09-10","flag":"ECU","hours":2.153888888888889,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":0.9683333333333333,"lat":-1.25,"lon":-92.57,"vesselIDs":1},{"date":"2026-09-21","flag":"ECU","hours":0.5,"lat":-0.75,"lon":-90.31,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":0.7233333333333333,"lat":-1.65,"lon":-92.43,"vesselIDs":1},{"date":"2026-09-09","flag":"ECU","hours":0.35750000000000004,"lat":-0.8,"lon":-90.63,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.6027777777777779,"lat":-1.84,"lon":-92.09,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":2.250277777777778,"lat":-1.02,"lon":-89.59,"vesselIDs":1},{"date":"2026-09-01","flag":"ECU","hours":1.0013888888888889,"lat":-0.77,"lon":-90.34,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":1.0002777777777778,"lat":-0.77,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":0.7741666666666667,"lat":-1.98,"lon":-92.11,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":0.75,"lat":-0.71,"lon":-89.45,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":0.17194444444444446,"lat":-1.79,"lon":-92.27,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":0.6527777777777778,"lat":-1.94,"lon":-92.18,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":0.966388888888889,"lat":-0.39,"lon":-90.57,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.7138888888888888,"lat":-1.75,"lon":-92.23,"vesselIDs":1},{"date":"2026-09-21","flag":"ECU","hours":4.421666666666666,"lat":-1.2,"lon":-89.85,"vesselIDs":1},{"date":"2026-09-06","flag":"ECU","hours":1.2341666666666666,"lat":0.76,"lon":-90.75,"vesselIDs":1},{"date":"2026-09-08","flag":"ECU","hours":1.5008333333333335,"lat":-0.95,"lon":-89.38,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":1.568888888888889,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":1.1108333333333333,"lat":-1.75,"lon":-92.19,"vesselIDs":1},{"date":"2026-09-15","flag":"ECU","hours":0.01361111111111111,"lat":-1.74,"lon":-92.17,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":1.9863888888888888,"lat":-1.96,"lon":-92.16,"vesselIDs":1},{"date":"2026-09-21","flag":"ECU","hours":0.7538888888888888,"lat":-1.14,"lon":-89.89,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":2.801111111111111,"lat":-1.66,"lon":-92.34,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":0.8872222222222222,"lat":-1.39,"lon":-92.68,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":0.9602777777777778,"lat":-1.87,"lon":-92.21,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":2.2249999999999996,"lat":-1.7,"lon":-92.32,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":1.0425,"lat":-1.3,"lon":-92.55,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":0.8805555555555556,"lat":2.02,"lon":-88.82,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.18416666666666665,"lat":-0.87,"lon":-90.69,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":1.1616666666666666,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":0.9169444444444446,"lat":-0.77,"lon":-90.35,"vesselIDs":1},{"date":"2026-09-15","flag":"ECU","hours":0.30027777777777775,"lat":-1.74,"lon":-92.18,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":3.982222222222222,"lat":-1.03,"lon":-90.74,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":0.8511111111111112,"lat":-1.71,"lon":-92.3,"vesselIDs":1},{"date":"2026-09-19","flag":"ECU","hours":2.666944444444445,"lat":-0.75,"lon":-90.26,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":0.4411111111111111,"lat":-1.34,"lon":-92.55,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.8872222222222224,"lat":-0.31,"lon":-90.31,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":1.023888888888889,"lat":-1.47,"lon":-92.57,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":0.24194444444444446,"lat":-0.38,"lon":-90.57,"vesselIDs":1},{"date":"2026-09-15","flag":"ECU","hours":0.6444444444444446,"lat":-0.54,"lon":-90.85,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":1.0280555555555555,"lat":-1.27,"lon":-92.45,"vesselIDs":1},{"date":"2026-09-09","flag":"ECU","hours":12.25222222222222,"lat":-0.54,"lon":-90.85,"vesselIDs":1},{"date":"2026-09-01","flag":"ECU","hours":0.6663888888888888,"lat":-0.77,"lon":-90.35,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":1.1897222222222223,"lat":-0.34,"lon":-90.33,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.9450000000000001,"lat":-1.76,"lon":-92.25,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":0.8319444444444445,"lat":-1.87,"lon":-92.22,"vesselIDs":1},{"date":"2026-08-31","flag":"ECU","hours":0.9166666666666667,"lat":-1,"lon":-90.88,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":0.33944444444444444,"lat":-0.96,"lon":-89.59,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":0.513611111111111,"lat":-1.38,"lon":-92.63,"vesselIDs":1},{"date":"2026-09-12","flag":"USA","hours":2.3169444444444443,"lat":-1.9,"lon":-91.08,"vesselIDs":1},{"date":"2026-09-10","flag":"ECU","hours":0.9075000000000003,"lat":0.59,"lon":-90.72,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":0.9558333333333333,"lat":-1.66,"lon":-92.45,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":2.0824999999999996,"lat":-0.96,"lon":-89.39,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":0.9736111111111111,"lat":-1.52,"lon":-92.55,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":0.8505555555555555,"lat":-1.84,"lon":-92.25,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":0.8083333333333333,"lat":-1.59,"lon":-92.44,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":1.4166666666666665,"lat":-1.77,"lon":-92.17,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":1.4691666666666667,"lat":-1.44,"lon":-92.59,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":1.851388888888889,"lat":-0.37,"lon":-90.59,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":1.0963888888888889,"lat":-1.28,"lon":-92.56,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":0.5838888888888889,"lat":-0.39,"lon":-90.52,"vesselIDs":1},{"date":"2026-09-12","flag":"USA","hours":0.9208333333333333,"lat":-1.95,"lon":-91.06,"vesselIDs":1},{"date":"2026-09-04","flag":"ECU","hours":0.1663888888888889,"lat":-0.51,"lon":-90.47,"vesselIDs":1},{"date":"2026-08-29","flag":"ECU","hours":0.6822222222222224,"lat":-0.39,"lon":-90.35,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":1.031388888888889,"lat":-1.88,"lon":-92.2,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":0.9669444444444444,"lat":-0.33,"lon":-90.33,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":1.1686111111111113,"lat":-1.07,"lon":-90.88,"vesselIDs":1},{"date":"2026-09-02","flag":"ECU","hours":1.5825,"lat":-0.65,"lon":-89.32,"vesselIDs":1},{"date":"2026-09-18","flag":"ECU","hours":0.8516666666666667,"lat":-2.09,"lon":-92.07,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":0.9075,"lat":-1.99,"lon":-92.13,"vesselIDs":1},{"date":"2026-09-02","flag":"ECU","hours":1.9161111111111113,"lat":-1.03,"lon":-90.87,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":0.9830555555555555,"lat":-1.21,"lon":-92.51,"vesselIDs":1},{"date":"2026-09-07","flag":"ECU","hours":0.6680555555555555,"lat":-0.77,"lon":-90.37,"vesselIDs":1},{"date":"2026-09-21","flag":"ECU","hours":20.508055555555554,"lat":-0.77,"lon":-90.38,"vesselIDs":1},{"date":"2026-09-20","flag":"ECU","hours":0.75,"lat":-0.76,"lon":-90.3,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.23333333333333334,"lat":-0.64,"lon":-90.83,"vesselIDs":1},{"date":"2026-09-05","flag":"ECU","hours":0.1502777777777778,"lat":-0.29,"lon":-90.56,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":3.915833333333333,"lat":-0.95,"lon":-89.38,"vesselIDs":1},{"date":"2026-09-03","flag":"ECU","hours":3.582222222222222,"lat":-0.66,"lon":-89.31,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":3.495,"lat":-1.01,"lon":-89.6,"vesselIDs":1},{"date":"2026-09-08","flag":"ECU","hours":1.1669444444444443,"lat":-0.77,"lon":-90.35,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":0.9961111111111112,"lat":-1.82,"lon":-92.24,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":1.208611111111111,"lat":-1.24,"lon":-92.58,"vesselIDs":1},{"date":"2026-09-15","flag":"ECU","hours":2.456111111111111,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":1.0422222222222224,"lat":-1.74,"lon":-92.24,"vesselIDs":1},{"date":"2026-09-06","flag":"ECU","hours":0.9925000000000002,"lat":0.75,"lon":-90.73,"vesselIDs":1},{"date":"2026-09-09","flag":"ECU","hours":0.39888888888888885,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":0.9347222222222221,"lat":-1.37,"lon":-92.48,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.6658333333333334,"lat":-0.67,"lon":-89.27,"vesselIDs":1},{"date":"2026-09-10","flag":"ECU","hours":0.5766666666666667,"lat":-1.58,"lon":-92.57,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.8541666666666669,"lat":-0.28,"lon":-90.35,"vesselIDs":1},{"date":"2026-09-03","flag":"ECU","hours":0.9997222222222223,"lat":-0.77,"lon":-90.33,"vesselIDs":1},{"date":"2026-09-10","flag":"ECU","hours":0.7883333333333333,"lat":-1.51,"lon":-92.6,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":1.3675000000000002,"lat":-1.49,"lon":-92.54,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":1.0038888888888888,"lat":-1.6,"lon":-92.5,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":0.7258333333333333,"lat":-1.76,"lon":-92.28,"vesselIDs":1},{"date":"2026-08-31","flag":"ECU","hours":0.8316666666666667,"lat":-1.03,"lon":-90.86,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":1.017222222222222,"lat":-0.28,"lon":-90.34,"vesselIDs":1},{"date":"2026-09-03","flag":"ECU","hours":0.4161111111111111,"lat":-1.01,"lon":-90.87,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":0.645277777777778,"lat":-1.51,"lon":-92.53,"vesselIDs":1},{"date":"2026-09-10","flag":"ECU","hours":1.169722222222222,"lat":-1.39,"lon":-92.64,"vesselIDs":1},{"date":"2026-08-31","flag":"ECU","hours":2.249722222222222,"lat":-1.02,"lon":-90.89,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":0.41638888888888886,"lat":-1.05,"lon":-90.92,"vesselIDs":1},{"date":"2026-09-06","flag":"ECU","hours":0.025833333333333333,"lat":0.71,"lon":-90.74,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":20.198333333333334,"lat":-0.77,"lon":-90.37,"vesselIDs":1},{"date":"2026-09-08","flag":"ECU","hours":0.9163888888888889,"lat":-0.77,"lon":-90.34,"vesselIDs":1},{"date":"2026-09-01","flag":"ECU","hours":3.3333333333333335,"lat":-1.04,"lon":-90.86,"vesselIDs":1},{"date":"2026-09-10","flag":"ECU","hours":2.2305555555555556,"lat":-1.58,"lon":-92.58,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":0.21611111111111114,"lat":-0.41,"lon":-90.44,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.955,"lat":-1.87,"lon":-92.08,"vesselIDs":1},{"date":"2026-09-05","flag":"ECU","hours":2.010277777777778,"lat":0.75,"lon":-90.76,"vesselIDs":1},{"date":"2026-09-12","flag":"USA","hours":2.2119444444444447,"lat":-1.91,"lon":-91.08,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":0.43166666666666664,"lat":-0.39,"lon":-90.47,"vesselIDs":1},{"date":"2026-09-12","flag":"USA","hours":0.8116666666666666,"lat":-1.94,"lon":-91.07,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":1.0002777777777778,"lat":-0.39,"lon":-90.46,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":2.315,"lat":-1.73,"lon":-92.3,"vesselIDs":1},{"date":"2026-09-06","flag":"ECU","hours":1.9925000000000002,"lat":0.75,"lon":-90.74,"vesselIDs":1},{"date":"2026-09-08","flag":"ECU","hours":3.9122222222222223,"lat":-0.94,"lon":-89.38,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":1.071388888888889,"lat":-1.94,"lon":-92.19,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.5252777777777777,"lat":-0.86,"lon":-90.7,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":0.9844444444444443,"lat":-1.58,"lon":-92.52,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.08416666666666667,"lat":-0.93,"lon":-89.38,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":1.051111111111111,"lat":-1.75,"lon":-92.21,"vesselIDs":1},{"date":"2026-09-20","flag":"ECU","hours":1.3325,"lat":-0.58,"lon":-90.1,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":0.43222222222222223,"lat":-1.24,"lon":-92.59,"vesselIDs":1},{"date":"2026-09-01","flag":"ECU","hours":0.8380555555555556,"lat":-0.66,"lon":-89.3,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":1.3902777777777777,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":0.9988888888888889,"lat":-1.24,"lon":-92.46,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":18.209444444444443,"lat":-0.75,"lon":-90.31,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.4844444444444444,"lat":-1.76,"lon":-92.22,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":2.999444444444445,"lat":-1.03,"lon":-90.87,"vesselIDs":1},{"date":"2026-09-10","flag":"ECU","hours":1.0508333333333333,"lat":0.56,"lon":-90.72,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.8308333333333333,"lat":-1.89,"lon":-92.09,"vesselIDs":1},{"date":"2026-09-04","flag":"ECU","hours":0.6166666666666667,"lat":-0.5,"lon":-90.44,"vesselIDs":1},{"date":"2026-09-03","flag":"ECU","hours":3.251388888888889,"lat":-0.77,"lon":-90.34,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":2.0005555555555556,"lat":-0.78,"lon":-90.35,"vesselIDs":1},{"date":"2026-08-31","flag":"ECU","hours":1.0852777777777778,"lat":-0.66,"lon":-89.3,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":0.9911111111111109,"lat":-0.4,"lon":-90.57,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":0.8583333333333331,"lat":-0.39,"lon":-90.53,"vesselIDs":1},{"date":"2026-08-31","flag":"ECU","hours":0.17583333333333334,"lat":-0.81,"lon":-90.69,"vesselIDs":1},{"date":"2026-09-06","flag":"ECU","hours":0.9999999999999998,"lat":0.74,"lon":-90.73,"vesselIDs":1},{"date":"2026-09-10","flag":"ECU","hours":1.1255555555555556,"lat":0.58,"lon":-90.72,"vesselIDs":1},{"date":"2026-09-07","flag":"ECU","hours":0.45,"lat":0.73,"lon":-90.75,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":5.082777777777777,"lat":-0.88,"lon":-89.94,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.8958333333333334,"lat":-1.83,"lon":-92.21,"vesselIDs":1},{"date":"2026-09-08","flag":"ECU","hours":0.5013888888888889,"lat":-0.78,"lon":-90.34,"vesselIDs":1},{"date":"2026-09-01","flag":"ECU","hours":1.1672222222222222,"lat":-1.03,"lon":-90.87,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":1.0827777777777778,"lat":-0.7,"lon":-89.45,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":1.0341666666666667,"lat":-1.22,"lon":-92.48,"vesselIDs":1},{"date":"2026-09-06","flag":"ECU","hours":0.1361111111111111,"lat":-0.22,"lon":-90.6,"vesselIDs":1},{"date":"2026-09-06","flag":"ECU","hours":1.0155555555555558,"lat":0.72,"lon":-90.74,"vesselIDs":1},{"date":"2026-08-31","flag":"ECU","hours":0.41694444444444445,"lat":-1.03,"lon":-90.87,"vesselIDs":1},{"date":"2026-08-30","flag":"ECU","hours":0.1775,"lat":-0.37,"lon":-90.29,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":1.0791666666666668,"lat":-1.84,"lon":-92.2,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":1.6405555555555558,"lat":-0.39,"lon":-90.52,"vesselIDs":1},{"date":"2026-09-19","flag":"ECU","hours":0.9155555555555557,"lat":-0.75,"lon":-90.31,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":1.058611111111111,"lat":-1.28,"lon":-92.5,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":1.0191666666666666,"lat":-0.27,"lon":-90.35,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":1.403888888888889,"lat":-0.34,"lon":-90.33,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":2.7477777777777774,"lat":-1.02,"lon":-89.6,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":0.8008333333333334,"lat":-1.67,"lon":-92.42,"vesselIDs":1},{"date":"2026-09-08","flag":"ECU","hours":0.12972222222222224,"lat":-0.54,"lon":-90.85,"vesselIDs":1},{"date":"2026-09-21","flag":"ECU","hours":1.331388888888889,"lat":-0.78,"lon":-90.34,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":0.9891666666666669,"lat":-1.64,"lon":-92.38,"vesselIDs":1},{"date":"2026-09-10","flag":"ECU","hours":1.7119444444444443,"lat":-1.31,"lon":-92.66,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":0.08611111111111111,"lat":-0.23,"lon":-90.57,"vesselIDs":1},{"date":"2026-08-29","flag":"ECU","hours":0.30722222222222223,"lat":-0.35,"lon":-90.29,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":1.016111111111111,"lat":2,"lon":-88.78,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":0.8777777777777778,"lat":-1.9,"lon":-92.22,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":0.9902777777777777,"lat":-0.33,"lon":-90.3,"vesselIDs":1},{"date":"2026-09-19","flag":"ECU","hours":2.2875,"lat":-0.81,"lon":-90.69,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.4138888888888888,"lat":-0.33,"lon":-90.34,"vesselIDs":1},{"date":"2026-09-05","flag":"ECU","hours":2.275,"lat":0.75,"lon":-90.73,"vesselIDs":1},{"date":"2026-08-31","flag":"ECU","hours":1.1669444444444443,"lat":-1.05,"lon":-90.92,"vesselIDs":1},{"date":"2026-09-21","flag":"ECU","hours":0.7488888888888889,"lat":-1.18,"lon":-89.86,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":1.4483333333333333,"lat":-1.8,"lon":-92.26,"vesselIDs":1},{"date":"2026-09-08","flag":"ECU","hours":1.166388888888889,"lat":-0.78,"lon":-90.36,"vesselIDs":1},{"date":"2026-09-01","flag":"ECU","hours":0.7494444444444444,"lat":-0.67,"lon":-89.31,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":0.3475,"lat":1.97,"lon":-88.74,"vesselIDs":1},{"date":"2026-08-31","flag":"ECU","hours":2.247777777777778,"lat":-0.66,"lon":-89.26,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":0.7494444444444445,"lat":-1.26,"lon":-92.44,"vesselIDs":1},{"date":"2026-09-03","flag":"ECU","hours":0.8397222222222223,"lat":-1.01,"lon":-90.85,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":0.9877777777777779,"lat":-1.1,"lon":-90.9,"vesselIDs":1},{"date":"2026-09-10","flag":"ECU","hours":1.3216666666666665,"lat":-1.65,"lon":-92.47,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":1.2100000000000004,"lat":-1.91,"lon":-92.07,"vesselIDs":1},{"date":"2026-09-10","flag":"ECU","hours":1.3938888888888892,"lat":-1.45,"lon":-92.62,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":0.6611111111111111,"lat":-0.39,"lon":-90.51,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":1.4080555555555556,"lat":-1.87,"lon":-92.17,"vesselIDs":1},{"date":"2026-09-21","flag":"ECU","hours":2.25,"lat":-0.77,"lon":-90.37,"vesselIDs":1},{"date":"2026-09-06","flag":"ECU","hours":0.9994444444444445,"lat":0.74,"lon":-90.74,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":1.2036111111111112,"lat":-1.87,"lon":-92.24,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.33333333333333337,"lat":-0.95,"lon":-89.4,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":1.0283333333333338,"lat":-1.57,"lon":-92.53,"vesselIDs":1},{"date":"2026-09-01","flag":"ECU","hours":19.3225,"lat":-1.02,"lon":-90.86,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":1.073611111111111,"lat":-1.76,"lon":-92.27,"vesselIDs":1},{"date":"2026-09-07","flag":"ECU","hours":2.4988888888888887,"lat":-0.77,"lon":-90.35,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":1.0394444444444444,"lat":-1.83,"lon":-92.26,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":1.4416666666666667,"lat":-1.18,"lon":-92.5,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":1.1624999999999999,"lat":-2.09,"lon":-92.07,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":0.9883333333333333,"lat":-1.11,"lon":-90.91,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.9958333333333335,"lat":-0.27,"lon":-90.34,"vesselIDs":1},{"date":"2026-08-29","flag":"ECU","hours":6.417777777777777,"lat":-0.34,"lon":-90.29,"vesselIDs":1},{"date":"2026-09-05","flag":"ECU","hours":2.0327777777777776,"lat":0.74,"lon":-90.76,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":2.5033333333333334,"lat":-1.02,"lon":-89.59,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":1.3713888888888888,"lat":-1.27,"lon":-92.56,"vesselIDs":1},{"date":"2026-09-04","flag":"ECU","hours":0.008055555555555555,"lat":-0.39,"lon":-90.48,"vesselIDs":1},{"date":"2026-09-20","flag":"ECU","hours":20.10861111111111,"lat":-0.75,"lon":-90.31,"vesselIDs":1},{"date":"2026-09-15","flag":"ECU","hours":0.06472222222222222,"lat":-0.24,"lon":-90.58,"vesselIDs":1},{"date":"2026-09-07","flag":"ECU","hours":0.6397222222222223,"lat":-0.78,"lon":-90.37,"vesselIDs":1},{"date":"2026-09-04","flag":"ECU","hours":10.463611111111108,"lat":-0.54,"lon":-90.85,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":2.0283333333333333,"lat":-1.51,"lon":-92.48,"vesselIDs":1},{"date":"2026-08-31","flag":"ECU","hours":0.9177777777777778,"lat":-1.05,"lon":-90.9,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":0.3980555555555555,"lat":2.03,"lon":-88.9,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.9958333333333337,"lat":-0.29,"lon":-90.33,"vesselIDs":1},{"date":"2026-09-03","flag":"ECU","hours":0.04611111111111111,"lat":-0.54,"lon":-90.86,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":0.8072222222222223,"lat":-1.94,"lon":-92.19,"vesselIDs":1},{"date":"2026-09-08","flag":"ECU","hours":1,"lat":-0.78,"lon":-90.35,"vesselIDs":1},{"date":"2026-09-21","flag":"ECU","hours":0.8816666666666667,"lat":-0.05,"lon":-91.19,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":1.246388888888889,"lat":-1.73,"lon":-92.32,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":6.411388888888888,"lat":-0.24,"lon":-90.58,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":0.84,"lat":-0.31,"lon":-90.31,"vesselIDs":1},{"date":"2026-09-01","flag":"ECU","hours":1.5044444444444443,"lat":-0.67,"lon":-89.3,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":0.1688888888888889,"lat":-1.64,"lon":-92.37,"vesselIDs":1},{"date":"2026-09-09","flag":"ECU","hours":3.1655555555555552,"lat":-0.77,"lon":-90.32,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":0.7044444444444444,"lat":-1.49,"lon":-92.53,"vesselIDs":1},{"date":"2026-09-07","flag":"ECU","hours":6.018611111111111,"lat":0.74,"lon":-90.76,"vesselIDs":1},{"date":"2026-08-31","flag":"ECU","hours":2.166944444444445,"lat":-0.67,"lon":-89.3,"vesselIDs":1},{"date":"2026-09-20","flag":"ECU","hours":5,"lat":-0.77,"lon":-90.32,"vesselIDs":1},{"date":"2026-09-15","flag":"ECU","hours":4.917222222222223,"lat":-0.94,"lon":-89.38,"vesselIDs":1},{"date":"2026-09-01","flag":"ECU","hours":0.3336111111111111,"lat":-0.77,"lon":-90.37,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":1.2174999999999998,"lat":-1.92,"lon":-92.21,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":1.4388888888888889,"lat":-1.78,"lon":-92.28,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.856111111111111,"lat":-1.74,"lon":-92.22,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":1.0791666666666666,"lat":-1.53,"lon":-92.52,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":1.0075,"lat":-1.59,"lon":-92.51,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":0.995,"lat":-0.3,"lon":-90.34,"vesselIDs":1},{"date":"2026-08-31","flag":"ECU","hours":0.7505555555555555,"lat":-0.99,"lon":-90.88,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":0.9908333333333332,"lat":-1.17,"lon":-92.51,"vesselIDs":1},{"date":"2026-09-06","flag":"ECU","hours":0.850277777777778,"lat":0.76,"lon":-90.74,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":1.193888888888889,"lat":-0.33,"lon":-90.31,"vesselIDs":1},{"date":"2026-09-03","flag":"ECU","hours":1.3333333333333335,"lat":-1.05,"lon":-90.9,"vesselIDs":1},{"date":"2026-08-31","flag":"ECU","hours":0.24972222222222223,"lat":-0.94,"lon":-90.88,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":0.9922222222222221,"lat":-1.54,"lon":-92.51,"vesselIDs":1},{"date":"2026-09-05","flag":"ECU","hours":0.9983333333333334,"lat":0.76,"lon":-90.75,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":2.8341666666666665,"lat":-0.77,"lon":-90.37,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":1.4141666666666668,"lat":-1.26,"lon":-92.57,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.9597222222222221,"lat":-1.73,"lon":-92.23,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.9891666666666667,"lat":-1.08,"lon":-90.21,"vesselIDs":1},{"date":"2026-09-04","flag":"ECU","hours":1.8794444444444445,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":0.8369444444444445,"lat":-1.26,"lon":-92.56,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.7883333333333333,"lat":-1.93,"lon":-92.14,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.5144444444444444,"lat":-0.55,"lon":-90.86,"vesselIDs":1},{"date":"2026-09-03","flag":"ECU","hours":1.25,"lat":-1.02,"lon":-90.86,"vesselIDs":1},{"date":"2026-09-05","flag":"ECU","hours":0.13305555555555557,"lat":0.73,"lon":-90.77,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":0.9130555555555555,"lat":-1.62,"lon":-92.42,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":1.0230555555555556,"lat":-1.5,"lon":-92.57,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.6144444444444446,"lat":-0.54,"lon":-90.86,"vesselIDs":1},{"date":"2026-09-01","flag":"ECU","hours":1.8333333333333335,"lat":-0.78,"lon":-90.35,"vesselIDs":1},{"date":"2026-09-18","flag":"ECU","hours":0.8208333333333333,"lat":-0.85,"lon":-90.74,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.16777777777777778,"lat":-0.82,"lon":-90.65,"vesselIDs":1},{"date":"2026-09-18","flag":"ECU","hours":0.5011111111111111,"lat":-0.81,"lon":-90.66,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":0.990555555555556,"lat":-1.56,"lon":-92.53,"vesselIDs":1},{"date":"2026-09-18","flag":"ECU","hours":0.5491666666666667,"lat":-0.86,"lon":-90.78,"vesselIDs":1},{"date":"2026-09-01","flag":"ECU","hours":1.1666666666666667,"lat":-0.78,"lon":-90.34,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":1.3030555555555554,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":0.9738888888888889,"lat":-1.11,"lon":-90.92,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":1.75,"lat":-0.78,"lon":-90.36,"vesselIDs":1},{"date":"2026-09-08","flag":"ECU","hours":2.508055555555556,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-08-31","flag":"ECU","hours":1.9569444444444446,"lat":-1.02,"lon":-90.73,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":2.0127777777777776,"lat":-0.32,"lon":-90.31,"vesselIDs":1},{"date":"2026-09-10","flag":"ECU","hours":1.0452777777777778,"lat":-1.54,"lon":-92.58,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.6675,"lat":-0.66,"lon":-89.27,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":1.528611111111111,"lat":-1.46,"lon":-92.53,"vesselIDs":1},{"date":"2026-09-02","flag":"ECU","hours":1.9988888888888887,"lat":-0.66,"lon":-89.32,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":1.068888888888889,"lat":-1.98,"lon":-92.13,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":0.9619444444444444,"lat":-1.1,"lon":-90.91,"vesselIDs":1},{"date":"2026-09-21","flag":"ECU","hours":0.41944444444444445,"lat":-1.13,"lon":-89.89,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":1.5569444444444445,"lat":-1.78,"lon":-92.15,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":2.1733333333333333,"lat":-1.01,"lon":-89.6,"vesselIDs":1},{"date":"2026-09-07","flag":"ECU","hours":0.9833333333333334,"lat":0.74,"lon":-90.77,"vesselIDs":1},{"date":"2026-09-15","flag":"ECU","hours":1.1308333333333334,"lat":-1.79,"lon":-92.13,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":1.0622222222222222,"lat":-1.77,"lon":-92.3,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":1.0830555555555557,"lat":-1.01,"lon":-90.87,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":0.8638888888888888,"lat":-2,"lon":-92.15,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.9913888888888889,"lat":-1.86,"lon":-92.13,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":0.9183333333333333,"lat":-0.3,"lon":-90.35,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":10.418055555555556,"lat":-0.38,"lon":-90.96,"vesselIDs":1},{"date":"2026-09-09","flag":"ECU","hours":1.8333333333333333,"lat":-0.77,"lon":-90.33,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":0.525,"lat":-1.21,"lon":-92.48,"vesselIDs":1},{"date":"2026-09-21","flag":"ECU","hours":0.9980555555555556,"lat":-1.13,"lon":-89.9,"vesselIDs":1},{"date":"2026-09-11","flag":"ECU","hours":1.0652777777777778,"lat":-1.65,"lon":-92.46,"vesselIDs":1},{"date":"2026-09-03","flag":"ECU","hours":0.6602777777777777,"lat":-1.03,"lon":-90.87,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":1.4149999999999998,"lat":-0.29,"lon":-90.33,"vesselIDs":1},{"date":"2026-08-31","flag":"ECU","hours":0.3219444444444445,"lat":-0.85,"lon":-90.58,"vesselIDs":1},{"date":"2026-09-13","flag":"ECU","hours":2.247222222222222,"lat":-1.52,"lon":-92.49,"vesselIDs":1},{"date":"2026-09-18","flag":"ECU","hours":2.9927777777777775,"lat":-0.86,"lon":-90.69,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":0.6944444444444445,"lat":-0.34,"lon":-90.29,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.2147222222222222,"lat":-1.07,"lon":-90.21,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":1.2491666666666665,"lat":-1.73,"lon":-92.24,"vesselIDs":1},{"date":"2026-09-01","flag":"ECU","hours":0.08333333333333333,"lat":-0.78,"lon":-90.36,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.8175,"lat":-1.76,"lon":-92.19,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.28972222222222227,"lat":-0.61,"lon":-90.85,"vesselIDs":1},{"date":"2026-09-08","flag":"ECU","hours":0.2513888888888889,"lat":-0.93,"lon":-89.4,"vesselIDs":1}]}]} \ No newline at end of file diff --git a/test/fixtures/gfw-fishing-galapagos-gear-2026-09-27.json b/test/fixtures/gfw-fishing-galapagos-gear-2026-09-27.json new file mode 100644 index 0000000..05d6016 --- /dev/null +++ b/test/fixtures/gfw-fishing-galapagos-gear-2026-09-27.json @@ -0,0 +1 @@ +{"total":1,"limit":null,"offset":null,"nextOffset":null,"metadata":{},"entries":[{"public-global-fishing-effort:v4.0":[{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":3.1525,"lat":-1.4,"lon":-92.6,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":3.310277777777778,"lat":-0.8,"lon":-90.7,"vesselIDs":2},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":2.0824999999999996,"lat":-1,"lon":-89.4,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":7.997222222222224,"lat":-1.1,"lon":-90.9,"vesselIDs":2},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":27.04,"lat":-0.3,"lon":-90.3,"vesselIDs":2},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":1.7774999999999999,"lat":-1.3,"lon":-92.4,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":11.312777777777777,"lat":-1.5,"lon":-92.5,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":12.57888888888889,"lat":0.7,"lon":-90.8,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":6.128333333333333,"lat":-1.3,"lon":-92.6,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":0.8397222222222223,"lat":-1,"lon":-90.8,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":10.204166666666666,"lat":-1.7,"lon":-92.3,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":3.6144444444444446,"lat":-2,"lon":-92.1,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":13.509166666666665,"lat":-1,"lon":-89.6,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":1.988611111111111,"lat":-1.4,"lon":-92.5,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":2.101111111111111,"lat":-1.3,"lon":-92.5,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":56.51583333333333,"lat":-0.8,"lon":-90.4,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":6.248055555555556,"lat":-1.5,"lon":-92.6,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":0.1502777777777778,"lat":-0.3,"lon":-90.6,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":1.9863888888888888,"lat":-2,"lon":-92.2,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":24.249444444444443,"lat":-0.8,"lon":-90.3,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":10.418055555555556,"lat":-0.4,"lon":-91,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"set_longlines","hours":1.3325,"lat":-0.6,"lon":-90.1,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":1.6408333333333334,"lat":-1.2,"lon":-92.6,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":1.1952777777777779,"lat":-0.4,"lon":-90.3,"vesselIDs":2},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":0.8983333333333335,"lat":-0.4,"lon":-90.4,"vesselIDs":2},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":3.982222222222222,"lat":-1,"lon":-90.7,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"inconclusive","hours":2.8497222222222223,"lat":2,"lon":-88.8,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":8.206111111111111,"lat":-1.2,"lon":-92.5,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":8.300833333333333,"lat":0.7,"lon":-90.7,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":0.5663888888888888,"lat":-0.3,"lon":-90.5,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":5.050833333333334,"lat":-0.4,"lon":-90.6,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":0.8872222222222222,"lat":-1.4,"lon":-92.7,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":40.481944444444444,"lat":-1,"lon":-90.9,"vesselIDs":2},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":1.7119444444444443,"lat":-1.3,"lon":-92.7,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":0.5230555555555556,"lat":-0.6,"lon":-90.8,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"set_longlines","hours":1.2038888888888888,"lat":-1.1,"lon":-90.2,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":17.978611111111114,"lat":-0.8,"lon":-89.5,"vesselIDs":2},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":8.755833333333333,"lat":-1.8,"lon":-92.3,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":2.171388888888889,"lat":-1.1,"lon":-89.9,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":5.226944444444444,"lat":-0.4,"lon":-90.5,"vesselIDs":2},{"date":"2026-08-28,2026-09-27","geartype":"inconclusive","hours":6.26138888888889,"lat":-1.9,"lon":-91.1,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":0.1663888888888889,"lat":-0.5,"lon":-90.5,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":42.400555555555556,"lat":-0.7,"lon":-90.3,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":5.666388888888889,"lat":-0.7,"lon":-89.4,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":0.24972222222222223,"lat":-0.9,"lon":-90.9,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":2.8072222222222223,"lat":-1.6,"lon":-92.6,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"inconclusive","hours":0.3980555555555555,"lat":2,"lon":-88.9,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":10.061944444444444,"lat":-1.9,"lon":-92.2,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"set_longlines","hours":0.3219444444444445,"lat":-0.9,"lon":-90.6,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":1.2844444444444445,"lat":-2.1,"lon":-92.2,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":4.088055555555556,"lat":-1.6,"lon":-92.4,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":1.615277777777778,"lat":0.8,"lon":-90.7,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":8.171944444444444,"lat":-1.8,"lon":-92.2,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"set_longlines","hours":2.0922222222222224,"lat":-1,"lon":-90.7,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":6.336388888888889,"lat":-1.6,"lon":-92.5,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":2.131111111111111,"lat":-0.5,"lon":-90.9,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":4.1691666666666665,"lat":-0.9,"lon":-90.7,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":5.170555555555555,"lat":-1.2,"lon":-89.9,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":7.180555555555555,"lat":-0.2,"lon":-90.6,"vesselIDs":2},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":3.083888888888889,"lat":0.6,"lon":-90.7,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":0.6166666666666667,"lat":-0.5,"lon":-90.4,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"set_longlines","hours":0.35750000000000004,"lat":-0.8,"lon":-90.6,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"inconclusive","hours":0.3475,"lat":2,"lon":-88.7,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"set_longlines","hours":0.17583333333333334,"lat":-0.8,"lon":-90.7,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":2.3575,"lat":0.8,"lon":-90.8,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":2.021111111111111,"lat":-1.7,"lon":-92.5,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":5.472222222222222,"lat":-1.7,"lon":-92.2,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":2.0141666666666667,"lat":-2.1,"lon":-92.1,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":4.181111111111111,"lat":-1.8,"lon":-92.1,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":14.915,"lat":-0.9,"lon":-89.4,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":4.775555555555556,"lat":-1.9,"lon":-92.1,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"set_longlines","hours":22.891666666666662,"lat":-0.5,"lon":-90.9,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":1.0850000000000002,"lat":-0,"lon":-91.2,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"drifting_longlines","hours":1.5241666666666667,"lat":-1.7,"lon":-92.4,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":0.3880555555555556,"lat":1.4,"lon":-91.8,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":5.082777777777777,"lat":-0.9,"lon":-89.9,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":0.5491666666666667,"lat":-0.9,"lon":-90.8,"vesselIDs":1},{"date":"2026-08-28,2026-09-27","geartype":"fishing","hours":17.08888888888889,"lat":-0.7,"lon":-89.3,"vesselIDs":1}]}]} \ No newline at end of file diff --git a/test/fixtures/gfw-fishing-galapagos-mpa-2026-09-27.json b/test/fixtures/gfw-fishing-galapagos-mpa-2026-09-27.json new file mode 100644 index 0000000..a439c75 --- /dev/null +++ b/test/fixtures/gfw-fishing-galapagos-mpa-2026-09-27.json @@ -0,0 +1 @@ +{"total":1,"limit":null,"offset":null,"nextOffset":null,"metadata":{},"entries":[{"public-global-fishing-effort:v4.0":[{"date":"2026-09-10","flag":"ECU","hours":3.833611111111111,"lat":-0.7,"lon":-89.42,"vesselIDs":1},{"date":"2026-09-05","flag":"ECU","hours":0.7649999999999999,"lat":0.76,"lon":-90.74,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.7055555555555555,"lat":-0.32,"lon":-90.34,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.3880555555555556,"lat":1.38,"lon":-91.81,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":0.1661111111111111,"lat":-0.78,"lon":-89.53,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":0.7105555555555556,"lat":-0.37,"lon":-90.28,"vesselIDs":1},{"date":"2026-09-10","flag":"ECU","hours":2.153888888888889,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-21","flag":"ECU","hours":0.5,"lat":-0.75,"lon":-90.31,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":2.250277777777778,"lat":-1.02,"lon":-89.59,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":1.0002777777777778,"lat":-0.77,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":0.75,"lat":-0.71,"lon":-89.45,"vesselIDs":1},{"date":"2026-09-19","flag":"ECU","hours":0.16722222222222222,"lat":-0.75,"lon":-90.27,"vesselIDs":1},{"date":"2026-09-07","flag":"ECU","hours":1.9919444444444445,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":1.1130555555555555,"lat":-0.32,"lon":-90.31,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":0.33944444444444444,"lat":-0.96,"lon":-89.59,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":1.1897222222222223,"lat":-0.34,"lon":-90.33,"vesselIDs":1},{"date":"2026-09-19","flag":"ECU","hours":2.666944444444445,"lat":-0.75,"lon":-90.26,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.8872222222222224,"lat":-0.31,"lon":-90.31,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":1.1616666666666666,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-21","flag":"ECU","hours":0.7538888888888888,"lat":-1.14,"lon":-89.89,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":1.568888888888889,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-08","flag":"ECU","hours":1.5008333333333335,"lat":-0.95,"lon":-89.38,"vesselIDs":1},{"date":"2026-09-21","flag":"ECU","hours":4.421666666666666,"lat":-1.2,"lon":-89.85,"vesselIDs":1},{"date":"2026-09-07","flag":"ECU","hours":1.0758333333333336,"lat":0.75,"lon":-90.76,"vesselIDs":1},{"date":"2026-09-06","flag":"ECU","hours":1.2341666666666666,"lat":0.76,"lon":-90.75,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.8541666666666669,"lat":-0.28,"lon":-90.35,"vesselIDs":1},{"date":"2026-09-09","flag":"ECU","hours":0.39888888888888885,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.6658333333333334,"lat":-0.67,"lon":-89.27,"vesselIDs":1},{"date":"2026-09-15","flag":"ECU","hours":2.456111111111111,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-06","flag":"ECU","hours":0.9925000000000002,"lat":0.75,"lon":-90.73,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":3.495,"lat":-1.01,"lon":-89.6,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":3.915833333333333,"lat":-0.95,"lon":-89.38,"vesselIDs":1},{"date":"2026-09-03","flag":"ECU","hours":3.582222222222222,"lat":-0.66,"lon":-89.31,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":1.017222222222222,"lat":-0.28,"lon":-90.34,"vesselIDs":1},{"date":"2026-09-02","flag":"ECU","hours":1.5825,"lat":-0.65,"lon":-89.32,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":0.9669444444444444,"lat":-0.33,"lon":-90.33,"vesselIDs":1},{"date":"2026-09-10","flag":"ECU","hours":0.9075000000000003,"lat":0.59,"lon":-90.72,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":2.0824999999999996,"lat":-0.96,"lon":-89.39,"vesselIDs":1},{"date":"2026-09-20","flag":"ECU","hours":0.75,"lat":-0.76,"lon":-90.3,"vesselIDs":1},{"date":"2026-08-29","flag":"ECU","hours":0.6822222222222224,"lat":-0.39,"lon":-90.35,"vesselIDs":1},{"date":"2026-09-10","flag":"ECU","hours":1.0508333333333333,"lat":0.56,"lon":-90.72,"vesselIDs":1},{"date":"2026-08-31","flag":"ECU","hours":1.0852777777777778,"lat":-0.66,"lon":-89.3,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":18.209444444444443,"lat":-0.75,"lon":-90.31,"vesselIDs":1},{"date":"2026-09-01","flag":"ECU","hours":0.8380555555555556,"lat":-0.66,"lon":-89.3,"vesselIDs":1},{"date":"2026-09-12","flag":"ECU","hours":1.3902777777777777,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-20","flag":"ECU","hours":1.3325,"lat":-0.58,"lon":-90.1,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.08416666666666667,"lat":-0.93,"lon":-89.38,"vesselIDs":1},{"date":"2026-09-05","flag":"ECU","hours":2.010277777777778,"lat":0.75,"lon":-90.76,"vesselIDs":1},{"date":"2026-09-06","flag":"ECU","hours":1.9925000000000002,"lat":0.75,"lon":-90.74,"vesselIDs":1},{"date":"2026-09-06","flag":"ECU","hours":0.9999999999999998,"lat":0.74,"lon":-90.73,"vesselIDs":1},{"date":"2026-09-06","flag":"ECU","hours":0.025833333333333333,"lat":0.71,"lon":-90.74,"vesselIDs":1},{"date":"2026-09-08","flag":"ECU","hours":3.9122222222222223,"lat":-0.94,"lon":-89.38,"vesselIDs":1},{"date":"2026-09-10","flag":"ECU","hours":1.1255555555555556,"lat":0.58,"lon":-90.72,"vesselIDs":1},{"date":"2026-09-07","flag":"ECU","hours":0.45,"lat":0.73,"lon":-90.75,"vesselIDs":1},{"date":"2026-09-17","flag":"ECU","hours":5.082777777777777,"lat":-0.88,"lon":-89.94,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":1.0827777777777778,"lat":-0.7,"lon":-89.45,"vesselIDs":1},{"date":"2026-09-06","flag":"ECU","hours":1.0155555555555558,"lat":0.72,"lon":-90.74,"vesselIDs":1},{"date":"2026-08-30","flag":"ECU","hours":0.1775,"lat":-0.37,"lon":-90.29,"vesselIDs":1},{"date":"2026-09-19","flag":"ECU","hours":0.9155555555555557,"lat":-0.75,"lon":-90.31,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":1.0191666666666666,"lat":-0.27,"lon":-90.35,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":1.403888888888889,"lat":-0.34,"lon":-90.33,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":2.7477777777777774,"lat":-1.02,"lon":-89.6,"vesselIDs":1},{"date":"2026-08-29","flag":"ECU","hours":0.30722222222222223,"lat":-0.35,"lon":-90.29,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":0.9902777777777777,"lat":-0.33,"lon":-90.3,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.4138888888888888,"lat":-0.33,"lon":-90.34,"vesselIDs":1},{"date":"2026-09-05","flag":"ECU","hours":2.275,"lat":0.75,"lon":-90.73,"vesselIDs":1},{"date":"2026-09-21","flag":"ECU","hours":0.7488888888888889,"lat":-1.18,"lon":-89.86,"vesselIDs":1},{"date":"2026-09-01","flag":"ECU","hours":0.7494444444444444,"lat":-0.67,"lon":-89.31,"vesselIDs":1},{"date":"2026-08-31","flag":"ECU","hours":2.247777777777778,"lat":-0.66,"lon":-89.26,"vesselIDs":1},{"date":"2026-09-06","flag":"ECU","hours":0.9994444444444445,"lat":0.74,"lon":-90.74,"vesselIDs":1},{"date":"2026-09-16","flag":"ECU","hours":0.33333333333333337,"lat":-0.95,"lon":-89.4,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.9958333333333335,"lat":-0.27,"lon":-90.34,"vesselIDs":1},{"date":"2026-08-29","flag":"ECU","hours":6.417777777777777,"lat":-0.34,"lon":-90.29,"vesselIDs":1},{"date":"2026-09-05","flag":"ECU","hours":2.0327777777777776,"lat":0.74,"lon":-90.76,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":2.5033333333333334,"lat":-1.02,"lon":-89.59,"vesselIDs":1},{"date":"2026-09-20","flag":"ECU","hours":20.10861111111111,"lat":-0.75,"lon":-90.31,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.9958333333333337,"lat":-0.29,"lon":-90.33,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":0.84,"lat":-0.31,"lon":-90.31,"vesselIDs":1},{"date":"2026-09-01","flag":"ECU","hours":1.5044444444444443,"lat":-0.67,"lon":-89.3,"vesselIDs":1},{"date":"2026-09-07","flag":"ECU","hours":6.018611111111111,"lat":0.74,"lon":-90.76,"vesselIDs":1},{"date":"2026-08-31","flag":"ECU","hours":2.166944444444445,"lat":-0.67,"lon":-89.3,"vesselIDs":1},{"date":"2026-09-15","flag":"ECU","hours":4.917222222222223,"lat":-0.94,"lon":-89.38,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":0.995,"lat":-0.3,"lon":-90.34,"vesselIDs":1},{"date":"2026-09-06","flag":"ECU","hours":0.850277777777778,"lat":0.76,"lon":-90.74,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":1.193888888888889,"lat":-0.33,"lon":-90.31,"vesselIDs":1},{"date":"2026-09-05","flag":"ECU","hours":0.9983333333333334,"lat":0.76,"lon":-90.75,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.9891666666666667,"lat":-1.08,"lon":-90.21,"vesselIDs":1},{"date":"2026-09-04","flag":"ECU","hours":1.8794444444444445,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-05","flag":"ECU","hours":0.13305555555555557,"lat":0.73,"lon":-90.77,"vesselIDs":1},{"date":"2026-09-14","flag":"ECU","hours":1.3030555555555554,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-08","flag":"ECU","hours":2.508055555555556,"lat":-0.78,"lon":-89.52,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":2.0127777777777776,"lat":-0.32,"lon":-90.31,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.6675,"lat":-0.66,"lon":-89.27,"vesselIDs":1},{"date":"2026-09-02","flag":"ECU","hours":1.9988888888888887,"lat":-0.66,"lon":-89.32,"vesselIDs":1},{"date":"2026-09-21","flag":"ECU","hours":0.41944444444444445,"lat":-1.13,"lon":-89.89,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":2.1733333333333333,"lat":-1.01,"lon":-89.6,"vesselIDs":1},{"date":"2026-09-07","flag":"ECU","hours":0.9833333333333334,"lat":0.74,"lon":-90.77,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":0.9183333333333333,"lat":-0.3,"lon":-90.35,"vesselIDs":1},{"date":"2026-09-21","flag":"ECU","hours":0.9980555555555556,"lat":-1.13,"lon":-89.9,"vesselIDs":1},{"date":"2026-09-23","flag":"ECU","hours":1.4149999999999998,"lat":-0.29,"lon":-90.33,"vesselIDs":1},{"date":"2026-09-22","flag":"ECU","hours":0.6944444444444445,"lat":-0.34,"lon":-90.29,"vesselIDs":1},{"date":"2026-08-28","flag":"ECU","hours":0.2147222222222222,"lat":-1.07,"lon":-90.21,"vesselIDs":1},{"date":"2026-09-08","flag":"ECU","hours":0.2513888888888889,"lat":-0.93,"lon":-89.4,"vesselIDs":1}]}]} \ No newline at end of file diff --git a/test/fixtures/imp-air-delhi-15d-2026-09-27.json b/test/fixtures/imp-air-delhi-15d-2026-09-27.json new file mode 100644 index 0000000..f63d0e4 --- /dev/null +++ b/test/fixtures/imp-air-delhi-15d-2026-09-27.json @@ -0,0 +1,85 @@ +{ + "source": "CAMS via Open-Meteo.com (CC-BY 4.0)", + "pm25Daily": [ + { + "t": "2026-09-12", + "v": 27.1, + "hours": 24 + }, + { + "t": "2026-09-13", + "v": 25.2, + "hours": 24 + }, + { + "t": "2026-09-14", + "v": 37.5, + "hours": 24 + }, + { + "t": "2026-09-15", + "v": 56.8, + "hours": 24 + }, + { + "t": "2026-09-16", + "v": 72.7, + "hours": 24 + }, + { + "t": "2026-09-17", + "v": 41.9, + "hours": 24 + }, + { + "t": "2026-09-18", + "v": 37.4, + "hours": 24 + }, + { + "t": "2026-09-19", + "v": 72.9, + "hours": 24 + }, + { + "t": "2026-09-20", + "v": 72.5, + "hours": 24 + }, + { + "t": "2026-09-21", + "v": 73.3, + "hours": 24 + }, + { + "t": "2026-09-22", + "v": 62.3, + "hours": 24 + }, + { + "t": "2026-09-23", + "v": 71.8, + "hours": 24 + }, + { + "t": "2026-09-24", + "v": 43.3, + "hours": 24 + }, + { + "t": "2026-09-25", + "v": 39.8, + "hours": 24 + }, + { + "t": "2026-09-26", + "v": 48.8, + "hours": 24 + }, + { + "t": "2026-09-27", + "v": 49.1, + "hours": 9 + } + ] +} diff --git a/test/fixtures/imp-coral-galapagos-2026-09-25.json b/test/fixtures/imp-coral-galapagos-2026-09-25.json new file mode 100644 index 0000000..f22dbdd --- /dev/null +++ b/test/fixtures/imp-coral-galapagos-2026-09-25.json @@ -0,0 +1,352 @@ +{ + "source": "NOAA Coral Reef Watch CoralTemp v3.1 daily 5 km (NOAA_DHW via CoastWatch/PacIOOS ERDDAP) — free to use; credit NOAA CRW", + "gridCell": { + "lat": -0.975, + "lon": -91.975 + }, + "latest": { + "date": "2026-09-25", + "dhw": 0.44, + "sst": 26.71, + "sstAnomaly": 6.7, + "alertLevel": 1, + "alert": "Bleaching Watch", + "reading": "accumulating heat stress — bleaching possible" + }, + "window": { + "days": 90, + "from": "2026-06-27", + "to": "2026-09-25", + "strideDays": 2, + "earliestAvailable": "1985-04-01" + }, + "peak": { + "date": "2026-07-31", + "dhw": 0.45, + "alert": "Bleaching Watch" + }, + "series": [ + { + "t": "2026-06-27", + "dhw": 0.15, + "sstAnomaly": 4.55, + "baa": 1, + "sst": 26.03 + }, + { + "t": "2026-06-29", + "dhw": 0.15, + "sstAnomaly": 4.66, + "baa": 1, + "sst": 26.05 + }, + { + "t": "2026-07-01", + "dhw": 0.15, + "sstAnomaly": 4.75, + "baa": 1, + "sst": 26.05 + }, + { + "t": "2026-07-03", + "dhw": 0.15, + "sstAnomaly": 4.56, + "baa": 0, + "sst": 25.77 + }, + { + "t": "2026-07-05", + "dhw": 0.15, + "sstAnomaly": 4.49, + "baa": 0, + "sst": 25.61 + }, + { + "t": "2026-07-07", + "dhw": 0.15, + "sstAnomaly": 4.57, + "baa": 0, + "sst": 25.6 + }, + { + "t": "2026-07-09", + "dhw": 0.15, + "sstAnomaly": 4.34, + "baa": 0, + "sst": 25.27 + }, + { + "t": "2026-07-11", + "dhw": 0.15, + "sstAnomaly": 4.88, + "baa": 0, + "sst": 25.72 + }, + { + "t": "2026-07-13", + "dhw": 0.15, + "sstAnomaly": 4.92, + "baa": 0, + "sst": 25.67 + }, + { + "t": "2026-07-15", + "dhw": 0.15, + "sstAnomaly": 4.81, + "baa": 0, + "sst": 25.47 + }, + { + "t": "2026-07-17", + "dhw": 0.15, + "sstAnomaly": 4.92, + "baa": 0, + "sst": 25.52 + }, + { + "t": "2026-07-19", + "dhw": 0.15, + "sstAnomaly": 4.99, + "baa": 0, + "sst": 25.52 + }, + { + "t": "2026-07-21", + "dhw": 0.15, + "sstAnomaly": 4.74, + "baa": 0, + "sst": 25.21 + }, + { + "t": "2026-07-23", + "dhw": 0.15, + "sstAnomaly": 4.62, + "baa": 0, + "sst": 25.03 + }, + { + "t": "2026-07-25", + "dhw": 0.15, + "sstAnomaly": 5.32, + "baa": 0, + "sst": 25.66 + }, + { + "t": "2026-07-27", + "dhw": 0.15, + "sstAnomaly": 5.22, + "baa": 0, + "sst": 25.5 + }, + { + "t": "2026-07-29", + "dhw": 0.29, + "sstAnomaly": 6.58, + "baa": 2, + "sst": 26.8 + }, + { + "t": "2026-07-31", + "dhw": 0.45, + "sstAnomaly": 6.44, + "baa": 1, + "sst": 26.59 + }, + { + "t": "2026-08-02", + "dhw": 0.45, + "sstAnomaly": 5.81, + "baa": 1, + "sst": 25.9 + }, + { + "t": "2026-08-04", + "dhw": 0.45, + "sstAnomaly": 5.51, + "baa": 0, + "sst": 25.54 + }, + { + "t": "2026-08-06", + "dhw": 0.45, + "sstAnomaly": 5.2, + "baa": 0, + "sst": 25.16 + }, + { + "t": "2026-08-08", + "dhw": 0.45, + "sstAnomaly": 4.6, + "baa": 0, + "sst": 24.5 + }, + { + "t": "2026-08-10", + "dhw": 0.45, + "sstAnomaly": 4.83, + "baa": 0, + "sst": 24.67 + }, + { + "t": "2026-08-12", + "dhw": 0.45, + "sstAnomaly": 5.57, + "baa": 0, + "sst": 25.34 + }, + { + "t": "2026-08-14", + "dhw": 0.45, + "sstAnomaly": 5.48, + "baa": 0, + "sst": 25.19 + }, + { + "t": "2026-08-16", + "dhw": 0.45, + "sstAnomaly": 5.88, + "baa": 0, + "sst": 25.56 + }, + { + "t": "2026-08-18", + "dhw": 0.45, + "sstAnomaly": 5.56, + "baa": 0, + "sst": 25.25 + }, + { + "t": "2026-08-20", + "dhw": 0.45, + "sstAnomaly": 5.54, + "baa": 0, + "sst": 25.23 + }, + { + "t": "2026-08-22", + "dhw": 0.45, + "sstAnomaly": 5.71, + "baa": 0, + "sst": 25.41 + }, + { + "t": "2026-08-24", + "dhw": 0.45, + "sstAnomaly": 5.56, + "baa": 0, + "sst": 25.26 + }, + { + "t": "2026-08-26", + "dhw": 0.3, + "sstAnomaly": 5.77, + "baa": 0, + "sst": 25.48 + }, + { + "t": "2026-08-28", + "dhw": 0.3, + "sstAnomaly": 5.99, + "baa": 0, + "sst": 25.7 + }, + { + "t": "2026-08-30", + "dhw": 0.3, + "sstAnomaly": 5.87, + "baa": 0, + "sst": 25.59 + }, + { + "t": "2026-09-01", + "dhw": 0.3, + "sstAnomaly": 6.28, + "baa": 1, + "sst": 26 + }, + { + "t": "2026-09-03", + "dhw": 0.3, + "sstAnomaly": 6.08, + "baa": 1, + "sst": 25.81 + }, + { + "t": "2026-09-05", + "dhw": 0.3, + "sstAnomaly": 6.17, + "baa": 1, + "sst": 25.9 + }, + { + "t": "2026-09-07", + "dhw": 0.3, + "sstAnomaly": 6.16, + "baa": 1, + "sst": 25.9 + }, + { + "t": "2026-09-09", + "dhw": 0.3, + "sstAnomaly": 6.38, + "baa": 1, + "sst": 26.12 + }, + { + "t": "2026-09-11", + "dhw": 0.3, + "sstAnomaly": 6.69, + "baa": 1, + "sst": 26.44 + }, + { + "t": "2026-09-13", + "dhw": 0.3, + "sstAnomaly": 6.57, + "baa": 1, + "sst": 26.32 + }, + { + "t": "2026-09-15", + "dhw": 0.3, + "sstAnomaly": 6.39, + "baa": 1, + "sst": 26.15 + }, + { + "t": "2026-09-17", + "dhw": 0.3, + "sstAnomaly": 6.07, + "baa": 1, + "sst": 25.88 + }, + { + "t": "2026-09-19", + "dhw": 0.3, + "sstAnomaly": 6.49, + "baa": 1, + "sst": 26.35 + }, + { + "t": "2026-09-21", + "dhw": 0.3, + "sstAnomaly": 6.45, + "baa": 1, + "sst": 26.36 + }, + { + "t": "2026-09-23", + "dhw": 0.3, + "sstAnomaly": 6.6, + "baa": 1, + "sst": 26.56 + }, + { + "t": "2026-09-25", + "dhw": 0.44, + "sstAnomaly": 6.7, + "baa": 1, + "sst": 26.71 + } + ] +} diff --git a/test/fixtures/imp-fires-pacaas-novos.json b/test/fixtures/imp-fires-pacaas-novos.json new file mode 100644 index 0000000..490a4a9 --- /dev/null +++ b/test/fixtures/imp-fires-pacaas-novos.json @@ -0,0 +1,402 @@ +{ + "_recorded": "fires_in live 2026-09-27, Pacaás Novos bbox, VIIRS_NOAA21_NRT, dayRange 5", + "now_2026-09-23": { + "count": 5, + "dashboard": "dashboard offline", + "source": "VIIRS_NOAA21_NRT", + "fires": [ + { + "lat": -11.38916, + "lon": -63.41916, + "brightness": 335.95, + "confidence": "nominal", + "acqDate": "2026-09-24", + "acqTime": "1826", + "frp": 3.87, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.38844, + "lon": -63.41542, + "brightness": 331.82, + "confidence": "nominal", + "acqDate": "2026-09-24", + "acqTime": "1826", + "frp": 3.87, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.10739, + "lon": -62.64053, + "brightness": 338.37, + "confidence": "nominal", + "acqDate": "2026-09-25", + "acqTime": "1806", + "frp": 7.7, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.16254, + "lon": -62.86516, + "brightness": 299.05, + "confidence": "nominal", + "acqDate": "2026-09-27", + "acqTime": "453", + "frp": 0.46, + "satellite": "N21", + "daynight": "N" + }, + { + "lat": -11.16193, + "lon": -62.86835, + "brightness": 301.15, + "confidence": "nominal", + "acqDate": "2026-09-27", + "acqTime": "453", + "frp": 0.46, + "satellite": "N21", + "daynight": "N" + } + ] + }, + "yearAgo_2025-09-08": { + "count": 30, + "dashboard": "dashboard offline", + "source": "VIIRS_NOAA21_NRT", + "fires": [ + { + "lat": -11.39074, + "lon": -63.28289, + "brightness": 339.65, + "confidence": "nominal", + "acqDate": "2025-09-08", + "acqTime": "1728", + "frp": 13.61, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.31132, + "lon": -63.32183, + "brightness": 337.64, + "confidence": "nominal", + "acqDate": "2025-09-08", + "acqTime": "1728", + "frp": 8.02, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.30884, + "lon": -63.33192, + "brightness": 337.94, + "confidence": "nominal", + "acqDate": "2025-09-08", + "acqTime": "1728", + "frp": 12.22, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.30817, + "lon": -63.32714, + "brightness": 347.55, + "confidence": "nominal", + "acqDate": "2025-09-08", + "acqTime": "1728", + "frp": 8.02, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.30749, + "lon": -63.32235, + "brightness": 334.46, + "confidence": "nominal", + "acqDate": "2025-09-08", + "acqTime": "1728", + "frp": 8.02, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -10.62699, + "lon": -63.51736, + "brightness": 337.36, + "confidence": "nominal", + "acqDate": "2025-09-08", + "acqTime": "1728", + "frp": 7.16, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -10.62634, + "lon": -63.51266, + "brightness": 339.7, + "confidence": "nominal", + "acqDate": "2025-09-08", + "acqTime": "1728", + "frp": 7.16, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.38677, + "lon": -63.33571, + "brightness": 338.49, + "confidence": "nominal", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 5.73, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.38554, + "lon": -63.32812, + "brightness": 335.64, + "confidence": "nominal", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 10.76, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.38396, + "lon": -63.34006, + "brightness": 334.64, + "confidence": "low", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 5.73, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.38334, + "lon": -63.33628, + "brightness": 340.39, + "confidence": "nominal", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 5.73, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.38212, + "lon": -63.32869, + "brightness": 345.23, + "confidence": "nominal", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 10.76, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.38053, + "lon": -63.34063, + "brightness": 335.18, + "confidence": "low", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 9.07, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.37991, + "lon": -63.33684, + "brightness": 337.82, + "confidence": "nominal", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 9.07, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.37869, + "lon": -63.32926, + "brightness": 342.14, + "confidence": "nominal", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 133.6, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.37726, + "lon": -63.34129, + "brightness": 333.88, + "confidence": "low", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 12.85, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.3771, + "lon": -63.34119, + "brightness": 334.68, + "confidence": "low", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 9.07, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.37383, + "lon": -63.34185, + "brightness": 331.15, + "confidence": "low", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 12.85, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.37263, + "lon": -63.33426, + "brightness": 330.21, + "confidence": "low", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 74.22, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.37203, + "lon": -63.33046, + "brightness": 336.03, + "confidence": "low", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 74.22, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.3698, + "lon": -63.33862, + "brightness": 332.23, + "confidence": "nominal", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 23.8, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.3692, + "lon": -63.33483, + "brightness": 334.46, + "confidence": "low", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 40.27, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.36577, + "lon": -63.3354, + "brightness": 343.21, + "confidence": "nominal", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 40.27, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -11.02195, + "lon": -62.63457, + "brightness": 334.59, + "confidence": "nominal", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 3.28, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -10.64218, + "lon": -63.55476, + "brightness": 347.96, + "confidence": "nominal", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 28.58, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -10.63829, + "lon": -63.57458, + "brightness": 337.15, + "confidence": "nominal", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 3.31, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -10.62994, + "lon": -63.52168, + "brightness": 353.13, + "confidence": "nominal", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 7.74, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -10.62711, + "lon": -63.52605, + "brightness": 335.01, + "confidence": "low", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 7.74, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -10.62652, + "lon": -63.52226, + "brightness": 345.81, + "confidence": "nominal", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 7.74, + "satellite": "N21", + "daynight": "D" + }, + { + "lat": -10.57689, + "lon": -63.5419, + "brightness": 331.63, + "confidence": "low", + "acqDate": "2025-09-12", + "acqTime": "1754", + "frp": 2.65, + "satellite": "N21", + "daynight": "D" + } + ] + } +} diff --git a/test/fixtures/imp-flaring-rumaila-2026-09-27.json b/test/fixtures/imp-flaring-rumaila-2026-09-27.json new file mode 100644 index 0000000..3748d68 --- /dev/null +++ b/test/fixtures/imp-flaring-rumaila-2026-09-27.json @@ -0,0 +1,48 @@ +{ + "_recorded": "flaring live 2026-09-27, Rumaila bbox, NOAA-21 only: registry = days 1 with VNF; yearAgo = 30 d to 2025-09-26, vnf false (clusters/sites dropped)", + "registry": { + "window": { + "from": "2026-09-27", + "to": "2026-09-27", + "days": 1 + }, + "counts": { + "detections": 0, + "nightDetections": 0, + "hotNightDetections": 0, + "clusters": 0, + "persistentClusters": 0 + }, + "vnf": { + "available": true, + "year": 2024, + "bcmTotal": 3.201, + "sitesInBbox": 25, + "previous": { + "available": true, + "year": 2023, + "sensor": "VIIRS S-NPP", + "file": "https://eogdata.mines.edu/global_flare_data/2023_flare_summary_v20240314_npp.kml", + "sitesInBbox": 23, + "bcmTotal": 2.869 + } + } + }, + "yearAgo": { + "window": { + "from": "2025-08-28", + "to": "2025-09-26", + "days": 30 + }, + "counts": { + "detections": 2474, + "nightDetections": 1787, + "hotNightDetections": 882, + "clusters": 22, + "persistentClusters": 15 + }, + "vnf": { + "available": false + } + } +} diff --git a/test/fixtures/imp-gfw-sao-felix-2026-09-27.json b/test/fixtures/imp-gfw-sao-felix-2026-09-27.json new file mode 100644 index 0000000..3f8c784 --- /dev/null +++ b/test/fixtures/imp-gfw-sao-felix-2026-09-27.json @@ -0,0 +1,43 @@ +{ + "_recorded": "forest_alerts live 2026-09-27, São Félix do Xingu bbox, days 90, high; yearAgo = endDate 2025-09-27 (dailyCounts dropped)", + "now": { + "source": "Integrated Deforestation Alerts (GLAD-L + GLAD-S2 + RADD), UMD/GLAD and WUR, via Global Forest Watch", + "window": { + "from": "2026-06-29", + "to": "2026-09-27" + }, + "minConfidence": "high", + "alertCount": 13841, + "areaHa": 169.25, + "byConfidence": { + "high": { + "alertCount": 13272, + "areaHa": 162.29 + }, + "highest": { + "alertCount": 569, + "areaHa": 6.96 + } + } + }, + "yearAgo": { + "source": "Integrated Deforestation Alerts (GLAD-L + GLAD-S2 + RADD), UMD/GLAD and WUR, via Global Forest Watch", + "window": { + "from": "2025-06-29", + "to": "2025-09-27" + }, + "minConfidence": "high", + "alertCount": 67791, + "areaHa": 828.87, + "byConfidence": { + "high": { + "alertCount": 60773, + "areaHa": 743.07 + }, + "highest": { + "alertCount": 7018, + "areaHa": 85.81 + } + } + } +} diff --git a/test/fixtures/ind-air-delhi-2026-09-27.json b/test/fixtures/ind-air-delhi-2026-09-27.json new file mode 100644 index 0000000..d6e5066 --- /dev/null +++ b/test/fixtures/ind-air-delhi-2026-09-27.json @@ -0,0 +1,338 @@ +{ + "source": "CAMS via Open-Meteo.com (CC-BY 4.0)", + "latest": { + "pm2_5": { + "t": "2026-09-27T23:00", + "v": 39.3 + }, + "pm10": { + "t": "2026-09-27T23:00", + "v": 42.8 + }, + "ozone": { + "t": "2026-09-27T23:00", + "v": 9 + }, + "nitrogen_dioxide": { + "t": "2026-09-27T23:00", + "v": 45 + }, + "us_aqi": { + "t": "2026-09-27T23:00", + "v": 102 + } + }, + "units": { + "pm2_5": "μg/m³", + "pm10": "μg/m³", + "ozone": "μg/m³", + "nitrogen_dioxide": "μg/m³", + "us_aqi": "USAQI" + }, + "summary": "Air quality at (28.61, 77.21): US AQI 102, PM2.5 39.3 µg/m³ (2026-09-27T23:00). ⚠️ PM2.5 39.3 µg/m³ exceeds the WHO 24h guideline (15).", + "pm25Last48h": [ + { + "t": "2026-09-20T00:00", + "v": 85 + }, + { + "t": "2026-09-20T03:00", + "v": 79.4 + }, + { + "t": "2026-09-20T06:00", + "v": 52.2 + }, + { + "t": "2026-09-20T09:00", + "v": 52.9 + }, + { + "t": "2026-09-20T12:00", + "v": 60.3 + }, + { + "t": "2026-09-20T15:00", + "v": 66.4 + }, + { + "t": "2026-09-20T18:00", + "v": 85.9 + }, + { + "t": "2026-09-20T21:00", + "v": 94.5 + }, + { + "t": "2026-09-21T00:00", + "v": 67.8 + }, + { + "t": "2026-09-21T03:00", + "v": 65.4 + }, + { + "t": "2026-09-21T06:00", + "v": 51.6 + }, + { + "t": "2026-09-21T09:00", + "v": 54.8 + }, + { + "t": "2026-09-21T12:00", + "v": 60.1 + }, + { + "t": "2026-09-21T15:00", + "v": 75 + }, + { + "t": "2026-09-21T18:00", + "v": 95 + }, + { + "t": "2026-09-21T21:00", + "v": 102.4 + }, + { + "t": "2026-09-22T00:00", + "v": 107.8 + }, + { + "t": "2026-09-22T03:00", + "v": 69.8 + }, + { + "t": "2026-09-22T06:00", + "v": 50.3 + }, + { + "t": "2026-09-22T09:00", + "v": 46 + }, + { + "t": "2026-09-22T12:00", + "v": 43.2 + }, + { + "t": "2026-09-22T15:00", + "v": 53.7 + }, + { + "t": "2026-09-22T18:00", + "v": 63.3 + }, + { + "t": "2026-09-22T21:00", + "v": 71.2 + }, + { + "t": "2026-09-23T00:00", + "v": 62.9 + }, + { + "t": "2026-09-23T03:00", + "v": 63.1 + }, + { + "t": "2026-09-23T06:00", + "v": 55.5 + }, + { + "t": "2026-09-23T09:00", + "v": 52.2 + }, + { + "t": "2026-09-23T12:00", + "v": 62.9 + }, + { + "t": "2026-09-23T15:00", + "v": 87.5 + }, + { + "t": "2026-09-23T18:00", + "v": 109.7 + }, + { + "t": "2026-09-23T21:00", + "v": 76.1 + }, + { + "t": "2026-09-24T00:00", + "v": 65.9 + }, + { + "t": "2026-09-24T03:00", + "v": 50.8 + }, + { + "t": "2026-09-24T06:00", + "v": 37.6 + }, + { + "t": "2026-09-24T09:00", + "v": 39.6 + }, + { + "t": "2026-09-24T12:00", + "v": 53 + }, + { + "t": "2026-09-24T15:00", + "v": 49 + }, + { + "t": "2026-09-24T18:00", + "v": 40.7 + }, + { + "t": "2026-09-24T21:00", + "v": 29.4 + }, + { + "t": "2026-09-25T00:00", + "v": 24 + }, + { + "t": "2026-09-25T03:00", + "v": 23.1 + }, + { + "t": "2026-09-25T06:00", + "v": 24.3 + }, + { + "t": "2026-09-25T09:00", + "v": 23.2 + }, + { + "t": "2026-09-25T12:00", + "v": 40.3 + }, + { + "t": "2026-09-25T15:00", + "v": 63.6 + }, + { + "t": "2026-09-25T18:00", + "v": 66.6 + }, + { + "t": "2026-09-25T21:00", + "v": 51.1 + }, + { + "t": "2026-09-26T00:00", + "v": 43.9 + }, + { + "t": "2026-09-26T03:00", + "v": 48.5 + }, + { + "t": "2026-09-26T06:00", + "v": 48.3 + }, + { + "t": "2026-09-26T09:00", + "v": 54.9 + }, + { + "t": "2026-09-26T12:00", + "v": 64.3 + }, + { + "t": "2026-09-26T15:00", + "v": 48.2 + }, + { + "t": "2026-09-26T18:00", + "v": 45.2 + }, + { + "t": "2026-09-26T21:00", + "v": 44.4 + }, + { + "t": "2026-09-27T00:00", + "v": 47.3 + }, + { + "t": "2026-09-27T03:00", + "v": 49.8 + }, + { + "t": "2026-09-27T06:00", + "v": 49.5 + }, + { + "t": "2026-09-27T09:00", + "v": 37.7 + }, + { + "t": "2026-09-27T12:00", + "v": 18.6 + }, + { + "t": "2026-09-27T15:00", + "v": 22.3 + }, + { + "t": "2026-09-27T18:00", + "v": 28.7 + }, + { + "t": "2026-09-27T21:00", + "v": 33.6 + }, + { + "t": "2026-09-27T23:00", + "v": 39.3 + } + ], + "pm25Daily": [ + { + "t": "2026-09-20", + "v": 72.5, + "hours": 24 + }, + { + "t": "2026-09-21", + "v": 73.3, + "hours": 24 + }, + { + "t": "2026-09-22", + "v": 62.3, + "hours": 24 + }, + { + "t": "2026-09-23", + "v": 71.8, + "hours": 24 + }, + { + "t": "2026-09-24", + "v": 43.3, + "hours": 24 + }, + { + "t": "2026-09-25", + "v": 39.8, + "hours": 24 + }, + { + "t": "2026-09-26", + "v": 48.8, + "hours": 24 + }, + { + "t": "2026-09-27", + "v": 49.3, + "hours": 8 + } + ], + "dashboard": "dashboard offline" +} \ No newline at end of file diff --git a/test/fixtures/ind-enso-2026-09-27.json b/test/fixtures/ind-enso-2026-09-27.json new file mode 100644 index 0000000..30e7d14 --- /dev/null +++ b/test/fixtures/ind-enso-2026-09-27.json @@ -0,0 +1,121 @@ +{ + "source": "NOAA CPC Oceanic Niño Index (ONI), ERSSTv5 Niño3.4 anomalies", + "phase": "El Niño", + "latest": { + "season": "JJA", + "year": 2026, + "oni": 1.8 + }, + "consecutiveSeasons": 3, + "meetsEventDefinition": false, + "interpretation": "El Niño conditions: latest ONI +1.8 °C (JJA 2026), 3 consecutive season(s) beyond the ±0.5 °C threshold — not yet an official event (needs 5).", + "strongestElNino": { + "season": "NDJ", + "year": 2015, + "oni": 2.59 + }, + "strongestLaNina": { + "season": "NDJ", + "year": 1973, + "oni": -2.04 + }, + "series": [ + { + "t": "2024-08", + "v": -0.04 + }, + { + "t": "2024-09", + "v": -0.12 + }, + { + "t": "2024-10", + "v": -0.19 + }, + { + "t": "2024-11", + "v": -0.29 + }, + { + "t": "2024-12", + "v": -0.43 + }, + { + "t": "2025-01", + "v": -0.46 + }, + { + "t": "2025-02", + "v": -0.22 + }, + { + "t": "2025-03", + "v": -0.08 + }, + { + "t": "2025-04", + "v": 0.02 + }, + { + "t": "2025-05", + "v": -0.04 + }, + { + "t": "2025-06", + "v": -0.02 + }, + { + "t": "2025-07", + "v": -0.11 + }, + { + "t": "2025-08", + "v": -0.26 + }, + { + "t": "2025-09", + "v": -0.43 + }, + { + "t": "2025-10", + "v": -0.57 + }, + { + "t": "2025-11", + "v": -0.61 + }, + { + "t": "2025-12", + "v": -0.6 + }, + { + "t": "2026-01", + "v": -0.39 + }, + { + "t": "2026-02", + "v": -0.21 + }, + { + "t": "2026-03", + "v": 0.11 + }, + { + "t": "2026-04", + "v": 0.46 + }, + { + "t": "2026-05", + "v": 0.95 + }, + { + "t": "2026-06", + "v": 1.39 + }, + { + "t": "2026-07", + "v": 1.8 + } + ], + "dashboard": "dashboard offline" +} \ No newline at end of file diff --git a/test/fixtures/ind-quakes-japan-2026-09-27.json b/test/fixtures/ind-quakes-japan-2026-09-27.json new file mode 100644 index 0000000..12164c1 --- /dev/null +++ b/test/fixtures/ind-quakes-japan-2026-09-27.json @@ -0,0 +1,45 @@ +{ + "source": "USGS Earthquake Hazards Program (FDSN event service)", + "window": { + "from": "2026-08-28", + "to": "2026-09-27" + }, + "count": 2, + "strongest": { + "mag": 5, + "place": "38 km E of Nobeoka, Japan", + "time": "2026-09-21T13:38:32.404Z", + "url": "https://earthquake.usgs.gov/earthquakes/eventpage/us7000tixp" + }, + "quakes": [ + { + "id": "us7000tixp", + "mag": 5, + "place": "38 km E of Nobeoka, Japan", + "time": "2026-09-21T13:38:32.404Z", + "lon": 132.0805, + "lat": 32.5978, + "depthKm": 42.7, + "tsunami": false, + "alert": null, + "url": "https://earthquake.usgs.gov/earthquakes/eventpage/us7000tixp", + "sig": 385, + "status": "reviewed" + }, + { + "id": "us7000ti89", + "mag": 5, + "place": "Izu Islands, Japan region", + "time": "2026-09-18T07:19:28.254Z", + "lon": 141.5763, + "lat": 32.243, + "depthKm": 35.3, + "tsunami": false, + "alert": null, + "url": "https://earthquake.usgs.gov/earthquakes/eventpage/us7000ti89", + "sig": 385, + "status": "reviewed" + } + ], + "dashboard": "dashboard offline" +} \ No newline at end of file diff --git a/test/fixtures/ind-river-ganges-patna-2026-09-27.json b/test/fixtures/ind-river-ganges-patna-2026-09-27.json new file mode 100644 index 0000000..faa2e6c --- /dev/null +++ b/test/fixtures/ind-river-ganges-patna-2026-09-27.json @@ -0,0 +1,1490 @@ +{ + "source": "GloFAS via Open-Meteo.com (CC-BY 4.0)", + "unit": "m³/s", + "window": { + "from": "2021-09-27", + "to": "2026-09-27" + }, + "latest": { + "t": "2026-09-27", + "v": 30059.77 + }, + "stats": { + "min": 989.83, + "max": 53087.44, + "mean": 9807.2499 + }, + "latestVsMean": 3.07, + "series": [ + { + "t": "2021-09-27", + "v": 24265.11 + }, + { + "t": "2021-10-02", + "v": 21776.09 + }, + { + "t": "2021-10-07", + "v": 18966.06 + }, + { + "t": "2021-10-12", + "v": 14520.12 + }, + { + "t": "2021-10-17", + "v": 10788.47 + }, + { + "t": "2021-10-22", + "v": 18070.74 + }, + { + "t": "2021-10-27", + "v": 13457.61 + }, + { + "t": "2021-11-01", + "v": 10208.39 + }, + { + "t": "2021-11-06", + "v": 8202.52 + }, + { + "t": "2021-11-11", + "v": 6791.04 + }, + { + "t": "2021-11-16", + "v": 5753.4 + }, + { + "t": "2021-11-21", + "v": 4896.79 + }, + { + "t": "2021-11-26", + "v": 4334.11 + }, + { + "t": "2021-12-01", + "v": 3952.67 + }, + { + "t": "2021-12-06", + "v": 3654.95 + }, + { + "t": "2021-12-11", + "v": 3474.36 + }, + { + "t": "2021-12-16", + "v": 3175.87 + }, + { + "t": "2021-12-21", + "v": 2896.34 + }, + { + "t": "2021-12-26", + "v": 2715.44 + }, + { + "t": "2021-12-31", + "v": 2804.43 + }, + { + "t": "2022-01-05", + "v": 2797.98 + }, + { + "t": "2022-01-10", + "v": 2386.81 + }, + { + "t": "2022-01-15", + "v": 2316.39 + }, + { + "t": "2022-01-20", + "v": 2487.86 + }, + { + "t": "2022-01-25", + "v": 2258.44 + }, + { + "t": "2022-01-30", + "v": 2196.86 + }, + { + "t": "2022-02-04", + "v": 2386.81 + }, + { + "t": "2022-02-09", + "v": 2830.39 + }, + { + "t": "2022-02-14", + "v": 2772.32 + }, + { + "t": "2022-02-19", + "v": 2611.16 + }, + { + "t": "2022-02-24", + "v": 2425.61 + }, + { + "t": "2022-03-01", + "v": 2217.2 + }, + { + "t": "2022-03-06", + "v": 2097.94 + }, + { + "t": "2022-03-11", + "v": 1975.97 + }, + { + "t": "2022-03-16", + "v": 1839.77 + }, + { + "t": "2022-03-21", + "v": 1756.92 + }, + { + "t": "2022-03-26", + "v": 1712.96 + }, + { + "t": "2022-03-31", + "v": 1650.96 + }, + { + "t": "2022-04-05", + "v": 1944.36 + }, + { + "t": "2022-04-10", + "v": 2069.14 + }, + { + "t": "2022-04-15", + "v": 2127.14 + }, + { + "t": "2022-04-20", + "v": 2117.36 + }, + { + "t": "2022-04-25", + "v": 2088.3 + }, + { + "t": "2022-04-30", + "v": 1994.26 + }, + { + "t": "2022-05-05", + "v": 2201.93 + }, + { + "t": "2022-05-10", + "v": 2575.32 + }, + { + "t": "2022-05-15", + "v": 2505.11 + }, + { + "t": "2022-05-20", + "v": 3053.92 + }, + { + "t": "2022-05-25", + "v": 3340.95 + }, + { + "t": "2022-05-30", + "v": 3325.6 + }, + { + "t": "2022-06-04", + "v": 3522.71 + }, + { + "t": "2022-06-09", + "v": 3514.6 + }, + { + "t": "2022-06-14", + "v": 3474.36 + }, + { + "t": "2022-06-19", + "v": 4676.35 + }, + { + "t": "2022-06-24", + "v": 4548.88 + }, + { + "t": "2022-06-29", + "v": 6965.26 + }, + { + "t": "2022-07-04", + "v": 10938.57 + }, + { + "t": "2022-07-09", + "v": 10888.31 + }, + { + "t": "2022-07-14", + "v": 12822.3 + }, + { + "t": "2022-07-19", + "v": 10913.41 + }, + { + "t": "2022-07-24", + "v": 17337.03 + }, + { + "t": "2022-07-29", + "v": 17337.03 + }, + { + "t": "2022-08-03", + "v": 20843.9 + }, + { + "t": "2022-08-08", + "v": 22697.65 + }, + { + "t": "2022-08-13", + "v": 22079.04 + }, + { + "t": "2022-08-18", + "v": 21977.6 + }, + { + "t": "2022-08-23", + "v": 23387.37 + }, + { + "t": "2022-08-28", + "v": 29443.21 + }, + { + "t": "2022-09-02", + "v": 33495.55 + }, + { + "t": "2022-09-07", + "v": 30759.96 + }, + { + "t": "2022-09-12", + "v": 24887.57 + }, + { + "t": "2022-09-17", + "v": 22437.81 + }, + { + "t": "2022-09-22", + "v": 30268.13 + }, + { + "t": "2022-09-27", + "v": 26483.99 + }, + { + "t": "2022-10-02", + "v": 24321.05 + }, + { + "t": "2022-10-07", + "v": 19185.69 + }, + { + "t": "2022-10-12", + "v": 28378.2 + }, + { + "t": "2022-10-17", + "v": 29106.19 + }, + { + "t": "2022-10-22", + "v": 20795.96 + }, + { + "t": "2022-10-27", + "v": 14858.36 + }, + { + "t": "2022-11-01", + "v": 10963.78 + }, + { + "t": "2022-11-06", + "v": 8335.81 + }, + { + "t": "2022-11-11", + "v": 6651.73 + }, + { + "t": "2022-11-16", + "v": 5507.08 + }, + { + "t": "2022-11-21", + "v": 4697.94 + }, + { + "t": "2022-11-26", + "v": 4063.43 + }, + { + "t": "2022-12-01", + "v": 3621.43 + }, + { + "t": "2022-12-06", + "v": 3295.1 + }, + { + "t": "2022-12-11", + "v": 3032.89 + }, + { + "t": "2022-12-16", + "v": 2804.43 + }, + { + "t": "2022-12-21", + "v": 2605.15 + }, + { + "t": "2022-12-26", + "v": 2499.35 + }, + { + "t": "2022-12-31", + "v": 2425.61 + }, + { + "t": "2023-01-05", + "v": 2253.24 + }, + { + "t": "2023-01-10", + "v": 1869.68 + }, + { + "t": "2023-01-15", + "v": 1591.21 + }, + { + "t": "2023-01-20", + "v": 1461.18 + }, + { + "t": "2023-01-25", + "v": 1421.33 + }, + { + "t": "2023-01-30", + "v": 1373.04 + }, + { + "t": "2023-02-04", + "v": 1392.16 + }, + { + "t": "2023-02-09", + "v": 1427.89 + }, + { + "t": "2023-02-14", + "v": 1516.05 + }, + { + "t": "2023-02-19", + "v": 1583.89 + }, + { + "t": "2023-02-24", + "v": 1540.7 + }, + { + "t": "2023-03-01", + "v": 1509.08 + }, + { + "t": "2023-03-06", + "v": 1408.29 + }, + { + "t": "2023-03-11", + "v": 1296.18 + }, + { + "t": "2023-03-16", + "v": 1240.65 + }, + { + "t": "2023-03-21", + "v": 1379.38 + }, + { + "t": "2023-03-26", + "v": 1587.55 + }, + { + "t": "2023-03-31", + "v": 1617.08 + }, + { + "t": "2023-04-05", + "v": 1685.55 + }, + { + "t": "2023-04-10", + "v": 1806.17 + }, + { + "t": "2023-04-15", + "v": 1752.88 + }, + { + "t": "2023-04-20", + "v": 1639.59 + }, + { + "t": "2023-04-25", + "v": 1609.65 + }, + { + "t": "2023-04-30", + "v": 1705.08 + }, + { + "t": "2023-05-05", + "v": 1930.97 + }, + { + "t": "2023-05-10", + "v": 2386.81 + }, + { + "t": "2023-05-15", + "v": 2375.84 + }, + { + "t": "2023-05-20", + "v": 2003.47 + }, + { + "t": "2023-05-25", + "v": 1930.97 + }, + { + "t": "2023-05-30", + "v": 2295.15 + }, + { + "t": "2023-06-04", + "v": 2408.91 + }, + { + "t": "2023-06-09", + "v": 2359.48 + }, + { + "t": "2023-06-14", + "v": 2022.02 + }, + { + "t": "2023-06-19", + "v": 2408.91 + }, + { + "t": "2023-06-24", + "v": 3117.89 + }, + { + "t": "2023-06-29", + "v": 4665.59 + }, + { + "t": "2023-07-04", + "v": 11938.89 + }, + { + "t": "2023-07-09", + "v": 13272.95 + }, + { + "t": "2023-07-14", + "v": 12940.96 + }, + { + "t": "2023-07-19", + "v": 18406.72 + }, + { + "t": "2023-07-24", + "v": 18922.43 + }, + { + "t": "2023-07-29", + "v": 19859.94 + }, + { + "t": "2023-08-03", + "v": 20988.4 + }, + { + "t": "2023-08-08", + "v": 24209.28 + }, + { + "t": "2023-08-13", + "v": 28839.32 + }, + { + "t": "2023-08-18", + "v": 27288.77 + }, + { + "t": "2023-08-23", + "v": 22802.41 + }, + { + "t": "2023-08-28", + "v": 27288.77 + }, + { + "t": "2023-09-02", + "v": 23066.47 + }, + { + "t": "2023-09-07", + "v": 17377 + }, + { + "t": "2023-09-12", + "v": 14995.85 + }, + { + "t": "2023-09-17", + "v": 18491.7 + }, + { + "t": "2023-09-22", + "v": 18449.15 + }, + { + "t": "2023-09-27", + "v": 18322.15 + }, + { + "t": "2023-10-02", + "v": 15065.07 + }, + { + "t": "2023-10-07", + "v": 15380.54 + }, + { + "t": "2023-10-12", + "v": 12940.96 + }, + { + "t": "2023-10-17", + "v": 9681.78 + }, + { + "t": "2023-10-22", + "v": 7260.06 + }, + { + "t": "2023-10-27", + "v": 5687.53 + }, + { + "t": "2023-11-01", + "v": 4665.59 + }, + { + "t": "2023-11-06", + "v": 4026.17 + }, + { + "t": "2023-11-11", + "v": 3596.49 + }, + { + "t": "2023-11-16", + "v": 3317.94 + }, + { + "t": "2023-11-21", + "v": 3053.92 + }, + { + "t": "2023-11-26", + "v": 2817.38 + }, + { + "t": "2023-12-01", + "v": 2641.41 + }, + { + "t": "2023-12-06", + "v": 2539.97 + }, + { + "t": "2023-12-11", + "v": 2487.86 + }, + { + "t": "2023-12-16", + "v": 2482.13 + }, + { + "t": "2023-12-21", + "v": 2354.05 + }, + { + "t": "2023-12-26", + "v": 2181.73 + }, + { + "t": "2023-12-31", + "v": 2102.78 + }, + { + "t": "2024-01-05", + "v": 1994.26 + }, + { + "t": "2024-01-10", + "v": 1632.05 + }, + { + "t": "2024-01-15", + "v": 1366.73 + }, + { + "t": "2024-01-20", + "v": 1223.62 + }, + { + "t": "2024-01-25", + "v": 1212.39 + }, + { + "t": "2024-01-30", + "v": 1179.32 + }, + { + "t": "2024-02-04", + "v": 1144.51 + }, + { + "t": "2024-02-09", + "v": 1240.65 + }, + { + "t": "2024-02-14", + "v": 1373.04 + }, + { + "t": "2024-02-19", + "v": 1471.31 + }, + { + "t": "2024-02-24", + "v": 1441.12 + }, + { + "t": "2024-02-29", + "v": 1464.55 + }, + { + "t": "2024-03-05", + "v": 1441.12 + }, + { + "t": "2024-03-10", + "v": 1533.62 + }, + { + "t": "2024-03-15", + "v": 1658.59 + }, + { + "t": "2024-03-20", + "v": 1478.11 + }, + { + "t": "2024-03-25", + "v": 1360.44 + }, + { + "t": "2024-03-30", + "v": 1351.07 + }, + { + "t": "2024-04-04", + "v": 1382.57 + }, + { + "t": "2024-04-09", + "v": 1376.21 + }, + { + "t": "2024-04-14", + "v": 1441.12 + }, + { + "t": "2024-04-19", + "v": 1441.12 + }, + { + "t": "2024-04-24", + "v": 1405.05 + }, + { + "t": "2024-04-29", + "v": 1369.88 + }, + { + "t": "2024-05-04", + "v": 1311.2 + }, + { + "t": "2024-05-09", + "v": 1287.25 + }, + { + "t": "2024-05-14", + "v": 1509.08 + }, + { + "t": "2024-05-19", + "v": 1602.25 + }, + { + "t": "2024-05-24", + "v": 1658.59 + }, + { + "t": "2024-05-29", + "v": 1831.31 + }, + { + "t": "2024-06-03", + "v": 2196.86 + }, + { + "t": "2024-06-08", + "v": 2431.2 + }, + { + "t": "2024-06-13", + "v": 2217.2 + }, + { + "t": "2024-06-18", + "v": 1939.89 + }, + { + "t": "2024-06-23", + "v": 3697.28 + }, + { + "t": "2024-06-28", + "v": 3646.54 + }, + { + "t": "2024-07-03", + "v": 7446.32 + }, + { + "t": "2024-07-08", + "v": 16217.1 + }, + { + "t": "2024-07-13", + "v": 26180.85 + }, + { + "t": "2024-07-18", + "v": 22489.56 + }, + { + "t": "2024-07-23", + "v": 20557.92 + }, + { + "t": "2024-07-28", + "v": 20043.72 + }, + { + "t": "2024-08-02", + "v": 21676.04 + }, + { + "t": "2024-08-07", + "v": 28972.43 + }, + { + "t": "2024-08-12", + "v": 36981.81 + }, + { + "t": "2024-08-17", + "v": 39173.18 + }, + { + "t": "2024-08-22", + "v": 39993.5 + }, + { + "t": "2024-08-27", + "v": 40456.58 + }, + { + "t": "2024-09-01", + "v": 37756.23 + }, + { + "t": "2024-09-06", + "v": 34913.05 + }, + { + "t": "2024-09-11", + "v": 32358.38 + }, + { + "t": "2024-09-16", + "v": 33961.54 + }, + { + "t": "2024-09-21", + "v": 40643.35 + }, + { + "t": "2024-09-26", + "v": 32808.52 + }, + { + "t": "2024-10-01", + "v": 39718.15 + }, + { + "t": "2024-10-06", + "v": 27668.41 + }, + { + "t": "2024-10-11", + "v": 19951.63 + }, + { + "t": "2024-10-16", + "v": 14587.14 + }, + { + "t": "2024-10-21", + "v": 10963.78 + }, + { + "t": "2024-10-26", + "v": 8451.79 + }, + { + "t": "2024-10-31", + "v": 6713.29 + }, + { + "t": "2024-11-05", + "v": 5570.86 + }, + { + "t": "2024-11-10", + "v": 4930.74 + }, + { + "t": "2024-11-15", + "v": 4435.09 + }, + { + "t": "2024-11-20", + "v": 3980.07 + }, + { + "t": "2024-11-25", + "v": 3547.13 + }, + { + "t": "2024-11-30", + "v": 3317.94 + }, + { + "t": "2024-12-05", + "v": 3103.56 + }, + { + "t": "2024-12-10", + "v": 2903.02 + }, + { + "t": "2024-12-15", + "v": 2721.7 + }, + { + "t": "2024-12-20", + "v": 2516.68 + }, + { + "t": "2024-12-25", + "v": 2375.84 + }, + { + "t": "2024-12-30", + "v": 2321.74 + }, + { + "t": "2025-01-04", + "v": 2305.75 + }, + { + "t": "2025-01-09", + "v": 2112.49 + }, + { + "t": "2025-01-14", + "v": 1689.44 + }, + { + "t": "2025-01-19", + "v": 1454.46 + }, + { + "t": "2025-01-24", + "v": 1354.19 + }, + { + "t": "2025-01-29", + "v": 1308.18 + }, + { + "t": "2025-02-03", + "v": 1220.8 + }, + { + "t": "2025-02-08", + "v": 1192.99 + }, + { + "t": "2025-02-13", + "v": 1173.9 + }, + { + "t": "2025-02-18", + "v": 1232.11 + }, + { + "t": "2025-02-23", + "v": 1369.88 + }, + { + "t": "2025-02-28", + "v": 1366.73 + }, + { + "t": "2025-03-05", + "v": 1392.16 + }, + { + "t": "2025-03-10", + "v": 1530.09 + }, + { + "t": "2025-03-15", + "v": 1565.75 + }, + { + "t": "2025-03-20", + "v": 1454.46 + }, + { + "t": "2025-03-25", + "v": 1329.45 + }, + { + "t": "2025-03-30", + "v": 1179.32 + }, + { + "t": "2025-04-04", + "v": 1003.62 + }, + { + "t": "2025-04-09", + "v": 1041.32 + }, + { + "t": "2025-04-14", + "v": 1184.77 + }, + { + "t": "2025-04-19", + "v": 1523.05 + }, + { + "t": "2025-04-24", + "v": 1740.81 + }, + { + "t": "2025-04-29", + "v": 1740.81 + }, + { + "t": "2025-05-04", + "v": 1720.87 + }, + { + "t": "2025-05-09", + "v": 1785.49 + }, + { + "t": "2025-05-14", + "v": 1886.99 + }, + { + "t": "2025-05-19", + "v": 1935.42 + }, + { + "t": "2025-05-24", + "v": 2414.46 + }, + { + "t": "2025-05-29", + "v": 2889.68 + }, + { + "t": "2025-06-03", + "v": 3234.94 + }, + { + "t": "2025-06-08", + "v": 3458.39 + }, + { + "t": "2025-06-13", + "v": 3039.89 + }, + { + "t": "2025-06-18", + "v": 2843.46 + }, + { + "t": "2025-06-23", + "v": 5010.87 + }, + { + "t": "2025-06-28", + "v": 7942.28 + }, + { + "t": "2025-07-03", + "v": 13211.95 + }, + { + "t": "2025-07-08", + "v": 17863.87 + }, + { + "t": "2025-07-13", + "v": 24830.33 + }, + { + "t": "2025-07-18", + "v": 31404.1 + }, + { + "t": "2025-07-23", + "v": 37756.23 + }, + { + "t": "2025-07-28", + "v": 36474.38 + }, + { + "t": "2025-08-02", + "v": 40363.54 + }, + { + "t": "2025-08-07", + "v": 50349.08 + }, + { + "t": "2025-08-12", + "v": 49772.71 + }, + { + "t": "2025-08-17", + "v": 47532.53 + }, + { + "t": "2025-08-22", + "v": 39173.18 + }, + { + "t": "2025-08-27", + "v": 37324.02 + }, + { + "t": "2025-09-01", + "v": 44257.83 + }, + { + "t": "2025-09-06", + "v": 43250.4 + }, + { + "t": "2025-09-11", + "v": 43450.03 + }, + { + "t": "2025-09-16", + "v": 39993.5 + }, + { + "t": "2025-09-21", + "v": 40830.95 + }, + { + "t": "2025-09-26", + "v": 31404.1 + }, + { + "t": "2025-10-01", + "v": 24773.22 + }, + { + "t": "2025-10-06", + "v": 24489.63 + }, + { + "t": "2025-10-11", + "v": 20605.31 + }, + { + "t": "2025-10-16", + "v": 15630.47 + }, + { + "t": "2025-10-21", + "v": 11480.54 + }, + { + "t": "2025-10-26", + "v": 8530 + }, + { + "t": "2025-10-31", + "v": 6775.42 + }, + { + "t": "2025-11-05", + "v": 8164.82 + }, + { + "t": "2025-11-10", + "v": 7078.46 + }, + { + "t": "2025-11-15", + "v": 5648.37 + }, + { + "t": "2025-11-20", + "v": 4676.35 + }, + { + "t": "2025-11-25", + "v": 3998.45 + }, + { + "t": "2025-11-30", + "v": 3654.95 + }, + { + "t": "2025-12-05", + "v": 3340.95 + }, + { + "t": "2025-12-10", + "v": 3082.19 + }, + { + "t": "2025-12-15", + "v": 2909.72 + }, + { + "t": "2025-12-20", + "v": 2709.19 + }, + { + "t": "2025-12-25", + "v": 2575.32 + }, + { + "t": "2025-12-30", + "v": 2510.89 + }, + { + "t": "2026-01-04", + "v": 2442.43 + }, + { + "t": "2026-01-09", + "v": 2093.11 + }, + { + "t": "2026-01-14", + "v": 1831.31 + }, + { + "t": "2026-01-19", + "v": 1624.55 + }, + { + "t": "2026-01-24", + "v": 1488.36 + }, + { + "t": "2026-01-29", + "v": 1441.12 + }, + { + "t": "2026-02-03", + "v": 1467.93 + }, + { + "t": "2026-02-08", + "v": 1732.8 + }, + { + "t": "2026-02-13", + "v": 1654.77 + }, + { + "t": "2026-02-18", + "v": 1572.98 + }, + { + "t": "2026-02-23", + "v": 1544.25 + }, + { + "t": "2026-02-28", + "v": 1484.94 + }, + { + "t": "2026-03-05", + "v": 1447.77 + }, + { + "t": "2026-03-10", + "v": 1388.95 + }, + { + "t": "2026-03-15", + "v": 1605.94 + }, + { + "t": "2026-03-20", + "v": 1647.16 + }, + { + "t": "2026-03-25", + "v": 1740.81 + }, + { + "t": "2026-03-30", + "v": 2026.68 + }, + { + "t": "2026-04-04", + "v": 2136.96 + }, + { + "t": "2026-04-09", + "v": 2050.16 + }, + { + "t": "2026-04-14", + "v": 2112.49 + }, + { + "t": "2026-04-19", + "v": 2186.76 + }, + { + "t": "2026-04-24", + "v": 2107.63 + }, + { + "t": "2026-04-29", + "v": 1935.42 + }, + { + "t": "2026-05-04", + "v": 3356.38 + }, + { + "t": "2026-05-09", + "v": 3197.9 + }, + { + "t": "2026-05-14", + "v": 3082.19 + }, + { + "t": "2026-05-19", + "v": 3053.92 + }, + { + "t": "2026-05-24", + "v": 2863.18 + }, + { + "t": "2026-05-29", + "v": 2850.02 + }, + { + "t": "2026-06-03", + "v": 3075.1 + }, + { + "t": "2026-06-08", + "v": 3132.29 + }, + { + "t": "2026-06-13", + "v": 3082.19 + }, + { + "t": "2026-06-18", + "v": 3197.9 + }, + { + "t": "2026-06-23", + "v": 3154.01 + }, + { + "t": "2026-06-28", + "v": 3490.4 + }, + { + "t": "2026-07-03", + "v": 4559.37 + }, + { + "t": "2026-07-08", + "v": 6440.69 + }, + { + "t": "2026-07-13", + "v": 8648.68 + }, + { + "t": "2026-07-18", + "v": 12970.79 + }, + { + "t": "2026-07-23", + "v": 14255.07 + }, + { + "t": "2026-07-28", + "v": 16031.45 + }, + { + "t": "2026-08-02", + "v": 17178.09 + }, + { + "t": "2026-08-07", + "v": 20416.38 + }, + { + "t": "2026-08-12", + "v": 22697.65 + }, + { + "t": "2026-08-17", + "v": 24042.63 + }, + { + "t": "2026-08-22", + "v": 33188.44 + }, + { + "t": "2026-08-27", + "v": 36642.77 + }, + { + "t": "2026-09-01", + "v": 40363.54 + }, + { + "t": "2026-09-06", + "v": 45707.81 + }, + { + "t": "2026-09-11", + "v": 46450.51 + }, + { + "t": "2026-09-16", + "v": 42265.86 + }, + { + "t": "2026-09-21", + "v": 34832.72 + }, + { + "t": "2026-09-26", + "v": 28772.99 + }, + { + "t": "2026-09-27", + "v": 30059.77 + } + ], + "summary": "River discharge at (25.62, 85.15): latest 30059.77 m³/s (2026-09-27), period mean 9807.2499, range 989.83–53087.44. Latest is 3.07× the period mean — elevated (possible flood).", + "dashboard": "dashboard offline" +} \ No newline at end of file diff --git a/test/fixtures/ind-sea-ice-north-2026-09-25.json b/test/fixtures/ind-sea-ice-north-2026-09-25.json new file mode 100644 index 0000000..2e4b543 --- /dev/null +++ b/test/fixtures/ind-sea-ice-north-2026-09-25.json @@ -0,0 +1,1095 @@ +{ + "source": "NSIDC Sea Ice Index v4 (G02135), daily extent + 1981–2010 climatology", + "pole": "north", + "latest": { + "t": "2026-09-25", + "v": 5.169 + }, + "anomalyVsAverage": -1.371, + "belowP10": true, + "climatologyForDay": { + "doy": 268, + "average": 6.54, + "p10": 5.329, + "p25": 6.085, + "p50": 6.635, + "p75": 7.298, + "p90": 7.629 + }, + "monthTrendPerDecade": -0.766, + "currentYearSeries": [ + { + "t": "2026-01-01", + "v": 12.368 + }, + { + "t": "2026-01-02", + "v": 12.478 + }, + { + "t": "2026-01-03", + "v": 12.466 + }, + { + "t": "2026-01-04", + "v": 12.564 + }, + { + "t": "2026-01-05", + "v": 12.693 + }, + { + "t": "2026-01-06", + "v": 12.787 + }, + { + "t": "2026-01-07", + "v": 12.931 + }, + { + "t": "2026-01-08", + "v": 12.965 + }, + { + "t": "2026-01-09", + "v": 12.966 + }, + { + "t": "2026-01-10", + "v": 13.075 + }, + { + "t": "2026-01-11", + "v": 13.105 + }, + { + "t": "2026-01-12", + "v": 13.349 + }, + { + "t": "2026-01-13", + "v": 13.149 + }, + { + "t": "2026-01-14", + "v": 13.144 + }, + { + "t": "2026-01-15", + "v": 13.099 + }, + { + "t": "2026-01-16", + "v": 13.102 + }, + { + "t": "2026-01-17", + "v": 13.124 + }, + { + "t": "2026-01-18", + "v": 13.029 + }, + { + "t": "2026-01-19", + "v": 13.062 + }, + { + "t": "2026-01-20", + "v": 13.117 + }, + { + "t": "2026-01-21", + "v": 13.205 + }, + { + "t": "2026-01-22", + "v": 13.287 + }, + { + "t": "2026-01-23", + "v": 13.177 + }, + { + "t": "2026-01-24", + "v": 13.353 + }, + { + "t": "2026-01-25", + "v": 13.38 + }, + { + "t": "2026-01-26", + "v": 13.371 + }, + { + "t": "2026-01-27", + "v": 13.475 + }, + { + "t": "2026-01-28", + "v": 13.541 + }, + { + "t": "2026-01-29", + "v": 13.592 + }, + { + "t": "2026-01-30", + "v": 13.631 + }, + { + "t": "2026-01-31", + "v": 13.721 + }, + { + "t": "2026-02-01", + "v": 13.686 + }, + { + "t": "2026-02-02", + "v": 13.776 + }, + { + "t": "2026-02-03", + "v": 13.854 + }, + { + "t": "2026-02-04", + "v": 13.838 + }, + { + "t": "2026-02-05", + "v": 13.993 + }, + { + "t": "2026-02-06", + "v": 14.049 + }, + { + "t": "2026-02-07", + "v": 14.062 + }, + { + "t": "2026-02-08", + "v": 14.079 + }, + { + "t": "2026-02-09", + "v": 14.083 + }, + { + "t": "2026-02-10", + "v": 14.156 + }, + { + "t": "2026-02-11", + "v": 14.098 + }, + { + "t": "2026-02-12", + "v": 14.181 + }, + { + "t": "2026-02-13", + "v": 14.241 + }, + { + "t": "2026-02-14", + "v": 14.212 + }, + { + "t": "2026-02-15", + "v": 14.165 + }, + { + "t": "2026-02-16", + "v": 14.227 + }, + { + "t": "2026-02-17", + "v": 14.162 + }, + { + "t": "2026-02-18", + "v": 14.207 + }, + { + "t": "2026-02-19", + "v": 14.217 + }, + { + "t": "2026-02-20", + "v": 14.272 + }, + { + "t": "2026-02-21", + "v": 14.216 + }, + { + "t": "2026-02-22", + "v": 14.166 + }, + { + "t": "2026-02-23", + "v": 14.062 + }, + { + "t": "2026-02-24", + "v": 14.135 + }, + { + "t": "2026-02-25", + "v": 14.248 + }, + { + "t": "2026-02-26", + "v": 14.178 + }, + { + "t": "2026-02-27", + "v": 14.069 + }, + { + "t": "2026-02-28", + "v": 14.122 + }, + { + "t": "2026-03-01", + "v": 14.128 + }, + { + "t": "2026-03-02", + "v": 14.051 + }, + { + "t": "2026-03-03", + "v": 14.136 + }, + { + "t": "2026-03-04", + "v": 14.13 + }, + { + "t": "2026-03-05", + "v": 14.136 + }, + { + "t": "2026-03-06", + "v": 14.257 + }, + { + "t": "2026-03-07", + "v": 14.284 + }, + { + "t": "2026-03-08", + "v": 14.238 + }, + { + "t": "2026-03-09", + "v": 14.114 + }, + { + "t": "2026-03-10", + "v": 14.196 + }, + { + "t": "2026-03-11", + "v": 14.23 + }, + { + "t": "2026-03-12", + "v": 14.351 + }, + { + "t": "2026-03-13", + "v": 14.358 + }, + { + "t": "2026-03-14", + "v": 14.283 + }, + { + "t": "2026-03-15", + "v": 14.207 + }, + { + "t": "2026-03-16", + "v": 14.191 + }, + { + "t": "2026-03-17", + "v": 14.106 + }, + { + "t": "2026-03-18", + "v": 14.15 + }, + { + "t": "2026-03-19", + "v": 14.056 + }, + { + "t": "2026-03-20", + "v": 14.105 + }, + { + "t": "2026-03-21", + "v": 14.059 + }, + { + "t": "2026-03-22", + "v": 13.962 + }, + { + "t": "2026-03-23", + "v": 13.981 + }, + { + "t": "2026-03-24", + "v": 14.012 + }, + { + "t": "2026-03-25", + "v": 14.038 + }, + { + "t": "2026-03-26", + "v": 14.09 + }, + { + "t": "2026-03-27", + "v": 14.09 + }, + { + "t": "2026-03-28", + "v": 14.036 + }, + { + "t": "2026-03-29", + "v": 14.047 + }, + { + "t": "2026-03-30", + "v": 14.055 + }, + { + "t": "2026-03-31", + "v": 13.983 + }, + { + "t": "2026-04-01", + "v": 13.991 + }, + { + "t": "2026-04-02", + "v": 13.952 + }, + { + "t": "2026-04-03", + "v": 13.986 + }, + { + "t": "2026-04-04", + "v": 14.011 + }, + { + "t": "2026-04-05", + "v": 13.978 + }, + { + "t": "2026-04-06", + "v": 14.047 + }, + { + "t": "2026-04-07", + "v": 14.041 + }, + { + "t": "2026-04-08", + "v": 13.981 + }, + { + "t": "2026-04-09", + "v": 13.851 + }, + { + "t": "2026-04-10", + "v": 13.793 + }, + { + "t": "2026-04-11", + "v": 13.719 + }, + { + "t": "2026-04-12", + "v": 13.692 + }, + { + "t": "2026-04-13", + "v": 13.635 + }, + { + "t": "2026-04-14", + "v": 13.601 + }, + { + "t": "2026-04-15", + "v": 13.484 + }, + { + "t": "2026-04-16", + "v": 13.458 + }, + { + "t": "2026-04-17", + "v": 13.512 + }, + { + "t": "2026-04-18", + "v": 13.624 + }, + { + "t": "2026-04-19", + "v": 13.648 + }, + { + "t": "2026-04-20", + "v": 13.413 + }, + { + "t": "2026-04-21", + "v": 13.372 + }, + { + "t": "2026-04-22", + "v": 13.314 + }, + { + "t": "2026-04-23", + "v": 13.224 + }, + { + "t": "2026-04-24", + "v": 13.193 + }, + { + "t": "2026-04-25", + "v": 13.215 + }, + { + "t": "2026-04-26", + "v": 13.197 + }, + { + "t": "2026-04-27", + "v": 13.066 + }, + { + "t": "2026-04-28", + "v": 13.078 + }, + { + "t": "2026-04-29", + "v": 12.998 + }, + { + "t": "2026-04-30", + "v": 12.979 + }, + { + "t": "2026-05-01", + "v": 12.841 + }, + { + "t": "2026-05-02", + "v": 12.795 + }, + { + "t": "2026-05-03", + "v": 12.691 + }, + { + "t": "2026-05-04", + "v": 12.668 + }, + { + "t": "2026-05-05", + "v": 12.58 + }, + { + "t": "2026-05-06", + "v": 12.473 + }, + { + "t": "2026-05-07", + "v": 12.455 + }, + { + "t": "2026-05-08", + "v": 12.391 + }, + { + "t": "2026-05-09", + "v": 12.381 + }, + { + "t": "2026-05-10", + "v": 12.445 + }, + { + "t": "2026-05-11", + "v": 12.445 + }, + { + "t": "2026-05-12", + "v": 12.455 + }, + { + "t": "2026-05-13", + "v": 12.359 + }, + { + "t": "2026-05-14", + "v": 12.295 + }, + { + "t": "2026-05-15", + "v": 12.267 + }, + { + "t": "2026-05-16", + "v": 12.244 + }, + { + "t": "2026-05-17", + "v": 12.192 + }, + { + "t": "2026-05-18", + "v": 12.019 + }, + { + "t": "2026-05-19", + "v": 12.036 + }, + { + "t": "2026-05-20", + "v": 11.861 + }, + { + "t": "2026-05-21", + "v": 11.902 + }, + { + "t": "2026-05-22", + "v": 11.794 + }, + { + "t": "2026-05-23", + "v": 11.79 + }, + { + "t": "2026-05-24", + "v": 11.703 + }, + { + "t": "2026-05-25", + "v": 11.72 + }, + { + "t": "2026-05-26", + "v": 11.771 + }, + { + "t": "2026-05-27", + "v": 11.638 + }, + { + "t": "2026-05-28", + "v": 11.586 + }, + { + "t": "2026-05-29", + "v": 11.57 + }, + { + "t": "2026-05-30", + "v": 11.535 + }, + { + "t": "2026-05-31", + "v": 11.439 + }, + { + "t": "2026-06-01", + "v": 11.359 + }, + { + "t": "2026-06-02", + "v": 11.285 + }, + { + "t": "2026-06-03", + "v": 11.227 + }, + { + "t": "2026-06-04", + "v": 11.18 + }, + { + "t": "2026-06-05", + "v": 11.077 + }, + { + "t": "2026-06-06", + "v": 11.048 + }, + { + "t": "2026-06-07", + "v": 10.998 + }, + { + "t": "2026-06-08", + "v": 10.97 + }, + { + "t": "2026-06-09", + "v": 10.884 + }, + { + "t": "2026-06-10", + "v": 10.793 + }, + { + "t": "2026-06-11", + "v": 10.759 + }, + { + "t": "2026-06-12", + "v": 10.62 + }, + { + "t": "2026-06-13", + "v": 10.644 + }, + { + "t": "2026-06-14", + "v": 10.648 + }, + { + "t": "2026-06-15", + "v": 10.57 + }, + { + "t": "2026-06-16", + "v": 10.452 + }, + { + "t": "2026-06-17", + "v": 10.368 + }, + { + "t": "2026-06-18", + "v": 10.374 + }, + { + "t": "2026-06-19", + "v": 10.234 + }, + { + "t": "2026-06-20", + "v": 10.18 + }, + { + "t": "2026-06-21", + "v": 10.108 + }, + { + "t": "2026-06-22", + "v": 10.112 + }, + { + "t": "2026-06-23", + "v": 10.058 + }, + { + "t": "2026-06-24", + "v": 9.982 + }, + { + "t": "2026-06-25", + "v": 9.764 + }, + { + "t": "2026-06-26", + "v": 9.555 + }, + { + "t": "2026-06-27", + "v": 9.576 + }, + { + "t": "2026-06-28", + "v": 9.48 + }, + { + "t": "2026-06-29", + "v": 9.262 + }, + { + "t": "2026-06-30", + "v": 9.103 + }, + { + "t": "2026-07-01", + "v": 9.034 + }, + { + "t": "2026-07-02", + "v": 8.933 + }, + { + "t": "2026-07-03", + "v": 8.836 + }, + { + "t": "2026-07-04", + "v": 8.773 + }, + { + "t": "2026-07-05", + "v": 8.738 + }, + { + "t": "2026-07-06", + "v": 8.671 + }, + { + "t": "2026-07-07", + "v": 8.541 + }, + { + "t": "2026-07-08", + "v": 8.528 + }, + { + "t": "2026-07-09", + "v": 8.429 + }, + { + "t": "2026-07-10", + "v": 8.376 + }, + { + "t": "2026-07-11", + "v": 8.255 + }, + { + "t": "2026-07-12", + "v": 8.141 + }, + { + "t": "2026-07-13", + "v": 8.04 + }, + { + "t": "2026-07-14", + "v": 7.964 + }, + { + "t": "2026-07-15", + "v": 7.883 + }, + { + "t": "2026-07-16", + "v": 7.691 + }, + { + "t": "2026-07-17", + "v": 7.576 + }, + { + "t": "2026-07-18", + "v": 7.416 + }, + { + "t": "2026-07-19", + "v": 7.316 + }, + { + "t": "2026-07-20", + "v": 7.279 + }, + { + "t": "2026-07-21", + "v": 7.146 + }, + { + "t": "2026-07-22", + "v": 7.111 + }, + { + "t": "2026-07-23", + "v": 7.029 + }, + { + "t": "2026-07-24", + "v": 6.972 + }, + { + "t": "2026-07-25", + "v": 6.832 + }, + { + "t": "2026-07-26", + "v": 6.787 + }, + { + "t": "2026-07-27", + "v": 6.683 + }, + { + "t": "2026-07-28", + "v": 6.565 + }, + { + "t": "2026-07-29", + "v": 6.544 + }, + { + "t": "2026-07-30", + "v": 6.507 + }, + { + "t": "2026-07-31", + "v": 6.526 + }, + { + "t": "2026-08-01", + "v": 6.495 + }, + { + "t": "2026-08-02", + "v": 6.479 + }, + { + "t": "2026-08-03", + "v": 6.465 + }, + { + "t": "2026-08-04", + "v": 6.369 + }, + { + "t": "2026-08-05", + "v": 6.255 + }, + { + "t": "2026-08-06", + "v": 6.18 + }, + { + "t": "2026-08-07", + "v": 6.131 + }, + { + "t": "2026-08-08", + "v": 6.042 + }, + { + "t": "2026-08-09", + "v": 6.031 + }, + { + "t": "2026-08-10", + "v": 5.896 + }, + { + "t": "2026-08-11", + "v": 5.829 + }, + { + "t": "2026-08-12", + "v": 5.726 + }, + { + "t": "2026-08-13", + "v": 5.676 + }, + { + "t": "2026-08-14", + "v": 5.513 + }, + { + "t": "2026-08-15", + "v": 5.354 + }, + { + "t": "2026-08-16", + "v": 5.334 + }, + { + "t": "2026-08-17", + "v": 5.382 + }, + { + "t": "2026-08-18", + "v": 5.414 + }, + { + "t": "2026-08-19", + "v": 5.387 + }, + { + "t": "2026-08-20", + "v": 5.303 + }, + { + "t": "2026-08-21", + "v": 5.265 + }, + { + "t": "2026-08-22", + "v": 5.117 + }, + { + "t": "2026-08-23", + "v": 5.107 + }, + { + "t": "2026-08-24", + "v": 5.087 + }, + { + "t": "2026-08-25", + "v": 4.998 + }, + { + "t": "2026-08-26", + "v": 4.983 + }, + { + "t": "2026-08-27", + "v": 5.028 + }, + { + "t": "2026-08-28", + "v": 4.96 + }, + { + "t": "2026-08-29", + "v": 4.911 + }, + { + "t": "2026-08-30", + "v": 4.849 + }, + { + "t": "2026-08-31", + "v": 4.838 + }, + { + "t": "2026-09-01", + "v": 4.733 + }, + { + "t": "2026-09-02", + "v": 4.674 + }, + { + "t": "2026-09-03", + "v": 4.656 + }, + { + "t": "2026-09-04", + "v": 4.69 + }, + { + "t": "2026-09-05", + "v": 4.668 + }, + { + "t": "2026-09-06", + "v": 4.632 + }, + { + "t": "2026-09-07", + "v": 4.596 + }, + { + "t": "2026-09-08", + "v": 4.59 + }, + { + "t": "2026-09-09", + "v": 4.615 + }, + { + "t": "2026-09-10", + "v": 4.609 + }, + { + "t": "2026-09-11", + "v": 4.6 + }, + { + "t": "2026-09-12", + "v": 4.574 + }, + { + "t": "2026-09-13", + "v": 4.595 + }, + { + "t": "2026-09-14", + "v": 4.651 + }, + { + "t": "2026-09-15", + "v": 4.724 + }, + { + "t": "2026-09-16", + "v": 4.656 + }, + { + "t": "2026-09-17", + "v": 4.634 + }, + { + "t": "2026-09-18", + "v": 4.666 + }, + { + "t": "2026-09-19", + "v": 4.708 + }, + { + "t": "2026-09-20", + "v": 4.709 + }, + { + "t": "2026-09-21", + "v": 4.772 + }, + { + "t": "2026-09-22", + "v": 4.868 + }, + { + "t": "2026-09-23", + "v": 4.95 + }, + { + "t": "2026-09-24", + "v": 4.993 + }, + { + "t": "2026-09-25", + "v": 5.169 + } + ], + "dashboard": "dashboard offline" +} \ No newline at end of file diff --git a/test/fixtures/ind-sst-gbr-base-2016-2025.json b/test/fixtures/ind-sst-gbr-base-2016-2025.json new file mode 100644 index 0000000..2d415a8 --- /dev/null +++ b/test/fixtures/ind-sst-gbr-base-2016-2025.json @@ -0,0 +1,1483 @@ +{ + "source": "NOAA OISST v2.1 (0.25° daily SST) via CoastWatch ERDDAP", + "gridCell": { + "lat": -18.375, + "lon": 147.625 + }, + "window": { + "from": "2016-01-01", + "to": "2025-12-31", + "strideDays": 10 + }, + "latest": { + "t": "2025-12-26", + "v": 29.6 + }, + "stats": { + "min": 23.25, + "max": 30.75, + "mean": 27.0116, + "n": 364 + }, + "trendPerDecade": 0.222, + "summary": "SST at (-18.375, 147.625): latest 29.6 °C (2025-12-26), 2016-01-01…2025-12-31 mean 27.0116 °C, range 23.25–30.75 °C, trend +0.22 °C/decade.", + "series": [ + { + "t": "2016-01-01", + "v": 28.01 + }, + { + "t": "2016-01-11", + "v": 28.4 + }, + { + "t": "2016-01-21", + "v": 28.67 + }, + { + "t": "2016-01-31", + "v": 29.16 + }, + { + "t": "2016-02-10", + "v": 29.04 + }, + { + "t": "2016-02-20", + "v": 29.97 + }, + { + "t": "2016-03-01", + "v": 29.94 + }, + { + "t": "2016-03-11", + "v": 29.6 + }, + { + "t": "2016-03-21", + "v": 28.99 + }, + { + "t": "2016-03-31", + "v": 29.12 + }, + { + "t": "2016-04-10", + "v": 28.45 + }, + { + "t": "2016-04-20", + "v": 27.84 + }, + { + "t": "2016-04-30", + "v": 27.64 + }, + { + "t": "2016-05-10", + "v": 27.65 + }, + { + "t": "2016-05-20", + "v": 26.56 + }, + { + "t": "2016-05-30", + "v": 27.13 + }, + { + "t": "2016-06-09", + "v": 26.54 + }, + { + "t": "2016-06-19", + "v": 25.44 + }, + { + "t": "2016-06-29", + "v": 26.21 + }, + { + "t": "2016-07-09", + "v": 25.79 + }, + { + "t": "2016-07-19", + "v": 25.32 + }, + { + "t": "2016-07-29", + "v": 25.34 + }, + { + "t": "2016-08-08", + "v": 24.68 + }, + { + "t": "2016-08-18", + "v": 24.06 + }, + { + "t": "2016-08-28", + "v": 24.67 + }, + { + "t": "2016-09-07", + "v": 24.94 + }, + { + "t": "2016-09-17", + "v": 25.8 + }, + { + "t": "2016-09-27", + "v": 26.98 + }, + { + "t": "2016-10-07", + "v": 26.38 + }, + { + "t": "2016-10-17", + "v": 26.92 + }, + { + "t": "2016-10-27", + "v": 26.66 + }, + { + "t": "2016-11-06", + "v": 27.63 + }, + { + "t": "2016-11-16", + "v": 27.54 + }, + { + "t": "2016-11-26", + "v": 27.74 + }, + { + "t": "2016-12-06", + "v": 28.07 + }, + { + "t": "2016-12-16", + "v": 27.96 + }, + { + "t": "2016-12-26", + "v": 28.38 + }, + { + "t": "2017-01-05", + "v": 28.77 + }, + { + "t": "2017-01-15", + "v": 28.93 + }, + { + "t": "2017-01-25", + "v": 29.72 + }, + { + "t": "2017-02-04", + "v": 29.22 + }, + { + "t": "2017-02-14", + "v": 29.72 + }, + { + "t": "2017-02-24", + "v": 29.59 + }, + { + "t": "2017-03-06", + "v": 29.63 + }, + { + "t": "2017-03-16", + "v": 29.48 + }, + { + "t": "2017-03-26", + "v": 29.61 + }, + { + "t": "2017-04-05", + "v": 28.77 + }, + { + "t": "2017-04-15", + "v": 28.14 + }, + { + "t": "2017-04-25", + "v": 26.74 + }, + { + "t": "2017-05-05", + "v": 26.37 + }, + { + "t": "2017-05-15", + "v": 26.04 + }, + { + "t": "2017-05-25", + "v": 26.26 + }, + { + "t": "2017-06-04", + "v": 25.65 + }, + { + "t": "2017-06-14", + "v": 25.19 + }, + { + "t": "2017-06-24", + "v": 24.46 + }, + { + "t": "2017-07-04", + "v": 24.85 + }, + { + "t": "2017-07-14", + "v": 24.62 + }, + { + "t": "2017-07-24", + "v": 24.57 + }, + { + "t": "2017-08-03", + "v": 24.73 + }, + { + "t": "2017-08-13", + "v": 25.35 + }, + { + "t": "2017-08-23", + "v": 25.4 + }, + { + "t": "2017-09-02", + "v": 24.91 + }, + { + "t": "2017-09-12", + "v": 25.05 + }, + { + "t": "2017-09-22", + "v": 25.06 + }, + { + "t": "2017-10-02", + "v": 25.32 + }, + { + "t": "2017-10-12", + "v": 26.3 + }, + { + "t": "2017-10-22", + "v": 26.29 + }, + { + "t": "2017-11-01", + "v": 27.48 + }, + { + "t": "2017-11-11", + "v": 26.4 + }, + { + "t": "2017-11-21", + "v": 26.68 + }, + { + "t": "2017-12-01", + "v": 27.69 + }, + { + "t": "2017-12-11", + "v": 28.16 + }, + { + "t": "2017-12-21", + "v": 28.46 + }, + { + "t": "2017-12-31", + "v": 29.2 + }, + { + "t": "2018-01-10", + "v": 28.74 + }, + { + "t": "2018-01-20", + "v": 29.16 + }, + { + "t": "2018-01-30", + "v": 29.2 + }, + { + "t": "2018-02-09", + "v": 28.42 + }, + { + "t": "2018-02-19", + "v": 29.35 + }, + { + "t": "2018-03-01", + "v": 28.76 + }, + { + "t": "2018-03-11", + "v": 28.12 + }, + { + "t": "2018-03-21", + "v": 28.05 + }, + { + "t": "2018-03-31", + "v": 28.28 + }, + { + "t": "2018-04-10", + "v": 27.59 + }, + { + "t": "2018-04-20", + "v": 27.24 + }, + { + "t": "2018-04-30", + "v": 26.73 + }, + { + "t": "2018-05-10", + "v": 26.5 + }, + { + "t": "2018-05-20", + "v": 26.25 + }, + { + "t": "2018-05-30", + "v": 25.2 + }, + { + "t": "2018-06-09", + "v": 25.01 + }, + { + "t": "2018-06-19", + "v": 24.57 + }, + { + "t": "2018-06-29", + "v": 24.42 + }, + { + "t": "2018-07-09", + "v": 24.28 + }, + { + "t": "2018-07-19", + "v": 24.21 + }, + { + "t": "2018-07-29", + "v": 24.43 + }, + { + "t": "2018-08-08", + "v": 24.28 + }, + { + "t": "2018-08-18", + "v": 24.63 + }, + { + "t": "2018-08-28", + "v": 24.57 + }, + { + "t": "2018-09-07", + "v": 24.8 + }, + { + "t": "2018-09-17", + "v": 24.91 + }, + { + "t": "2018-09-27", + "v": 25.17 + }, + { + "t": "2018-10-07", + "v": 25.39 + }, + { + "t": "2018-10-17", + "v": 26.37 + }, + { + "t": "2018-10-27", + "v": 26.73 + }, + { + "t": "2018-11-06", + "v": 26.81 + }, + { + "t": "2018-11-16", + "v": 27.01 + }, + { + "t": "2018-11-26", + "v": 27.86 + }, + { + "t": "2018-12-06", + "v": 28.24 + }, + { + "t": "2018-12-16", + "v": 29.08 + }, + { + "t": "2018-12-26", + "v": 27.53 + }, + { + "t": "2019-01-05", + "v": 28.1 + }, + { + "t": "2019-01-15", + "v": 28.76 + }, + { + "t": "2019-01-25", + "v": 28.2 + }, + { + "t": "2019-02-04", + "v": 27.95 + }, + { + "t": "2019-02-14", + "v": 28.57 + }, + { + "t": "2019-02-24", + "v": 28.46 + }, + { + "t": "2019-03-06", + "v": 27.65 + }, + { + "t": "2019-03-16", + "v": 28.7 + }, + { + "t": "2019-03-26", + "v": 28.66 + }, + { + "t": "2019-04-05", + "v": 27.83 + }, + { + "t": "2019-04-15", + "v": 27.24 + }, + { + "t": "2019-04-25", + "v": 27.41 + }, + { + "t": "2019-05-05", + "v": 27.01 + }, + { + "t": "2019-05-15", + "v": 26.01 + }, + { + "t": "2019-05-25", + "v": 25.61 + }, + { + "t": "2019-06-04", + "v": 26.41 + }, + { + "t": "2019-06-14", + "v": 25.13 + }, + { + "t": "2019-06-24", + "v": 24.43 + }, + { + "t": "2019-07-04", + "v": 24.32 + }, + { + "t": "2019-07-14", + "v": 24.16 + }, + { + "t": "2019-07-24", + "v": 23.44 + }, + { + "t": "2019-08-03", + "v": 23.25 + }, + { + "t": "2019-08-13", + "v": 23.52 + }, + { + "t": "2019-08-23", + "v": 23.39 + }, + { + "t": "2019-09-02", + "v": 23.7 + }, + { + "t": "2019-09-12", + "v": 23.99 + }, + { + "t": "2019-09-22", + "v": 24.47 + }, + { + "t": "2019-10-02", + "v": 24.94 + }, + { + "t": "2019-10-12", + "v": 25.54 + }, + { + "t": "2019-10-22", + "v": 25.76 + }, + { + "t": "2019-11-01", + "v": 25.77 + }, + { + "t": "2019-11-11", + "v": 26.16 + }, + { + "t": "2019-11-21", + "v": 26.73 + }, + { + "t": "2019-12-01", + "v": 27.29 + }, + { + "t": "2019-12-11", + "v": 27.48 + }, + { + "t": "2019-12-21", + "v": 27.75 + }, + { + "t": "2019-12-31", + "v": 28.64 + }, + { + "t": "2020-01-10", + "v": 28.55 + }, + { + "t": "2020-01-20", + "v": 29.26 + }, + { + "t": "2020-01-30", + "v": 28.98 + }, + { + "t": "2020-02-09", + "v": 30.01 + }, + { + "t": "2020-02-19", + "v": 30.75 + }, + { + "t": "2020-02-29", + "v": 29.69 + }, + { + "t": "2020-03-10", + "v": 29.91 + }, + { + "t": "2020-03-20", + "v": 28.03 + }, + { + "t": "2020-03-30", + "v": 27.76 + }, + { + "t": "2020-04-09", + "v": 27.8 + }, + { + "t": "2020-04-19", + "v": 27.99 + }, + { + "t": "2020-04-29", + "v": 27.63 + }, + { + "t": "2020-05-09", + "v": 26.95 + }, + { + "t": "2020-05-19", + "v": 26.03 + }, + { + "t": "2020-05-29", + "v": 26.05 + }, + { + "t": "2020-06-08", + "v": 25.56 + }, + { + "t": "2020-06-18", + "v": 25.17 + }, + { + "t": "2020-06-28", + "v": 25.2 + }, + { + "t": "2020-07-08", + "v": 24.67 + }, + { + "t": "2020-07-18", + "v": 24.42 + }, + { + "t": "2020-07-28", + "v": 24.32 + }, + { + "t": "2020-08-07", + "v": 24.55 + }, + { + "t": "2020-08-17", + "v": 24.42 + }, + { + "t": "2020-08-27", + "v": 25.1 + }, + { + "t": "2020-09-06", + "v": 25.07 + }, + { + "t": "2020-09-16", + "v": 25.16 + }, + { + "t": "2020-09-26", + "v": 26.23 + }, + { + "t": "2020-10-06", + "v": 25.37 + }, + { + "t": "2020-10-16", + "v": 25.21 + }, + { + "t": "2020-10-26", + "v": 27.17 + }, + { + "t": "2020-11-05", + "v": 26.97 + }, + { + "t": "2020-11-15", + "v": 27.71 + }, + { + "t": "2020-11-25", + "v": 27.82 + }, + { + "t": "2020-12-05", + "v": 27.94 + }, + { + "t": "2020-12-15", + "v": 28.3 + }, + { + "t": "2020-12-25", + "v": 29.45 + }, + { + "t": "2021-01-04", + "v": 29.44 + }, + { + "t": "2021-01-14", + "v": 28.7 + }, + { + "t": "2021-01-24", + "v": 28.06 + }, + { + "t": "2021-02-03", + "v": 28.7 + }, + { + "t": "2021-02-13", + "v": 28.93 + }, + { + "t": "2021-02-23", + "v": 29.66 + }, + { + "t": "2021-03-05", + "v": 28.27 + }, + { + "t": "2021-03-15", + "v": 28.51 + }, + { + "t": "2021-03-26", + "v": 28.45 + }, + { + "t": "2021-04-05", + "v": 27.47 + }, + { + "t": "2021-04-15", + "v": 27.31 + }, + { + "t": "2021-04-25", + "v": 27.25 + }, + { + "t": "2021-05-05", + "v": 26.91 + }, + { + "t": "2021-05-15", + "v": 26.49 + }, + { + "t": "2021-05-25", + "v": 25.77 + }, + { + "t": "2021-06-04", + "v": 25.53 + }, + { + "t": "2021-06-14", + "v": 25.55 + }, + { + "t": "2021-06-24", + "v": 25.25 + }, + { + "t": "2021-07-04", + "v": 24.87 + }, + { + "t": "2021-07-14", + "v": 24.38 + }, + { + "t": "2021-07-24", + "v": 24.61 + }, + { + "t": "2021-08-03", + "v": 24.69 + }, + { + "t": "2021-08-13", + "v": 24.39 + }, + { + "t": "2021-08-23", + "v": 24.53 + }, + { + "t": "2021-09-02", + "v": 24.82 + }, + { + "t": "2021-09-13", + "v": 25.03 + }, + { + "t": "2021-09-23", + "v": 24.75 + }, + { + "t": "2021-10-03", + "v": 26.34 + }, + { + "t": "2021-10-13", + "v": 27.12 + }, + { + "t": "2021-10-23", + "v": 27.92 + }, + { + "t": "2021-11-02", + "v": 27.6 + }, + { + "t": "2021-11-12", + "v": 27.87 + }, + { + "t": "2021-11-22", + "v": 27.97 + }, + { + "t": "2021-12-02", + "v": 28.75 + }, + { + "t": "2021-12-12", + "v": 29.37 + }, + { + "t": "2021-12-22", + "v": 29.4 + }, + { + "t": "2022-01-01", + "v": 29.29 + }, + { + "t": "2022-01-11", + "v": 29.45 + }, + { + "t": "2022-01-21", + "v": 28.99 + }, + { + "t": "2022-01-31", + "v": 29.06 + }, + { + "t": "2022-02-10", + "v": 28.84 + }, + { + "t": "2022-02-20", + "v": 28.79 + }, + { + "t": "2022-03-02", + "v": 29.69 + }, + { + "t": "2022-03-12", + "v": 29.79 + }, + { + "t": "2022-03-22", + "v": 28.7 + }, + { + "t": "2022-04-01", + "v": 29.04 + }, + { + "t": "2022-04-11", + "v": 28.79 + }, + { + "t": "2022-04-21", + "v": 28.18 + }, + { + "t": "2022-05-01", + "v": 27.46 + }, + { + "t": "2022-05-11", + "v": 27.43 + }, + { + "t": "2022-05-21", + "v": 27.01 + }, + { + "t": "2022-05-31", + "v": 26.45 + }, + { + "t": "2022-06-10", + "v": 26.64 + }, + { + "t": "2022-06-20", + "v": 25.47 + }, + { + "t": "2022-06-30", + "v": 24.94 + }, + { + "t": "2022-07-10", + "v": 24.41 + }, + { + "t": "2022-07-20", + "v": 24.17 + }, + { + "t": "2022-07-30", + "v": 24.11 + }, + { + "t": "2022-08-09", + "v": 24.76 + }, + { + "t": "2022-08-19", + "v": 24.58 + }, + { + "t": "2022-08-29", + "v": 24.32 + }, + { + "t": "2022-09-08", + "v": 25 + }, + { + "t": "2022-09-18", + "v": 26.53 + }, + { + "t": "2022-09-28", + "v": 27.11 + }, + { + "t": "2022-10-08", + "v": 27.22 + }, + { + "t": "2022-10-18", + "v": 27.59 + }, + { + "t": "2022-10-29", + "v": 28.63 + }, + { + "t": "2022-11-08", + "v": 28.01 + }, + { + "t": "2022-11-18", + "v": 28.66 + }, + { + "t": "2022-11-28", + "v": 28.76 + }, + { + "t": "2022-12-08", + "v": 29.19 + }, + { + "t": "2022-12-18", + "v": 29.19 + }, + { + "t": "2022-12-28", + "v": 28.53 + }, + { + "t": "2023-01-07", + "v": 28.9 + }, + { + "t": "2023-01-17", + "v": 29.34 + }, + { + "t": "2023-01-27", + "v": 29.17 + }, + { + "t": "2023-02-07", + "v": 29.29 + }, + { + "t": "2023-02-17", + "v": 29.37 + }, + { + "t": "2023-02-27", + "v": 28.56 + }, + { + "t": "2023-03-09", + "v": 28.58 + }, + { + "t": "2023-03-19", + "v": 29.11 + }, + { + "t": "2023-03-29", + "v": 28.92 + }, + { + "t": "2023-04-08", + "v": 29.3 + }, + { + "t": "2023-04-18", + "v": 29.2 + }, + { + "t": "2023-04-28", + "v": 27.75 + }, + { + "t": "2023-05-08", + "v": 27.43 + }, + { + "t": "2023-05-18", + "v": 26.72 + }, + { + "t": "2023-05-28", + "v": 26.42 + }, + { + "t": "2023-06-07", + "v": 25.76 + }, + { + "t": "2023-06-17", + "v": 25.9 + }, + { + "t": "2023-06-27", + "v": 26.27 + }, + { + "t": "2023-07-07", + "v": 26.11 + }, + { + "t": "2023-07-17", + "v": 25.79 + }, + { + "t": "2023-07-27", + "v": 25.26 + }, + { + "t": "2023-08-06", + "v": 24.98 + }, + { + "t": "2023-08-16", + "v": 25.03 + }, + { + "t": "2023-08-26", + "v": 25.1 + }, + { + "t": "2023-09-05", + "v": 25.27 + }, + { + "t": "2023-09-15", + "v": 24.93 + }, + { + "t": "2023-09-25", + "v": 25.06 + }, + { + "t": "2023-10-05", + "v": 25.44 + }, + { + "t": "2023-10-15", + "v": 25.68 + }, + { + "t": "2023-10-25", + "v": 26.3 + }, + { + "t": "2023-11-04", + "v": 26.17 + }, + { + "t": "2023-11-14", + "v": 26.39 + }, + { + "t": "2023-11-24", + "v": 26.76 + }, + { + "t": "2023-12-04", + "v": 28.45 + }, + { + "t": "2023-12-14", + "v": 27.52 + }, + { + "t": "2024-01-04", + "v": 29.69 + }, + { + "t": "2024-01-14", + "v": 29.39 + }, + { + "t": "2024-01-24", + "v": 29.27 + }, + { + "t": "2024-02-03", + "v": 29.6 + }, + { + "t": "2024-02-13", + "v": 29.67 + }, + { + "t": "2024-02-23", + "v": 29.08 + }, + { + "t": "2024-03-04", + "v": 29.54 + }, + { + "t": "2024-03-14", + "v": 29.03 + }, + { + "t": "2024-03-24", + "v": 28.52 + }, + { + "t": "2024-04-04", + "v": 28.31 + }, + { + "t": "2024-04-14", + "v": 28.3 + }, + { + "t": "2024-04-24", + "v": 28.18 + }, + { + "t": "2024-05-04", + "v": 27.16 + }, + { + "t": "2024-05-14", + "v": 27.01 + }, + { + "t": "2024-05-24", + "v": 26.17 + }, + { + "t": "2024-06-03", + "v": 25.96 + }, + { + "t": "2024-06-13", + "v": 25.43 + }, + { + "t": "2024-06-23", + "v": 25.35 + }, + { + "t": "2024-07-03", + "v": 25.54 + }, + { + "t": "2024-07-13", + "v": 25.21 + }, + { + "t": "2024-07-23", + "v": 24.88 + }, + { + "t": "2024-08-02", + "v": 24.55 + }, + { + "t": "2024-08-12", + "v": 24.1 + }, + { + "t": "2024-08-22", + "v": 24.38 + }, + { + "t": "2024-09-01", + "v": 24.9 + }, + { + "t": "2024-09-11", + "v": 25.11 + }, + { + "t": "2024-09-21", + "v": 25.38 + }, + { + "t": "2024-10-01", + "v": 25.45 + }, + { + "t": "2024-10-11", + "v": 25.94 + }, + { + "t": "2024-10-21", + "v": 26.44 + }, + { + "t": "2024-10-31", + "v": 26.62 + }, + { + "t": "2024-11-10", + "v": 27.03 + }, + { + "t": "2024-11-20", + "v": 27.38 + }, + { + "t": "2024-11-30", + "v": 28.05 + }, + { + "t": "2024-12-10", + "v": 29.09 + }, + { + "t": "2024-12-20", + "v": 28.87 + }, + { + "t": "2024-12-30", + "v": 29.66 + }, + { + "t": "2025-01-09", + "v": 29.46 + }, + { + "t": "2025-01-19", + "v": 30.07 + }, + { + "t": "2025-01-29", + "v": 30.19 + }, + { + "t": "2025-02-08", + "v": 29.16 + }, + { + "t": "2025-02-18", + "v": 29.42 + }, + { + "t": "2025-02-28", + "v": 28.22 + }, + { + "t": "2025-03-10", + "v": 29.61 + }, + { + "t": "2025-03-20", + "v": 28.65 + }, + { + "t": "2025-03-30", + "v": 28.45 + }, + { + "t": "2025-04-09", + "v": 28.83 + }, + { + "t": "2025-04-19", + "v": 27.62 + }, + { + "t": "2025-04-29", + "v": 27.56 + }, + { + "t": "2025-05-09", + "v": 26.86 + }, + { + "t": "2025-05-19", + "v": 26.91 + }, + { + "t": "2025-05-29", + "v": 26.93 + }, + { + "t": "2025-06-08", + "v": 26.38 + }, + { + "t": "2025-06-18", + "v": 25.61 + }, + { + "t": "2025-06-29", + "v": 25.26 + }, + { + "t": "2025-07-09", + "v": 24.87 + }, + { + "t": "2025-07-19", + "v": 25.4 + }, + { + "t": "2025-07-29", + "v": 25.97 + }, + { + "t": "2025-08-08", + "v": 25.48 + }, + { + "t": "2025-08-18", + "v": 25.38 + }, + { + "t": "2025-08-28", + "v": 25.74 + }, + { + "t": "2025-09-07", + "v": 25.63 + }, + { + "t": "2025-09-17", + "v": 25.47 + }, + { + "t": "2025-09-27", + "v": 25.55 + }, + { + "t": "2025-10-07", + "v": 26.22 + }, + { + "t": "2025-10-17", + "v": 26.65 + }, + { + "t": "2025-10-27", + "v": 27.28 + }, + { + "t": "2025-11-06", + "v": 28.02 + }, + { + "t": "2025-11-16", + "v": 28.27 + }, + { + "t": "2025-11-26", + "v": 28.79 + }, + { + "t": "2025-12-06", + "v": 28.33 + }, + { + "t": "2025-12-16", + "v": 28.94 + }, + { + "t": "2025-12-26", + "v": 29.6 + } + ], + "dashboard": "dashboard offline" +} \ No newline at end of file diff --git a/test/fixtures/ind-sst-gbr-recent-2026-09-27.json b/test/fixtures/ind-sst-gbr-recent-2026-09-27.json new file mode 100644 index 0000000..3c12b45 --- /dev/null +++ b/test/fixtures/ind-sst-gbr-recent-2026-09-27.json @@ -0,0 +1,207 @@ +{ + "source": "NOAA OISST v2.1 (0.25° daily SST) via CoastWatch ERDDAP", + "gridCell": { + "lat": -18.375, + "lon": 147.625 + }, + "window": { + "from": "2026-07-29", + "to": "2026-09-11", + "strideDays": 1 + }, + "latest": { + "t": "2026-09-11", + "v": 24.27 + }, + "stats": { + "min": 23.52, + "max": 24.4, + "mean": 23.9038, + "n": 45 + }, + "trendPerDecade": null, + "summary": "SST at (-18.375, 147.625): latest 24.27 °C (2026-09-11), 2026-07-29…2026-09-11 mean 23.9038 °C, range 23.52–24.4 °C.", + "series": [ + { + "t": "2026-07-29", + "v": 23.89 + }, + { + "t": "2026-07-30", + "v": 23.76 + }, + { + "t": "2026-07-31", + "v": 23.75 + }, + { + "t": "2026-08-01", + "v": 23.7 + }, + { + "t": "2026-08-02", + "v": 23.67 + }, + { + "t": "2026-08-03", + "v": 23.62 + }, + { + "t": "2026-08-04", + "v": 23.61 + }, + { + "t": "2026-08-05", + "v": 23.61 + }, + { + "t": "2026-08-06", + "v": 23.56 + }, + { + "t": "2026-08-07", + "v": 23.52 + }, + { + "t": "2026-08-08", + "v": 23.64 + }, + { + "t": "2026-08-09", + "v": 23.77 + }, + { + "t": "2026-08-10", + "v": 23.84 + }, + { + "t": "2026-08-11", + "v": 23.91 + }, + { + "t": "2026-08-12", + "v": 24.04 + }, + { + "t": "2026-08-13", + "v": 23.84 + }, + { + "t": "2026-08-14", + "v": 23.76 + }, + { + "t": "2026-08-15", + "v": 23.77 + }, + { + "t": "2026-08-16", + "v": 23.73 + }, + { + "t": "2026-08-17", + "v": 23.71 + }, + { + "t": "2026-08-18", + "v": 23.7 + }, + { + "t": "2026-08-19", + "v": 23.7 + }, + { + "t": "2026-08-20", + "v": 23.68 + }, + { + "t": "2026-08-21", + "v": 23.69 + }, + { + "t": "2026-08-22", + "v": 23.74 + }, + { + "t": "2026-08-23", + "v": 23.83 + }, + { + "t": "2026-08-24", + "v": 23.91 + }, + { + "t": "2026-08-25", + "v": 23.99 + }, + { + "t": "2026-08-26", + "v": 24.08 + }, + { + "t": "2026-08-27", + "v": 24.1 + }, + { + "t": "2026-08-28", + "v": 24.11 + }, + { + "t": "2026-08-29", + "v": 24.09 + }, + { + "t": "2026-08-30", + "v": 23.94 + }, + { + "t": "2026-08-31", + "v": 23.83 + }, + { + "t": "2026-09-01", + "v": 23.87 + }, + { + "t": "2026-09-02", + "v": 24 + }, + { + "t": "2026-09-03", + "v": 24.16 + }, + { + "t": "2026-09-04", + "v": 24.23 + }, + { + "t": "2026-09-05", + "v": 24.3 + }, + { + "t": "2026-09-06", + "v": 24.35 + }, + { + "t": "2026-09-07", + "v": 24.35 + }, + { + "t": "2026-09-08", + "v": 24.38 + }, + { + "t": "2026-09-09", + "v": 24.4 + }, + { + "t": "2026-09-10", + "v": 24.27 + }, + { + "t": "2026-09-11", + "v": 24.27 + } + ], + "dashboard": "dashboard offline" +} \ No newline at end of file diff --git a/test/fixtures/ind-sst-med-base-2016-2025.json b/test/fixtures/ind-sst-med-base-2016-2025.json new file mode 100644 index 0000000..7c66921 --- /dev/null +++ b/test/fixtures/ind-sst-med-base-2016-2025.json @@ -0,0 +1,1483 @@ +{ + "source": "NOAA OISST v2.1 (0.25° daily SST) via CoastWatch ERDDAP", + "gridCell": { + "lat": 38.625, + "lon": 5.625 + }, + "window": { + "from": "2016-01-01", + "to": "2025-12-31", + "strideDays": 10 + }, + "latest": { + "t": "2025-12-26", + "v": 17.16 + }, + "stats": { + "min": 14.22, + "max": 28.49, + "mean": 20.2951, + "n": 364 + }, + "trendPerDecade": 1.759, + "summary": "SST at (38.625, 5.625): latest 17.16 °C (2025-12-26), 2016-01-01…2025-12-31 mean 20.2951 °C, range 14.22–28.49 °C, trend +1.76 °C/decade.", + "series": [ + { + "t": "2016-01-01", + "v": 17.33 + }, + { + "t": "2016-01-11", + "v": 17.2 + }, + { + "t": "2016-01-21", + "v": 16.14 + }, + { + "t": "2016-01-31", + "v": 16.33 + }, + { + "t": "2016-02-10", + "v": 16.09 + }, + { + "t": "2016-02-20", + "v": 15.49 + }, + { + "t": "2016-03-01", + "v": 14.97 + }, + { + "t": "2016-03-11", + "v": 14.5 + }, + { + "t": "2016-03-21", + "v": 14.85 + }, + { + "t": "2016-03-31", + "v": 16.46 + }, + { + "t": "2016-04-10", + "v": 15.74 + }, + { + "t": "2016-04-20", + "v": 16.4 + }, + { + "t": "2016-04-30", + "v": 16.67 + }, + { + "t": "2016-05-10", + "v": 17.06 + }, + { + "t": "2016-05-20", + "v": 17.78 + }, + { + "t": "2016-05-30", + "v": 18.98 + }, + { + "t": "2016-06-09", + "v": 23.46 + }, + { + "t": "2016-06-19", + "v": 21.61 + }, + { + "t": "2016-06-29", + "v": 21.87 + }, + { + "t": "2016-07-09", + "v": 23.81 + }, + { + "t": "2016-07-19", + "v": 23.32 + }, + { + "t": "2016-07-29", + "v": 25.2 + }, + { + "t": "2016-08-08", + "v": 25.13 + }, + { + "t": "2016-08-18", + "v": 25.68 + }, + { + "t": "2016-08-28", + "v": 25.78 + }, + { + "t": "2016-09-07", + "v": 25.9 + }, + { + "t": "2016-09-17", + "v": 26.06 + }, + { + "t": "2016-09-27", + "v": 25.08 + }, + { + "t": "2016-10-07", + "v": 24.63 + }, + { + "t": "2016-10-17", + "v": 23.96 + }, + { + "t": "2016-10-27", + "v": 23.15 + }, + { + "t": "2016-11-06", + "v": 22.06 + }, + { + "t": "2016-11-16", + "v": 20.4 + }, + { + "t": "2016-11-26", + "v": 19.99 + }, + { + "t": "2016-12-06", + "v": 19.07 + }, + { + "t": "2016-12-16", + "v": 18.09 + }, + { + "t": "2016-12-26", + "v": 17.63 + }, + { + "t": "2017-01-05", + "v": 17.13 + }, + { + "t": "2017-01-15", + "v": 15.72 + }, + { + "t": "2017-01-25", + "v": 14.81 + }, + { + "t": "2017-02-04", + "v": 14.7 + }, + { + "t": "2017-02-14", + "v": 14.79 + }, + { + "t": "2017-02-24", + "v": 14.54 + }, + { + "t": "2017-03-06", + "v": 14.92 + }, + { + "t": "2017-03-16", + "v": 15.54 + }, + { + "t": "2017-03-26", + "v": 15.76 + }, + { + "t": "2017-04-05", + "v": 16.04 + }, + { + "t": "2017-04-15", + "v": 17.76 + }, + { + "t": "2017-04-25", + "v": 17.41 + }, + { + "t": "2017-05-05", + "v": 17.54 + }, + { + "t": "2017-05-15", + "v": 20.28 + }, + { + "t": "2017-05-25", + "v": 21.22 + }, + { + "t": "2017-06-04", + "v": 21.79 + }, + { + "t": "2017-06-14", + "v": 23.35 + }, + { + "t": "2017-06-24", + "v": 25.98 + }, + { + "t": "2017-07-04", + "v": 24.23 + }, + { + "t": "2017-07-14", + "v": 25.02 + }, + { + "t": "2017-07-24", + "v": 25.56 + }, + { + "t": "2017-08-03", + "v": 26.47 + }, + { + "t": "2017-08-13", + "v": 25.81 + }, + { + "t": "2017-08-23", + "v": 25.95 + }, + { + "t": "2017-09-02", + "v": 26.25 + }, + { + "t": "2017-09-12", + "v": 25.46 + }, + { + "t": "2017-09-22", + "v": 24.1 + }, + { + "t": "2017-10-02", + "v": 23.48 + }, + { + "t": "2017-10-12", + "v": 23.05 + }, + { + "t": "2017-10-22", + "v": 22.67 + }, + { + "t": "2017-11-01", + "v": 21.52 + }, + { + "t": "2017-11-11", + "v": 20.3 + }, + { + "t": "2017-11-21", + "v": 18.98 + }, + { + "t": "2017-12-01", + "v": 18.45 + }, + { + "t": "2017-12-11", + "v": 16.59 + }, + { + "t": "2017-12-21", + "v": 16.32 + }, + { + "t": "2017-12-31", + "v": 15.44 + }, + { + "t": "2018-01-10", + "v": 15.54 + }, + { + "t": "2018-01-20", + "v": 15.32 + }, + { + "t": "2018-01-30", + "v": 15.18 + }, + { + "t": "2018-02-09", + "v": 14.65 + }, + { + "t": "2018-02-19", + "v": 14.34 + }, + { + "t": "2018-03-01", + "v": 14.38 + }, + { + "t": "2018-03-11", + "v": 14.37 + }, + { + "t": "2018-03-21", + "v": 14.26 + }, + { + "t": "2018-03-31", + "v": 14.88 + }, + { + "t": "2018-04-10", + "v": 15.04 + }, + { + "t": "2018-04-20", + "v": 16.21 + }, + { + "t": "2018-04-30", + "v": 16.59 + }, + { + "t": "2018-05-10", + "v": 17.47 + }, + { + "t": "2018-05-20", + "v": 18.06 + }, + { + "t": "2018-05-30", + "v": 19.74 + }, + { + "t": "2018-06-09", + "v": 20.83 + }, + { + "t": "2018-06-19", + "v": 21.78 + }, + { + "t": "2018-06-29", + "v": 23.99 + }, + { + "t": "2018-07-09", + "v": 25.34 + }, + { + "t": "2018-07-19", + "v": 24.97 + }, + { + "t": "2018-07-29", + "v": 27.18 + }, + { + "t": "2018-08-08", + "v": 28.03 + }, + { + "t": "2018-08-18", + "v": 27.06 + }, + { + "t": "2018-08-28", + "v": 27.15 + }, + { + "t": "2018-09-07", + "v": 26.84 + }, + { + "t": "2018-09-17", + "v": 25.77 + }, + { + "t": "2018-09-27", + "v": 24.73 + }, + { + "t": "2018-10-07", + "v": 24.06 + }, + { + "t": "2018-10-17", + "v": 23.42 + }, + { + "t": "2018-10-27", + "v": 22.12 + }, + { + "t": "2018-11-06", + "v": 19.1 + }, + { + "t": "2018-11-16", + "v": 19.52 + }, + { + "t": "2018-11-26", + "v": 18.02 + }, + { + "t": "2018-12-06", + "v": 17.42 + }, + { + "t": "2018-12-16", + "v": 17.05 + }, + { + "t": "2018-12-26", + "v": 16.35 + }, + { + "t": "2019-01-05", + "v": 16.06 + }, + { + "t": "2019-01-15", + "v": 15.77 + }, + { + "t": "2019-01-25", + "v": 15.61 + }, + { + "t": "2019-02-04", + "v": 15.22 + }, + { + "t": "2019-02-14", + "v": 15.63 + }, + { + "t": "2019-02-24", + "v": 15.07 + }, + { + "t": "2019-03-06", + "v": 15.17 + }, + { + "t": "2019-03-16", + "v": 15.39 + }, + { + "t": "2019-03-26", + "v": 15.09 + }, + { + "t": "2019-04-05", + "v": 15.74 + }, + { + "t": "2019-04-15", + "v": 16.01 + }, + { + "t": "2019-04-25", + "v": 16.43 + }, + { + "t": "2019-05-05", + "v": 16.41 + }, + { + "t": "2019-05-15", + "v": 17.02 + }, + { + "t": "2019-05-25", + "v": 18.54 + }, + { + "t": "2019-06-04", + "v": 20.16 + }, + { + "t": "2019-06-14", + "v": 20.46 + }, + { + "t": "2019-06-24", + "v": 22.19 + }, + { + "t": "2019-07-04", + "v": 25.03 + }, + { + "t": "2019-07-14", + "v": 25.94 + }, + { + "t": "2019-07-24", + "v": 25.87 + }, + { + "t": "2019-08-03", + "v": 26.04 + }, + { + "t": "2019-08-13", + "v": 26.33 + }, + { + "t": "2019-08-23", + "v": 26.69 + }, + { + "t": "2019-09-02", + "v": 26.39 + }, + { + "t": "2019-09-12", + "v": 24.8 + }, + { + "t": "2019-09-22", + "v": 24.65 + }, + { + "t": "2019-10-02", + "v": 24.69 + }, + { + "t": "2019-10-12", + "v": 23.76 + }, + { + "t": "2019-10-22", + "v": 23.15 + }, + { + "t": "2019-11-01", + "v": 22.3 + }, + { + "t": "2019-11-11", + "v": 19.82 + }, + { + "t": "2019-11-21", + "v": 18.83 + }, + { + "t": "2019-12-01", + "v": 18.24 + }, + { + "t": "2019-12-11", + "v": 17.3 + }, + { + "t": "2019-12-21", + "v": 16.99 + }, + { + "t": "2019-12-31", + "v": 16.06 + }, + { + "t": "2020-01-10", + "v": 15.81 + }, + { + "t": "2020-01-20", + "v": 14.99 + }, + { + "t": "2020-01-30", + "v": 15.44 + }, + { + "t": "2020-02-09", + "v": 15.39 + }, + { + "t": "2020-02-19", + "v": 15.55 + }, + { + "t": "2020-02-29", + "v": 15.42 + }, + { + "t": "2020-03-10", + "v": 15.3 + }, + { + "t": "2020-03-20", + "v": 14.22 + }, + { + "t": "2020-03-30", + "v": 15.33 + }, + { + "t": "2020-04-09", + "v": 16.54 + }, + { + "t": "2020-04-19", + "v": 17.23 + }, + { + "t": "2020-04-29", + "v": 17.91 + }, + { + "t": "2020-05-09", + "v": 18.53 + }, + { + "t": "2020-05-19", + "v": 18.92 + }, + { + "t": "2020-05-29", + "v": 20.38 + }, + { + "t": "2020-06-08", + "v": 21.37 + }, + { + "t": "2020-06-18", + "v": 21.82 + }, + { + "t": "2020-06-28", + "v": 24.08 + }, + { + "t": "2020-07-08", + "v": 23.92 + }, + { + "t": "2020-07-18", + "v": 24.46 + }, + { + "t": "2020-07-28", + "v": 25.53 + }, + { + "t": "2020-08-07", + "v": 25.79 + }, + { + "t": "2020-08-17", + "v": 26.91 + }, + { + "t": "2020-08-27", + "v": 27.31 + }, + { + "t": "2020-09-06", + "v": 26.49 + }, + { + "t": "2020-09-16", + "v": 26.25 + }, + { + "t": "2020-09-26", + "v": 25.41 + }, + { + "t": "2020-10-06", + "v": 23.48 + }, + { + "t": "2020-10-16", + "v": 22.43 + }, + { + "t": "2020-10-26", + "v": 21.78 + }, + { + "t": "2020-11-05", + "v": 20.7 + }, + { + "t": "2020-11-15", + "v": 20.3 + }, + { + "t": "2020-11-25", + "v": 19.27 + }, + { + "t": "2020-12-05", + "v": 18.58 + }, + { + "t": "2020-12-15", + "v": 17.23 + }, + { + "t": "2020-12-25", + "v": 17.19 + }, + { + "t": "2021-01-04", + "v": 15.51 + }, + { + "t": "2021-01-14", + "v": 15.46 + }, + { + "t": "2021-01-24", + "v": 14.92 + }, + { + "t": "2021-02-03", + "v": 15.02 + }, + { + "t": "2021-02-13", + "v": 14.85 + }, + { + "t": "2021-02-23", + "v": 15.25 + }, + { + "t": "2021-03-05", + "v": 14.79 + }, + { + "t": "2021-03-15", + "v": 15.36 + }, + { + "t": "2021-03-26", + "v": 15.47 + }, + { + "t": "2021-04-05", + "v": 16.01 + }, + { + "t": "2021-04-15", + "v": 15.86 + }, + { + "t": "2021-04-25", + "v": 16.5 + }, + { + "t": "2021-05-05", + "v": 17.32 + }, + { + "t": "2021-05-15", + "v": 18.43 + }, + { + "t": "2021-05-25", + "v": 19 + }, + { + "t": "2021-06-04", + "v": 19.96 + }, + { + "t": "2021-06-14", + "v": 23.85 + }, + { + "t": "2021-06-24", + "v": 23.3 + }, + { + "t": "2021-07-04", + "v": 24.98 + }, + { + "t": "2021-07-14", + "v": 25.58 + }, + { + "t": "2021-07-24", + "v": 25.34 + }, + { + "t": "2021-08-03", + "v": 25.42 + }, + { + "t": "2021-08-13", + "v": 27.02 + }, + { + "t": "2021-08-23", + "v": 26.44 + }, + { + "t": "2021-09-02", + "v": 25.81 + }, + { + "t": "2021-09-13", + "v": 25.97 + }, + { + "t": "2021-09-23", + "v": 24.91 + }, + { + "t": "2021-10-03", + "v": 25.12 + }, + { + "t": "2021-10-13", + "v": 23.35 + }, + { + "t": "2021-10-23", + "v": 22.83 + }, + { + "t": "2021-11-02", + "v": 22.24 + }, + { + "t": "2021-11-12", + "v": 20.26 + }, + { + "t": "2021-11-22", + "v": 19.15 + }, + { + "t": "2021-12-02", + "v": 17.25 + }, + { + "t": "2021-12-12", + "v": 15.85 + }, + { + "t": "2021-12-22", + "v": 15.55 + }, + { + "t": "2022-01-01", + "v": 15.22 + }, + { + "t": "2022-01-11", + "v": 15.12 + }, + { + "t": "2022-01-21", + "v": 14.94 + }, + { + "t": "2022-01-31", + "v": 14.94 + }, + { + "t": "2022-02-10", + "v": 14.76 + }, + { + "t": "2022-02-20", + "v": 14.78 + }, + { + "t": "2022-03-02", + "v": 14.54 + }, + { + "t": "2022-03-12", + "v": 14.75 + }, + { + "t": "2022-03-22", + "v": 14.97 + }, + { + "t": "2022-04-01", + "v": 15.29 + }, + { + "t": "2022-04-11", + "v": 15.27 + }, + { + "t": "2022-04-21", + "v": 16 + }, + { + "t": "2022-05-01", + "v": 17.33 + }, + { + "t": "2022-05-11", + "v": 18.1 + }, + { + "t": "2022-05-21", + "v": 20.22 + }, + { + "t": "2022-05-31", + "v": 20.9 + }, + { + "t": "2022-06-10", + "v": 22.28 + }, + { + "t": "2022-06-20", + "v": 23.92 + }, + { + "t": "2022-06-30", + "v": 25.38 + }, + { + "t": "2022-07-10", + "v": 25.77 + }, + { + "t": "2022-07-20", + "v": 27.63 + }, + { + "t": "2022-07-30", + "v": 27.88 + }, + { + "t": "2022-08-09", + "v": 28.49 + }, + { + "t": "2022-08-19", + "v": 28.25 + }, + { + "t": "2022-08-29", + "v": 27.29 + }, + { + "t": "2022-09-08", + "v": 27.61 + }, + { + "t": "2022-09-18", + "v": 26.82 + }, + { + "t": "2022-09-28", + "v": 25.24 + }, + { + "t": "2022-10-08", + "v": 24.03 + }, + { + "t": "2022-10-18", + "v": 23.55 + }, + { + "t": "2022-10-29", + "v": 23.33 + }, + { + "t": "2022-11-08", + "v": 21.85 + }, + { + "t": "2022-11-18", + "v": 21.09 + }, + { + "t": "2022-11-28", + "v": 19.33 + }, + { + "t": "2022-12-08", + "v": 18.15 + }, + { + "t": "2022-12-18", + "v": 17.81 + }, + { + "t": "2022-12-28", + "v": 17.45 + }, + { + "t": "2023-01-07", + "v": 17.08 + }, + { + "t": "2023-01-17", + "v": 16.67 + }, + { + "t": "2023-01-27", + "v": 15.55 + }, + { + "t": "2023-02-07", + "v": 14.94 + }, + { + "t": "2023-02-17", + "v": 14.75 + }, + { + "t": "2023-02-27", + "v": 14.93 + }, + { + "t": "2023-03-09", + "v": 14.7 + }, + { + "t": "2023-03-19", + "v": 15.31 + }, + { + "t": "2023-03-29", + "v": 15.96 + }, + { + "t": "2023-04-08", + "v": 16.76 + }, + { + "t": "2023-04-18", + "v": 16.42 + }, + { + "t": "2023-04-28", + "v": 18.35 + }, + { + "t": "2023-05-08", + "v": 18.51 + }, + { + "t": "2023-05-18", + "v": 18.64 + }, + { + "t": "2023-05-28", + "v": 19.88 + }, + { + "t": "2023-06-07", + "v": 22.17 + }, + { + "t": "2023-06-17", + "v": 23.48 + }, + { + "t": "2023-06-27", + "v": 24.34 + }, + { + "t": "2023-07-07", + "v": 25.35 + }, + { + "t": "2023-07-17", + "v": 27.34 + }, + { + "t": "2023-07-27", + "v": 27.07 + }, + { + "t": "2023-08-06", + "v": 26.67 + }, + { + "t": "2023-08-16", + "v": 26.49 + }, + { + "t": "2023-08-26", + "v": 27.89 + }, + { + "t": "2023-09-05", + "v": 25.39 + }, + { + "t": "2023-09-15", + "v": 25.95 + }, + { + "t": "2023-09-25", + "v": 25.59 + }, + { + "t": "2023-10-05", + "v": 25.17 + }, + { + "t": "2023-10-15", + "v": 24.87 + }, + { + "t": "2023-10-25", + "v": 23.15 + }, + { + "t": "2023-11-04", + "v": 22.21 + }, + { + "t": "2023-11-14", + "v": 21.33 + }, + { + "t": "2023-11-24", + "v": 20.06 + }, + { + "t": "2023-12-04", + "v": 18.86 + }, + { + "t": "2023-12-14", + "v": 17.81 + }, + { + "t": "2024-01-04", + "v": 16.67 + }, + { + "t": "2024-01-14", + "v": 15.92 + }, + { + "t": "2024-01-24", + "v": 15.54 + }, + { + "t": "2024-02-03", + "v": 15.31 + }, + { + "t": "2024-02-13", + "v": 15.43 + }, + { + "t": "2024-02-23", + "v": 15.39 + }, + { + "t": "2024-03-04", + "v": 15.16 + }, + { + "t": "2024-03-14", + "v": 15.74 + }, + { + "t": "2024-03-24", + "v": 16.51 + }, + { + "t": "2024-04-04", + "v": 16.96 + }, + { + "t": "2024-04-14", + "v": 16.87 + }, + { + "t": "2024-04-24", + "v": 16.48 + }, + { + "t": "2024-05-04", + "v": 17.53 + }, + { + "t": "2024-05-14", + "v": 18.96 + }, + { + "t": "2024-05-24", + "v": 20.42 + }, + { + "t": "2024-06-03", + "v": 21.29 + }, + { + "t": "2024-06-13", + "v": 22.56 + }, + { + "t": "2024-06-23", + "v": 23.62 + }, + { + "t": "2024-07-03", + "v": 24.21 + }, + { + "t": "2024-07-13", + "v": 25.85 + }, + { + "t": "2024-07-23", + "v": 26.28 + }, + { + "t": "2024-08-02", + "v": 27.24 + }, + { + "t": "2024-08-12", + "v": 27.43 + }, + { + "t": "2024-08-22", + "v": 27.11 + }, + { + "t": "2024-09-01", + "v": 26.93 + }, + { + "t": "2024-09-11", + "v": 26.2 + }, + { + "t": "2024-09-21", + "v": 24.08 + }, + { + "t": "2024-10-01", + "v": 23.94 + }, + { + "t": "2024-10-11", + "v": 23.28 + }, + { + "t": "2024-10-21", + "v": 22.99 + }, + { + "t": "2024-10-31", + "v": 22.52 + }, + { + "t": "2024-11-10", + "v": 22.04 + }, + { + "t": "2024-11-20", + "v": 20.91 + }, + { + "t": "2024-11-30", + "v": 19.97 + }, + { + "t": "2024-12-10", + "v": 18.53 + }, + { + "t": "2024-12-20", + "v": 17.42 + }, + { + "t": "2024-12-30", + "v": 16.46 + }, + { + "t": "2025-01-09", + "v": 16.46 + }, + { + "t": "2025-01-19", + "v": 15.75 + }, + { + "t": "2025-01-29", + "v": 15.7 + }, + { + "t": "2025-02-08", + "v": 15.4 + }, + { + "t": "2025-02-18", + "v": 15.4 + }, + { + "t": "2025-02-28", + "v": 15.57 + }, + { + "t": "2025-03-10", + "v": 15.67 + }, + { + "t": "2025-03-20", + "v": 15.65 + }, + { + "t": "2025-03-30", + "v": 15.85 + }, + { + "t": "2025-04-09", + "v": 16.7 + }, + { + "t": "2025-04-19", + "v": 16.66 + }, + { + "t": "2025-04-29", + "v": 17.73 + }, + { + "t": "2025-05-09", + "v": 18.46 + }, + { + "t": "2025-05-19", + "v": 19.1 + }, + { + "t": "2025-05-29", + "v": 20.75 + }, + { + "t": "2025-06-08", + "v": 22.74 + }, + { + "t": "2025-06-18", + "v": 24.21 + }, + { + "t": "2025-06-29", + "v": 26.56 + }, + { + "t": "2025-07-09", + "v": 27.31 + }, + { + "t": "2025-07-19", + "v": 27.35 + }, + { + "t": "2025-07-29", + "v": 25.8 + }, + { + "t": "2025-08-08", + "v": 25.95 + }, + { + "t": "2025-08-18", + "v": 26.89 + }, + { + "t": "2025-08-28", + "v": 26.54 + }, + { + "t": "2025-09-07", + "v": 26.85 + }, + { + "t": "2025-09-17", + "v": 26.54 + }, + { + "t": "2025-09-27", + "v": 25.74 + }, + { + "t": "2025-10-07", + "v": 24.63 + }, + { + "t": "2025-10-17", + "v": 24.02 + }, + { + "t": "2025-10-27", + "v": 23.03 + }, + { + "t": "2025-11-06", + "v": 22.35 + }, + { + "t": "2025-11-16", + "v": 20.95 + }, + { + "t": "2025-11-26", + "v": 19.07 + }, + { + "t": "2025-12-06", + "v": 17.9 + }, + { + "t": "2025-12-16", + "v": 17.7 + }, + { + "t": "2025-12-26", + "v": 17.16 + } + ], + "dashboard": "dashboard offline" +} \ No newline at end of file diff --git a/test/fixtures/ind-sst-med-recent-2026-09-27.json b/test/fixtures/ind-sst-med-recent-2026-09-27.json new file mode 100644 index 0000000..5f5d61b --- /dev/null +++ b/test/fixtures/ind-sst-med-recent-2026-09-27.json @@ -0,0 +1,207 @@ +{ + "source": "NOAA OISST v2.1 (0.25° daily SST) via CoastWatch ERDDAP", + "gridCell": { + "lat": 38.625, + "lon": 5.625 + }, + "window": { + "from": "2026-07-29", + "to": "2026-09-11", + "strideDays": 1 + }, + "latest": { + "t": "2026-09-11", + "v": 28.18 + }, + "stats": { + "min": 28.07, + "max": 29.25, + "mean": 28.7222, + "n": 45 + }, + "trendPerDecade": null, + "summary": "SST at (38.625, 5.625): latest 28.18 °C (2026-09-11), 2026-07-29…2026-09-11 mean 28.7222 °C, range 28.07–29.25 °C.", + "series": [ + { + "t": "2026-07-29", + "v": 28.36 + }, + { + "t": "2026-07-30", + "v": 28.49 + }, + { + "t": "2026-07-31", + "v": 28.69 + }, + { + "t": "2026-08-01", + "v": 28.82 + }, + { + "t": "2026-08-02", + "v": 28.74 + }, + { + "t": "2026-08-03", + "v": 28.82 + }, + { + "t": "2026-08-04", + "v": 28.85 + }, + { + "t": "2026-08-05", + "v": 28.93 + }, + { + "t": "2026-08-06", + "v": 29.04 + }, + { + "t": "2026-08-07", + "v": 29.06 + }, + { + "t": "2026-08-08", + "v": 29.25 + }, + { + "t": "2026-08-09", + "v": 28.93 + }, + { + "t": "2026-08-10", + "v": 28.65 + }, + { + "t": "2026-08-11", + "v": 28.64 + }, + { + "t": "2026-08-12", + "v": 28.71 + }, + { + "t": "2026-08-13", + "v": 28.83 + }, + { + "t": "2026-08-14", + "v": 28.93 + }, + { + "t": "2026-08-15", + "v": 28.98 + }, + { + "t": "2026-08-16", + "v": 29.08 + }, + { + "t": "2026-08-17", + "v": 29.2 + }, + { + "t": "2026-08-18", + "v": 29.22 + }, + { + "t": "2026-08-19", + "v": 29.2 + }, + { + "t": "2026-08-20", + "v": 29.16 + }, + { + "t": "2026-08-21", + "v": 28.79 + }, + { + "t": "2026-08-22", + "v": 28.63 + }, + { + "t": "2026-08-23", + "v": 28.58 + }, + { + "t": "2026-08-24", + "v": 28.52 + }, + { + "t": "2026-08-25", + "v": 28.27 + }, + { + "t": "2026-08-26", + "v": 28.07 + }, + { + "t": "2026-08-27", + "v": 28.3 + }, + { + "t": "2026-08-28", + "v": 28.27 + }, + { + "t": "2026-08-29", + "v": 28.16 + }, + { + "t": "2026-08-30", + "v": 28.22 + }, + { + "t": "2026-08-31", + "v": 28.33 + }, + { + "t": "2026-09-01", + "v": 28.44 + }, + { + "t": "2026-09-02", + "v": 28.56 + }, + { + "t": "2026-09-03", + "v": 28.71 + }, + { + "t": "2026-09-04", + "v": 28.86 + }, + { + "t": "2026-09-05", + "v": 29.01 + }, + { + "t": "2026-09-06", + "v": 29.03 + }, + { + "t": "2026-09-07", + "v": 28.93 + }, + { + "t": "2026-09-08", + "v": 28.9 + }, + { + "t": "2026-09-09", + "v": 28.78 + }, + { + "t": "2026-09-10", + "v": 28.38 + }, + { + "t": "2026-09-11", + "v": 28.18 + } + ], + "dashboard": "dashboard offline" +} \ No newline at end of file diff --git a/test/fixtures/ind-sst-nino34-base-2016-2025.json b/test/fixtures/ind-sst-nino34-base-2016-2025.json new file mode 100644 index 0000000..aef3aa0 --- /dev/null +++ b/test/fixtures/ind-sst-nino34-base-2016-2025.json @@ -0,0 +1,1483 @@ +{ + "source": "NOAA OISST v2.1 (0.25° daily SST) via CoastWatch ERDDAP", + "gridCell": { + "lat": 0.125, + "lon": -144.875 + }, + "window": { + "from": "2016-01-01", + "to": "2025-12-31", + "strideDays": 10 + }, + "latest": { + "t": "2025-12-26", + "v": 24.95 + }, + "stats": { + "min": 23.35, + "max": 29.62, + "mean": 26.2625, + "n": 364 + }, + "trendPerDecade": -0.385, + "summary": "SST at (0.125, -144.875): latest 24.95 °C (2025-12-26), 2016-01-01…2025-12-31 mean 26.2625 °C, range 23.35–29.62 °C, trend -0.39 °C/decade.", + "series": [ + { + "t": "2016-01-01", + "v": 28.45 + }, + { + "t": "2016-01-11", + "v": 29.05 + }, + { + "t": "2016-01-21", + "v": 29.62 + }, + { + "t": "2016-01-31", + "v": 29.62 + }, + { + "t": "2016-02-10", + "v": 28.88 + }, + { + "t": "2016-02-20", + "v": 28.67 + }, + { + "t": "2016-03-01", + "v": 28.87 + }, + { + "t": "2016-03-11", + "v": 28.15 + }, + { + "t": "2016-03-21", + "v": 27.81 + }, + { + "t": "2016-03-31", + "v": 27.07 + }, + { + "t": "2016-04-10", + "v": 29.08 + }, + { + "t": "2016-04-20", + "v": 29.06 + }, + { + "t": "2016-04-30", + "v": 27.83 + }, + { + "t": "2016-05-10", + "v": 26.75 + }, + { + "t": "2016-05-20", + "v": 26.27 + }, + { + "t": "2016-05-30", + "v": 25.64 + }, + { + "t": "2016-06-09", + "v": 26.58 + }, + { + "t": "2016-06-19", + "v": 25.99 + }, + { + "t": "2016-06-29", + "v": 25.52 + }, + { + "t": "2016-07-09", + "v": 24.48 + }, + { + "t": "2016-07-19", + "v": 24.98 + }, + { + "t": "2016-07-29", + "v": 26.65 + }, + { + "t": "2016-08-08", + "v": 25.46 + }, + { + "t": "2016-08-18", + "v": 24.2 + }, + { + "t": "2016-08-28", + "v": 24.93 + }, + { + "t": "2016-09-07", + "v": 24.67 + }, + { + "t": "2016-09-17", + "v": 24.96 + }, + { + "t": "2016-09-27", + "v": 25.55 + }, + { + "t": "2016-10-07", + "v": 25.46 + }, + { + "t": "2016-10-17", + "v": 23.96 + }, + { + "t": "2016-10-27", + "v": 25.45 + }, + { + "t": "2016-11-06", + "v": 24.89 + }, + { + "t": "2016-11-16", + "v": 24.43 + }, + { + "t": "2016-11-26", + "v": 24.61 + }, + { + "t": "2016-12-06", + "v": 24.92 + }, + { + "t": "2016-12-16", + "v": 25.43 + }, + { + "t": "2016-12-26", + "v": 25.34 + }, + { + "t": "2017-01-05", + "v": 25.66 + }, + { + "t": "2017-01-15", + "v": 25.47 + }, + { + "t": "2017-01-25", + "v": 25.43 + }, + { + "t": "2017-02-04", + "v": 25.7 + }, + { + "t": "2017-02-14", + "v": 26.43 + }, + { + "t": "2017-02-24", + "v": 26.8 + }, + { + "t": "2017-03-06", + "v": 25.76 + }, + { + "t": "2017-03-16", + "v": 26.78 + }, + { + "t": "2017-03-26", + "v": 26.6 + }, + { + "t": "2017-04-05", + "v": 27.72 + }, + { + "t": "2017-04-15", + "v": 28.4 + }, + { + "t": "2017-04-25", + "v": 27.3 + }, + { + "t": "2017-05-05", + "v": 27.82 + }, + { + "t": "2017-05-15", + "v": 27.55 + }, + { + "t": "2017-05-25", + "v": 27.59 + }, + { + "t": "2017-06-04", + "v": 27.37 + }, + { + "t": "2017-06-14", + "v": 28.03 + }, + { + "t": "2017-06-24", + "v": 27.57 + }, + { + "t": "2017-07-04", + "v": 27.62 + }, + { + "t": "2017-07-14", + "v": 26.69 + }, + { + "t": "2017-07-24", + "v": 26.18 + }, + { + "t": "2017-08-03", + "v": 26.08 + }, + { + "t": "2017-08-13", + "v": 25.37 + }, + { + "t": "2017-08-23", + "v": 25.79 + }, + { + "t": "2017-09-02", + "v": 25.27 + }, + { + "t": "2017-09-12", + "v": 25.22 + }, + { + "t": "2017-09-22", + "v": 25.31 + }, + { + "t": "2017-10-02", + "v": 26.33 + }, + { + "t": "2017-10-12", + "v": 24.99 + }, + { + "t": "2017-10-22", + "v": 24.7 + }, + { + "t": "2017-11-01", + "v": 23.96 + }, + { + "t": "2017-11-11", + "v": 24.24 + }, + { + "t": "2017-11-21", + "v": 24.71 + }, + { + "t": "2017-12-01", + "v": 23.99 + }, + { + "t": "2017-12-11", + "v": 25.29 + }, + { + "t": "2017-12-21", + "v": 24.14 + }, + { + "t": "2017-12-31", + "v": 24.45 + }, + { + "t": "2018-01-10", + "v": 23.72 + }, + { + "t": "2018-01-20", + "v": 25.45 + }, + { + "t": "2018-01-30", + "v": 25.28 + }, + { + "t": "2018-02-09", + "v": 24.78 + }, + { + "t": "2018-02-19", + "v": 25.04 + }, + { + "t": "2018-03-01", + "v": 24.85 + }, + { + "t": "2018-03-11", + "v": 25.72 + }, + { + "t": "2018-03-21", + "v": 25.46 + }, + { + "t": "2018-03-31", + "v": 26.02 + }, + { + "t": "2018-04-10", + "v": 26.27 + }, + { + "t": "2018-04-20", + "v": 26.18 + }, + { + "t": "2018-04-30", + "v": 26.78 + }, + { + "t": "2018-05-10", + "v": 27.26 + }, + { + "t": "2018-05-20", + "v": 27 + }, + { + "t": "2018-05-30", + "v": 27.1 + }, + { + "t": "2018-06-09", + "v": 27 + }, + { + "t": "2018-06-19", + "v": 27.4 + }, + { + "t": "2018-06-29", + "v": 27.25 + }, + { + "t": "2018-07-09", + "v": 27.1 + }, + { + "t": "2018-07-19", + "v": 26.91 + }, + { + "t": "2018-07-29", + "v": 26.33 + }, + { + "t": "2018-08-08", + "v": 26.66 + }, + { + "t": "2018-08-18", + "v": 27.13 + }, + { + "t": "2018-08-28", + "v": 26.27 + }, + { + "t": "2018-09-07", + "v": 27.35 + }, + { + "t": "2018-09-17", + "v": 26.59 + }, + { + "t": "2018-09-27", + "v": 26.63 + }, + { + "t": "2018-10-07", + "v": 26.96 + }, + { + "t": "2018-10-17", + "v": 26.93 + }, + { + "t": "2018-10-27", + "v": 27.44 + }, + { + "t": "2018-11-06", + "v": 27.51 + }, + { + "t": "2018-11-16", + "v": 27.25 + }, + { + "t": "2018-11-26", + "v": 26.97 + }, + { + "t": "2018-12-06", + "v": 27.4 + }, + { + "t": "2018-12-16", + "v": 26.93 + }, + { + "t": "2018-12-26", + "v": 27.02 + }, + { + "t": "2019-01-05", + "v": 26.56 + }, + { + "t": "2019-01-15", + "v": 25.83 + }, + { + "t": "2019-01-25", + "v": 26.21 + }, + { + "t": "2019-02-04", + "v": 26.14 + }, + { + "t": "2019-02-14", + "v": 27.01 + }, + { + "t": "2019-02-24", + "v": 26.82 + }, + { + "t": "2019-03-06", + "v": 27.74 + }, + { + "t": "2019-03-16", + "v": 28.32 + }, + { + "t": "2019-03-26", + "v": 28.2 + }, + { + "t": "2019-04-05", + "v": 27.85 + }, + { + "t": "2019-04-15", + "v": 27.76 + }, + { + "t": "2019-04-25", + "v": 27.95 + }, + { + "t": "2019-05-05", + "v": 28.3 + }, + { + "t": "2019-05-15", + "v": 27.75 + }, + { + "t": "2019-05-25", + "v": 28.14 + }, + { + "t": "2019-06-04", + "v": 28.26 + }, + { + "t": "2019-06-14", + "v": 27.9 + }, + { + "t": "2019-06-24", + "v": 27.14 + }, + { + "t": "2019-07-04", + "v": 27.4 + }, + { + "t": "2019-07-14", + "v": 27.68 + }, + { + "t": "2019-07-24", + "v": 27.43 + }, + { + "t": "2019-08-03", + "v": 27.26 + }, + { + "t": "2019-08-13", + "v": 26.77 + }, + { + "t": "2019-08-23", + "v": 25.92 + }, + { + "t": "2019-09-02", + "v": 25.07 + }, + { + "t": "2019-09-12", + "v": 25.93 + }, + { + "t": "2019-09-22", + "v": 27.1 + }, + { + "t": "2019-10-02", + "v": 26.86 + }, + { + "t": "2019-10-12", + "v": 26.95 + }, + { + "t": "2019-10-22", + "v": 26.73 + }, + { + "t": "2019-11-01", + "v": 26.77 + }, + { + "t": "2019-11-11", + "v": 26.92 + }, + { + "t": "2019-11-21", + "v": 25.95 + }, + { + "t": "2019-12-01", + "v": 25.86 + }, + { + "t": "2019-12-11", + "v": 25.98 + }, + { + "t": "2019-12-21", + "v": 26.28 + }, + { + "t": "2019-12-31", + "v": 26.7 + }, + { + "t": "2020-01-10", + "v": 26.73 + }, + { + "t": "2020-01-20", + "v": 26.26 + }, + { + "t": "2020-01-30", + "v": 26.4 + }, + { + "t": "2020-02-09", + "v": 25.91 + }, + { + "t": "2020-02-19", + "v": 26.33 + }, + { + "t": "2020-02-29", + "v": 26.71 + }, + { + "t": "2020-03-10", + "v": 26.92 + }, + { + "t": "2020-03-20", + "v": 27.38 + }, + { + "t": "2020-03-30", + "v": 27.22 + }, + { + "t": "2020-04-09", + "v": 27.48 + }, + { + "t": "2020-04-19", + "v": 27.81 + }, + { + "t": "2020-04-29", + "v": 27.14 + }, + { + "t": "2020-05-09", + "v": 26.07 + }, + { + "t": "2020-05-19", + "v": 26.35 + }, + { + "t": "2020-05-29", + "v": 26.02 + }, + { + "t": "2020-06-08", + "v": 26.06 + }, + { + "t": "2020-06-18", + "v": 26.79 + }, + { + "t": "2020-06-28", + "v": 26.14 + }, + { + "t": "2020-07-08", + "v": 27.14 + }, + { + "t": "2020-07-18", + "v": 25.74 + }, + { + "t": "2020-07-28", + "v": 25.95 + }, + { + "t": "2020-08-07", + "v": 24.88 + }, + { + "t": "2020-08-17", + "v": 25.98 + }, + { + "t": "2020-08-27", + "v": 24.52 + }, + { + "t": "2020-09-06", + "v": 25.96 + }, + { + "t": "2020-09-16", + "v": 25.37 + }, + { + "t": "2020-09-26", + "v": 25.32 + }, + { + "t": "2020-10-06", + "v": 25.04 + }, + { + "t": "2020-10-16", + "v": 25.8 + }, + { + "t": "2020-10-26", + "v": 24.5 + }, + { + "t": "2020-11-05", + "v": 23.35 + }, + { + "t": "2020-11-15", + "v": 25.15 + }, + { + "t": "2020-11-25", + "v": 24.96 + }, + { + "t": "2020-12-05", + "v": 24.64 + }, + { + "t": "2020-12-15", + "v": 24.67 + }, + { + "t": "2020-12-25", + "v": 24.74 + }, + { + "t": "2021-01-04", + "v": 25.15 + }, + { + "t": "2021-01-14", + "v": 24.51 + }, + { + "t": "2021-01-24", + "v": 24.75 + }, + { + "t": "2021-02-03", + "v": 24.89 + }, + { + "t": "2021-02-13", + "v": 24.56 + }, + { + "t": "2021-02-23", + "v": 24.52 + }, + { + "t": "2021-03-05", + "v": 25.31 + }, + { + "t": "2021-03-15", + "v": 25.78 + }, + { + "t": "2021-03-26", + "v": 25.91 + }, + { + "t": "2021-04-05", + "v": 26.34 + }, + { + "t": "2021-04-15", + "v": 26.68 + }, + { + "t": "2021-04-25", + "v": 26.4 + }, + { + "t": "2021-05-05", + "v": 26.88 + }, + { + "t": "2021-05-15", + "v": 27.17 + }, + { + "t": "2021-05-25", + "v": 27.16 + }, + { + "t": "2021-06-04", + "v": 26.93 + }, + { + "t": "2021-06-14", + "v": 26.36 + }, + { + "t": "2021-06-24", + "v": 26.65 + }, + { + "t": "2021-07-04", + "v": 26.71 + }, + { + "t": "2021-07-14", + "v": 26.52 + }, + { + "t": "2021-07-24", + "v": 27.3 + }, + { + "t": "2021-08-03", + "v": 25.99 + }, + { + "t": "2021-08-13", + "v": 25.75 + }, + { + "t": "2021-08-23", + "v": 25.23 + }, + { + "t": "2021-09-02", + "v": 25.77 + }, + { + "t": "2021-09-13", + "v": 26.36 + }, + { + "t": "2021-09-23", + "v": 26.12 + }, + { + "t": "2021-10-03", + "v": 24.04 + }, + { + "t": "2021-10-13", + "v": 25.83 + }, + { + "t": "2021-10-23", + "v": 24.79 + }, + { + "t": "2021-11-02", + "v": 24.89 + }, + { + "t": "2021-11-12", + "v": 24.42 + }, + { + "t": "2021-11-22", + "v": 25.02 + }, + { + "t": "2021-12-02", + "v": 24.59 + }, + { + "t": "2021-12-12", + "v": 24.44 + }, + { + "t": "2021-12-22", + "v": 25.46 + }, + { + "t": "2022-01-01", + "v": 25.1 + }, + { + "t": "2022-01-11", + "v": 24.62 + }, + { + "t": "2022-01-21", + "v": 24.98 + }, + { + "t": "2022-01-31", + "v": 25.7 + }, + { + "t": "2022-02-10", + "v": 25.53 + }, + { + "t": "2022-02-20", + "v": 25.37 + }, + { + "t": "2022-03-02", + "v": 25.13 + }, + { + "t": "2022-03-12", + "v": 25.7 + }, + { + "t": "2022-03-22", + "v": 26.17 + }, + { + "t": "2022-04-01", + "v": 26.18 + }, + { + "t": "2022-04-11", + "v": 26.09 + }, + { + "t": "2022-04-21", + "v": 25.58 + }, + { + "t": "2022-05-01", + "v": 25.64 + }, + { + "t": "2022-05-11", + "v": 25.94 + }, + { + "t": "2022-05-21", + "v": 26.08 + }, + { + "t": "2022-05-31", + "v": 25.97 + }, + { + "t": "2022-06-10", + "v": 26.39 + }, + { + "t": "2022-06-20", + "v": 26.7 + }, + { + "t": "2022-06-30", + "v": 26.6 + }, + { + "t": "2022-07-10", + "v": 26.1 + }, + { + "t": "2022-07-20", + "v": 25.78 + }, + { + "t": "2022-07-30", + "v": 24.87 + }, + { + "t": "2022-08-09", + "v": 25.22 + }, + { + "t": "2022-08-19", + "v": 24.67 + }, + { + "t": "2022-08-29", + "v": 25.11 + }, + { + "t": "2022-09-08", + "v": 24.73 + }, + { + "t": "2022-09-18", + "v": 25.3 + }, + { + "t": "2022-09-28", + "v": 25.03 + }, + { + "t": "2022-10-08", + "v": 26.41 + }, + { + "t": "2022-10-18", + "v": 25.21 + }, + { + "t": "2022-10-29", + "v": 24.9 + }, + { + "t": "2022-11-08", + "v": 24.61 + }, + { + "t": "2022-11-18", + "v": 25.1 + }, + { + "t": "2022-11-28", + "v": 24.82 + }, + { + "t": "2022-12-08", + "v": 24.58 + }, + { + "t": "2022-12-18", + "v": 25.13 + }, + { + "t": "2022-12-28", + "v": 24.91 + }, + { + "t": "2023-01-07", + "v": 24.88 + }, + { + "t": "2023-01-17", + "v": 25.46 + }, + { + "t": "2023-01-27", + "v": 25.31 + }, + { + "t": "2023-02-07", + "v": 25.37 + }, + { + "t": "2023-02-17", + "v": 25.49 + }, + { + "t": "2023-02-27", + "v": 25.86 + }, + { + "t": "2023-03-09", + "v": 26.23 + }, + { + "t": "2023-03-19", + "v": 26.14 + }, + { + "t": "2023-03-29", + "v": 26.47 + }, + { + "t": "2023-04-08", + "v": 27 + }, + { + "t": "2023-04-18", + "v": 27.5 + }, + { + "t": "2023-04-28", + "v": 27.77 + }, + { + "t": "2023-05-08", + "v": 27.73 + }, + { + "t": "2023-05-18", + "v": 27.73 + }, + { + "t": "2023-05-28", + "v": 27.96 + }, + { + "t": "2023-06-07", + "v": 28.87 + }, + { + "t": "2023-06-17", + "v": 27.91 + }, + { + "t": "2023-06-27", + "v": 28.04 + }, + { + "t": "2023-07-07", + "v": 27.99 + }, + { + "t": "2023-07-17", + "v": 27.93 + }, + { + "t": "2023-07-27", + "v": 27.59 + }, + { + "t": "2023-08-06", + "v": 27.29 + }, + { + "t": "2023-08-16", + "v": 27.45 + }, + { + "t": "2023-08-26", + "v": 27.81 + }, + { + "t": "2023-09-05", + "v": 28.2 + }, + { + "t": "2023-09-15", + "v": 28.23 + }, + { + "t": "2023-09-25", + "v": 27.5 + }, + { + "t": "2023-10-05", + "v": 27.32 + }, + { + "t": "2023-10-15", + "v": 27.59 + }, + { + "t": "2023-10-25", + "v": 27.45 + }, + { + "t": "2023-11-04", + "v": 27.97 + }, + { + "t": "2023-11-14", + "v": 27.54 + }, + { + "t": "2023-11-24", + "v": 28.6 + }, + { + "t": "2023-12-04", + "v": 28.04 + }, + { + "t": "2023-12-14", + "v": 28.11 + }, + { + "t": "2024-01-04", + "v": 28.14 + }, + { + "t": "2024-01-14", + "v": 27.43 + }, + { + "t": "2024-01-24", + "v": 27.8 + }, + { + "t": "2024-02-03", + "v": 27.81 + }, + { + "t": "2024-02-13", + "v": 27.47 + }, + { + "t": "2024-02-23", + "v": 27.39 + }, + { + "t": "2024-03-04", + "v": 27.79 + }, + { + "t": "2024-03-14", + "v": 27.5 + }, + { + "t": "2024-03-24", + "v": 27.55 + }, + { + "t": "2024-04-04", + "v": 28.74 + }, + { + "t": "2024-04-14", + "v": 27.25 + }, + { + "t": "2024-04-24", + "v": 27.85 + }, + { + "t": "2024-05-04", + "v": 27.3 + }, + { + "t": "2024-05-14", + "v": 26.85 + }, + { + "t": "2024-05-24", + "v": 26.57 + }, + { + "t": "2024-06-03", + "v": 27.21 + }, + { + "t": "2024-06-13", + "v": 26.63 + }, + { + "t": "2024-06-23", + "v": 27.26 + }, + { + "t": "2024-07-03", + "v": 26.91 + }, + { + "t": "2024-07-13", + "v": 26.41 + }, + { + "t": "2024-07-23", + "v": 26.11 + }, + { + "t": "2024-08-02", + "v": 25.96 + }, + { + "t": "2024-08-12", + "v": 24.97 + }, + { + "t": "2024-08-22", + "v": 25.92 + }, + { + "t": "2024-09-01", + "v": 26.04 + }, + { + "t": "2024-09-11", + "v": 25.49 + }, + { + "t": "2024-09-21", + "v": 25 + }, + { + "t": "2024-10-01", + "v": 24.41 + }, + { + "t": "2024-10-11", + "v": 24.99 + }, + { + "t": "2024-10-21", + "v": 24.89 + }, + { + "t": "2024-10-31", + "v": 25.15 + }, + { + "t": "2024-11-10", + "v": 25.11 + }, + { + "t": "2024-11-20", + "v": 26.79 + }, + { + "t": "2024-11-30", + "v": 25.85 + }, + { + "t": "2024-12-10", + "v": 24.77 + }, + { + "t": "2024-12-20", + "v": 24.77 + }, + { + "t": "2024-12-30", + "v": 24.14 + }, + { + "t": "2025-01-09", + "v": 24.08 + }, + { + "t": "2025-01-19", + "v": 23.7 + }, + { + "t": "2025-01-29", + "v": 24.36 + }, + { + "t": "2025-02-08", + "v": 25.15 + }, + { + "t": "2025-02-18", + "v": 24.99 + }, + { + "t": "2025-02-28", + "v": 26.29 + }, + { + "t": "2025-03-10", + "v": 26.11 + }, + { + "t": "2025-03-20", + "v": 25.86 + }, + { + "t": "2025-03-30", + "v": 26.05 + }, + { + "t": "2025-04-09", + "v": 26.45 + }, + { + "t": "2025-04-19", + "v": 27.12 + }, + { + "t": "2025-04-29", + "v": 27.7 + }, + { + "t": "2025-05-09", + "v": 27.32 + }, + { + "t": "2025-05-19", + "v": 26.69 + }, + { + "t": "2025-05-29", + "v": 27.11 + }, + { + "t": "2025-06-08", + "v": 26.54 + }, + { + "t": "2025-06-18", + "v": 26.67 + }, + { + "t": "2025-06-29", + "v": 26.8 + }, + { + "t": "2025-07-09", + "v": 26.71 + }, + { + "t": "2025-07-19", + "v": 26.34 + }, + { + "t": "2025-07-29", + "v": 25.58 + }, + { + "t": "2025-08-08", + "v": 25.61 + }, + { + "t": "2025-08-18", + "v": 25.71 + }, + { + "t": "2025-08-28", + "v": 25.6 + }, + { + "t": "2025-09-07", + "v": 26.21 + }, + { + "t": "2025-09-17", + "v": 25.43 + }, + { + "t": "2025-09-27", + "v": 24.68 + }, + { + "t": "2025-10-07", + "v": 26.46 + }, + { + "t": "2025-10-17", + "v": 25.83 + }, + { + "t": "2025-10-27", + "v": 25.72 + }, + { + "t": "2025-11-06", + "v": 24.81 + }, + { + "t": "2025-11-16", + "v": 24.89 + }, + { + "t": "2025-11-26", + "v": 24.78 + }, + { + "t": "2025-12-06", + "v": 26.15 + }, + { + "t": "2025-12-16", + "v": 25.01 + }, + { + "t": "2025-12-26", + "v": 24.95 + } + ], + "dashboard": "dashboard offline" +} \ No newline at end of file diff --git a/test/fixtures/ind-sst-nino34-recent-2026-09-27.json b/test/fixtures/ind-sst-nino34-recent-2026-09-27.json new file mode 100644 index 0000000..2511698 --- /dev/null +++ b/test/fixtures/ind-sst-nino34-recent-2026-09-27.json @@ -0,0 +1,431 @@ +{ + "source": "NOAA OISST v2.1 (0.25° daily SST) via CoastWatch ERDDAP", + "gridCell": { + "lat": 0.125, + "lon": -144.875 + }, + "window": { + "from": "2026-06-01", + "to": "2026-09-11", + "strideDays": 1 + }, + "latest": { + "t": "2026-09-11", + "v": 29.89 + }, + "stats": { + "min": 28.52, + "max": 30.13, + "mean": 29.3171, + "n": 101 + }, + "trendPerDecade": null, + "summary": "SST at (0.125, -144.875): latest 29.89 °C (2026-09-11), 2026-06-01…2026-09-11 mean 29.3171 °C, range 28.52–30.13 °C.", + "series": [ + { + "t": "2026-06-01", + "v": 28.52 + }, + { + "t": "2026-06-02", + "v": 28.74 + }, + { + "t": "2026-06-03", + "v": 28.9 + }, + { + "t": "2026-06-04", + "v": 28.99 + }, + { + "t": "2026-06-05", + "v": 29.03 + }, + { + "t": "2026-06-06", + "v": 29.02 + }, + { + "t": "2026-06-07", + "v": 28.99 + }, + { + "t": "2026-06-09", + "v": 28.92 + }, + { + "t": "2026-06-10", + "v": 28.91 + }, + { + "t": "2026-06-11", + "v": 28.89 + }, + { + "t": "2026-06-12", + "v": 28.94 + }, + { + "t": "2026-06-13", + "v": 29.06 + }, + { + "t": "2026-06-14", + "v": 29.16 + }, + { + "t": "2026-06-15", + "v": 29.16 + }, + { + "t": "2026-06-16", + "v": 29.06 + }, + { + "t": "2026-06-17", + "v": 29.1 + }, + { + "t": "2026-06-18", + "v": 29.03 + }, + { + "t": "2026-06-19", + "v": 28.92 + }, + { + "t": "2026-06-20", + "v": 29 + }, + { + "t": "2026-06-21", + "v": 29.06 + }, + { + "t": "2026-06-22", + "v": 29 + }, + { + "t": "2026-06-23", + "v": 29 + }, + { + "t": "2026-06-24", + "v": 29.08 + }, + { + "t": "2026-06-25", + "v": 29.02 + }, + { + "t": "2026-06-26", + "v": 28.88 + }, + { + "t": "2026-06-27", + "v": 28.75 + }, + { + "t": "2026-06-28", + "v": 28.72 + }, + { + "t": "2026-06-29", + "v": 28.59 + }, + { + "t": "2026-06-30", + "v": 28.55 + }, + { + "t": "2026-07-01", + "v": 28.59 + }, + { + "t": "2026-07-02", + "v": 28.57 + }, + { + "t": "2026-07-03", + "v": 28.55 + }, + { + "t": "2026-07-04", + "v": 28.64 + }, + { + "t": "2026-07-05", + "v": 28.67 + }, + { + "t": "2026-07-06", + "v": 29 + }, + { + "t": "2026-07-07", + "v": 29.14 + }, + { + "t": "2026-07-08", + "v": 29.07 + }, + { + "t": "2026-07-09", + "v": 28.97 + }, + { + "t": "2026-07-10", + "v": 28.96 + }, + { + "t": "2026-07-11", + "v": 28.95 + }, + { + "t": "2026-07-12", + "v": 28.9 + }, + { + "t": "2026-07-13", + "v": 28.9 + }, + { + "t": "2026-07-14", + "v": 29.11 + }, + { + "t": "2026-07-15", + "v": 29.07 + }, + { + "t": "2026-07-16", + "v": 29.01 + }, + { + "t": "2026-07-17", + "v": 29.05 + }, + { + "t": "2026-07-19", + "v": 29.08 + }, + { + "t": "2026-07-20", + "v": 29.16 + }, + { + "t": "2026-07-21", + "v": 29.22 + }, + { + "t": "2026-07-22", + "v": 29.31 + }, + { + "t": "2026-07-23", + "v": 29.34 + }, + { + "t": "2026-07-24", + "v": 29.29 + }, + { + "t": "2026-07-25", + "v": 29.32 + }, + { + "t": "2026-07-26", + "v": 29.35 + }, + { + "t": "2026-07-27", + "v": 29.36 + }, + { + "t": "2026-07-28", + "v": 29.35 + }, + { + "t": "2026-07-29", + "v": 29.36 + }, + { + "t": "2026-07-30", + "v": 29.46 + }, + { + "t": "2026-07-31", + "v": 29.56 + }, + { + "t": "2026-08-01", + "v": 29.61 + }, + { + "t": "2026-08-02", + "v": 29.68 + }, + { + "t": "2026-08-03", + "v": 29.77 + }, + { + "t": "2026-08-04", + "v": 29.9 + }, + { + "t": "2026-08-05", + "v": 29.81 + }, + { + "t": "2026-08-06", + "v": 29.7 + }, + { + "t": "2026-08-07", + "v": 29.86 + }, + { + "t": "2026-08-08", + "v": 29.92 + }, + { + "t": "2026-08-09", + "v": 30.05 + }, + { + "t": "2026-08-10", + "v": 29.97 + }, + { + "t": "2026-08-11", + "v": 29.79 + }, + { + "t": "2026-08-12", + "v": 29.65 + }, + { + "t": "2026-08-13", + "v": 29.66 + }, + { + "t": "2026-08-14", + "v": 29.7 + }, + { + "t": "2026-08-15", + "v": 29.7 + }, + { + "t": "2026-08-16", + "v": 29.69 + }, + { + "t": "2026-08-17", + "v": 29.46 + }, + { + "t": "2026-08-18", + "v": 29.37 + }, + { + "t": "2026-08-19", + "v": 29.43 + }, + { + "t": "2026-08-20", + "v": 29.39 + }, + { + "t": "2026-08-21", + "v": 29.43 + }, + { + "t": "2026-08-22", + "v": 29.56 + }, + { + "t": "2026-08-23", + "v": 29.52 + }, + { + "t": "2026-08-24", + "v": 29.55 + }, + { + "t": "2026-08-25", + "v": 29.55 + }, + { + "t": "2026-08-26", + "v": 29.63 + }, + { + "t": "2026-08-27", + "v": 29.65 + }, + { + "t": "2026-08-28", + "v": 29.74 + }, + { + "t": "2026-08-29", + "v": 29.85 + }, + { + "t": "2026-08-30", + "v": 29.83 + }, + { + "t": "2026-08-31", + "v": 29.8 + }, + { + "t": "2026-09-01", + "v": 29.76 + }, + { + "t": "2026-09-02", + "v": 29.82 + }, + { + "t": "2026-09-03", + "v": 29.88 + }, + { + "t": "2026-09-04", + "v": 30 + }, + { + "t": "2026-09-05", + "v": 29.97 + }, + { + "t": "2026-09-06", + "v": 29.97 + }, + { + "t": "2026-09-07", + "v": 30.13 + }, + { + "t": "2026-09-08", + "v": 30.1 + }, + { + "t": "2026-09-09", + "v": 30.07 + }, + { + "t": "2026-09-10", + "v": 29.92 + }, + { + "t": "2026-09-11", + "v": 29.89 + } + ], + "dashboard": "dashboard offline" +} \ No newline at end of file diff --git a/test/fixtures/ind-world-pulse-life-2026-09-27.json b/test/fixtures/ind-world-pulse-life-2026-09-27.json new file mode 100644 index 0000000..4c60def --- /dev/null +++ b/test/fixtures/ind-world-pulse-life-2026-09-27.json @@ -0,0 +1,145 @@ +{ + "source": "Our World in Data (CC BY 4.0; upstream licences per indicator)", + "counts": { + "improving": 1, + "worsening": 5, + "flat": 0, + "unavailable": 0 + }, + "summary": "1 improving · 5 worsening · 0 flat. Improving: Marine protected areas. Worsening: Living Planet Index (wildlife populations), Red List Index (species survival), Fish stocks within sustainable levels, Tree cover loss, Ocean surface pH (Station ALOHA).", + "indicators": [ + { + "slug": "global-living-planet-index", + "label": "Living Planet Index (wildlife populations)", + "unit": "index, 1970 = 100", + "group": "life", + "betterWhen": "up", + "upstream": "WWF / ZSL Living Planet Report", + "licence": "CC BY 4.0 (OWID); WWF/ZSL — attribute", + "status": "ok", + "latest": { + "t": "2020", + "v": 27.134067 + }, + "previous": { + "t": "2019", + "v": 27.327447999999997 + }, + "direction": "worsening", + "pace": "slowing", + "pctPerDecade": -9.2, + "perDecade": -2.567 + }, + { + "slug": "red-list-index", + "label": "Red List Index (species survival)", + "unit": "index, 1 = none threatened", + "group": "life", + "betterWhen": "up", + "upstream": "IUCN / BirdLife via UN SDG 15.5.1", + "licence": "CC BY 4.0", + "status": "ok", + "latest": { + "t": "2025", + "v": 0.74 + }, + "previous": { + "t": "2024", + "v": 0.75 + }, + "direction": "worsening", + "pace": "steady", + "pctPerDecade": -3.5, + "perDecade": -0.0261 + }, + { + "slug": "fish-stocks-within-sustainable-levels", + "label": "Fish stocks within sustainable levels", + "unit": "% of stocks", + "group": "life", + "betterWhen": "up", + "upstream": "FAO SOFIA", + "licence": "CC BY 4.0", + "status": "ok", + "latest": { + "t": "2021", + "v": 64.5 + }, + "previous": { + "t": "2020", + "v": 63.45 + }, + "direction": "worsening", + "pace": "accelerating", + "pctPerDecade": -8.8, + "perDecade": -5.8061 + }, + { + "slug": "tree-cover-loss", + "label": "Tree cover loss", + "unit": "ha/yr", + "group": "life", + "betterWhen": "down", + "upstream": "Global Forest Watch (Hansen / UMD)", + "licence": "CC BY 4.0", + "status": "ok", + "latest": { + "t": "2024", + "v": 29559676 + }, + "previous": { + "t": "2023", + "v": 28231408 + }, + "direction": "worsening", + "pace": "steady", + "pctPerDecade": 11.9, + "perDecade": 3075819.8788 + }, + { + "slug": "marine-protected-areas", + "label": "Marine protected areas", + "unit": "% of territorial waters", + "group": "life", + "betterWhen": "up", + "upstream": "UNEP-WCMC via World Bank", + "licence": "CC BY 4.0", + "status": "ok", + "latest": { + "t": "2025", + "v": 17.464169 + }, + "previous": { + "t": "2024", + "v": 14.014829 + }, + "direction": "improving", + "pace": "steady", + "pctPerDecade": 31.8, + "perDecade": 4.3452 + }, + { + "slug": "seawater-ph", + "label": "Ocean surface pH (Station ALOHA)", + "unit": "pH", + "group": "planet", + "betterWhen": "up", + "upstream": "Hawaii Ocean Time-series (Univ. of Hawaii)", + "licence": "CC BY 4.0", + "status": "ok", + "latest": { + "t": "2024", + "v": 8.042414 + }, + "previous": { + "t": "2023", + "v": 8.037277 + }, + "direction": "worsening", + "pace": "accelerating", + "pctPerDecade": -0.4, + "perDecade": -0.0346 + } + ], + "dashboard": "dashboard not running" +} \ No newline at end of file diff --git a/test/fixtures/naturalvalue-no-gee-snapshot.json b/test/fixtures/naturalvalue-no-gee-snapshot.json new file mode 100644 index 0000000..a0c4444 --- /dev/null +++ b/test/fixtures/naturalvalue-no-gee-snapshot.json @@ -0,0 +1,605 @@ +{ + "recorded": "2026-09-27, before the GEE land-cover change (commit 5961df3)", + "clms": { + "area": { + "bbox": [ + -52.4, + -6.9, + -51.9, + -6.4 + ], + "place": null, + "ha": 307028 + }, + "landCover": { + "source": "CLMS Global Land Cover 2020 (raster 10 m, v1) via CDSE Sentinel Hub", + "licence": "Copernicus full, free and open access (Reg. (EU) 1159/2013) — attribute the source, state modifications", + "doi": "10.2909/602507b2-96c7-47bb-b79d-7ba25e97d0a9", + "legend": "ESA WorldCover's 11 LCCS classes, but numbered differently (e.g. 50 = herbaceous wetland, 90 = built-up, 100 = water)", + "pixels": 4096, + "classes": [ + { + "code": 10, + "label": "Tree cover", + "pct": 48.5, + "biome": "tropical_forest" + }, + { + "code": 30, + "label": "Grassland", + "pct": 45.6, + "biome": "grassland" + }, + { + "code": 100, + "label": "Permanent water bodies", + "pct": 4.8, + "biome": "lakes_rivers" + }, + { + "code": 20, + "label": "Shrubland", + "pct": 0.6, + "biome": "grassland" + }, + { + "code": 90, + "label": "Built-up", + "pct": 0.3, + "biome": "urban" + }, + { + "code": 40, + "label": "Cropland", + "pct": 0.2, + "biome": "cropland" + }, + { + "code": 50, + "label": "Herbaceous wetland", + "pct": 0, + "biome": "wetland" + } + ] + }, + "byBiome": [ + { + "biome": "tropical_forest", + "label": "Tropical forest", + "sharePct": 48.5, + "ha": 148867, + "annualUsd": { + "low": 293713824, + "mid": 1000085895, + "high": 3874551292 + }, + "source": "Costanza R. et al. (2014) Changes in the global value of ecosystem services. Global Environmental Change 26:152–158, Table 3 (2011 unit values)" + }, + { + "biome": "grassland", + "label": "Grassland & rangeland", + "sharePct": 46.1, + "ha": 141671, + "annualUsd": { + "low": 21958950, + "mid": 736687339, + "high": 1048646093 + }, + "source": "Costanza R. et al. (2014) Changes in the global value of ecosystem services. Global Environmental Change 26:152–158, Table 3 (2011 unit values)" + }, + { + "biome": "lakes_rivers", + "label": "Lakes & rivers", + "sharePct": 4.8, + "ha": 14767, + "annualUsd": { + "low": 26653945, + "mid": 230626763, + "high": 230626763 + }, + "source": "Costanza R. et al. (2014) Changes in the global value of ecosystem services. Global Environmental Change 26:152–158, Table 3 (2011 unit values)" + }, + { + "biome": "urban", + "label": "Urban", + "sharePct": 0.3, + "ha": 1049, + "annualUsd": { + "low": 8724813, + "mid": 8724813, + "high": 8724813 + }, + "source": "Costanza R. et al. (2014) Changes in the global value of ecosystem services. Global Environmental Change 26:152–158, Table 3 (2011 unit values)" + }, + { + "biome": "cropland", + "label": "Cropland", + "sharePct": 0.2, + "ha": 600, + "annualUsd": { + "low": 4167066, + "mid": 4167066, + "high": 4167066 + }, + "source": "Costanza R. et al. (2014) Changes in the global value of ecosystem services. Global Environmental Change 26:152–158, Table 3 (2011 unit values)" + }, + { + "biome": "wetland", + "label": "Inland wetland (swamps, floodplains)", + "sharePct": 0, + "ha": 75, + "annualUsd": { + "low": 282367, + "mid": 2402854, + "high": 9817251 + }, + "source": "Costanza R. et al. (2014) Changes in the global value of ecosystem services. Global Environmental Change 26:152–158, Table 3 (2011 unit values)" + } + ], + "annualUsd": { + "low": 355500964, + "mid": 1982694729, + "high": 5176533277 + }, + "horizon": { + "years": 100, + "discountRate": 0.02, + "undiscountedUsd": { + "low": 35550096400, + "mid": 198269472900, + "high": 517653327700 + }, + "npvUsd": { + "low": 15321505555, + "mid": 85450874625, + "high": 223100051449 + }, + "annuityFactor": 43.1, + "sensitivity": [ + { + "discountRate": 0, + "npvUsdMid": 198269472900 + }, + { + "discountRate": 0.014, + "npvUsdMid": 106356991678 + }, + { + "discountRate": 0.02, + "npvUsdMid": 85450874625 + }, + { + "discountRate": 0.03, + "npvUsdMid": 62650983056 + }, + { + "discountRate": 0.07, + "npvUsdMid": 28291568168 + } + ] + }, + "clearedComparator": { + "line": "A hectare of tropical forest here does ~$6,718/yr of work alive (band $1,973–$26,027), every year — vs ~$1,900–$6,800 once as cleared land (southern Pará, 2023).", + "biome": "tropical_forest", + "usdPerHaOnce": { + "low": 1900, + "high": 6800 + }, + "dollarYear": 2023, + "what": "sale price of cleared land in southern Pará, once (R$10,000–35,000/ha), per a regional land dealer", + "source": { + "cite": "Mongabay (Feb 2023) The $20m flip: the story of the largest land grab in the Brazilian Amazon", + "url": "https://news.mongabay.com/2023/02/the-20m-flip-the-story-of-the-largest-land-grab-in-the-brazilian-amazon/" + }, + "quality": "journalistic quote, not a peer-reviewed land-price series" + }, + "services": [ + { + "service": "provisioning", + "label": "Food, water & raw materials", + "annualUsd": 785768617 + }, + { + "service": "climate", + "label": "Climate & air regulation", + "annualUsd": 388433361 + }, + { + "service": "cultural", + "label": "Recreation & cultural", + "annualUsd": 331679028 + }, + { + "service": "habitat", + "label": "Habitat, nursery & genetic diversity", + "annualUsd": 319101755 + }, + { + "service": "regulating", + "label": "Other regulating (not split further by the source)", + "annualUsd": 141846171 + }, + { + "service": "unsplit", + "label": "Not split by service in the source", + "annualUsd": 12891879 + }, + { + "service": "erosion", + "label": "Erosion control, soil & nutrients", + "annualUsd": 2900249 + } + ], + "summary": "307,028 ha: living ecosystems worth ~$2.0B/yr (band $356M–$5.2B), ~$198B over 100 yr undiscounted or $85B NPV at 2.0 %; largest share Tropical forest (49 %). Benefit transfer, order of magnitude — not a price for sale.", + "references": { + "organisms": [ + { + "id": "great_whale", + "label": "Great whale (one individual)", + "usd": { + "low": 2000000, + "mid": 2000000, + "high": 2000000 + }, + "unit": "USD per whale, lifetime present value (published as 'more than $2 million')", + "dollarYear": 2019, + "source": { + "cite": "Chami R., Cosimano T., Fullenkamp C., Oztosun S. (2019) Nature's Solution to Climate Change. IMF Finance & Development 56(4)", + "url": "https://www.elibrary.imf.org/view/journals/022/0056/004/article-A011-en.xml" + }, + "method": "present value of lifetime carbon sequestration (~33 t CO₂ per whale) at market carbon prices + fishery enhancement + ecotourism", + "caveat": "A lower bound as published; >$1 trillion for the current stock (~1.3 M great whales vs 4–5 M before whaling). Carbon-price dependent." + }, + { + "id": "forest_elephant", + "label": "African forest elephant (one individual)", + "usd": { + "low": 1750000, + "mid": 1750000, + "high": 3750000 + }, + "unit": "USD per elephant, present value of carbon-capture services", + "dollarYear": 2020, + "source": { + "cite": "Chami R., Fullenkamp C., Cosimano T., Berzaghi F. (2020) The Secret Work of Elephants. IMF Finance & Development 57(4)", + "url": "https://www.imf.org/en/publications/fandd/issues/2020/09/how-african-elephants-fight-climate-change-ralph-chami" + }, + "method": "elephants thin small trees, raising forest carbon stock; the extra carbon valued at a carbon price over the elephant's lifetime", + "caveat": "High = the paper's scenario if poaching ended ($375 bn for the population vs $176 bn today). Carbon only — no tourism, cultural or intrinsic value." + }, + { + "id": "street_tree_yr", + "label": "Street tree (California average), per year", + "usd": { + "low": 110.63, + "mid": 110.63, + "high": 110.63 + }, + "unit": "USD per tree per year", + "dollarYear": 2016, + "source": { + "cite": "McPherson E.G., van Doorn N., de Goede J. (2016) Structure, function and value of street trees in California, USA. Urban Forestry & Urban Greening 17:104–115 (i-Tree Streets)", + "url": "https://research.fs.usda.gov/treesearch/50951" + }, + "method": "i-Tree Streets: energy, CO₂, air quality, stormwater and aesthetic/property value of 9.1 M street trees ($1.0 bn/yr); management costs $19/tree/yr", + "caveat": "Urban street trees in California; aesthetics/property value dominates (~$839 M of $1.0 bn). Not transferable to a forest tree." + }, + { + "id": "street_tree_100y", + "label": "Street tree over 100 years (derived)", + "usd": { + "low": 4768, + "mid": 11063, + "high": 11063 + }, + "unit": "USD per tree over 100 years — low = NPV at 2 %, mid/high = undiscounted", + "dollarYear": 2016, + "source": { + "cite": "Derived from McPherson et al. (2016): $110.63/tree/yr × 100 years (annuity factor 43.10 at 2 %)", + "url": "https://research.fs.usda.gov/treesearch/50951" + }, + "method": "derived: constant annual benefit × horizon; a real tree's benefits grow with its canopy", + "caveat": "Assumes the tree lives and is maintained for 100 years at today's average benefit." + }, + { + "id": "coral_reefs_flood_protection", + "label": "All coral reefs — flood protection, per year", + "usd": { + "low": 4300000000, + "mid": 4300000000, + "high": 4300000000 + }, + "unit": "USD per year of flood damage averted worldwide", + "dollarYear": 2018, + "source": { + "cite": "Beck M.W. et al. (2018) The global flood protection savings provided by coral reefs. Nature Communications 9:2186", + "url": "https://doi.org/10.1038/s41467-018-04568-z" + }, + "method": "expected annual flood damage with vs without the top 1 m of reef (damage rises from $3.7 bn to $8 bn/yr)", + "caveat": "One service only; dollar-year given as the publication year (the paper's price base is UNCONFIRMED)." + } + ], + "globalNatureValue": { + "usdPerYear": { + "low": 125000000000000, + "high": 145000000000000 + }, + "dollarYear": 2007, + "usdPerYear2020": { + "low": 156029048624977, + "high": 180993696404973 + }, + "note": "$125 T/yr with 2011 biome areas, $145 T/yr at 1997 areas; loss from land-use change 1997–2011: $4.3–20.2 T/yr (2007 US$). Global GDP 2011: $75.2 T in the same dollars.", + "source": { + "cite": "Costanza R. et al. (2014) Changes in the global value of ecosystem services. Global Environmental Change 26:152–158, Table 3 (2011 unit values)", + "url": "https://doi.org/10.1016/j.gloenvcha.2014.04.002" + } + } + }, + "method": { + "unit": "2020 US dollars", + "formula": "annual = Σ_biome area_ha × unit value (USD/ha/yr, low/mid/high); horizon undiscounted = annual × T; NPV = annual × (1 − (1+r)^−T) / r (flows at year-end, constant real value)", + "transfer": "benefit transfer: global per-biome mean unit values (Costanza et al. 2014, Table 2; de Groot et al. 2012) moved to this place without local calibration; 2007 → 2020 USD via US CPI-U", + "band": "low/high = the per-biome band stated in the registry entry (see byBiome[].source); treat the mid as an order of magnitude", + "discountRate": "0.02 — a low social rate because these are life-support flows to future people, not a private investment. The Stern Review used ~1.4 %; the Nov 2023 US OMB Circular A-4 used 2.0 % (rescinded in 2025 by OMB M-25-15, which reinstated 3 % / 7 %). Over 100 years a constant flow is worth 100× annual undiscounted, ~53.6× at 1.4 %, ~43.1× at 2 %, ~31.6× at 3 %, ~14.3× at 7 % — see horizon.sensitivity.", + "assumptions": [], + "blindSpots": [ + "Benefit transfer: a global average hectare of 'tropical forest' is not this hectare — no local calibration, condition, degradation or fragmentation is accounted for.", + "The unit values are means of a skewed literature (few studies, many regions missing); the true local value can be an order of magnitude off either way.", + "Land cover is a 2020 snapshot at 10 m sampled at ≤256 px; recent clearing, cloud-era errors and mixed pixels shift the mix. Water is valued as lakes/rivers even where it is sea.", + "Pasture is not grassland: the land-cover map cannot tell cattle pasture on cleared forest from natural grassland, and both get Costanza's grass/rangeland value (~$5,200/ha/yr) — in deforestation frontiers this overstates the 'alive' total and understates the gap between forest and cleared land.", + "Plural values are not captured: sacred, relational and intrinsic values (IPBES 2022) and Indigenous stewardship have no dollar column here — the number is a floor for one kind of value, not the worth of the place.", + "Distribution: who benefits (downstream towns, the global climate) is not who pays or who owns the land; the total hides that.", + "Not a market price: nobody will pay this for the land, and clearing does not remove all of it at once (some services persist, some are lost for decades).", + "Double counting between services and between biomes, and non-linear effects (tipping points), are not modelled." + ] + }, + "dashboard": "card pushed" + }, + "assumed": { + "area": { + "bbox": [ + -52.4, + -6.9, + -51.9, + -6.4 + ], + "place": null, + "ha": 307028 + }, + "landCover": { + "source": "assumption", + "note": "land cover unavailable (Copernicus Statistics failed (500)) — ASSUMPTION: no land-cover measurement; the whole box is treated as Tropical forest from its latitude (-6.65°). This overstates value wherever the land is already cleared, farmed or built on — pass `biome` or enable CDSE land cover." + }, + "byBiome": [ + { + "biome": "tropical_forest", + "label": "Tropical forest", + "sharePct": 100, + "ha": 307028, + "annualUsd": { + "low": 605766276, + "mid": 2062614212, + "high": 7991018173 + }, + "source": "Costanza R. et al. (2014) Changes in the global value of ecosystem services. Global Environmental Change 26:152–158, Table 3 (2011 unit values)" + } + ], + "annualUsd": { + "low": 605766276, + "mid": 2062614212, + "high": 7991018173 + }, + "horizon": { + "years": 100, + "discountRate": 0.02, + "undiscountedUsd": { + "low": 60576627600, + "mid": 206261421200, + "high": 799101817300 + }, + "npvUsd": { + "low": 26107527975, + "mid": 88895272607, + "high": 344399711182 + }, + "annuityFactor": 43.1, + "sensitivity": [ + { + "discountRate": 0, + "npvUsdMid": 206261421200 + }, + { + "discountRate": 0.014, + "npvUsdMid": 110644084222 + }, + { + "discountRate": 0.02, + "npvUsdMid": 88895272607 + }, + { + "discountRate": 0.03, + "npvUsdMid": 65176351234 + }, + { + "discountRate": 0.07, + "npvUsdMid": 29431959307 + } + ] + }, + "clearedComparator": { + "line": "A hectare of tropical forest here does ~$6,718/yr of work alive (band $1,973–$26,027), every year — vs ~$1,900–$6,800 once as cleared land (southern Pará, 2023).", + "biome": "tropical_forest", + "usdPerHaOnce": { + "low": 1900, + "high": 6800 + }, + "dollarYear": 2023, + "what": "sale price of cleared land in southern Pará, once (R$10,000–35,000/ha), per a regional land dealer", + "source": { + "cite": "Mongabay (Feb 2023) The $20m flip: the story of the largest land grab in the Brazilian Amazon", + "url": "https://news.mongabay.com/2023/02/the-20m-flip-the-story-of-the-largest-land-grab-in-the-brazilian-amazon/" + }, + "quality": "journalistic quote, not a peer-reviewed land-price series" + }, + "services": [ + { + "service": "climate", + "label": "Climate & air regulation", + "annualUsd": 801119360 + }, + { + "service": "provisioning", + "label": "Food, water & raw materials", + "annualUsd": 716345916 + }, + { + "service": "cultural", + "label": "Recreation & cultural", + "annualUsd": 339712561 + }, + { + "service": "regulating", + "label": "Other regulating (not split further by the source)", + "annualUsd": 184191449 + }, + { + "service": "habitat", + "label": "Habitat, nursery & genetic diversity", + "annualUsd": 15263345 + }, + { + "service": "erosion", + "label": "Erosion control, soil & nutrients", + "annualUsd": 5981581 + } + ], + "summary": "307,028 ha: living ecosystems worth ~$2.1B/yr (band $606M–$8.0B), ~$206B over 100 yr undiscounted or $89B NPV at 2.0 %; largest share Tropical forest (100 %). Benefit transfer, order of magnitude — not a price for sale.", + "references": { + "organisms": [ + { + "id": "great_whale", + "label": "Great whale (one individual)", + "usd": { + "low": 2000000, + "mid": 2000000, + "high": 2000000 + }, + "unit": "USD per whale, lifetime present value (published as 'more than $2 million')", + "dollarYear": 2019, + "source": { + "cite": "Chami R., Cosimano T., Fullenkamp C., Oztosun S. (2019) Nature's Solution to Climate Change. IMF Finance & Development 56(4)", + "url": "https://www.elibrary.imf.org/view/journals/022/0056/004/article-A011-en.xml" + }, + "method": "present value of lifetime carbon sequestration (~33 t CO₂ per whale) at market carbon prices + fishery enhancement + ecotourism", + "caveat": "A lower bound as published; >$1 trillion for the current stock (~1.3 M great whales vs 4–5 M before whaling). Carbon-price dependent." + }, + { + "id": "forest_elephant", + "label": "African forest elephant (one individual)", + "usd": { + "low": 1750000, + "mid": 1750000, + "high": 3750000 + }, + "unit": "USD per elephant, present value of carbon-capture services", + "dollarYear": 2020, + "source": { + "cite": "Chami R., Fullenkamp C., Cosimano T., Berzaghi F. (2020) The Secret Work of Elephants. IMF Finance & Development 57(4)", + "url": "https://www.imf.org/en/publications/fandd/issues/2020/09/how-african-elephants-fight-climate-change-ralph-chami" + }, + "method": "elephants thin small trees, raising forest carbon stock; the extra carbon valued at a carbon price over the elephant's lifetime", + "caveat": "High = the paper's scenario if poaching ended ($375 bn for the population vs $176 bn today). Carbon only — no tourism, cultural or intrinsic value." + }, + { + "id": "street_tree_yr", + "label": "Street tree (California average), per year", + "usd": { + "low": 110.63, + "mid": 110.63, + "high": 110.63 + }, + "unit": "USD per tree per year", + "dollarYear": 2016, + "source": { + "cite": "McPherson E.G., van Doorn N., de Goede J. (2016) Structure, function and value of street trees in California, USA. Urban Forestry & Urban Greening 17:104–115 (i-Tree Streets)", + "url": "https://research.fs.usda.gov/treesearch/50951" + }, + "method": "i-Tree Streets: energy, CO₂, air quality, stormwater and aesthetic/property value of 9.1 M street trees ($1.0 bn/yr); management costs $19/tree/yr", + "caveat": "Urban street trees in California; aesthetics/property value dominates (~$839 M of $1.0 bn). Not transferable to a forest tree." + }, + { + "id": "street_tree_100y", + "label": "Street tree over 100 years (derived)", + "usd": { + "low": 4768, + "mid": 11063, + "high": 11063 + }, + "unit": "USD per tree over 100 years — low = NPV at 2 %, mid/high = undiscounted", + "dollarYear": 2016, + "source": { + "cite": "Derived from McPherson et al. (2016): $110.63/tree/yr × 100 years (annuity factor 43.10 at 2 %)", + "url": "https://research.fs.usda.gov/treesearch/50951" + }, + "method": "derived: constant annual benefit × horizon; a real tree's benefits grow with its canopy", + "caveat": "Assumes the tree lives and is maintained for 100 years at today's average benefit." + }, + { + "id": "coral_reefs_flood_protection", + "label": "All coral reefs — flood protection, per year", + "usd": { + "low": 4300000000, + "mid": 4300000000, + "high": 4300000000 + }, + "unit": "USD per year of flood damage averted worldwide", + "dollarYear": 2018, + "source": { + "cite": "Beck M.W. et al. (2018) The global flood protection savings provided by coral reefs. Nature Communications 9:2186", + "url": "https://doi.org/10.1038/s41467-018-04568-z" + }, + "method": "expected annual flood damage with vs without the top 1 m of reef (damage rises from $3.7 bn to $8 bn/yr)", + "caveat": "One service only; dollar-year given as the publication year (the paper's price base is UNCONFIRMED)." + } + ], + "globalNatureValue": { + "usdPerYear": { + "low": 125000000000000, + "high": 145000000000000 + }, + "dollarYear": 2007, + "usdPerYear2020": { + "low": 156029048624977, + "high": 180993696404973 + }, + "note": "$125 T/yr with 2011 biome areas, $145 T/yr at 1997 areas; loss from land-use change 1997–2011: $4.3–20.2 T/yr (2007 US$). Global GDP 2011: $75.2 T in the same dollars.", + "source": { + "cite": "Costanza R. et al. (2014) Changes in the global value of ecosystem services. Global Environmental Change 26:152–158, Table 3 (2011 unit values)", + "url": "https://doi.org/10.1016/j.gloenvcha.2014.04.002" + } + } + }, + "method": { + "unit": "2020 US dollars", + "formula": "annual = Σ_biome area_ha × unit value (USD/ha/yr, low/mid/high); horizon undiscounted = annual × T; NPV = annual × (1 − (1+r)^−T) / r (flows at year-end, constant real value)", + "transfer": "benefit transfer: global per-biome mean unit values (Costanza et al. 2014, Table 2; de Groot et al. 2012) moved to this place without local calibration; 2007 → 2020 USD via US CPI-U", + "band": "low/high = the per-biome band stated in the registry entry (see byBiome[].source); treat the mid as an order of magnitude", + "discountRate": "0.02 — a low social rate because these are life-support flows to future people, not a private investment. The Stern Review used ~1.4 %; the Nov 2023 US OMB Circular A-4 used 2.0 % (rescinded in 2025 by OMB M-25-15, which reinstated 3 % / 7 %). Over 100 years a constant flow is worth 100× annual undiscounted, ~53.6× at 1.4 %, ~43.1× at 2 %, ~31.6× at 3 %, ~14.3× at 7 % — see horizon.sensitivity.", + "assumptions": [ + "land cover unavailable (Copernicus Statistics failed (500)) — ASSUMPTION: no land-cover measurement; the whole box is treated as Tropical forest from its latitude (-6.65°). This overstates value wherever the land is already cleared, farmed or built on — pass `biome` or enable CDSE land cover." + ], + "blindSpots": [ + "Benefit transfer: a global average hectare of 'tropical forest' is not this hectare — no local calibration, condition, degradation or fragmentation is accounted for.", + "The unit values are means of a skewed literature (few studies, many regions missing); the true local value can be an order of magnitude off either way.", + "Land cover is a 2020 snapshot at 10 m sampled at ≤256 px; recent clearing, cloud-era errors and mixed pixels shift the mix. Water is valued as lakes/rivers even where it is sea.", + "Pasture is not grassland: the land-cover map cannot tell cattle pasture on cleared forest from natural grassland, and both get Costanza's grass/rangeland value (~$5,200/ha/yr) — in deforestation frontiers this overstates the 'alive' total and understates the gap between forest and cleared land.", + "Plural values are not captured: sacred, relational and intrinsic values (IPBES 2022) and Indigenous stewardship have no dollar column here — the number is a floor for one kind of value, not the worth of the place.", + "Distribution: who benefits (downstream towns, the global climate) is not who pays or who owns the land; the total hides that.", + "Not a market price: nobody will pay this for the land, and clearing does not remove all of it at once (some services persist, some are lost for decades).", + "Double counting between services and between biomes, and non-linear effects (tipping points), are not modelled." + ] + }, + "dashboard": "card pushed" + } +} diff --git a/test/fixtures/nhc-currentstorms-2026-09-27.json b/test/fixtures/nhc-currentstorms-2026-09-27.json new file mode 100644 index 0000000..5b5fd48 --- /dev/null +++ b/test/fixtures/nhc-currentstorms-2026-09-27.json @@ -0,0 +1,426 @@ +{ + "activeStorms": [ + { + "id": "al062026", + "binNumber": "AT1", + "name": "Fay", + "classification": "TD", + "intensity": "30", + "pressure": "1010", + "latitude": "29.6N", + "longitude": "43.9W", + "latitudeNumeric": 29.6, + "longitudeNumeric": -43.9, + "movementDir": 190, + "movementSpeed": 2, + "lastUpdate": "2026-09-27T03:00:00.000Z", + "publicAdvisory": { + "advNum": "028", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:35:30.437Z", + "url": "https://www.nhc.noaa.gov/text/MIATCPAT1.shtml" + }, + "forecastAdvisory": { + "advNum": "028", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:34:30.306Z", + "url": "https://www.nhc.noaa.gov/text/MIATCMAT1.shtml" + }, + "windSpeedProbabilities": { + "advNum": "028", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:36:01.406Z", + "url": "https://www.nhc.noaa.gov/text/MIAPWSAT1.shtml" + }, + "forecastDiscussion": { + "advNum": "028", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:36:31.993Z", + "url": "https://www.nhc.noaa.gov/text/MIATCDAT1.shtml" + }, + "forecastGraphics": { + "advNum": "028", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:35:30.437Z", + "url": "https://www.nhc.noaa.gov/graphics_at1.shtml" + }, + "forecastTrack": { + "advNum": "028", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:37:38.931Z", + "zipFile": "https://www.nhc.noaa.gov/gis/forecast/archive/al062026_5day_028.zip", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/AL062026_028adv_TRACK.kmz" + }, + "windWatchesWarnings": null, + "trackCone": { + "advNum": "028", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:37:33.375Z", + "zipFile": "https://www.nhc.noaa.gov/gis/forecast/archive/al062026_5day_028.zip", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/AL062026_028adv_CONE.kmz" + }, + "initialWindExtent": { + "advNum": "028", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:38:08.407Z", + "zipFile": "https://www.nhc.noaa.gov/gis/forecast/archive/al062026_fcst_028.zip", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/AL062026_initialradii_028adv.kmz" + }, + "forecastWindRadiiGIS": { + "advNum": "028", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:38:04.507Z", + "zipFile": "https://www.nhc.noaa.gov/gis/forecast/archive/al062026_fcst_028.zip", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/AL062026_forecastradii_028adv.kmz" + }, + "bestTrackGIS": { + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:37:48.229Z", + "zipFile": "https://www.nhc.noaa.gov/gis/best_track/al062026_best_track.zip", + "kmzFile": "https://www.nhc.noaa.gov/gis/best_track/al062026_best_track.kmz" + }, + "earliestArrivalTimeTSWindsGIS": { + "advNum": "028", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:37:35.245Z", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/AL062026_028adv_earliest_reasonable_toa_34.kmz" + }, + "mostLikelyTimeTSWindsGIS": { + "advNum": "028", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:37:37.085Z", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/AL062026_028adv_most_likely_toa_34.kmz" + }, + "windSpeedProbabilitiesGIS": { + "issuance": "2026-09-27T00:00:00.000Z", + "fileUpdateTime": "2026-09-27T03:22:54.192Z", + "zipFile5km": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp_120hr5km.zip", + "zipFile0p5deg": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp_120hrhalfDeg.zip", + "kmzFile34kt": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp34knt120hr_5km.kmz", + "kmzFile50kt": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp50knt120hr_5km.kmz", + "kmzFile64kt": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp64knt120hr_5km.kmz" + }, + "stormSurgeWatchWarningGIS": null, + "potentialStormSurgeFloodingGIS": null, + "peakSurgeKML": null + }, + { + "id": "ep162026", + "binNumber": "EP1", + "name": "Odalys", + "classification": "HU", + "intensity": "70", + "pressure": "979", + "latitude": "21.1N", + "longitude": "123.6W", + "latitudeNumeric": 21.1, + "longitudeNumeric": -123.6, + "movementDir": 360, + "movementSpeed": 7, + "lastUpdate": "2026-09-27T03:00:00.000Z", + "publicAdvisory": { + "advNum": "029", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:53:07.533Z", + "url": "https://www.nhc.noaa.gov/text/MIATCPEP1.shtml" + }, + "forecastAdvisory": { + "advNum": "029", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:52:32.283Z", + "url": "https://www.nhc.noaa.gov/text/MIATCMEP1.shtml" + }, + "windSpeedProbabilities": { + "advNum": "029", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:53:11.737Z", + "url": "https://www.nhc.noaa.gov/text/MIAPWSEP1.shtml" + }, + "forecastDiscussion": { + "advNum": "029", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:54:33.439Z", + "url": "https://www.nhc.noaa.gov/text/MIATCDEP1.shtml" + }, + "forecastGraphics": { + "advNum": "029", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:53:07.533Z", + "url": "https://www.nhc.noaa.gov/graphics_ep1.shtml" + }, + "forecastTrack": { + "advNum": "029", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:55:41.239Z", + "zipFile": "https://www.nhc.noaa.gov/gis/forecast/archive/ep162026_5day_029.zip", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP162026_029adv_TRACK.kmz" + }, + "windWatchesWarnings": null, + "trackCone": { + "advNum": "029", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:55:35.365Z", + "zipFile": "https://www.nhc.noaa.gov/gis/forecast/archive/ep162026_5day_029.zip", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP162026_029adv_CONE.kmz" + }, + "initialWindExtent": { + "advNum": "029", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:56:11.976Z", + "zipFile": "https://www.nhc.noaa.gov/gis/forecast/archive/ep162026_fcst_029.zip", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP162026_initialradii_029adv.kmz" + }, + "forecastWindRadiiGIS": { + "advNum": "029", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:56:08.076Z", + "zipFile": "https://www.nhc.noaa.gov/gis/forecast/archive/ep162026_fcst_029.zip", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP162026_forecastradii_029adv.kmz" + }, + "bestTrackGIS": { + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:55:51.029Z", + "zipFile": "https://www.nhc.noaa.gov/gis/best_track/ep162026_best_track.zip", + "kmzFile": "https://www.nhc.noaa.gov/gis/best_track/ep162026_best_track.kmz" + }, + "earliestArrivalTimeTSWindsGIS": { + "advNum": "029", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:55:37.376Z", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP162026_029adv_earliest_reasonable_toa_34.kmz" + }, + "mostLikelyTimeTSWindsGIS": { + "advNum": "029", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:55:39.299Z", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP162026_029adv_most_likely_toa_34.kmz" + }, + "windSpeedProbabilitiesGIS": { + "issuance": "2026-09-27T00:00:00.000Z", + "fileUpdateTime": "2026-09-27T03:22:54.192Z", + "zipFile5km": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp_120hr5km.zip", + "zipFile0p5deg": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp_120hrhalfDeg.zip", + "kmzFile34kt": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp34knt120hr_5km.kmz", + "kmzFile50kt": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp50knt120hr_5km.kmz", + "kmzFile64kt": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp64knt120hr_5km.kmz" + }, + "stormSurgeWatchWarningGIS": null, + "potentialStormSurgeFloodingGIS": null, + "peakSurgeKML": null + }, + { + "id": "ep172026", + "binNumber": "EP2", + "name": "Polo", + "classification": "HU", + "intensity": "105", + "pressure": "950", + "latitude": "19.8N", + "longitude": "113.4W", + "latitudeNumeric": 19.8, + "longitudeNumeric": -113.4, + "movementDir": 320, + "movementSpeed": 10, + "lastUpdate": "2026-09-27T06:00:00.000Z", + "publicAdvisory": { + "advNum": "026a", + "issuance": "2026-09-27T06:00:00.000Z", + "fileUpdateTime": "2026-09-27T05:47:37.263Z", + "url": "https://www.nhc.noaa.gov/text/MIATCPEP2.shtml" + }, + "forecastAdvisory": { + "advNum": "026", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:55:28.589Z", + "url": "https://www.nhc.noaa.gov/text/MIATCMEP2.shtml" + }, + "windSpeedProbabilities": { + "advNum": "026", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:45:00.761Z", + "url": "https://www.nhc.noaa.gov/text/MIAPWSEP2.shtml" + }, + "forecastDiscussion": { + "advNum": "026", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:46:00.344Z", + "url": "https://www.nhc.noaa.gov/text/MIATCDEP2.shtml" + }, + "forecastGraphics": { + "advNum": "026a", + "issuance": "2026-09-27T06:00:00.000Z", + "fileUpdateTime": "2026-09-27T05:47:37.263Z", + "url": "https://www.nhc.noaa.gov/graphics_ep2.shtml" + }, + "forecastTrack": { + "advNum": "026a", + "issuance": "2026-09-27T06:00:00.000Z", + "fileUpdateTime": "2026-09-27T05:47:48.802Z", + "zipFile": "https://www.nhc.noaa.gov/gis/forecast/archive/ep172026_5day_026A.zip", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP172026_026Aadv_TRACK.kmz" + }, + "windWatchesWarnings": { + "advNum": "026a", + "issuance": "2026-09-27T06:00:00.000Z", + "fileUpdateTime": "2026-09-27T05:47:50.893Z", + "zipFile": "https://www.nhc.noaa.gov/gis/forecast/archive/ep172026_5day_026A.zip", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP172026_026Aadv_WW.kmz" + }, + "trackCone": { + "advNum": "026a", + "issuance": "2026-09-27T06:00:00.000Z", + "fileUpdateTime": "2026-09-27T05:47:46.498Z", + "zipFile": "https://www.nhc.noaa.gov/gis/forecast/archive/ep172026_5day_026A.zip", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP172026_026Aadv_CONE.kmz" + }, + "initialWindExtent": { + "advNum": "026a", + "issuance": "2026-09-27T06:00:00.000Z", + "fileUpdateTime": "2026-09-27T05:48:19.945Z", + "zipFile": "https://www.nhc.noaa.gov/gis/forecast/archive/ep172026_fcst_026A.zip", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP172026_initialradii_026Aadv.kmz" + }, + "forecastWindRadiiGIS": { + "advNum": "026a", + "issuance": "2026-09-27T06:00:00.000Z", + "fileUpdateTime": "2026-09-27T05:48:16.060Z", + "zipFile": "https://www.nhc.noaa.gov/gis/forecast/archive/ep172026_fcst_026A.zip", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP172026_forecastradii_026Aadv.kmz" + }, + "bestTrackGIS": { + "issuance": "2026-09-27T06:00:00.000Z", + "fileUpdateTime": "2026-09-27T05:48:00.481Z", + "zipFile": "https://www.nhc.noaa.gov/gis/best_track/ep172026_best_track.zip", + "kmzFile": "https://www.nhc.noaa.gov/gis/best_track/ep172026_best_track.kmz" + }, + "earliestArrivalTimeTSWindsGIS": { + "advNum": "026", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:47:15.856Z", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP172026_026adv_earliest_reasonable_toa_34.kmz" + }, + "mostLikelyTimeTSWindsGIS": { + "advNum": "026", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:47:17.837Z", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP172026_026adv_most_likely_toa_34.kmz" + }, + "windSpeedProbabilitiesGIS": { + "issuance": "2026-09-27T00:00:00.000Z", + "fileUpdateTime": "2026-09-27T03:22:54.192Z", + "zipFile5km": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp_120hr5km.zip", + "zipFile0p5deg": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp_120hrhalfDeg.zip", + "kmzFile34kt": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp34knt120hr_5km.kmz", + "kmzFile50kt": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp50knt120hr_5km.kmz", + "kmzFile64kt": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp64knt120hr_5km.kmz" + }, + "stormSurgeWatchWarningGIS": null, + "potentialStormSurgeFloodingGIS": null, + "peakSurgeKML": null + }, + { + "id": "ep152026", + "binNumber": "CP2", + "name": "Nolo", + "classification": "HU", + "intensity": "80", + "pressure": "969", + "latitude": "16.7N", + "longitude": "156.5W", + "latitudeNumeric": 16.7, + "longitudeNumeric": -156.5, + "movementDir": 265, + "movementSpeed": 8, + "lastUpdate": "2026-09-27T03:00:00.000Z", + "publicAdvisory": { + "advNum": "026", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:55:01.795Z", + "url": "https://www.nhc.noaa.gov/text/HFOTCPCP2.shtml" + }, + "forecastAdvisory": { + "advNum": "026", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:55:01.738Z", + "url": "https://www.nhc.noaa.gov/text/HFOTCMCP2.shtml" + }, + "windSpeedProbabilities": { + "advNum": "026", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:55:31.920Z", + "url": "https://www.nhc.noaa.gov/text/HFOPWSCP2.shtml" + }, + "forecastDiscussion": { + "advNum": "026", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:56:00.385Z", + "url": "https://www.nhc.noaa.gov/text/HFOTCDCP2.shtml" + }, + "forecastGraphics": { + "advNum": "026", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T02:55:01.795Z", + "url": "https://www.nhc.noaa.gov/graphics_cp2.shtml" + }, + "forecastTrack": { + "advNum": "026", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T03:47:58.264Z", + "zipFile": "https://www.nhc.noaa.gov/gis/forecast/archive/ep152026_5day_026.zip", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP152026_026adv_TRACK.kmz" + }, + "windWatchesWarnings": null, + "trackCone": { + "advNum": "026", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T03:47:51.755Z", + "zipFile": "https://www.nhc.noaa.gov/gis/forecast/archive/ep152026_5day_026.zip", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP152026_026adv_CONE.kmz" + }, + "initialWindExtent": { + "advNum": "026", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T03:48:29.587Z", + "zipFile": "https://www.nhc.noaa.gov/gis/forecast/archive/ep152026_fcst_026.zip", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP152026_initialradii_026adv.kmz" + }, + "forecastWindRadiiGIS": { + "advNum": "026", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T03:48:25.475Z", + "zipFile": "https://www.nhc.noaa.gov/gis/forecast/archive/ep152026_fcst_026.zip", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP152026_forecastradii_026adv.kmz" + }, + "bestTrackGIS": { + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T03:48:08.366Z", + "zipFile": "https://www.nhc.noaa.gov/gis/best_track/ep152026_best_track.zip", + "kmzFile": "https://www.nhc.noaa.gov/gis/best_track/ep152026_best_track.kmz" + }, + "earliestArrivalTimeTSWindsGIS": { + "advNum": "026", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T03:47:53.858Z", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP152026_026adv_earliest_reasonable_toa_34.kmz" + }, + "mostLikelyTimeTSWindsGIS": { + "advNum": "026", + "issuance": "2026-09-27T03:00:00.000Z", + "fileUpdateTime": "2026-09-27T03:47:56.184Z", + "kmzFile": "https://www.nhc.noaa.gov/storm_graphics/api/EP152026_026adv_most_likely_toa_34.kmz" + }, + "windSpeedProbabilitiesGIS": { + "issuance": "2026-09-27T00:00:00.000Z", + "fileUpdateTime": "2026-09-27T03:22:54.192Z", + "zipFile5km": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp_120hr5km.zip", + "zipFile0p5deg": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp_120hrhalfDeg.zip", + "kmzFile34kt": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp34knt120hr_5km.kmz", + "kmzFile50kt": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp50knt120hr_5km.kmz", + "kmzFile64kt": "https://www.nhc.noaa.gov/gis/forecast/archive/2026092700_wsp64knt120hr_5km.kmz" + }, + "stormSurgeWatchWarningGIS": null, + "potentialStormSurgeFloodingGIS": null, + "peakSurgeKML": null + } + ] +} \ No newline at end of file diff --git a/test/fixtures/nhc-gis-cone-2026-09-27.json b/test/fixtures/nhc-gis-cone-2026-09-27.json new file mode 100644 index 0000000..3ec0f2c --- /dev/null +++ b/test/fixtures/nhc-gis-cone-2026-09-27.json @@ -0,0 +1 @@ +{"type":"FeatureCollection","features":[{"type":"Feature","id":217,"geometry":{"type":"Polygon","coordinates":[[[-47.96,22.415],[-47.49,22.465],[-47.089,22.605],[-45.91,23.207],[-45.233,23.666],[-44.231,24.613],[-43.198,26.071],[-42.825,26.833],[-42.653,27.638],[-42.743,28.064],[-43.258,29.357],[-43.588,29.827],[-43.935,29.883],[-44.217,29.675],[-44.427,28.516],[-44.42,27.786],[-45.359,26.66],[-45.998,26.176],[-46.694,25.801],[-48.624,25.435],[-49.174,25.082],[-49.401,24.793],[-49.638,24.023],[-49.448,23.299],[-49.137,22.9],[-48.795,22.648],[-47.96,22.415]]]},"properties":{"objectid":217,"stormname":"Fay","stormtype":"TD","basin":"AL","advdate":"300 AM GMT Sun Sep 27 2026","advisnum":"28","fcstprd":120,"stormnum":6,"idp_source":"al062026-028_5day_pgn","idp_filedate":1790478147000,"idp_ingestdate":1790478167000,"st_area(shape)":21.574996613020193,"st_perimeter(shape)":22.382923259877558,"binnumber":"AT1"}},{"type":"Feature","id":218,"geometry":{"type":"Polygon","coordinates":[[[-122.151,17.908],[-121.518,17.984],[-121.011,18.296],[-120.694,18.799],[-120.641,19.407],[-120.956,20.642],[-121.793,22.308],[-122.326,22.829],[-122.702,22.969],[-123.099,22.971],[-123.519,22.785],[-123.737,22.498],[-123.856,21.887],[-123.875,21.042],[-123.644,20.837],[-123.457,20.87],[-123.307,21.005],[-123.265,20.934],[-123.165,20.173],[-123.365,19.105],[-123.23,18.623],[-122.778,18.132],[-122.151,17.908]]]},"properties":{"objectid":218,"stormname":"Odalys","stormtype":"HU","basin":"EP","advdate":"800 PM PDT Sat Sep 26 2026","advisnum":"29","fcstprd":120,"stormnum":16,"idp_source":"ep162026-029_5day_pgn","idp_filedate":1790478148000,"idp_ingestdate":1790478237000,"st_area(shape)":11.408823571296738,"st_perimeter(shape)":13.98224658709713,"binnumber":"EP1"}},{"type":"Feature","id":222,"geometry":{"type":"Polygon","coordinates":[[[-158.532,16.168],[-157.492,16.194],[-156.878,16.318],[-156.342,16.49],[-156.249,16.604],[-156.247,16.785],[-156.434,16.952],[-157.567,16.999],[-159.053,17.357],[-160.262,17.861],[-160.962,18.312],[-161.622,19.143],[-162.406,20.516],[-162.715,21.24],[-162.906,22.232],[-163.146,22.849],[-163.612,23.505],[-164.402,24.177],[-165.137,24.564],[-166.107,24.907],[-169.084,25.383],[-169.816,25.347],[-170.503,25.12],[-171.009,24.784],[-171.495,24.206],[-171.778,23.411],[-171.722,22.563],[-171.34,21.794],[-170.711,21.211],[-169.924,20.877],[-169.173,20.802],[-166.304,21.327],[-165.376,21.309],[-164.838,20.282],[-164.182,19.357],[-162.866,17.794],[-162.111,17.132],[-161.573,16.828],[-160.713,16.522],[-159.514,16.26],[-158.532,16.168]]]},"properties":{"objectid":222,"stormname":"Nolo","stormtype":"HU","basin":"EP","advdate":"500 PM HST Sat Sep 26 2026","advisnum":"26","fcstprd":120,"stormnum":15,"idp_source":"ep152026-026_5day_pgn","idp_filedate":1790481769000,"idp_ingestdate":1790481843000,"st_area(shape)":45.842637027694913,"st_perimeter(shape)":40.306990985150811,"binnumber":"CP2"}},{"type":"Feature","id":223,"geometry":{"type":"Polygon","coordinates":[[[-113.472,19.546],[-113.226,19.597],[-113.122,19.825],[-113.364,20.779],[-113.565,22.113],[-113.446,22.734],[-113.107,23.521],[-112.512,24.376],[-111.049,25.843],[-110.008,26.76],[-107.186,28.949],[-106.941,29.429],[-106.935,29.966],[-107.231,30.519],[-107.622,30.806],[-108.102,30.973],[-108.589,30.987],[-109.099,30.85],[-109.431,30.642],[-111.25,28.853],[-112.389,27.586],[-113.865,25.638],[-114.335,24.889],[-114.586,24.308],[-114.787,23.552],[-114.853,22.251],[-114.631,21.455],[-114.098,20.321],[-113.628,19.65],[-113.472,19.546]]]},"properties":{"objectid":223,"stormname":"Polo","stormtype":"HU","basin":"EP","advdate":"1100 PM MST Sat Sep 26 2026","advisnum":"26A","fcstprd":120,"stormnum":17,"idp_source":"ep172026-026A_5day_pgn","idp_filedate":1790488954000,"idp_ingestdate":1790489025000,"st_area(shape)":26.009865146732665,"st_perimeter(shape)":29.962167082335544,"binnumber":"EP2"}}]} \ No newline at end of file diff --git a/test/fixtures/nhc-gis-points-2026-09-27.json b/test/fixtures/nhc-gis-points-2026-09-27.json new file mode 100644 index 0000000..9a31d6e --- /dev/null +++ b/test/fixtures/nhc-gis-points-2026-09-27.json @@ -0,0 +1 @@ +{"type":"FeatureCollection","features":[{"type":"Feature","id":1880,"geometry":{"type":"Point","coordinates":[-43.900000000299656,29.600000000299929]},"properties":{"objectid":1880,"stormname":"Tropical Depression Fay","stormtype":"TD","dvlbl":"D","basin":"AL","advdate":"300 AM GMT Sun Sep 27 2026","advisnum":"28","fcstprd":120,"gust":40,"maxwind":30,"mslp":1010,"ssnum":0,"datelbl":"3:00 AM Sun","tcdvlp":"Tropical Depression","tcdir":190,"tcspd":2,"fldatelbl":"2026-09-27 12:00 AM Sun GMT","lat":30,"lon":-44,"stormnum":6,"stormsrc":"Tropical Cyclone","timezone":"GMT","validtime":"27/0000","tau":0,"idp_source":"al062026-028_5day_pts","idp_subset":"al062026","idp_filedate":1790478147000,"idp_ingestdate":1790478155000,"binnumber":"AT1"}},{"type":"Feature","id":1881,"geometry":{"type":"Point","coordinates":[-43.799999999600175,29.399999999800286]},"properties":{"objectid":1881,"stormname":"Tropical Depression Fay","stormtype":"TD","dvlbl":"D","basin":"AL","advdate":"300 AM GMT Sun Sep 27 2026","advisnum":"28","fcstprd":120,"gust":40,"maxwind":30,"mslp":9999,"ssnum":0,"datelbl":"12:00 PM Sun","tcdvlp":"Tropical Depression","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-27 12:00 PM Sun GMT","lat":29,"lon":-44,"stormnum":6,"stormsrc":"Tropical Cyclone","timezone":"GMT","validtime":"27/1200","tau":12,"idp_source":"al062026-028_5day_pts","idp_subset":"al062026","idp_filedate":1790478147000,"idp_ingestdate":1790478155000,"binnumber":"AT1"}},{"type":"Feature","id":1882,"geometry":{"type":"Point","coordinates":[-43.699999999800013,28.400000000000148]},"properties":{"objectid":1882,"stormname":"Tropical Depression Fay","stormtype":"TD","dvlbl":"D","basin":"AL","advdate":"300 AM GMT Sun Sep 27 2026","advisnum":"28","fcstprd":120,"gust":35,"maxwind":25,"mslp":9999,"ssnum":0,"datelbl":"12:00 AM Mon","tcdvlp":"Tropical Depression","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-28 12:00 AM Mon GMT","lat":28,"lon":-44,"stormnum":6,"stormsrc":"Tropical Cyclone","timezone":"GMT","validtime":"28/0000","tau":24,"idp_source":"al062026-028_5day_pts","idp_subset":"al062026","idp_filedate":1790478147000,"idp_ingestdate":1790478155000,"binnumber":"AT1"}},{"type":"Feature","id":1883,"geometry":{"type":"Point","coordinates":[-43.599999999999909,27.400000000200009]},"properties":{"objectid":1883,"stormname":"Tropical Depression Fay","stormtype":"TD","dvlbl":"D","basin":"AL","advdate":"300 AM GMT Sun Sep 27 2026","advisnum":"28","fcstprd":120,"gust":40,"maxwind":30,"mslp":9999,"ssnum":0,"datelbl":"12:00 PM Mon","tcdvlp":"Tropical Depression","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-28 12:00 PM Mon GMT","lat":27,"lon":-44,"stormnum":6,"stormsrc":"Tropical Cyclone","timezone":"GMT","validtime":"28/1200","tau":36,"idp_source":"al062026-028_5day_pts","idp_subset":"al062026","idp_filedate":1790478147000,"idp_ingestdate":1790478155000,"binnumber":"AT1"}},{"type":"Feature","id":1884,"geometry":{"type":"Point","coordinates":[-44.699999999600209,25.79999999980032]},"properties":{"objectid":1884,"stormname":"Tropical Depression Fay","stormtype":"TD","dvlbl":"D","basin":"AL","advdate":"300 AM GMT Sun Sep 27 2026","advisnum":"28","fcstprd":120,"gust":40,"maxwind":30,"mslp":9999,"ssnum":0,"datelbl":"12:00 AM Tue","tcdvlp":"Tropical Depression","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-29 12:00 AM Tue GMT","lat":26,"lon":-45,"stormnum":6,"stormsrc":"Tropical Cyclone","timezone":"GMT","validtime":"29/0000","tau":48,"idp_source":"al062026-028_5day_pts","idp_subset":"al062026","idp_filedate":1790478147000,"idp_ingestdate":1790478155000,"binnumber":"AT1"}},{"type":"Feature","id":1885,"geometry":{"type":"Point","coordinates":[-46.200000000199736,24.600000000399859]},"properties":{"objectid":1885,"stormname":"Tropical Depression Fay","stormtype":"TD","dvlbl":"D","basin":"AL","advdate":"300 AM GMT Sun Sep 27 2026","advisnum":"28","fcstprd":120,"gust":40,"maxwind":30,"mslp":9999,"ssnum":0,"datelbl":"12:00 PM Tue","tcdvlp":"Tropical Depression","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-29 12:00 PM Tue GMT","lat":25,"lon":-46,"stormnum":6,"stormsrc":"Tropical Cyclone","timezone":"GMT","validtime":"29/1200","tau":60,"idp_source":"al062026-028_5day_pts","idp_subset":"al062026","idp_filedate":1790478147000,"idp_ingestdate":1790478155000,"binnumber":"AT1"}},{"type":"Feature","id":1886,"geometry":{"type":"Point","coordinates":[-47.900000000399586,23.999999999800309]},"properties":{"objectid":1886,"stormname":"Tropical Depression Fay","stormtype":"STD","dvlbl":"D","basin":"AL","advdate":"300 AM GMT Sun Sep 27 2026","advisnum":"28","fcstprd":120,"gust":35,"maxwind":25,"mslp":9999,"ssnum":0,"datelbl":"12:00 AM Wed","tcdvlp":"Subtropical Depression","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-30 12:00 AM Wed GMT","lat":24,"lon":-48,"stormnum":6,"stormsrc":"Post-Tropical Cyclone","timezone":"GMT","validtime":"30/0000","tau":72,"idp_source":"al062026-028_5day_pts","idp_subset":"al062026","idp_filedate":1790478147000,"idp_ingestdate":1790478155000,"binnumber":"AT1"}},{"type":"Feature","id":1928,"geometry":{"type":"Point","coordinates":[-113.39999999989999,19.800000000100056]},"properties":{"objectid":1928,"stormname":"Hurricane Polo","stormtype":"MH","dvlbl":"M","basin":"EP","advdate":"1100 PM MST Sat Sep 26 2026","advisnum":"26A","fcstprd":120,"gust":125,"maxwind":105,"mslp":950,"ssnum":3,"datelbl":"11:00 PM Sat","tcdvlp":"Major Hurricane","tcdir":315,"tcspd":9,"fldatelbl":"2026-09-26 8:00 PM Sat MST","lat":20,"lon":-113,"stormnum":17,"stormsrc":"Tropical Cyclone","timezone":"MST","validtime":"27/0300","tau":0,"idp_source":"ep172026-026A_5day_pts","idp_subset":"ep172026","idp_filedate":1790488954000,"idp_ingestdate":1790489009000,"binnumber":"EP2"}},{"type":"Feature","id":1922,"geometry":{"type":"Point","coordinates":[-161.49999999999991,17.699999999800298]},"properties":{"objectid":1922,"stormname":"Hurricane Nolo","stormtype":"MH","dvlbl":"M","basin":"EP","advdate":"500 PM HST Sat Sep 26 2026","advisnum":"26","fcstprd":120,"gust":140,"maxwind":115,"mslp":9999,"ssnum":4,"datelbl":"2:00 AM Mon","tcdvlp":"Major Hurricane","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-28 2:00 AM Mon HST","lat":18,"lon":-162,"stormnum":15,"stormsrc":"Tropical Cyclone","timezone":"HST","validtime":"28/1200","tau":36,"idp_source":"ep152026-026_5day_pts","idp_subset":"ep152026","idp_filedate":1790481769000,"idp_ingestdate":1790481848000,"binnumber":"CP2"}},{"type":"Feature","id":1923,"geometry":{"type":"Point","coordinates":[-162.80000000009986,19.200000000399825]},"properties":{"objectid":1923,"stormname":"Hurricane Nolo","stormtype":"MH","dvlbl":"M","basin":"EP","advdate":"500 PM HST Sat Sep 26 2026","advisnum":"26","fcstprd":120,"gust":135,"maxwind":110,"mslp":9999,"ssnum":3,"datelbl":"2:00 PM Mon","tcdvlp":"Major Hurricane","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-28 2:00 PM Mon HST","lat":19,"lon":-163,"stormnum":15,"stormsrc":"Tropical Cyclone","timezone":"HST","validtime":"29/0000","tau":48,"idp_source":"ep152026-026_5day_pts","idp_subset":"ep152026","idp_filedate":1790481769000,"idp_ingestdate":1790481848000,"binnumber":"CP2"}},{"type":"Feature","id":1924,"geometry":{"type":"Point","coordinates":[-163.7999999999,20.799999999900194]},"properties":{"objectid":1924,"stormname":"Hurricane Nolo","stormtype":"HU","dvlbl":"H","basin":"EP","advdate":"500 PM HST Sat Sep 26 2026","advisnum":"26","fcstprd":120,"gust":115,"maxwind":95,"mslp":9999,"ssnum":2,"datelbl":"2:00 AM Tue","tcdvlp":"Hurricane","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-29 2:00 AM Tue HST","lat":21,"lon":-164,"stormnum":15,"stormsrc":"Tropical Cyclone","timezone":"HST","validtime":"29/1200","tau":60,"idp_source":"ep152026-026_5day_pts","idp_subset":"ep152026","idp_filedate":1790481769000,"idp_ingestdate":1790481848000,"binnumber":"CP2"}},{"type":"Feature","id":1925,"geometry":{"type":"Point","coordinates":[-164.50000000029971,22.40000000029994]},"properties":{"objectid":1925,"stormname":"Hurricane Nolo","stormtype":"HU","dvlbl":"H","basin":"EP","advdate":"500 PM HST Sat Sep 26 2026","advisnum":"26","fcstprd":120,"gust":100,"maxwind":80,"mslp":9999,"ssnum":1,"datelbl":"2:00 PM Tue","tcdvlp":"Hurricane","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-29 2:00 PM Tue HST","lat":22,"lon":-164,"stormnum":15,"stormsrc":"Tropical Cyclone","timezone":"HST","validtime":"30/0000","tau":72,"idp_source":"ep152026-026_5day_pts","idp_subset":"ep152026","idp_filedate":1790481769000,"idp_ingestdate":1790481848000,"binnumber":"CP2"}},{"type":"Feature","id":1926,"geometry":{"type":"Point","coordinates":[-166.30000000029969,23.099999999800275]},"properties":{"objectid":1926,"stormname":"Hurricane Nolo","stormtype":"HU","dvlbl":"H","basin":"EP","advdate":"500 PM HST Sat Sep 26 2026","advisnum":"26","fcstprd":120,"gust":80,"maxwind":65,"mslp":9999,"ssnum":1,"datelbl":"2:00 PM Wed","tcdvlp":"Hurricane","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-30 2:00 PM Wed HST","lat":23,"lon":-166,"stormnum":15,"stormsrc":"Tropical Cyclone","timezone":"HST","validtime":"01/0000","tau":96,"idp_source":"ep152026-026_5day_pts","idp_subset":"ep152026","idp_filedate":1790481769000,"idp_ingestdate":1790481848000,"binnumber":"CP2"}},{"type":"Feature","id":1927,"geometry":{"type":"Point","coordinates":[-169.29999999970016,23.099999999800275]},"properties":{"objectid":1927,"stormname":"Hurricane Nolo","stormtype":"HU","dvlbl":"H","basin":"EP","advdate":"500 PM HST Sat Sep 26 2026","advisnum":"26","fcstprd":120,"gust":80,"maxwind":65,"mslp":9999,"ssnum":1,"datelbl":"2:00 PM Thu","tcdvlp":"Hurricane","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-10-01 2:00 PM Thu HST","lat":23,"lon":-169,"stormnum":15,"stormsrc":"Tropical Cyclone","timezone":"HST","validtime":"02/0000","tau":120,"idp_source":"ep152026-026_5day_pts","idp_subset":"ep152026","idp_filedate":1790481769000,"idp_ingestdate":1790481848000,"binnumber":"CP2"}},{"type":"Feature","id":1929,"geometry":{"type":"Point","coordinates":[-113.7999999999999,20.70000000010009]},"properties":{"objectid":1929,"stormname":"Hurricane Polo","stormtype":"MH","dvlbl":"M","basin":"EP","advdate":"1100 PM MST Sat Sep 26 2026","advisnum":"26A","fcstprd":120,"gust":120,"maxwind":100,"mslp":9999,"ssnum":3,"datelbl":"5:00 AM Sun","tcdvlp":"Major Hurricane","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-27 5:00 AM Sun MST","lat":21,"lon":-114,"stormnum":17,"stormsrc":"Tropical Cyclone","timezone":"MST","validtime":"27/1200","tau":12,"idp_source":"ep172026-026A_5day_pts","idp_subset":"ep172026","idp_filedate":1790488954000,"idp_ingestdate":1790489009000,"binnumber":"EP2"}},{"type":"Feature","id":1930,"geometry":{"type":"Point","coordinates":[-114.20000000009981,22.40000000029994]},"properties":{"objectid":1930,"stormname":"Hurricane Polo","stormtype":"HU","dvlbl":"H","basin":"EP","advdate":"1100 PM MST Sat Sep 26 2026","advisnum":"26A","fcstprd":120,"gust":115,"maxwind":95,"mslp":9999,"ssnum":2,"datelbl":"5:00 PM Sun","tcdvlp":"Hurricane","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-27 5:00 PM Sun MST","lat":22,"lon":-114,"stormnum":17,"stormsrc":"Tropical Cyclone","timezone":"MST","validtime":"28/0000","tau":24,"idp_source":"ep172026-026A_5day_pts","idp_subset":"ep172026","idp_filedate":1790488954000,"idp_ingestdate":1790489009000,"binnumber":"EP2"}},{"type":"Feature","id":1931,"geometry":{"type":"Point","coordinates":[-113.70000000019974,24.200000000299895]},"properties":{"objectid":1931,"stormname":"Hurricane Polo","stormtype":"HU","dvlbl":"H","basin":"EP","advdate":"1100 PM MST Sat Sep 26 2026","advisnum":"26A","fcstprd":120,"gust":110,"maxwind":90,"mslp":9999,"ssnum":2,"datelbl":"5:00 AM Mon","tcdvlp":"Hurricane","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-28 5:00 AM Mon MST","lat":24,"lon":-114,"stormnum":17,"stormsrc":"Tropical Cyclone","timezone":"MST","validtime":"28/1200","tau":36,"idp_source":"ep172026-026A_5day_pts","idp_subset":"ep172026","idp_filedate":1790488954000,"idp_ingestdate":1790489009000,"binnumber":"EP2"}},{"type":"Feature","id":1932,"geometry":{"type":"Point","coordinates":[-112.49999999989996,25.79999999980032]},"properties":{"objectid":1932,"stormname":"Hurricane Polo","stormtype":"HU","dvlbl":"H","basin":"EP","advdate":"1100 PM MST Sat Sep 26 2026","advisnum":"26A","fcstprd":120,"gust":100,"maxwind":80,"mslp":9999,"ssnum":1,"datelbl":"5:00 PM Mon","tcdvlp":"Hurricane","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-28 5:00 PM Mon MST","lat":26,"lon":-112,"stormnum":17,"stormsrc":"Tropical Cyclone","timezone":"MST","validtime":"29/0000","tau":48,"idp_source":"ep172026-026A_5day_pts","idp_subset":"ep172026","idp_filedate":1790488954000,"idp_ingestdate":1790489009000,"binnumber":"EP2"}},{"type":"Feature","id":1933,"geometry":{"type":"Point","coordinates":[-110.79999999970011,27.599999999800275]},"properties":{"objectid":1933,"stormname":"Hurricane Polo","stormtype":"HU","dvlbl":"H","basin":"EP","advdate":"1100 PM MST Sat Sep 26 2026","advisnum":"26A","fcstprd":120,"gust":80,"maxwind":65,"mslp":9999,"ssnum":1,"datelbl":"5:00 AM Tue","tcdvlp":"Hurricane","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-29 5:00 AM Tue MST","lat":28,"lon":-111,"stormnum":17,"stormsrc":"Tropical Cyclone","timezone":"MST","validtime":"29/1200","tau":60,"idp_source":"ep172026-026A_5day_pts","idp_subset":"ep172026","idp_filedate":1790488954000,"idp_ingestdate":1790489009000,"binnumber":"EP2"}},{"type":"Feature","id":1934,"geometry":{"type":"Point","coordinates":[-108.39999999999992,29.70000000010009]},"properties":{"objectid":1934,"stormname":"Hurricane Polo","stormtype":"STD","dvlbl":"D","basin":"EP","advdate":"1100 PM MST Sat Sep 26 2026","advisnum":"26A","fcstprd":120,"gust":40,"maxwind":30,"mslp":9999,"ssnum":0,"datelbl":"5:00 PM Tue","tcdvlp":"Subtropical Depression","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-29 5:00 PM Tue MST","lat":30,"lon":-108,"stormnum":17,"stormsrc":"Post-Tropical Cyclone","timezone":"MST","validtime":"30/0000","tau":72,"idp_source":"ep172026-026A_5day_pts","idp_subset":"ep172026","idp_filedate":1790488954000,"idp_ingestdate":1790489009000,"binnumber":"EP2"}},{"type":"Feature","id":1887,"geometry":{"type":"Point","coordinates":[-123.60000000019977,21.100000000199998]},"properties":{"objectid":1887,"stormname":"Hurricane Odalys","stormtype":"HU","dvlbl":"H","basin":"EP","advdate":"800 PM PDT Sat Sep 26 2026","advisnum":"29","fcstprd":120,"gust":85,"maxwind":70,"mslp":979,"ssnum":1,"datelbl":"8:00 PM Sat","tcdvlp":"Hurricane","tcdir":360,"tcspd":6,"fldatelbl":"2026-09-26 5:00 PM Sat PDT","lat":21,"lon":-124,"stormnum":16,"stormsrc":"Tropical Cyclone","timezone":"PDT","validtime":"27/0000","tau":0,"idp_source":"ep162026-029_5day_pts","idp_subset":"ep162026","idp_filedate":1790478148000,"idp_ingestdate":1790478227000,"binnumber":"EP1"}},{"type":"Feature","id":1888,"geometry":{"type":"Point","coordinates":[-123.39999999970013,21.900000000399814]},"properties":{"objectid":1888,"stormname":"Hurricane Odalys","stormtype":"TS","dvlbl":"S","basin":"EP","advdate":"800 PM PDT Sat Sep 26 2026","advisnum":"29","fcstprd":120,"gust":65,"maxwind":55,"mslp":9999,"ssnum":0,"datelbl":"5:00 AM Sun","tcdvlp":"Tropical Storm","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-27 5:00 AM Sun PDT","lat":22,"lon":-123,"stormnum":16,"stormsrc":"Tropical Cyclone","timezone":"PDT","validtime":"27/1200","tau":12,"idp_source":"ep162026-029_5day_pts","idp_subset":"ep162026","idp_filedate":1790478148000,"idp_ingestdate":1790478227000,"binnumber":"EP1"}},{"type":"Feature","id":1889,"geometry":{"type":"Point","coordinates":[-123.1000000002997,22.299999999600459]},"properties":{"objectid":1889,"stormname":"Hurricane Odalys","stormtype":"TS","dvlbl":"S","basin":"EP","advdate":"800 PM PDT Sat Sep 26 2026","advisnum":"29","fcstprd":120,"gust":55,"maxwind":45,"mslp":9999,"ssnum":0,"datelbl":"5:00 PM Sun","tcdvlp":"Tropical Storm","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-27 5:00 PM Sun PDT","lat":22,"lon":-123,"stormnum":16,"stormsrc":"Tropical Cyclone","timezone":"PDT","validtime":"28/0000","tau":24,"idp_source":"ep162026-029_5day_pts","idp_subset":"ep162026","idp_filedate":1790478148000,"idp_ingestdate":1790478227000,"binnumber":"EP1"}},{"type":"Feature","id":1890,"geometry":{"type":"Point","coordinates":[-122.70000000019974,22.100000000000136]},"properties":{"objectid":1890,"stormname":"Hurricane Odalys","stormtype":"STS","dvlbl":"S","basin":"EP","advdate":"800 PM PDT Sat Sep 26 2026","advisnum":"29","fcstprd":120,"gust":45,"maxwind":35,"mslp":9999,"ssnum":0,"datelbl":"5:00 AM Mon","tcdvlp":"Subtropical Storm","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-28 5:00 AM Mon PDT","lat":22,"lon":-123,"stormnum":16,"stormsrc":"Post-Tropical Cyclone","timezone":"PDT","validtime":"28/1200","tau":36,"idp_source":"ep162026-029_5day_pts","idp_subset":"ep162026","idp_filedate":1790478148000,"idp_ingestdate":1790478227000,"binnumber":"EP1"}},{"type":"Feature","id":1891,"geometry":{"type":"Point","coordinates":[-122.30000000009983,21.200000000000159]},"properties":{"objectid":1891,"stormname":"Hurricane Odalys","stormtype":"STD","dvlbl":"D","basin":"EP","advdate":"800 PM PDT Sat Sep 26 2026","advisnum":"29","fcstprd":120,"gust":35,"maxwind":25,"mslp":9999,"ssnum":0,"datelbl":"5:00 PM Mon","tcdvlp":"Subtropical Depression","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-28 5:00 PM Mon PDT","lat":21,"lon":-122,"stormnum":16,"stormsrc":"Post-Tropical Cyclone","timezone":"PDT","validtime":"29/0000","tau":48,"idp_source":"ep162026-029_5day_pts","idp_subset":"ep162026","idp_filedate":1790478148000,"idp_ingestdate":1790478227000,"binnumber":"EP1"}},{"type":"Feature","id":1892,"geometry":{"type":"Point","coordinates":[-121.99999999980008,20.100000000399859]},"properties":{"objectid":1892,"stormname":"Hurricane Odalys","stormtype":"STD","dvlbl":"D","basin":"EP","advdate":"800 PM PDT Sat Sep 26 2026","advisnum":"29","fcstprd":120,"gust":35,"maxwind":25,"mslp":9999,"ssnum":0,"datelbl":"5:00 AM Tue","tcdvlp":"Subtropical Depression","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-29 5:00 AM Tue PDT","lat":20,"lon":-122,"stormnum":16,"stormsrc":"Post-Tropical Cyclone","timezone":"PDT","validtime":"29/1200","tau":60,"idp_source":"ep162026-029_5day_pts","idp_subset":"ep162026","idp_filedate":1790478148000,"idp_ingestdate":1790478227000,"binnumber":"EP1"}},{"type":"Feature","id":1893,"geometry":{"type":"Point","coordinates":[-121.99999999980008,19.200000000399825]},"properties":{"objectid":1893,"stormname":"Hurricane Odalys","stormtype":"STD","dvlbl":"D","basin":"EP","advdate":"800 PM PDT Sat Sep 26 2026","advisnum":"29","fcstprd":120,"gust":30,"maxwind":20,"mslp":9999,"ssnum":0,"datelbl":"5:00 PM Tue","tcdvlp":"Subtropical Depression","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-29 5:00 PM Tue PDT","lat":19,"lon":-122,"stormnum":16,"stormsrc":"Post-Tropical Cyclone","timezone":"PDT","validtime":"30/0000","tau":72,"idp_source":"ep162026-029_5day_pts","idp_subset":"ep162026","idp_filedate":1790478148000,"idp_ingestdate":1790478227000,"binnumber":"EP1"}},{"type":"Feature","id":1919,"geometry":{"type":"Point","coordinates":[-156.50000000009985,16.700000000000159]},"properties":{"objectid":1919,"stormname":"Hurricane Nolo","stormtype":"HU","dvlbl":"H","basin":"EP","advdate":"500 PM HST Sat Sep 26 2026","advisnum":"26","fcstprd":120,"gust":100,"maxwind":80,"mslp":969,"ssnum":1,"datelbl":"5:00 PM Sat","tcdvlp":"Hurricane","tcdir":265,"tcspd":7,"fldatelbl":"2026-09-26 2:00 PM Sat HST","lat":17,"lon":-156,"stormnum":15,"stormsrc":"Tropical Cyclone","timezone":"HST","validtime":"27/0000","tau":0,"idp_source":"ep152026-026_5day_pts","idp_subset":"ep152026","idp_filedate":1790481769000,"idp_ingestdate":1790481848000,"binnumber":"CP2"}},{"type":"Feature","id":1920,"geometry":{"type":"Point","coordinates":[-157.70000000039963,16.600000000199998]},"properties":{"objectid":1920,"stormname":"Hurricane Nolo","stormtype":"HU","dvlbl":"H","basin":"EP","advdate":"500 PM HST Sat Sep 26 2026","advisnum":"26","fcstprd":120,"gust":110,"maxwind":90,"mslp":9999,"ssnum":2,"datelbl":"2:00 AM Sun","tcdvlp":"Hurricane","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-27 2:00 AM Sun HST","lat":17,"lon":-158,"stormnum":15,"stormsrc":"Tropical Cyclone","timezone":"HST","validtime":"27/1200","tau":12,"idp_source":"ep152026-026_5day_pts","idp_subset":"ep152026","idp_filedate":1790481769000,"idp_ingestdate":1790481848000,"binnumber":"CP2"}},{"type":"Feature","id":1921,"geometry":{"type":"Point","coordinates":[-159.60000000019977,16.899999999600425]},"properties":{"objectid":1921,"stormname":"Hurricane Nolo","stormtype":"MH","dvlbl":"M","basin":"EP","advdate":"500 PM HST Sat Sep 26 2026","advisnum":"26","fcstprd":120,"gust":130,"maxwind":105,"mslp":9999,"ssnum":3,"datelbl":"2:00 PM Sun","tcdvlp":"Major Hurricane","tcdir":9999,"tcspd":9999,"fldatelbl":"2026-09-27 2:00 PM Sun HST","lat":17,"lon":-160,"stormnum":15,"stormsrc":"Tropical Cyclone","timezone":"HST","validtime":"28/0000","tau":24,"idp_source":"ep152026-026_5day_pts","idp_subset":"ep152026","idp_filedate":1790481769000,"idp_ingestdate":1790481848000,"binnumber":"CP2"}}]} \ No newline at end of file diff --git a/test/fixtures/openmeteo-era5-delhi-1991-window.json b/test/fixtures/openmeteo-era5-delhi-1991-window.json new file mode 100644 index 0000000..3cdc15f --- /dev/null +++ b/test/fixtures/openmeteo-era5-delhi-1991-window.json @@ -0,0 +1 @@ +{"latitude":28.5,"longitude":77.25,"generationtime_ms":0.2104043960571289,"utc_offset_seconds":19800,"timezone":"Asia/Kolkata","timezone_abbreviation":"GMT+5:30","elevation":217.0,"daily_units":{"time":"iso8601","temperature_2m_max":"°C","precipitation_sum":"mm"},"daily":{"time":["1991-09-17","1991-09-18","1991-09-19","1991-09-20","1991-09-21","1991-09-22","1991-09-23","1991-09-24","1991-09-25","1991-09-26","1991-09-27","1991-09-28","1991-09-29","1991-09-30","1991-10-01","1991-10-02","1991-10-03","1991-10-04","1991-10-05","1991-10-06"],"temperature_2m_max":[34.2,35.2,35.2,35.2,35.2,35.7,35.5,35.6,37.1,36.6,36.1,35.5,34.9,34.4,33.9,32.6,33.5,33.4,34.5,35.0],"precipitation_sum":[0.00,0.10,0.00,0.00,0.20,0.00,0.20,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00,0.00]}} \ No newline at end of file diff --git a/test/fixtures/openmeteo-era5-delhi-2026-09-20.json b/test/fixtures/openmeteo-era5-delhi-2026-09-20.json new file mode 100644 index 0000000..65f26ee --- /dev/null +++ b/test/fixtures/openmeteo-era5-delhi-2026-09-20.json @@ -0,0 +1 @@ +{"latitude":28.5,"longitude":77.25,"generationtime_ms":0.4895925521850586,"utc_offset_seconds":19800,"timezone":"Asia/Kolkata","timezone_abbreviation":"GMT+5:30","elevation":217.0,"daily_units":{"time":"iso8601","temperature_2m_max":"°C","precipitation_sum":"mm"},"daily":{"time":["2026-09-20","2026-09-21","2026-09-22","2026-09-23","2026-09-24","2026-09-25","2026-09-26"],"temperature_2m_max":[33.7,34.3,null,null,null,null,null],"precipitation_sum":[0.00,0.10,null,null,null,null,null]}} \ No newline at end of file diff --git a/test/fixtures/openmeteo-forecast-delhi-2026-09-27.json b/test/fixtures/openmeteo-forecast-delhi-2026-09-27.json new file mode 100644 index 0000000..3faa174 --- /dev/null +++ b/test/fixtures/openmeteo-forecast-delhi-2026-09-27.json @@ -0,0 +1 @@ +{"latitude":28.576448,"longitude":77.18678,"generationtime_ms":0.3370046615600586,"utc_offset_seconds":19800,"timezone":"Asia/Kolkata","timezone_abbreviation":"GMT+5:30","elevation":217.0,"current_units":{"time":"iso8601","interval":"seconds","temperature_2m":"°C","apparent_temperature":"°C","relative_humidity_2m":"%","precipitation":"mm","wind_speed_10m":"km/h","wind_direction_10m":"°","weather_code":"wmo code"},"current":{"time":"2026-09-27T13:30","interval":900,"temperature_2m":28.7,"apparent_temperature":32.4,"relative_humidity_2m":61,"precipitation":0.00,"wind_speed_10m":9.4,"wind_direction_10m":85,"weather_code":0},"daily_units":{"time":"iso8601","temperature_2m_max":"°C","temperature_2m_min":"°C","apparent_temperature_max":"°C","precipitation_sum":"mm","wind_speed_10m_max":"km/h","wind_gusts_10m_max":"km/h"},"daily":{"time":["2026-09-20","2026-09-21","2026-09-22","2026-09-23","2026-09-24","2026-09-25","2026-09-26","2026-09-27","2026-09-28","2026-09-29","2026-09-30","2026-10-01","2026-10-02","2026-10-03"],"temperature_2m_max":[33.7,33.7,35.8,36.9,34.6,31.2,29.6,28.7,30.2,31.6,33.0,34.9,35.7,34.8],"temperature_2m_min":[25.4,26.2,26.3,27.0,26.2,25.0,22.1,22.2,21.6,23.1,23.2,24.1,24.0,24.3],"apparent_temperature_max":[38.6,37.7,39.2,40.3,38.3,34.3,32.6,32.5,34.5,34.8,35.2,36.0,36.7,35.4],"precipitation_sum":[1.50,0.10,0.00,0.00,0.00,0.00,4.60,0.90,0.40,0.40,0.00,0.00,0.00,0.00],"wind_speed_10m_max":[6.9,7.1,10.1,9.1,12.1,12.7,13.6,9.7,7.2,9.6,12.4,14.4,14.0,10.5],"wind_gusts_10m_max":[15.5,18.0,25.2,25.2,28.1,34.6,32.0,25.9,19.4,25.6,31.0,37.1,37.1,32.8]}} \ No newline at end of file diff --git a/test/improvement.test.ts b/test/improvement.test.ts new file mode 100644 index 0000000..d00b904 --- /dev/null +++ b/test/improvement.test.ts @@ -0,0 +1,298 @@ +// improvement@1.0 end to end through the kernel with a scripted tool caller. Tool outputs are +// real responses recorded live on 2026-09-27 (GFW, FIRMS + EOG VNF, NOAA CRW, CAMS) — see +// test/fixtures/imp-*.json — edited only where a test needs the good-news branch to fire. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { select, type AnalystLedger } from "../src/analyst/analyst.js"; +import { alertsWhere } from "../src/clients/gfw.js"; +import { parseVnfKml } from "../src/clients/vnf.js"; +import type { Finding } from "../src/ledger/schema.js"; +import { Ledger } from "../src/ledger/store.js"; +import { Journal } from "../src/watch/journal.js"; +import { sweep } from "../src/watch/kernel.js"; +import { airClean, bleachingRelief, fireClusters, improvementParams } from "../src/watch/rules/improvement.js"; +import { RULES, ToolError, type ToolCall } from "../src/watch/rules/index.js"; +import { loadWatchlists, parseWatchlist, type Watchlist } from "../src/watch/watchlist.js"; +import { addDays } from "../src/util.js"; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type Json = any; +const fx = (f: string): Json => JSON.parse(readFileSync(new URL(`./fixtures/${f}`, import.meta.url), "utf8")); +const clone = (v: T): T => JSON.parse(JSON.stringify(v)) as T; + +const GFW = fx("imp-gfw-sao-felix-2026-09-27.json"); // 169.25 ha now vs 828.87 ha a year earlier +const FLARE = fx("imp-flaring-rumaila-2026-09-27.json"); // VNF 2.869 → 3.201 BCM (up); 882 hot nights a year ago +const CORAL = fx("imp-coral-galapagos-2026-09-25.json"); // Watch now; Warning 07-29, clear 08-04…08-30 +const AIR = fx("imp-air-delhi-15d-2026-09-27.json"); // 15 full days, all > 15 µg/m³ +const FIRES = fx("imp-fires-pacaas-novos.json"); // 5 low-FRP detections now; 7 hot (one 6-detection cell) a year ago + +const NOW = "2026-09-27T06:00:00Z"; + +function fakeCall(script: Record) => unknown>): { call: ToolCall; calls: { tool: string; args: Record }[] } { + const calls: { tool: string; args: Record }[] = []; + const call: ToolCall = async (tool, args) => { + calls.push({ tool, args }); + const fn = script[tool]; + if (!fn) throw new ToolError(tool, "not scripted"); + return JSON.parse(JSON.stringify(await fn(args))); + }; + return { call, calls }; +} + +function setup() { + const dir = mkdtempSync(join(tmpdir(), "earthdeck-improvement-")); + return { ledger: Ledger.open(dir), journal: new Journal(join(dir, "watch")) }; +} + +const context = { enso: () => ({ phase: "El Niño", latest: { oni: 1.8 } }), events: () => ({ events: [] }) }; + +function list(params: Record, bbox: [number, number, number, number] = [-52.4, -6.9, -51.9, -6.4], name = "São Félix do Xingu (PA)"): Watchlist { + return parseWatchlist({ version: 1, name: "t", aois: [{ id: "t-aoi", name, bbox, tags: ["test"], rules: [{ name: "improvement", params }] }] }); +} + +async function run(s: ReturnType, wl: Watchlist, call: ToolCall, now = NOW) { + return sweep({ watchlists: [wl], rules: RULES, ledger: s.ledger, journal: s.journal, call, now, hasKey: () => true }); +} + +// ---- forest_recovery --------------------------------------------------------------------- + +test("forest_recovery: loss ≤ 30 % of the same window last year and below the ring → improvement case, opt-in NDVI confirms", async () => { + const s = setup(); + const end = addDays(NOW.slice(0, 10), -14); // alert lag + const { call, calls } = fakeCall({ + ...context, + forest_alerts: (a) => { + if (a.endDate === end && (a.bbox as number[])[0] === -52.4) return GFW.now; + if (a.endDate === addDays(end, -365)) return GFW.yearAgo; + return { ...GFW.now, areaHa: 2000 }; // the 25 km ring: busier than the AOI + }, + eo_compare: () => ({ dateA: "x", dateB: "y", validPctA: 98, validPctB: 98, delta: { meanChange: 0.038 } }), + }); + const r = await run(s, list({ kind: "forest_recovery", confirmWithNdvi: true }), call); + assert.equal(r.created.length, 1); + assert.equal(r.confirmed.length, 1); + const off = fakeCall({ ...context, forest_alerts: (a) => ((a.bbox as number[])[0] !== -52.4 ? { ...GFW.now, areaHa: 2000 } : a.endDate === end ? GFW.now : GFW.yearAgo), eo_compare: () => ({ validPctA: 98, validPctB: 98, delta: { meanChange: 0.038 } }) }); + const r0 = await run(setup(), list({ kind: "forest_recovery" }), off.call); + assert.equal(r0.created.length, 1); + assert.equal(r0.confirmed.length, 0, "default: NDVI never confirms; waits for the next window"); + assert.equal(off.calls.filter((c) => c.tool === "eo_compare").length, 0); + const f = s.ledger.get(r.created[0]!)!; + assert.equal(f.title, "Forest loss near São Félix do Xingu (PA) fell 80 % year on year"); + assert.ok(f.aoi?.tags?.includes("improvement"), "the case carries the improvement tag"); + assert.equal(f.observedAt, `${end}T00:00:00Z`); + assert.equal(f.evidence[0]!.values!.drop_pct, 80); + assert.ok(f.context?.baseline && f.context.baseline.ratio! < 1); + assert.equal(f.confirmed!.independence, "sensor"); + const fa = calls.filter((c) => c.tool === "forest_alerts"); + assert.deepEqual(fa.map((c) => c.args.endDate), [end, addDays(end, -365), end]); + assert.equal(calls.find((c) => c.tool === "eo_compare")!.args.dateA, addDays(end, -365), "NDVI compared year on year"); +}); + +test("forest_recovery: quiet when the ring is quieter, or last year was already small", async () => { + const s = setup(); + const quietRing = fakeCall({ ...context, forest_alerts: (a) => ((a.bbox as number[])[0] === -52.4 ? (a.endDate === addDays(NOW.slice(0, 10), -14) ? GFW.now : GFW.yearAgo) : { ...GFW.now, areaHa: 10 }) }); + assert.equal((await run(s, list({ kind: "forest_recovery" }), quietRing.call)).created.length, 0); + const small = fakeCall({ ...context, forest_alerts: () => ({ ...GFW.now, areaHa: 5 }) }); + assert.equal((await run(setup(), list({ kind: "forest_recovery" }), small.call)).created.length, 0); + assert.equal(small.calls.filter((c) => c.tool === "forest_alerts").length, 2, "no ring pull once last year is too small"); +}); + +test("forest_recovery: no optical check → stays candidate; the next 30 days still low confirms (revisit)", async () => { + const s = setup(); + const end = addDays(NOW.slice(0, 10), -14); + const first = fakeCall({ + ...context, + forest_alerts: (a) => ((a.bbox as number[])[0] !== -52.4 ? { ...GFW.now, areaHa: 2000 } : a.endDate === end ? GFW.now : GFW.yearAgo), + // eo_compare unscripted: throws like a missing CDSE key would + }); + const r = await run(s, list({ kind: "forest_recovery" }), first.call); + assert.equal(r.created.length, 1); + assert.equal(r.confirmed.length, 0); + assert.equal(r.gaps.length, 0, "a failed optical check is not a coverage gap"); + // 23 days later the next window has not cleared the alert lag yet + const early = fakeCall({ ...context, forest_alerts: () => GFW.now }); + const r2 = await run(s, list({ kind: "forest_recovery" }), early.call, "2026-10-20T06:00:00Z"); + assert.equal(r2.confirmed.length, 0); + assert.equal(early.calls.filter((c) => c.tool === "forest_alerts").length, 0); + // 45 days later: next 30 d = 20 ha vs 300 ha a year earlier + const later = fakeCall({ ...context, forest_alerts: (a) => ({ ...GFW.now, areaHa: String(a.endDate) < "2026-01-01" ? 300 : 20 }) }); + const r3 = await run(s, list({ kind: "forest_recovery" }), later.call, "2026-11-11T06:00:00Z"); + assert.equal(r3.confirmed.length, 1); + const f = s.ledger.get(r.created[0]!)!; + assert.equal(f.confirmed!.independence, "revisit"); + assert.deepEqual(later.calls.filter((c) => c.tool === "forest_alerts").map((c) => [c.args.days, c.args.endDate]), [[30, addDays(end, 30)], [30, addDays(end, 30 - 365)]]); +}); + +// ---- flaring_decline --------------------------------------------------------------------- + +test("flaring_decline: Rumaila's live VNF went up 2023→2024 → quiet after one registry pull", async () => { + const { call, calls } = fakeCall({ ...context, flaring: () => FLARE.registry }); + const r = await run(setup(), list({ kind: "flaring_decline" }, [47.0, 30.2, 47.6, 30.8], "Rumaila field (Basra, Iraq)"), call); + assert.equal(r.created.length, 0); + assert.equal(calls.filter((c) => c.tool === "flaring").length, 1); + assert.deepEqual(calls[0]!.args, { bbox: [47.0, 30.2, 47.6, 30.8], days: 1, sources: ["VIIRS_NOAA21_NRT"], limit: 1 }); +}); + +test("flaring_decline: VNF −36 % and fewer hot nights than a year ago → improvement; a second lower window confirms", async () => { + const s = setup(); + const reg = clone(FLARE.registry); + reg.vnf.previous.bcmTotal = 5.0; // 5.0 → 3.201 BCM + const nowWin = { ...clone(FLARE.yearAgo), window: { from: "2026-08-29", to: "2026-09-27", days: 30 }, counts: { ...FLARE.yearAgo.counts, hotNightDetections: 400 } }; + const script = (a: Record) => (a.days === 1 ? reg : String(a.endDate) < "2026-01-01" ? FLARE.yearAgo : nowWin); + const first = fakeCall({ ...context, flaring: script }); + const wl = list({ kind: "flaring_decline" }, [47.0, 30.2, 47.6, 30.8], "Rumaila field (Basra, Iraq)"); + const r = await run(s, wl, first.call); + assert.equal(r.created.length, 1); + assert.equal(r.confirmed.length, 0, "the next window has not elapsed"); + const f = s.ledger.get(r.created[0]!)!; + assert.equal(f.title, "Gas flaring near Rumaila field (Basra, Iraq) fell 36 % year on year"); + assert.ok(f.aoi?.tags?.includes("improvement")); + assert.equal(f.evidence.length, 2); + assert.equal(f.evidence[1]!.values!.hot_nights_year_ago, 882); + const firms = first.calls.filter((c) => c.tool === "flaring" && c.args.days === 30); + assert.deepEqual(firms.map((c) => c.args.endDate), ["2026-09-27", "2025-09-27"]); + assert.ok(firms.every((c) => (c.args.sources as string[]).join() === "VIIRS_NOAA21_NRT" && c.args.vnf === false), "same satellite both years"); + const later = fakeCall({ ...context, flaring: script }); + const r2 = await run(s, wl, later.call, "2026-10-29T06:00:00Z"); + assert.equal(r2.confirmed.length, 1); + assert.deepEqual(later.calls.map((c) => c.args.endDate), ["2026-10-27", "2025-10-27"]); +}); + +// ---- bleaching_relief -------------------------------------------------------------------- + +test("bleaching_relief: live Galápagos is on Watch today → quiet; the same series cut at 08-30 → 27 clear days after a Warning", async () => { + const reef = (fixture: Json) => fakeCall({ ...context, coral_bleaching: () => fixture }); + const wl = list({ kind: "bleaching_relief", lat: -1.0, lon: -92.0, minPeakLevel: 1 }, [-92.5, -1.5, -91.5, -0.5], "Galápagos (west of Isabela, Ecuador)"); + assert.equal((await run(setup(), wl, reef(CORAL).call)).created.length, 0); + + const cut = clone(CORAL); + cut.series = cut.series.filter((p: { t: string }) => p.t <= "2026-08-30"); + cut.latest = { ...cut.latest, date: "2026-08-30", alertLevel: 0, alert: "No stress", dhw: 0.45 }; + assert.deepEqual(bleachingRelief(cut), { peak: 2, peakDhw: 0.45, lastAlert: "2026-08-02", clearDays: 27 }); + const dflt = list({ kind: "bleaching_relief", lat: -1.0, lon: -92.0 }, [-92.5, -1.5, -91.5, -0.5], "Galápagos"); + assert.equal((await run(setup(), dflt, reef(cut).call, "2026-09-01T06:00:00Z")).created.length, 0, "default peak is Alert Level 1 (3); a Warning (2) is not enough"); + const s = setup(); + const r = await run(s, wl, reef(cut).call, "2026-09-01T06:00:00Z"); + assert.equal(r.created.length, 1); + assert.equal(r.confirmed.length, 0, "same data day: persistence waits"); + const f = s.ledger.get(r.created[0]!)!; + assert.equal(f.title, "Coral heat stress has eased at Galápagos (west of Isabela, Ecuador): no bleaching alert for 27 days"); + assert.match(f.summary, /Bleaching Warning/); + assert.ok(f.aoi?.tags?.includes("improvement")); + // A later day still "No stress" confirms; a relapse would not. + const next = clone(cut); + next.latest.date = "2026-09-01"; + next.series.push({ t: "2026-09-01", dhw: 0.44, sstAnomaly: 0, baa: 0, sst: 26 }); + const r2 = await run(s, wl, reef(next).call, "2026-09-03T06:00:00Z"); + assert.equal(r2.confirmed.length, 1); +}); + +// ---- air_quality_clean ------------------------------------------------------------------- + +test("air_quality_clean: live Delhi (15 days above) → quiet; a clean last week after 7 above → improvement, confirmed a day later", async () => { + const wl = list({ kind: "air_quality_clean", lat: 28.61, lon: 77.21 }, [76.96, 28.36, 77.46, 28.86], "Delhi (India)"); + const live = fakeCall({ ...context, air_quality: () => AIR }); + assert.equal((await run(setup(), wl, live.call)).created.length, 0); + assert.deepEqual(live.calls.find((c) => c.tool === "air_quality")!.args, { lat: 28.61, lon: 77.21, pastDays: 15 }); + + const clean = clone(AIR); + for (const d of clean.pm25Daily.slice(-8, -1)) d.v = 11.5; // 09-20…09-26; 09-27 is partial (9 h) + assert.deepEqual(airClean(clean.pm25Daily, 15), { last: "2026-09-26", mean: 11.5, priorAbove: 7, priorMean: 49.2 }); + const s = setup(); + const r = await run(s, wl, fakeCall({ ...context, air_quality: () => clean }).call); + assert.equal(r.created.length, 1); + assert.equal(r.confirmed.length, 0); + const f = s.ledger.get(r.created[0]!)!; + assert.equal(f.title, "Cleaner air in Delhi (India): a week below the WHO fine-particle guideline"); + assert.ok(f.aoi?.tags?.includes("improvement")); + const next = clone(clean); + next.pm25Daily[next.pm25Daily.length - 1] = { t: "2026-09-27", v: 12, hours: 24 }; + next.pm25Daily.push({ t: "2026-09-28", v: 10, hours: 6 }); + const r2 = await run(s, wl, fakeCall({ ...context, air_quality: () => next }).call, "2026-09-28T06:00:00Z"); + assert.equal(r2.confirmed.length, 1); +}); + +// ---- fires_absent ------------------------------------------------------------------------ + +test("fires_absent: live Pacaás Novos — no hot cluster this season, one a year ago, sensor alive nearby → improvement", async () => { + const LY = FIRES["yearAgo_2025-09-08"]; + const NOWF = FIRES["now_2026-09-23"]; + assert.deepEqual(fireClusters(LY.fires, { minFrp: 20, clusterMin: 3, cellDeg: 0.05 }), { hot: 7, clusters: 1 }); + assert.deepEqual(fireClusters(NOWF.fires, { minFrp: 20, clusterMin: 3, cellDeg: 0.05 }), { hot: 0, clusters: 0 }); + const script = (a: Record) => (a.date === undefined ? NOWF : a.date === "2025-09-08" ? LY : String(a.date) < "2026-01-01" ? { count: 0, fires: [] } : a.date === "2026-09-23" ? NOWF : { count: 0, fires: [] }); + const s = setup(); + const wl = list({ kind: "fires_absent", minHotLastYear: 5 }, [-64.04, -11.69, -62.53, -10.52], "Pacaás Novos National Park (Brazil)"); + const first = fakeCall({ ...context, fires_in: script }); + const r = await run(s, wl, first.call); + assert.equal(r.created.length, 1); + assert.equal(r.confirmed.length, 0); + const f = s.ledger.get(r.created[0]!)!; + assert.equal(f.title, "No fire clusters in Pacaás Novos National Park (Brazil) so far this season — 7 hot fire detections in the same weeks last year"); + assert.ok(f.aoi?.tags?.includes("improvement")); + const fi = first.calls.filter((c) => c.tool === "fires_in"); + assert.equal(fi.length, 13, "6 chunks this year + 6 a year ago + 1 alive check"); + assert.ok(fi.every((c) => c.args.source === "VIIRS_NOAA21_NRT")); + assert.equal(fi[0]!.args.date, "2026-09-23", "newest chunk first"); + // Too soon for persistence; 6 days on, still no cluster → confirmed. + const r2 = await run(s, wl, fakeCall({ ...context, fires_in: script }).call, "2026-09-29T06:00:00Z"); + assert.equal(r2.confirmed.length, 0); + const r3 = await run(s, wl, fakeCall({ ...context, fires_in: () => NOWF }).call, "2026-10-03T06:00:00Z"); + assert.equal(r3.confirmed.length, 1); +}); + +test("fires_absent: a cluster this season stops after one pull; a silent sensor opens nothing", async () => { + const LY = FIRES["yearAgo_2025-09-08"]; + const wl = list({ kind: "fires_absent", minHotLastYear: 5 }, [-64.04, -11.69, -62.53, -10.52], "Pacaás Novos"); + const burning = fakeCall({ ...context, fires_in: () => LY }); + assert.equal((await run(setup(), wl, burning.call)).created.length, 0); + assert.equal(burning.calls.filter((c) => c.tool === "fires_in").length, 1); + const dark = fakeCall({ ...context, fires_in: (a) => (a.date === "2025-09-08" ? LY : { count: 0, fires: [] }) }); + assert.equal((await run(setup(), wl, dark.call)).created.length, 0, "no detection within 100 km either: can't tell calm from a gap"); +}); + +// ---- plumbing ---------------------------------------------------------------------------- + +test("improvement params: unknown kind fails loudly; defaults merge under AOI params", () => { + assert.throws(() => improvementParams({ kind: "vibes" }), /params.kind must be one of/); + assert.equal(improvementParams({ kind: "forest_recovery", maxShareOfBaseline: 0.5 }).p.maxShareOfBaseline, 0.5); + assert.equal(improvementParams({ kind: "forest_recovery" }).p.lagDays, 14); +}); + +test("watchlists: good-news + the amazon/flaring improvement pairs load and name known kinds", () => { + const wls = [...loadWatchlists("watchlists/good-news.json"), ...loadWatchlists("watchlists/amazon.json"), ...loadWatchlists("watchlists/flaring.json")]; + const pairs = wls.flatMap((w) => w.aois.flatMap((a) => a.rules.filter((r) => r.name === "improvement").map((r) => [a.id, improvementParams(r.params).kind] as const))); + const count = (k: string) => pairs.filter(([, kind]) => kind === k).length; + assert.deepEqual([count("forest_recovery"), count("flaring_decline"), count("bleaching_relief"), count("air_quality_clean"), count("fires_absent")], [4, 3, 4, 6, 6]); + assert.ok(RULES.has("improvement")); +}); + +test("analyst select: a confirmed good-news case gets a slot even when busier rules outrank it", () => { + const mk = (id: string, rule: string, ratio: number, tags: string[] = []) => + ({ findingId: id, status: "confirmed", rule: { name: rule, version: "1.0", params: {} }, observedAt: "2026-09-20T00:00:00Z", aoi: { id: id, tags }, evidence: [{ id: `ev-${id}`, values: {} }], context: { baseline: { metric: "m", ringKm: 25, aoiValue: 1, regionalValue: 1, ratio } }, narration: null, reviews: [] }) as unknown as Finding; + const findings = [mk("fl-1", "flaring", 9), mk("fo-1", "forest_loss", 8), mk("me-1", "methane_anomaly", 7), mk("st-1", "flaring_stopped", 0.1, ["improvement"]), mk("im-1", "improvement", 0.2, ["amazon", "improvement"])]; + const ledger = { list: () => findings, get: () => undefined, append: () => ({}) } as unknown as AnalystLedger; + const two = select(ledger, 2).map((s) => s.finding.findingId); + assert.deepEqual(two, ["im-1", "fl-1"], "good news leads the first round, then novelty"); + // flaring_stopped and improvement@1.0 share one group: one per round, not two. + assert.deepEqual(select(ledger, 5).map((s) => s.finding.findingId), ["im-1", "fl-1", "fo-1", "me-1", "st-1"]); +}); + +// ---- client changes the rule relies on --------------------------------------------------- + +test("parseVnfKml reads scientific notation (the 2023 file writes tiny sites as 2.67e-05)", () => { + const kml = `IRQ_UPS_2015_47.3351E_30.4018N_v0.2IRQ
    Lat=30.401752, Lon=47.335143 deg. +20232.674e-053680.543%3550 +BCM_total=2.67e-05Type: oil upstream]]>`; + const [s] = parseVnfKml(kml); + assert.equal(s!.bcm, 2.67e-5); + assert.equal(s!.clearObs, 368); +}); + +test("forest_alerts window can end in the past (GFW WHERE gets an upper date bound)", () => { + assert.equal(alertsWhere("2025-06-29", "nominal", "2025-09-27"), "gfw_integrated_alerts__date >= '2025-06-29' AND gfw_integrated_alerts__date <= '2025-09-27'"); + assert.equal(alertsWhere("2025-06-29", "nominal"), "gfw_integrated_alerts__date >= '2025-06-29'"); +}); diff --git a/test/indicator-rules.test.ts b/test/indicator-rules.test.ts new file mode 100644 index 0000000..0577524 --- /dev/null +++ b/test/indicator-rules.test.ts @@ -0,0 +1,491 @@ +// indicator_threshold@1.0 + indicator_trend@1.0 end to end through the kernel with a scripted +// tool caller. Tool outputs are real responses recorded live on 2026-09-27 (NSIDC, OISST via +// ERDDAP, GloFAS + CAMS via Open-Meteo, CPC ONI, USGS, OWID) — see test/fixtures/ind-*.json. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { INDICATORS } from "../src/clients/owid.js"; +import { Ledger } from "../src/ledger/store.js"; +import { dailyMeans } from "../src/tools/climate.js"; +import { Journal } from "../src/watch/journal.js"; +import { sweep } from "../src/watch/kernel.js"; +import { costOf } from "../src/watch/quota.js"; +import { indicatorBlindSpots, indicatorParams, indicatorThreshold, pm25Streak, sstAnomalies } from "../src/watch/rules/indicatorThreshold.js"; +import { fmtValue } from "../src/watch/rules/indicatorTrend.js"; +import { RULES, ToolError, type ToolCall } from "../src/watch/rules/index.js"; +import { loadWatchlists, parseWatchlist, type Watchlist } from "../src/watch/watchlist.js"; +import { addDays } from "../src/util.js"; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +type Json = any; +const fx = (f: string): Json => JSON.parse(readFileSync(new URL(`./fixtures/${f}`, import.meta.url), "utf8")); +const clone = (v: T): T => JSON.parse(JSON.stringify(v)) as T; + +const SEA_ICE = fx("ind-sea-ice-north-2026-09-25.json"); // latest 2026-09-25: 5.169 < p10 5.329 +const ENSO = fx("ind-enso-2026-09-27.json"); // El Niño, 3 seasons: not yet an event +const QUAKES = fx("ind-quakes-japan-2026-09-27.json"); // two M5.0, sig 385, reviewed +const AIR = fx("ind-air-delhi-2026-09-27.json"); // 7 full days > 15 µg/m³ +const RIVER = fx("ind-river-ganges-patna-2026-09-27.json"); // 3.07× period mean, monsoon +const PULSE = fx("ind-world-pulse-life-2026-09-27.json"); +const MED = { recent: fx("ind-sst-med-recent-2026-09-27.json"), base: fx("ind-sst-med-base-2016-2025.json") }; +const GBR = { recent: fx("ind-sst-gbr-recent-2026-09-27.json"), base: fx("ind-sst-gbr-base-2016-2025.json") }; +const NINO = { recent: fx("ind-sst-nino34-recent-2026-09-27.json"), base: fx("ind-sst-nino34-base-2016-2025.json") }; + +const NOW = "2026-09-27T06:00:00Z"; +const NEXT = "2026-09-28T06:00:00Z"; + +function fakeCall(script: Record) => unknown>): { call: ToolCall; calls: { tool: string; args: Record }[] } { + const calls: { tool: string; args: Record }[] = []; + const call: ToolCall = async (tool, args) => { + calls.push({ tool, args }); + const fn = script[tool]; + if (!fn) throw new ToolError(tool, "not scripted"); + return JSON.parse(JSON.stringify(await fn(args))); + }; + return { call, calls }; +} + +function setup() { + const dir = mkdtempSync(join(tmpdir(), "earthdeck-indicators-")); + return { ledger: Ledger.open(dir), journal: new Journal(join(dir, "watch")) }; +} + +const context = { enso: () => ({ phase: "El Niño", latest: { oni: 1.8 } }), events: () => ({ events: [] }) }; + +function aoiList(params: Record, extra: Record = {}, rule = "indicator_threshold"): Watchlist { + return parseWatchlist({ version: 1, name: "t", aois: [{ id: "t-aoi", name: "Test place", bbox: [5, 38, 6, 39], rules: [{ name: rule, params }], ...extra }] }); +} + +const run = (s: ReturnType, wl: Watchlist, call: ToolCall, now: string) => sweep({ watchlists: [wl], rules: RULES, ledger: s.ledger, journal: s.journal, call, now, hasKey: () => true }); + +/** A sea_ice result moved to a later day with a given extent. */ +function seaIceOn(date: string, v: number): Json { + const r = clone(SEA_ICE); + r.latest = { t: date, v }; + return r; +} + +// ---- sea ice ----------------------------------------------------------------------------- + +test("sea_ice: below p10 opens a candidate; a later day still below confirms it (revisit)", async () => { + const s = setup(); + let today = SEA_ICE; + const { call, calls } = fakeCall({ sea_ice: () => today, ...context }); + const wl = aoiList({ indicator: "sea_ice", hemisphere: "arctic" }); + + const r1 = await run(s, wl, call, NOW); + assert.equal(r1.created.length, 1); + assert.equal(r1.confirmed.length, 0, "same data day cannot confirm itself"); + assert.deepEqual(calls.find((c) => c.tool === "sea_ice")!.args, { pole: "north" }); + const f = s.ledger.get(r1.created[0]!)!; + assert.equal(f.tier, 1); + assert.match(f.title, /^Arctic sea ice is below the lowest tenth of past years — 5\.17 M km², 0\.16 M km² under the p10 line$/); + assert.equal(f.evidence[0]!.kind, "series"); + assert.deepEqual(f.evidence[0]!.values, { extent_mkm2: 5.169, p10_mkm2: 5.329, anomaly_mkm2: -1.371, below_p10_mkm2: 0.16 }); + assert.ok(f.context?.notes?.some((n) => n.includes("NSIDC Sea Ice Index"))); + assert.ok(f.blindSpots?.some((b) => b.startsWith("Sea ice:"))); + assert.ok(f.blindSpots?.every((b) => b.startsWith("Sea ice:") || b.startsWith("All:")), "only this indicator's blind spots (+ All)"); + + // Next sweep, data has not moved on → still unconfirmed. + const r2 = await run(s, wl, call, "2026-09-27T18:00:00Z"); + assert.equal(r2.confirmed.length, 0); + // A later day, still below p10 → confirmed as a revisit. + today = seaIceOn("2026-09-26", 5.2); + const r3 = await run(s, wl, call, NEXT); + assert.deepEqual(r3.confirmed, [f.findingId]); + const g = s.ledger.get(f.findingId)!; + assert.equal(g.status, "confirmed"); + assert.equal(g.confirmed?.independence, "revisit"); + assert.equal(g.confirmed?.signal.values?.extent_mkm2, 5.2); +}); + +test("sea_ice: above p10 is quiet; a later day back above p10 does not confirm", async () => { + const s = setup(); + const quiet = fakeCall({ sea_ice: () => seaIceOn("2026-09-25", 5.5), ...context }); + const r = await run(s, aoiList({ indicator: "sea_ice", hemisphere: "antarctic" }), quiet.call, NOW); + assert.equal(r.created.length, 0); + assert.deepEqual(quiet.calls.find((c) => c.tool === "sea_ice")!.args, { pole: "south" }); + + const s2 = setup(); + let today = SEA_ICE; + const { call } = fakeCall({ sea_ice: () => today, ...context }); + const wl = aoiList({ indicator: "sea_ice", hemisphere: "arctic" }); + await run(s2, wl, call, NOW); + today = seaIceOn("2026-09-26", 5.4); + const r2 = await run(s2, wl, call, NEXT); + assert.equal(r2.confirmed.length, 0); +}); + +// ---- marine heatwave --------------------------------------------------------------------- + +test("sstAnomalies: day-of-year climatology from a strided baseline, trailing streak", () => { + const base = [2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025].flatMap((y) => [`${y}-08-25`, `${y}-09-04`, `${y}-09-14`].map((t) => ({ t, v: 20 }))); + const recent = ["2026-09-01", "2026-09-02", "2026-09-03", "2026-09-04"].map((t, i) => ({ t, v: [20.5, 22, 22, 21.6][i]! })); + const a = sstAnomalies(recent, base, 1.5)!; + assert.equal(a.latest.clim, 20); + assert.equal(a.latest.anomaly, 1.6); + assert.equal(a.streak, 3); + assert.equal(a.wholeWindow, false); + assert.equal(a.maxAnomaly, 2); + assert.equal(sstAnomalies(recent, base.slice(0, 5), 1.5), null, "too thin a baseline"); +}); + +function sstScript(pair: { recent: Json; base: Json }) { + return (args: Record) => (args.end ? pair.base : pair.recent); +} + +test("marine_heatwave: real Mediterranean pull opens a candidate; GBR is quiet", async () => { + const s = setup(); + const { call, calls } = fakeCall({ ocean_temp: sstScript(MED), ...context }); + const r = await run(s, aoiList({ indicator: "marine_heatwave", lat: 38.5, lon: 5.5 }), call, NOW); + assert.equal(r.created.length, 1); + const f = s.ledger.get(r.created[0]!)!; + const v = f.evidence[0]!.values!; + assert.ok(v.anomaly_c! >= 1.5 && v.days_over! >= 5, JSON.stringify(v)); + assert.match(f.title, /^Marine heatwave at Test place: the sea surface is \d+\.\d °C warmer than normal, \d+ days running$/); + assert.deepEqual(f.geometry, { type: "Point", coordinates: [5.625, 38.625] }); + // detect + confirm share one pull per args within the sweep (recent + baseline = 2 calls). + assert.equal(calls.filter((c) => c.tool === "ocean_temp").length, 2); + const baseArgs = calls.find((c) => c.tool === "ocean_temp" && c.args.end)!.args; + assert.deepEqual(baseArgs, { lat: 38.5, lon: 5.5, start: "2016-01-01", end: "2025-12-31" }); + + const q = setup(); + const quiet = fakeCall({ ocean_temp: sstScript(GBR), ...context }); + const rq = await run(q, aoiList({ indicator: "marine_heatwave", lat: -18.5, lon: 147.5 }), quiet.call, NOW); + assert.equal(rq.created.length, 0); + assert.equal(rq.gaps.length, 0); +}); + +test("marine_heatwave: persistence on the next data day confirms (revisit)", async () => { + const s = setup(); + let pair = MED; + // One caller across both sweeps: the per-sweep memo must not serve the first sweep's pull. + const { call } = fakeCall({ ocean_temp: (a) => sstScript(pair)(a), ...context }); + const wl = aoiList({ indicator: "marine_heatwave", lat: 38.5, lon: 5.5 }); + const r1 = await run(s, wl, call, NOW); + assert.equal(r1.confirmed.length, 0); + const recent = clone(MED.recent); + const last = recent.series[recent.series.length - 1]; + recent.series.push({ t: addDays(last.t, 1), v: last.v }); + recent.window.to = addDays(last.t, 1); + pair = { recent, base: MED.base }; + const r2 = await run(s, wl, call, NEXT); + assert.equal(r2.confirmed.length, 1); + assert.equal(s.ledger.get(r1.created[0]!)!.confirmed?.independence, "revisit"); +}); + +// ---- river discharge --------------------------------------------------------------------- + +test("river_discharge: 3× the period mean opens a case; the seasonal gate keeps a normal monsoon quiet", async () => { + const s = setup(); + const { call } = fakeCall({ river_discharge: () => RIVER, ...context }); + const r = await run(s, aoiList({ indicator: "river_discharge", lat: 25.62, lon: 85.15 }), call, NOW); + assert.equal(r.created.length, 1); + const f = s.ledger.get(r.created[0]!)!; + const v = f.evidence[0]!.values!; + assert.equal(v.ratio, 3.07); + assert.equal(v.threshold_ratio, 2); + assert.ok(typeof v.seasonal_ratio === "number" && v.seasonal_ratio < 1.5, `seasonal ${v.seasonal_ratio}`); + assert.match(f.title, /is running high: 30,060 m³\/s, 3\.07× its 10-year average/); + assert.equal(r.confirmed.length, 0, "no flood event, same data day"); + + const q = setup(); + const r2 = await run(q, aoiList({ indicator: "river_discharge", lat: 25.62, lon: 85.15, minSeasonalRatio: 1.5 }), fakeCall({ river_discharge: () => RIVER, ...context }).call, NOW); + assert.equal(r2.created.length, 0); +}); + +test("river_discharge: an EONET flood within 200 km confirms (provider); one 400 km away does not", async () => { + const flood = (lon: number) => ({ events: [{ id: "EONET_9999", title: "Floods — Bihar", category: "Floods", closed: false, lastDate: "2026-09-25T00:00:00Z", coordinates: [lon, 25.6], magnitude: null, link: "https://eonet.gsfc.nasa.gov/api/v3/events/EONET_9999" }] }); + const far = setup(); + const r1 = await run(far, aoiList({ indicator: "river_discharge", lat: 25.62, lon: 85.15 }), fakeCall({ river_discharge: () => RIVER, enso: context.enso, events: (a) => (a.category === "floods" ? flood(89.2) : { events: [] }) }).call, NOW); + assert.equal(r1.confirmed.length, 0); + + const near = setup(); + const { call, calls } = fakeCall({ river_discharge: () => RIVER, enso: context.enso, events: (a) => (a.category === "floods" ? flood(85.9) : { events: [] }) }); + const r2 = await run(near, aoiList({ indicator: "river_discharge", lat: 25.62, lon: 85.15 }), call, NOW); + assert.equal(r2.confirmed.length, 1); + const f = near.ledger.get(r2.created[0]!)!; + assert.equal(f.confirmed?.independence, "provider"); + assert.equal(f.confirmed?.signal.source, "nasa-eonet"); + const ev = calls.find((c) => c.tool === "events" && c.args.category === "floods")!.args; + assert.equal(ev.status, "all"); +}); + +// ---- air quality ------------------------------------------------------------------------- + +test("dailyMeans: UTC-day means from hourly CAMS, forecast hours excluded", () => { + const pts = [ + { t: "2026-09-26T22:00", v: 10 }, + { t: "2026-09-26T23:00", v: 20 }, + { t: "2026-09-27T00:00", v: 40 }, + { t: "2026-09-27T01:00", v: null }, + { t: "2026-09-27T07:00", v: 999 }, // forecast + ]; + assert.deepEqual(dailyMeans(pts, "2026-09-27T06:30:00.000Z"), [ + { t: "2026-09-26", v: 15, hours: 2 }, + { t: "2026-09-27", v: 40, hours: 1 }, + ]); +}); + +test("pm25Streak: partial days are ignored; the streak is the trailing run above the guideline", () => { + const s = pm25Streak([{ t: "a", v: 30, hours: 24 }, { t: "b", v: 10, hours: 24 }, { t: "c", v: 20, hours: 24 }, { t: "d", v: 25, hours: 24 }, { t: "e", v: 5, hours: 6 }], 15)!; + assert.equal(s.last.t, "d"); + assert.equal(s.days, 2); + assert.equal(s.max, 25); + assert.equal(s.mean, 22.5); +}); + +test("air_quality: Delhi above the WHO guideline 7 days → candidate; a later full day above confirms", async () => { + const s = setup(); + let today = AIR; + const { call, calls } = fakeCall({ air_quality: () => today, ...context }); + const wl = aoiList({ indicator: "air_quality", lat: 28.61, lon: 77.21 }); + const r1 = await run(s, wl, call, NOW); + assert.equal(r1.created.length, 1); + assert.equal(r1.confirmed.length, 0); + assert.deepEqual(calls.find((c) => c.tool === "air_quality")!.args, { lat: 28.61, lon: 77.21, pastDays: 7 }); + const f = s.ledger.get(r1.created[0]!)!; + assert.deepEqual(f.evidence[0]!.values, { pm25_daily_ugm3: 48.8, days_over: 7, guideline_ugm3: 15, pm25_mean_ugm3: 58.8, pm25_max_ugm3: 73.3, times_guideline: 3.3 }); + assert.equal(f.observedAt, "2026-09-26T00:00:00Z", "today's partial day (8 h) is not a full day"); + + today = clone(AIR); + today.pm25Daily[today.pm25Daily.length - 1] = { t: "2026-09-27", v: 51, hours: 24 }; + const r2 = await run(s, wl, call, NEXT); + assert.equal(r2.confirmed.length, 1); + assert.equal(s.ledger.get(f.findingId)!.confirmed?.independence, "revisit"); +}); + +test("air_quality: fewer than minDays above the guideline is quiet", async () => { + const s = setup(); + const clean = clone(AIR); + clean.pm25Daily = clean.pm25Daily.map((d: Json, i: number) => ({ ...d, v: i >= 5 ? 30 : 8 })); // 2 full days above + const r = await run(s, aoiList({ indicator: "air_quality", lat: 28.61, lon: 77.21 }), fakeCall({ air_quality: () => clean, ...context }).call, NOW); + assert.equal(r.created.length, 0); +}); + +// ---- ENSO -------------------------------------------------------------------------------- + +test("enso: 3 seasons is not an event (quiet); 5 seasons opens one global case, confirmed by Niño3.4 OISST", async () => { + const q = setup(); + const quiet = await run(q, aoiList({ indicator: "enso" }), fakeCall({ enso: () => ENSO, events: () => ({ events: [] }) }).call, NOW); + assert.equal(quiet.created.length, 0); + + const declared = clone(ENSO); + declared.consecutiveSeasons = 5; + declared.meetsEventDefinition = true; + const s = setup(); + const { call, calls } = fakeCall({ enso: () => declared, events: () => ({ events: [] }), ocean_temp: sstScript(NINO) }); + const wl = aoiList({ indicator: "enso" }, { cooldownDays: 180 }); + const r = await run(s, wl, call, NOW); + assert.equal(r.created.length, 1); + const f = s.ledger.get(r.created[0]!)!; + assert.match(f.title, /^El Niño is here: the Pacific has been warmer than normal for 5 seasons in a row \(ONI \+1\.8 °C\)$/); + assert.deepEqual(f.evidence[0]!.values, { oni_c: 1.8, consecutive_seasons: 5, phase_sign: 1 }); + assert.ok(f.aoi?.tags?.includes("el-nino")); + assert.equal(r.confirmed.length, 1, "OISST at the Niño3.4 centre is warm too"); + const g = s.ledger.get(f.findingId)!; + assert.equal(g.confirmed?.independence, "method"); + assert.ok(g.confirmed!.signal.values!.nino34_point_anomaly_c! >= 0.3); + assert.ok(calls.some((c) => c.tool === "ocean_temp" && c.args.lat === 0 && c.args.lon === -145)); + + // Same event next day: no duplicate case, no new evidence (same ONI release). + const r2 = await run(s, wl, call, NEXT); + assert.equal(r2.created.length, 0); + assert.equal(r2.evidenceAdded.length, 0); +}); + +// ---- earthquakes ------------------------------------------------------------------------- + +test("quake: M7 floor keeps two M5s quiet; at M5 they open a case; USGS review + sig confirms (method)", async () => { + const q = setup(); + const quiet = await run(q, aoiList({ indicator: "quake" }), fakeCall({ quakes: () => QUAKES, ...context }).call, NOW); + assert.equal(quiet.created.length, 0); + + const s = setup(); + const { call, calls } = fakeCall({ quakes: () => QUAKES, ...context }); + const wl = aoiList({ indicator: "quake", minMagnitude: 5 }); + const r = await run(s, wl, call, NOW); + assert.equal(r.created.length, 1); + assert.equal(r.confirmed.length, 0, "sig 385 < 600"); + const f = s.ledger.get(r.created[0]!)!; + assert.equal(f.title, "M5 earthquake — 38 km E of Nobeoka, Japan"); + assert.equal(f.evidence.length, 2); + assert.equal(f.evidence[0]!.kind, "record"); + assert.deepEqual(f.evidence[0]!.values, { magnitude: 5, depth_km: 42.7, sig: 385 }); + assert.equal(calls.find((c) => c.tool === "quakes")!.args.days, 7, "first sweep: default 7-day lookback"); + + const s2 = setup(); + const r2 = await run(s2, aoiList({ indicator: "quake", minMagnitude: 5, minSig: 300 }), fakeCall({ quakes: () => QUAKES, ...context }).call, NOW); + assert.equal(r2.confirmed.length, 1); + const g = s2.ledger.get(r2.created[0]!)!; + assert.equal(g.confirmed?.independence, "method"); + assert.equal(g.confirmed?.signal.source, "usgs-comcat-review"); + + // The second sweep looks back only to the last one (+1 day overlap). + await run(s, wl, call, "2026-09-29T06:00:00Z"); + assert.equal(calls.filter((c) => c.tool === "quakes").pop()!.args.days, 3); +}); + +test("quake: an unreviewed (automatic) event does not confirm", async () => { + const auto = clone(QUAKES); + for (const q of auto.quakes) Object.assign(q, { status: "automatic", sig: 900 }); + const s = setup(); + const r = await run(s, aoiList({ indicator: "quake", minMagnitude: 5 }), fakeCall({ quakes: () => auto, ...context }).call, NOW); + assert.equal(r.created.length, 1); + assert.equal(r.confirmed.length, 0); +}); + +test("indicator_threshold: unknown indicator is a gap, not a crash", async () => { + const s = setup(); + const r = await run(s, aoiList({ indicator: "volcano" }), fakeCall(context).call, NOW); + assert.equal(r.gaps.length, 1); + assert.match(r.gaps[0]!.message, /params\.indicator must be one of/); + assert.throws(() => indicatorParams({ indicator: "sea_ice", hemisphere: "north" }), /arctic or antarctic/); +}); + +// ---- indicator_trend --------------------------------------------------------------------- + +function pulseWith(slug: string, patch: (row: Json) => void = () => {}): Json { + const r = clone(PULSE); + r.indicators = r.indicators.filter((i: Json) => i.slug === slug); + patch(r.indicators[0]); + return r; +} + +/** `ledger_list` over the test ledger — what the real tool returns (compact rows). */ +function ledgerList(s: ReturnType) { + return (a: Record) => ({ + findings: s.ledger + .list({}) + .filter((f) => (!a.rule || f.rule.name === a.rule) && (!a.aoi || f.aoi?.id === a.aoi)) + .map((f) => ({ findingId: f.findingId, observedAt: f.observedAt, rule: `${f.rule.name}@${f.rule.version}`, aoi: f.aoi ? { id: f.aoi.id, name: f.aoi.name } : undefined })), + }); +} + +const trendList = (slug: string) => parseWatchlist({ version: 1, name: "t", aois: [{ id: "wp-test", name: "World: test", bbox: [-180, -90, 180, 90], cooldownDays: 1, rules: [{ name: "indicator_trend", params: { indicator: slug } }] }] }); + +test("indicator_trend: a new year opens one case; a later unchanged read confirms; the year never re-opens; next year opens a new case", async () => { + const s = setup(); + let pulse = pulseWith("global-living-planet-index"); + const { call, calls } = fakeCall({ world_pulse: () => pulse, ledger_list: ledgerList(s), ...context }); + const wl = trendList("global-living-planet-index"); + + const r1 = await run(s, wl, call, NOW); + assert.equal(r1.created.length, 1); + assert.equal(r1.confirmed.length, 0, "the same sweep's read is not a second read"); + assert.deepEqual(calls.find((c) => c.tool === "world_pulse")!.args, { indicators: ["global-living-planet-index"] }); + const f = s.ledger.get(r1.created[0]!)!; + assert.equal(f.title, "Living Planet Index (wildlife populations) fell to 27.1 (index, 1970 = 100) in 2020 — wildlife populations keep shrinking"); + assert.equal(f.observedAt, "2020-01-01T00:00:00Z"); + assert.equal(f.evidence[0]!.id, "owid-global-living-planet-index-2020"); + assert.equal(f.evidence[0]!.kind, "series"); + assert.deepEqual(Object.keys(f.evidence[0]!.values!).sort(), ["changePct", "pctPerDecade", "previous", "value", "year"]); + assert.equal(f.evidence[0]!.values!.changePct, -0.71); + assert.ok(f.aoi?.tags?.includes("worsening")); + + const r2 = await run(s, wl, call, NEXT); + assert.deepEqual(r2.confirmed, [f.findingId]); + assert.equal(s.ledger.get(f.findingId)!.confirmed?.independence, "method"); + + // Days, then a year later: same indicator-year → never re-opened (cooldown 1 day notwithstanding). + for (const now of ["2026-09-30T06:00:00Z", "2027-09-30T06:00:00Z"]) { + const r = await run(s, wl, call, now); + assert.equal(r.created.length + r.evidenceAdded.length, 0, now); + } + + // A new year appears → a new case for 2021. + pulse = pulseWith("global-living-planet-index", (row) => { + row.previous = row.latest; + row.latest = { t: "2021", v: 26.5 }; + }); + const r4 = await run(s, wl, call, "2027-10-01T06:00:00Z"); + assert.equal(r4.created.length, 1); + const g = s.ledger.get(r4.created[0]!)!; + assert.match(g.title, /fell to 26\.5 .* in 2021/); + assert.ok(g.context?.notes?.some((n) => n.includes("Last year this watch reported: 2020"))); + assert.equal(s.ledger.list({}).length, 2); +}); + +test("indicator_trend: improving → tag improvement; flat → quiet; a revised value does not confirm", async () => { + const s = setup(); + let pulse = pulseWith("marine-protected-areas"); + const { call } = fakeCall({ world_pulse: () => pulse, ledger_list: ledgerList(s), ...context }); + const r = await run(s, trendList("marine-protected-areas"), call, NOW); + const f = s.ledger.get(r.created[0]!)!; + assert.ok(f.aoi?.tags?.includes("improvement")); + assert.match(f.title, /^Marine protected areas rose to 17\.5 \(% of territorial waters\) in 2025 — more of the ocean is protected$/); + pulse = pulseWith("marine-protected-areas", (row) => (row.latest.v = 17.9)); + const r2 = await run(s, trendList("marine-protected-areas"), call, NEXT); + assert.equal(r2.confirmed.length, 0); + + const q = setup(); + const flat = pulseWith("red-list-index", (row) => (row.direction = "flat")); + const rq = await run(q, trendList("red-list-index"), fakeCall({ world_pulse: () => flat, ledger_list: ledgerList(q), ...context }).call, NOW); + assert.equal(rq.created.length, 0); +}); + +test("indicator_trend: a year moving against the trend says so; the ledger read failing is a gap", async () => { + const s = setup(); + const r = await run(s, trendList("fish-stocks-within-sustainable-levels"), fakeCall({ world_pulse: () => pulseWith("fish-stocks-within-sustainable-levels"), ledger_list: ledgerList(s), ...context }).call, NOW); + const f = s.ledger.get(r.created[0]!)!; + assert.match(f.title, /rose to 64\.5 \(% of stocks\) in 2021 — a better year, but over ten years more of the ocean's fish stocks are overfished/); + assert.ok(f.aoi?.tags?.includes("worsening")); + + const g = setup(); + const rg = await run(g, trendList("red-list-index"), fakeCall({ world_pulse: () => pulseWith("red-list-index"), ...context }).call, NOW); + assert.equal(rg.created.length, 0); + assert.equal(rg.gaps.length, 1); +}); + +test("fmtValue: readable numbers", () => { + assert.equal(fmtValue(29559676), "29.6 million"); + assert.equal(fmtValue(4321.4), "4,321"); + assert.equal(fmtValue(27.134067), "27.1"); + assert.equal(fmtValue(8.042414), "8.042"); + assert.equal(fmtValue(0.74), "0.74"); +}); + +// ---- watchlist, registry, quota ------------------------------------------------------------ + +test("watchlists/indicators.json: valid, ~30 AOIs, every rule known, every indicator param valid", () => { + const [wl] = loadWatchlists(new URL("../watchlists/indicators.json", import.meta.url).pathname); + assert.ok(wl!.aois.length >= 25); + const kinds: Record = {}; + for (const a of wl!.aois) + for (const r of a.rules) { + assert.ok(RULES.has(r.name), r.name); + if (r.name === "indicator_threshold") { + const { kind } = indicatorParams(r.params); + kinds[kind] = (kinds[kind] ?? 0) + 1; + } else { + assert.ok(INDICATORS.some((i) => i.slug === r.params.indicator), String(r.params.indicator)); + assert.equal(a.cooldownDays, 1); + assert.match(a.id, /^wp-/); + kinds.trend = (kinds.trend ?? 0) + 1; + } + } + assert.deepEqual(kinds, { sea_ice: 2, marine_heatwave: 6, river_discharge: 5, air_quality: 6, enso: 1, quake: 4, trend: 6 }); +}); + +test("indicator rules: registered, tier 1, zero-key, blind spots fit the ledger contract; their tools are not quota-governed", () => { + for (const name of ["indicator_threshold", "indicator_trend"]) { + const r = RULES.get(name)!; + assert.equal(r.tier, 1); + assert.deepEqual(r.requires, []); + assert.ok(r.blindSpots.length <= 20 && r.blindSpots.every((b) => b.length <= 300)); + } + for (const tool of ["sea_ice", "ocean_temp", "river_discharge", "air_quality", "enso", "quakes", "world_pulse", "events", "ledger_list"]) assert.equal(costOf(tool, {}), null, tool); +}); + +test("indicatorBlindSpots: filters the generic list to one indicator, keeps All, fails open", () => { + const all = indicatorThreshold.blindSpots; + const sst = indicatorBlindSpots(all, "marine_heatwave"); + assert.ok(sst.length >= 3 && sst.every((b) => b.startsWith("Marine heatwave:") || b.startsWith("All:"))); + assert.ok(!sst.some((b) => b.startsWith("Sea ice:"))); + assert.ok(indicatorBlindSpots(all, "air_quality").some((b) => b.startsWith("Air quality:"))); + assert.deepEqual(indicatorBlindSpots(all, undefined), [...all], "unknown indicator → nothing hidden"); + assert.deepEqual(indicatorBlindSpots(all, "nope"), [...all]); +}); diff --git a/test/jsonschema.test.ts b/test/jsonschema.test.ts index e3d32e8..449e39a 100644 --- a/test/jsonschema.test.ts +++ b/test/jsonschema.test.ts @@ -56,7 +56,7 @@ test("json schema: structure — 2020-12, one branch per event kind, statement assert.equal(committed.$ref, "#/$defs/FindingEvent"); const branches = committed.$defs.FindingEvent.oneOf as Record[]; const kinds = branches.map((b) => b.properties.kind.const).sort(); - assert.deepEqual(kinds, ["attributed", "confirmed", "created", "evidence_added", "narrated", "notified", "replied", "retracted", "reviewed", "status_changed"]); + assert.deepEqual(kinds, ["attributed", "commented", "confirmed", "created", "evidence_added", "narrated", "notified", "replied", "retracted", "reviewed", "status_changed"]); for (const b of branches) { for (const k of ["v", "eventId", "findingId", "at", "actor", "prev", "kind"]) assert.ok(b.required.includes(k), `${b.properties.kind.const} requires ${k}`); } diff --git a/test/marine.test.ts b/test/marine.test.ts new file mode 100644 index 0000000..fa0b253 --- /dev/null +++ b/test/marine.test.ts @@ -0,0 +1,361 @@ +// marine: Global Fishing Watch 4Wings client + fishing_activity (fetch-mocked against reports +// recorded live over the Galápagos on 2026-09-27), mpa_fishing@1.0 detect/confirm through the +// kernel, the aisstream sampler/aggregator (one live 20 s Gibraltar sample, identities +// pseudonymised), the marine export files, the quota provider, and the privacy guarantee that +// no vessel identity survives into any tool or export output. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, writeFileSync, mkdirSync, existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { AisAggregator, AIS_REGIONS, sampleAis, shipClass, subscription } from "../src/clients/ais.js"; +import { effortGrid, parseReport, reportBody, reportUrl, summarize } from "../src/clients/gfwfishing.js"; +import { Ledger } from "../src/ledger/store.js"; +import { fishingActivity } from "../src/tools/marine.js"; +import { exportSite } from "../src/watch/export.js"; +import { Journal } from "../src/watch/journal.js"; +import { sweep } from "../src/watch/kernel.js"; +import { buildFishingGeoJson, fishingAreas, marineSnapshots, shipsGeoJson } from "../src/watch/marine-export.js"; +import { capsFromEnv, costOf, providersForRequires } from "../src/watch/quota.js"; +import { insetBBox } from "../src/watch/rules/mpaFishing.js"; +import { RULES, ToolError, type ToolCall } from "../src/watch/rules/index.js"; +import { loadWatchlists, parseWatchlist } from "../src/watch/watchlist.js"; +import type { BBox } from "../src/types.js"; +import { jsonResponse, mockFetch } from "./helpers.js"; + +const fixture = (f: string) => JSON.parse(readFileSync(new URL(`./fixtures/${f}`, import.meta.url), "utf8")) as Record; +const BOX = fixture("gfw-fishing-galapagos-bbox-2026-09-27.json"); +const GEAR = fixture("gfw-fishing-galapagos-gear-2026-09-27.json"); +const MPA = fixture("gfw-fishing-galapagos-mpa-2026-09-27.json"); +const AIS = fixture("aisstream-gibraltar-2026-09-27.json") as { messages: unknown[] }; +const GALAPAGOS: BBox = [-92.68, -2.09, -88.57, 2.36]; +const ENV = { GFW_FISHING_TOKEN: "test-token" } as NodeJS.ProcessEnv; + +/** Anything that could identify a vessel, in any casing. */ +const IDENTITY = /mmsi|shipname|ship_name|callsign|call_sign|imo|vesselid|vessel_id|TEST VESSEL|99000\d{4}/i; + +// ---- client ------------------------------------------------------------------------------- + +test("reportUrl/reportBody: v3 4Wings shape; group-by is mandatory (ungrouped = per-vessel rows)", () => { + const u = reportUrl({ from: "2026-08-28", to: "2026-09-27", spatial: "HIGH", temporal: "DAILY", groupBy: "FLAG" }); + assert.equal( + u, + "https://gateway.api.globalfishingwatch.org/v3/4wings/report?spatial-resolution=HIGH&temporal-resolution=DAILY&group-by=FLAG&datasets[0]=public-global-fishing-effort:latest&date-range=2026-08-28,2026-09-27&format=JSON", + ); + assert.throws(() => reportUrl({ from: "a", to: "b", spatial: "LOW", temporal: "ENTIRE", groupBy: undefined as never }), /group-by/); + assert.deepEqual(JSON.parse(reportBody({ mpaId: "11753" })), { region: { dataset: "public-mpa-all", id: "11753" } }); + assert.deepEqual(JSON.parse(reportBody({ bbox: [1, 2, 3, 4] })).geojson.coordinates[0][2], [3, 4]); +}); + +test("parseReport + summarize: live Galápagos box — totals, flags, zero-filled daily series, clip", () => { + const { dataset, rows } = parseReport(BOX); + assert.equal(dataset, "public-global-fishing-effort:v4.0"); + assert.equal(rows.length, 333); + const s = summarize({ area: { bbox: GALAPAGOS }, from: "2026-08-28", to: "2026-09-27", resolution: "HIGH", clip: insetBBox(GALAPAGOS, 0.15), maxCells: 3 }, dataset, rows, null); + assert.equal(s.totalHours, 519.7); + assert.deepEqual(s.byFlag, [{ flag: "ECU", hours: 513.4 }, { flag: "USA", hours: 6.3 }]); + assert.equal(s.lastDataDate, "2026-09-23", "~4-day lag"); + assert.equal(s.daily.length, 27); + assert.equal(s.daily[0]!.date, "2026-08-28"); + assert.equal(s.cellDeg, 0.01); + assert.equal(s.grid.length, 3); + assert.ok(s.clip && s.clip.hours > 0 && s.clip.hours < s.totalHours); + assert.equal(s.byGear, null); +}); + +test("fishing_activity: two sequential reports (flag+daily HIGH, gear LOW), bearer auth, attribution in provenance", async (t) => { + const fm = mockFetch((url) => jsonResponse(url.includes("group-by=GEARTYPE") ? GEAR : BOX)); + t.after(fm.restore); + const r = await fishingActivity({ bbox: GALAPAGOS, from: "2026-08-28", to: "2026-09-27", resolution: "HIGH" }, ENV); + assert.equal(fm.calls.length, 2); + assert.ok(fm.calls.every((c) => c.method === "POST" && c.headers.authorization === "Bearer test-token")); + assert.match(fm.calls[0]!.url, /spatial-resolution=HIGH&temporal-resolution=DAILY&group-by=FLAG/); + assert.match(fm.calls[1]!.url, /spatial-resolution=LOW&temporal-resolution=ENTIRE&group-by=GEARTYPE/); + assert.equal(r.totalHours, 519.7); + assert.deepEqual(r.byGear!.slice(0, 2), [{ gear: "fishing", hours: 359 }, { gear: "drifting_longlines", hours: 122.5 }]); + assert.equal(r.provenance.attribution, "Global Fishing Watch, 2026. www.globalfishingwatch.org"); + assert.match(r.summary, /519\.7 hours of apparent fishing/); + + await assert.rejects(fishingActivity({ bbox: GALAPAGOS }, {} as NodeJS.ProcessEnv), /GFW_FISHING_TOKEN/); + await assert.rejects(fishingActivity({ bbox: GALAPAGOS, mpaId: "11753" }, ENV), /exactly one/); +}); + +test("fishing_activity by MPA: region body, clip to the AOI box, 422 surfaces GFW's message", async (t) => { + let status = 200; + const fm = mockFetch(() => (status === 200 ? jsonResponse(MPA) : jsonResponse({ statusCode: 422, messages: [{ title: "region", detail: "Region not found" }] }, { status }))); + t.after(fm.restore); + const r = await fishingActivity({ mpaId: "11753", from: "2026-08-28", to: "2026-09-27", resolution: "HIGH", byGear: false, clipBBox: GALAPAGOS }, ENV); + assert.equal(fm.calls.length, 1); + assert.deepEqual(JSON.parse(fm.calls[0]!.body!), { region: { dataset: "public-mpa-all", id: "11753" } }); + assert.equal(r.totalHours, 186.8); + assert.equal(r.clip!.hours, 186.8); + assert.deepEqual(r.area, { kind: "mpa", regionDataset: "public-mpa-all", id: "11753" }); + status = 422; + await assert.rejects(fishingActivity({ mpaId: "999", byGear: false }, ENV), /Region not found/); +}); + +// ---- privacy ------------------------------------------------------------------------------ + +test("privacy: vessel identities never survive — GFW rows, tool output, AIS aggregates, export files", async (t) => { + // A report reply with per-vessel columns (what GFW returns when group-by is omitted). + const leaky = { + entries: [{ "public-global-fishing-effort:v4.0": [{ date: "2026-09-01", flag: "XXX", hours: 3, lat: 1, lon: 2, vesselIDs: 1, callsign: "HC0000", shipName: "TEST VESSEL 9", mmsi: "990009999", vesselId: "abc", imo: "1" }] }], + }; + const parsed = parseReport(leaky); + assert.doesNotMatch(JSON.stringify(parsed), IDENTITY); + assert.deepEqual(Object.keys(parsed.rows[0]!).sort(), ["date", "flag", "hours", "lat", "lon"]); + + const fm = mockFetch(() => jsonResponse(leaky)); + t.after(fm.restore); + const tool = await fishingActivity({ bbox: GALAPAGOS, maxCells: 50 }, ENV); + assert.doesNotMatch(JSON.stringify({ ...tool, provenance: { ...tool.provenance, privacy: "" } }), IDENTITY); + const grid = await effortGrid("t", { bbox: GALAPAGOS }, "2026-09-01", "2026-09-27"); + assert.doesNotMatch(JSON.stringify(grid), IDENTITY); + + // The AIS fixture carries (pseudonymised) MMSI + names; the aggregate must not. + const agg = new AisAggregator(); + for (const m of AIS.messages) agg.add(m); + const density = agg.result({ regions: AIS_REGIONS, sampleSeconds: 20 }); + assert.match(JSON.stringify(AIS), /TEST VESSEL/, "fixture really has names to drop"); + assert.doesNotMatch(JSON.stringify({ ...density, privacy: "" }), IDENTITY); + assert.doesNotMatch(shipsGeoJson({ ...density, privacy: "" }), IDENTITY); + assert.doesNotMatch((await buildFishingGeoJson("t", [{ mpaId: "11753", name: "Galápagos", bbox: GALAPAGOS }], new Date("2026-09-27T12:00:00Z"))) ?? "", IDENTITY); +}); + +// ---- AIS ---------------------------------------------------------------------------------- + +test("AIS: live Gibraltar sample → density grid + counts by type; subscription uses [lat, lon] corners", () => { + const agg = new AisAggregator(); + for (const m of AIS.messages) agg.add(m); + const d = agg.result({ regions: AIS_REGIONS, sampleSeconds: 20, now: new Date("2026-09-27T08:43:00Z") }); + assert.equal(d.messages, 18, "confirmation frame not counted"); + assert.equal(d.vessels, 18); + assert.equal(d.byType.tanker, 1); + assert.equal(d.byType.cargo, 1); + assert.equal(d.byType.unknown, 16, "static data is rare in a 20 s sample"); + assert.equal(d.regions.find((r) => r.id === "gibraltar")!.vessels, 18); + assert.equal(d.cells.reduce((a, c) => a + c.count, 0), 18); + assert.ok(d.cells.every((c) => Math.abs(((c.lon - 0.05) / 0.1) - Math.round((c.lon - 0.05) / 0.1)) < 1e-6), "cell centres on the 0.1° grid"); + const sub = JSON.parse(subscription("k", [{ id: "g", name: "G", bbox: [-6.6, 35.6, -4.8, 36.4] }])); + assert.deepEqual(sub.BoundingBoxes, [[[35.6, -6.6], [36.4, -4.8]]]); + assert.equal(shipClass(30), "fishing"); + assert.equal(shipClass(84), "tanker"); + assert.equal(shipClass(undefined), "unknown"); +}); + +test("sampleAis: replays frames through a fake socket, closes on time, reports a bad key", async () => { + const frames = AIS.messages.map((m) => new TextEncoder().encode(JSON.stringify(m))); + let sent = ""; + class FakeWs { + onopen: (() => void) | null = null; + onmessage: ((e: { data: unknown }) => void) | null = null; + onerror: ((e: unknown) => void) | null = null; + onclose: (() => void) | null = null; + constructor(readonly url: string) { + setTimeout(() => { + this.onopen?.(); + for (const f of frames) this.onmessage?.({ data: f }); + }, 5); + } + send(d: string) { + sent = d; + } + close() { + this.onclose?.(); + } + } + const d = await sampleAis("secret", { seconds: 1, WebSocketImpl: FakeWs }); + assert.equal(d.vessels, 18); + assert.equal(JSON.parse(sent).APIKey, "secret"); + assert.doesNotMatch(JSON.stringify(d), /secret/); + + class BadKey extends FakeWs { + constructor(url: string) { + super(url); + frames.length = 0; + setTimeout(() => this.onmessage?.({ data: '{"error":"Api Key Is Not Valid"}' }), 10); + } + } + await assert.rejects(sampleAis("bad", { seconds: 1, WebSocketImpl: BadKey }), /Api Key Is Not Valid/); +}); + +// ---- rule --------------------------------------------------------------------------------- + +function fakeCall(script: Record) => unknown>): { call: ToolCall; calls: { tool: string; args: Record }[] } { + const calls: { tool: string; args: Record }[] = []; + const call: ToolCall = async (tool, args) => { + calls.push({ tool, args }); + const fn = script[tool]; + if (!fn) throw new ToolError(tool, "not scripted"); + return JSON.parse(JSON.stringify(await fn(args))); + }; + return { call, calls }; +} + +function fishing(total: number, opts: { clip?: number; last?: string; flags?: [string, number][] } = {}) { + return { + dataset: "public-global-fishing-effort:v4.0", + totalHours: total, + activeDays: total > 0 ? 20 : 0, + lastDataDate: opts.last ?? "2026-09-23", + byFlag: (opts.flags ?? [["ECU", total]]).map(([flag, hours]) => ({ flag, hours })), + clip: opts.clip === undefined ? null : { hours: opts.clip, share: null }, + provenance: { attribution: "Global Fishing Watch, 2026. www.globalfishingwatch.org" }, + }; +} + +const NOW = "2026-09-27T06:00:00Z"; +const galAoi = { id: "mpa-galapagos", name: "Galápagos Marine Reserve", bbox: GALAPAGOS, tags: [], control: false, cooldownDays: 30, rules: [{ name: "mpa_fishing", params: { mpaId: "11753", mpaName: "Galápagos Marine Reserve" } }] }; + +function setup() { + const dir = mkdtempSync(join(tmpdir(), "earthdeck-marine-")); + return { ledger: Ledger.open(dir), journal: new Journal(join(dir, "watch")) }; +} + +test("mpa_fishing detect: counts only effort inside the WDPA polygon ∩ tile; plain title; quiet below minHours", async () => { + const rule = RULES.get("mpa_fishing")!; + assert.equal(rule.tier, 2); + assert.ok(rule.blindSpots.some((b) => /dark/i.test(b)) && rule.blindSpots.some((b) => /transit/i.test(b))); + // 519.7 h in the reserve, but only 49.9 h inside this tile → quiet. + const quiet = fakeCall({ fishing_activity: () => fishing(519.7, { clip: 49.9 }) }); + assert.equal(await rule.detect({ aoi: galAoi, params: galAoi.rules[0]!.params, now: NOW, since: null, call: quiet.call }), null); + + const { call, calls } = fakeCall({ fishing_activity: () => fishing(186.8, { clip: 186.8, flags: [["ECU", 180.4], ["USA", 6.4]] }) }); + const c = (await rule.detect({ aoi: galAoi, params: galAoi.rules[0]!.params, now: NOW, since: null, call }))!; + assert.equal(c.title, "Fishing activity inside Galápagos Marine Reserve: 187 hours in 30 days"); + assert.equal(c.observedAt, "2026-09-23T00:00:00Z"); + assert.deepEqual(calls[0]!.args, { mpaId: "11753", from: "2026-08-28", to: "2026-09-27", resolution: "HIGH", byGear: false, clipBBox: GALAPAGOS }); + assert.equal(c.values.hours, 186.8); + assert.equal(c.values.flagStates, 2); + assert.equal(c.geometry!.type, "Polygon"); + assert.match(c.evidence[0]!.summary!, /inside the legal boundary of MPA 11753.*ECU 180 h, USA 6 h.*Global Fishing Watch, 2026/); + assert.doesNotMatch(JSON.stringify(c), IDENTITY); + + // No WDPA id → the box total is the measure. + const noId = { ...galAoi, rules: [{ name: "mpa_fishing", params: {} }] }; + const box = fakeCall({ fishing_activity: () => fishing(519.7) }); + const c2 = (await rule.detect({ aoi: noId, params: {}, now: NOW, since: null, call: box.call }))!; + assert.equal(c2.values.hours, 519.7); + assert.deepEqual(box.calls[0]!.args, { bbox: GALAPAGOS, from: "2026-08-28", to: "2026-09-27", resolution: "HIGH", byGear: false }); +}); + +test("mpa_fishing through the kernel: confirmed when the effort lies well inside, not on the edge (method)", async () => { + const s = setup(); + const inset = insetBBox(GALAPAGOS, 0.15); + const { call, calls } = fakeCall({ fishing_activity: (a) => fishing(186.8, { clip: JSON.stringify(a.clipBBox) === JSON.stringify(inset) ? 150.2 : 186.8 }) }); + const wl = parseWatchlist({ version: 1, name: "t", aois: [galAoi] }); + const r = await sweep({ watchlists: [wl], rules: RULES, ledger: s.ledger, journal: s.journal, call, now: NOW, hasKey: () => true }); + assert.deepEqual(r.gaps, []); + assert.equal(r.created.length, 1); + assert.equal(r.confirmed.length, 1); + const f = s.ledger.list()[0]!; + assert.equal(f.status, "confirmed"); + assert.deepEqual(calls.filter((c) => c.tool === "fishing_activity")[1]!.args, { mpaId: "11753", from: "2026-08-28", to: "2026-09-27", resolution: "HIGH", byGear: false, clipBBox: inset }); + assert.match(JSON.stringify(f), /150\.2 h \(80% of the 186\.8 h\) lie in 0\.01° cells well inside the area/); +}); + +test("mpa_fishing confirm: edge-only effort stays a candidate; persistence a week later confirms (revisit)", async () => { + const rule = RULES.get("mpa_fishing")!; + const params = galAoi.rules[0]!.params; + const det = fakeCall({ fishing_activity: () => fishing(120, { clip: 120 }) }); + const cand = (await rule.detect({ aoi: galAoi, params, now: NOW, since: null, call: det.call }))!; + + const edge = fakeCall({ fishing_activity: () => fishing(120, { clip: 24.9 }) }); + assert.equal(await rule.confirm({ aoi: galAoi, params, now: NOW, since: null, call: edge.call }, cand), null, "below half the bar in the inset box"); + assert.equal(edge.calls.length, 1, "too soon for a revisit"); + + const later = "2026-10-04T06:00:00Z"; + const cont = fakeCall({ fishing_activity: (a) => (a.from === "2026-08-28" ? fishing(120, { clip: 10 }) : fishing(30, { clip: 25, last: "2026-09-30" })) }); + const conf = (await rule.confirm({ aoi: galAoi, params, now: later, since: null, call: cont.call }, cand))!; + assert.equal(conf.independence, "revisit"); + assert.deepEqual(cont.calls[1]!.args, { mpaId: "11753", from: "2026-09-24", to: "2026-10-04", resolution: "HIGH", byGear: false, clipBBox: GALAPAGOS }); + assert.equal(conf.signal.values!.hours, 25, "polygon ∩ tile hours in the new window"); + + const stopped = fakeCall({ fishing_activity: (a) => (a.from === "2026-08-28" ? fishing(120, { clip: 10 }) : fishing(3, { clip: 3, last: "2026-09-30" })) }); + assert.equal(await rule.confirm({ aoi: galAoi, params, now: later, since: null, call: stopped.call }, cand), null, "3 h < pro-rated bar"); +}); + +// ---- quota -------------------------------------------------------------------------------- + +test("quota: gfw_fishing provider — cost, requires mapping, env caps incl. per-rule", () => { + assert.deepEqual(costOf("fishing_activity", {}), { provider: "gfw_fishing", units: 2 }); + assert.deepEqual(costOf("fishing_activity", { byGear: false }), { provider: "gfw_fishing", units: 1 }); + assert.deepEqual(providersForRequires(RULES.get("mpa_fishing")!.requires), ["gfw_fishing"]); + assert.equal(capsFromEnv({}).gfw_fishing, 200); + const caps = capsFromEnv({ EARTHDECK_MAX_GFW_FISHING_CALLS: "5", EARTHDECK_MAX_GFW_FISHING_CALLS_MPA_FISHING: "3", EARTHDECK_MAX_GFW_CALLS: "7" }); + assert.equal(caps.gfw_fishing, 5); + assert.equal(caps.gfw, 7); + assert.deepEqual(caps.perRule!.MPA_FISHING, { gfw_fishing: 3 }); +}); + +// ---- watchlist ---------------------------------------------------------------------------- + +test("watchlists/marine.json: 12–20 strict MPAs, tiles ≤ 25 deg², every AOI on mpa_fishing with a WDPA id", () => { + const [wl] = loadWatchlists(new URL("../watchlists/marine.json", import.meta.url).pathname); + const ids = new Set(); + for (const a of wl!.aois) { + assert.equal(a.rules.length, 1); + assert.equal(a.rules[0]!.name, "mpa_fishing"); + assert.ok(RULES.has(a.rules[0]!.name)); + const p = a.rules[0]!.params as { mpaId: string; mpaName: string }; + assert.match(p.mpaId, /^\d+(_\d+)?$/); + assert.ok(p.mpaName); + ids.add(p.mpaId); + assert.ok((a.bbox[2] - a.bbox[0]) * (a.bbox[3] - a.bbox[1]) <= 25.0001, `${a.id} tile too big`); + } + assert.ok(ids.size >= 12 && ids.size <= 20, `${ids.size} MPAs`); + for (const id of ["220201", "309888", "11753", "555629385", "555624172", "555651558", "303552", "313615"]) assert.ok(ids.has(id), id); + // One export query per reserve and side of the antimeridian (Papahānaumokuākea straddles it). + const areas = fishingAreas(new URL("../watchlists/marine.json", import.meta.url).pathname); + assert.equal(areas.filter((a) => a.mpaId === "220201").length, 2); + assert.equal(areas.length, ids.size + 1); +}); + +// ---- export ------------------------------------------------------------------------------- + +test("marine export: built only with keys, cached, copied into api/marine/ by exportSite", async () => { + const dir = mkdtempSync(join(tmpdir(), "earthdeck-marine-export-")); + const wlPath = new URL("../watchlists/marine.json", import.meta.url).pathname; + let gridCalls = 0; + const grid = (async () => { + gridCalls++; + return { dataset: "public-global-fishing-effort:v4.0", cells: [{ lon: -90.35, lat: -0.35, hours: 12.5 }] }; + }) as unknown as typeof effortGrid; + const agg = new AisAggregator(); + for (const m of AIS.messages) agg.add(m); + const sample = (async () => agg.result({ regions: AIS_REGIONS, sampleSeconds: 20 })) as unknown as typeof sampleAis; + const now = new Date("2026-09-27T12:00:00Z"); + + assert.deepEqual(await marineSnapshots({ mode: "auto", cacheDir: join(dir, "c0"), watchlist: wlPath, env: {}, now, grid, sample }), {}); + assert.equal(gridCalls, 0, "no keys → nothing produced"); + + const cacheDir = join(dir, "cache"); + const env = { GFW_FISHING_TOKEN: "t", AISSTREAM_KEY: "k" } as NodeJS.ProcessEnv; + const m = await marineSnapshots({ mode: "auto", cacheDir, watchlist: wlPath, env, now, grid, sample }); + const fish = JSON.parse(m.fishing!); + assert.equal(fish.type, "FeatureCollection"); + assert.equal(fish.meta.attribution, "Global Fishing Watch, 2026. www.globalfishingwatch.org"); + assert.equal(fish.meta.areas.length, 16); + const ships = JSON.parse(m.ships!); + assert.equal(ships.meta.vessels, 18); + assert.equal(ships.features.reduce((a: number, f: { properties: { count: number } }) => a + f.properties.count, 0), 18); + const calls = gridCalls; + await marineSnapshots({ mode: "auto", cacheDir, watchlist: wlPath, env, now, grid, sample }); + assert.equal(gridCalls, calls, "fresh cache → no new GFW calls"); + + // exportSite: default off → no marine files; "cache" → copied from the cache dir. + const ledgerDir = join(dir, "ledger"); + mkdirSync(ledgerDir, { recursive: true }); + const out1 = join(dir, "site1"); + const r1 = await exportSite({ out: out1, ledgerDir, siteDir: null, pulse: "off" }); + assert.deepEqual(r1.marine, { fishing: false, ships: false }); + assert.equal(existsSync(join(out1, "api", "marine")), false); + const out2 = join(dir, "site2"); + const r2 = await exportSite({ out: out2, ledgerDir, siteDir: null, pulse: "off", marine: "cache", marineCacheDir: cacheDir }); + assert.deepEqual(r2.marine, { fishing: true, ships: true }); + assert.doesNotMatch(readFileSync(join(out2, "api/marine/ships.json"), "utf8").replace(/"privacy":"[^"]*"/, ""), IDENTITY); + writeFileSync(join(cacheDir, "ships.json"), "not json"); + const r3 = await exportSite({ out: join(dir, "site3"), ledgerDir, siteDir: null, pulse: "off", marine: "cache", marineCacheDir: cacheDir }); + assert.deepEqual(r3.marine, { fishing: true, ships: false }, "a broken cache is omitted, not published"); +}); diff --git a/test/naturalvalue-gee.test.ts b/test/naturalvalue-gee.test.ts new file mode 100644 index 0000000..93d0325 --- /dev/null +++ b/test/naturalvalue-gee.test.ts @@ -0,0 +1,253 @@ +// natural_value with Earth Engine land USE: MapBiomas (Brazil) → Dynamic World → CLMS → assumed. +// Fixtures: ONE live value:compute each (test/fixtures/gee-landcover-live-2026-09-27.json) — +// MapBiomas 2024 over São Félix do Xingu and a 6-month Dynamic World mode over Kalimantan. +// The no-GEE path is pinned to a snapshot recorded before this change. + +import { test, type TestContext } from "node:test"; +import assert from "node:assert/strict"; +import { generateKeyPairSync } from "node:crypto"; +import { mkdtempSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; +import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import { DW_CLASSES, MAPBIOMAS_CLASSES, classShares } from "../src/clients/gee.js"; +import { + BIOMES, + DW_VALUATION, + MAPBIOMAS_VALUATION, + geeDatasetsFor, + geeLandCoverFromResult, + insideMapBiomasBrazil, + mapbiomasConvertedPct, +} from "../src/clients/naturalvalue.js"; +import { registerNaturalValueTools } from "../src/tools/naturalvalue.js"; +import { Ledger } from "../src/ledger/store.js"; +import { Journal } from "../src/watch/journal.js"; +import { sweep } from "../src/watch/kernel.js"; +import { RULES, ToolError, type ToolCall } from "../src/watch/rules/index.js"; +import { parseWatchlist } from "../src/watch/watchlist.js"; +import type { BBox } from "../src/types.js"; +import { jsonResponse, mockFetch } from "./helpers.js"; + +const LIVE = JSON.parse(readFileSync(new URL("./fixtures/gee-landcover-live-2026-09-27.json", import.meta.url), "utf8")); +const SNAP = JSON.parse(readFileSync(new URL("./fixtures/naturalvalue-no-gee-snapshot.json", import.meta.url), "utf8")); +const SFX = LIVE.mapbiomas.bbox as BBox; +const KAL = LIVE.dynamicWorld.bbox as BBox; +const SFX_HIST: [number, number][] = [[10, 1986], [20, 23], [30, 1867], [40, 8], [50, 1], [90, 14], [100, 197]]; +const statsResponse = { + data: [{ interval: { from: "2020-01-01T00:00:00Z", to: "2021-12-31T00:00:00Z" }, outputs: { data: { bands: { B0: { stats: { sampleCount: 4096, noDataCount: 0 }, histogram: { bins: SFX_HIST.map(([v, count]) => ({ lowEdge: v, highEdge: v + 1, count })) } } } } } }], + status: "OK", +}; + +const { privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048, privateKeyEncoding: { type: "pkcs8", format: "pem" }, publicKeyEncoding: { type: "spki", format: "pem" } }); +const KEY = JSON.stringify({ client_email: "t@p.iam.gserviceaccount.com", private_key: privateKey, project_id: "p" }); + +/** Set (or clear, with null) the GEE env for one test. */ +function geeEnv(t: TestContext, on: boolean) { + const saved = { a: process.env.GEE_SERVICE_ACCOUNT_JSON, b: process.env.GEE_PROJECT }; + if (on) { + process.env.GEE_SERVICE_ACCOUNT_JSON = KEY; + process.env.GEE_PROJECT = "p"; + } else { + delete process.env.GEE_SERVICE_ACCOUNT_JSON; + delete process.env.GEE_PROJECT; + } + t.after(() => { + for (const [k, v] of [["GEE_SERVICE_ACCOUNT_JSON", saved.a], ["GEE_PROJECT", saved.b]] as const) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + }); +} + +/** Mock: EE token + value:compute (per dataset), CDSE token + statistics, dashboard push. */ +function mockAll(t: TestContext, o: { mapbiomas?: unknown; dw?: unknown; cdseFails?: boolean } = {}) { + process.env.CDSE_CLIENT_ID ??= "test-id"; + process.env.CDSE_CLIENT_SECRET ??= "test-secret"; + const fm = mockFetch((url, call) => { + if (url.startsWith("https://oauth2.googleapis.com/token")) return jsonResponse({ access_token: "ee-tok", expires_in: 3600 }); + if (url.includes("value:compute")) { + const body = call.body ?? ""; + const dw = typeof o.dw === "function" ? (o.dw as (b: string) => unknown)(body) : o.dw; + const r = body.includes("mapbiomas") ? o.mapbiomas : body.includes("DYNAMICWORLD") ? dw : undefined; + return r === undefined ? jsonResponse({ error: { code: 400, message: "not scripted" } }, { status: 400 }) : jsonResponse({ result: r }); + } + if (url.includes("/openid-connect/token")) return jsonResponse({ access_token: "tok", expires_in: 600 }); + if (url.endsWith("/statistics")) return o.cdseFails ? jsonResponse({ error: "boom" }, { status: 500 }) : jsonResponse(statsResponse); + return new Response("{}", { status: 200 }); + }); + t.after(fm.restore); + return fm; +} + +async function callTool(args: Record) { + const server = new McpServer({ name: "t", version: "0" }); + registerNaturalValueTools(server); + const [st, ct] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: "t", version: "0" }); + await Promise.all([server.connect(st), client.connect(ct)]); + const res = await client.callTool({ name: "natural_value", arguments: args }); + await client.close(); + await server.close(); + const text = (res.content as { type: string; text: string }[]).find((c) => c.type === "text")!.text; + return { isError: Boolean(res.isError), body: JSON.parse(text) }; +} + +test("mapping: every MapBiomas / Dynamic World class is mapped with a basis; pasture & co. are converted and unvalued", () => { + for (const code of Object.keys(MAPBIOMAS_CLASSES).map(Number).filter((c) => c !== 27)) { + assert.ok(MAPBIOMAS_VALUATION[code], `mapbiomas ${code} mapped`); + assert.ok(MAPBIOMAS_VALUATION[code]!.basis.length > 10); + } + for (const code of Object.keys(DW_CLASSES).map(Number)) assert.ok(DW_VALUATION[code], `dw ${code} mapped`); + // pasture, mosaic, mining, other non-vegetated: converted with no value; crops/urban: converted, reference only + for (const code of [15, 21, 30, 25]) assert.deepEqual([MAPBIOMAS_VALUATION[code]!.use, MAPBIOMAS_VALUATION[code]!.biome], ["converted", null]); + assert.equal(MAPBIOMAS_VALUATION[39]!.biome, "cropland"); + assert.equal(MAPBIOMAS_VALUATION[24]!.biome, "urban"); + assert.match(MAPBIOMAS_VALUATION[15]!.basis, /no sourced ESV for planted pasture/); + assert.equal(MAPBIOMAS_VALUATION[12]!.use, "natural"); + for (const code of [4, 6, 7]) assert.equal(DW_VALUATION[code]!.use, "converted"); + // Brazil check + assert.equal(insideMapBiomasBrazil(SFX), true); + assert.equal(insideMapBiomasBrazil(KAL), false); + assert.deepEqual(geeDatasetsFor(SFX), ["mapbiomas", "dynamic-world"]); + assert.deepEqual(geeDatasetsFor(KAL), ["dynamic-world"]); +}); + +test("pure: live MapBiomas São Félix histogram → natural vs converted", () => { + const lc = geeLandCoverFromResult(LIVE.mapbiomas.result, "mapbiomas", SFX, LIVE.mapbiomas.scaleM, { year: 2024 }); + assert.equal(lc.provider, "mapbiomas-ee"); + assert.ok(lc.coveragePct > 95 && lc.coveragePct < 105, String(lc.coveragePct)); + const pasture = lc.classes.find((c) => c.name === "pasture")!; + assert.equal(pasture.use, "converted"); + assert.equal(pasture.biome, null); + assert.ok(Math.abs(pasture.sharePct - 56) < 0.5, String(pasture.sharePct)); + assert.ok(!lc.classes.some((c) => c.code === 0), "no-data dropped"); + const areaHa = lc.naturalHa + lc.convertedHa + lc.unmappedHa; + assert.ok(Math.abs(areaHa - 307_028) <= 3); + assert.equal(lc.unmappedHa, 0); + assert.ok(lc.convertedHa > lc.naturalHa); + const forest = lc.mix.find((m) => m.biome === "tropical_forest")!.share; + assert.ok(Math.abs(forest - 0.371) < 0.002, String(forest)); // forest formation + floodable forest + assert.ok(!lc.mix.some((m) => m.biome === "cropland" || m.biome === "urban"), "converted never in the natural mix"); + assert.deepEqual(lc.convertedReferenceMix.map((m) => m.biome).sort(), ["cropland", "urban"]); + // gee_query-shaped classes → converted % (same live result) + const pct = mapbiomasConvertedPct(classShares(LIVE.mapbiomas.result, "classification", MAPBIOMAS_CLASSES)); + assert.ok(pct !== null && Math.abs(pct - 57.1) < 0.3, String(pct)); + // Border box: too little MapBiomas coverage → throws (caller falls through to Dynamic World) + assert.throws(() => geeLandCoverFromResult({ classification: { "3": 10 } }, "mapbiomas", SFX, 30), /cover 0 %/); +}); + +test("pure: live Dynamic World Kalimantan histogram → all natural forest", () => { + const lc = geeLandCoverFromResult(LIVE.dynamicWorld.result, "dynamic-world", KAL, LIVE.dynamicWorld.scaleM); + assert.equal(lc.provider, "dynamicworld-ee"); + assert.deepEqual(lc.mix, [{ biome: "tropical_forest", share: 1 }]); + assert.equal(lc.convertedHa, 0); +}); + +test("tool without GEE: output identical to the pre-change snapshot (CLMS and assumed paths)", async (t) => { + geeEnv(t, false); + mockAll(t); + const clms = (await callTool({ bbox: SFX })).body; + assert.equal(clms.landCover.provider, "clms-cdse"); + delete clms.landCover.provider; + assert.deepStrictEqual(clms, SNAP.clms); +}); + +test("tool without GEE: assumed fallback identical to the snapshot", async (t) => { + geeEnv(t, false); + const fm = mockAll(t, { cdseFails: true }); + const assumed = (await callTool({ bbox: SFX })).body; + assert.equal(assumed.landCover.provider, "assumed"); + delete assumed.landCover.provider; + assert.deepStrictEqual(assumed, SNAP.assumed); + assert.ok(!fm.calls.some((c) => c.url.includes("googleapis")), "no Earth Engine call without GEE env"); +}); + +test("tool with GEE: MapBiomas over São Félix values natural land only and reports converted ha", async (t) => { + geeEnv(t, true); + const fm = mockAll(t, { mapbiomas: LIVE.mapbiomas.result }); + const { isError, body } = await callTool({ bbox: SFX }); + assert.equal(isError, false, JSON.stringify(body)); + assert.equal(body.landCover.provider, "mapbiomas-ee"); + assert.equal(body.landCover.year, 2024); + assert.ok(body.landCover.convertedHa > 170_000); + assert.equal(body.converted.byClass[0].name, "pasture"); + assert.ok(body.converted.referenceAnnualUsd.mid > 0); + assert.ok(!body.byBiome.some((b: { biome: string; sharePct: number }) => b.biome === "grassland" && b.sharePct > 5), "pasture is not valued as grassland"); + // Far below the CLMS total, which valued pasture at the grassland rate. + assert.ok(body.annualUsd.mid < SNAP.clms.annualUsd.mid * 0.8, `${body.annualUsd.mid} vs ${SNAP.clms.annualUsd.mid}`); + const forest = body.byBiome.find((b: { biome: string }) => b.biome === "tropical_forest"); + assert.ok(Math.abs(forest.annualUsd.mid - forest.ha * BIOMES.tropical_forest.usdPerHaYr.mid) <= BIOMES.tropical_forest.usdPerHaYr.mid); + assert.match(body.summary, /converted land \(mostly pasture\) and is not valued/); + assert.match(body.method.formula, /NATURAL/); + assert.ok(body.method.blindSpots.some((b: string) => /MapBiomas Brazil Collection 10 for 2024/.test(b))); + assert.ok(!body.method.blindSpots.some((b: string) => /^Pasture is not grassland/.test(b))); + assert.ok(!fm.calls.some((c) => c.url.endsWith("/statistics")), "CDSE not called"); +}); + +test("tool with GEE: Dynamic World outside Brazil; MapBiomas gap falls through; EE down falls to CLMS", async (t) => { + geeEnv(t, true); + // DW over SFX: a synthetic all-trees histogram big enough to cover the box at its ~18 m scale. + const dw = (body: string) => (body.includes("-52.4") ? { label: { "1": 1e7, "2": 1e6 } } : LIVE.dynamicWorld.result); + mockAll(t, { dw, mapbiomas: { classification: { "3": 5 } } }); + const kal = (await callTool({ bbox: KAL })).body; + assert.equal(kal.landCover.provider, "dynamicworld-ee"); + assert.equal(kal.landCover.window.to.length, 10); + assert.equal(kal.byBiome[0].biome, "tropical_forest"); + assert.ok(kal.method.blindSpots.some((b: string) => /probabilistic/.test(b))); + // SFX: MapBiomas coverage too low → Dynamic World, with the reason kept. + const sfx = (await callTool({ bbox: SFX })).body; + assert.equal(sfx.landCover.provider, "dynamicworld-ee"); + assert.match(sfx.landCover.fallbacks[0], /^mapbiomas: .*cover/); +}); + +test("tool with GEE: every EE dataset failing → CLMS with the failures listed", async (t) => { + geeEnv(t, true); + mockAll(t, {}); + const { body } = await callTool({ bbox: SFX }); + assert.equal(body.landCover.provider, "clms-cdse"); + assert.equal(body.landCover.fallbacks.length, 2); + assert.equal(body.annualUsd.mid, SNAP.clms.annualUsd.mid); +}); + +test("forest_loss: with GEE, the case notes how much of the watch area MapBiomas calls converted", async (t) => { + const aoi = { id: "br-sfx", name: "São Félix do Xingu", bbox: SFX, rules: [{ name: "forest_loss", params: { minAlerts: 100, minHa: 10 } }] }; + const alerts = { window: { from: "2026-06-28", to: "2026-09-26" }, alertCount: 420, areaHa: 38.2, byConfidence: { high: { alertCount: 420, areaHa: 38.2 } } }; + const script: Record) => unknown> = { + forest_alerts: () => alerts, + eo_compare: () => ({ dateA: "2026-05-14", dateB: "2026-09-26", validPctA: 95, validPctB: 95, delta: { meanChange: -0.2 } }), + gee_query: (a) => { + assert.equal(a.dataset, "mapbiomas"); + return { classes: classShares(LIVE.mapbiomas.result, "classification", MAPBIOMAS_CLASSES) }; + }, + }; + const run = async () => { + const dir = mkdtempSync(join(tmpdir(), "nv-gee-")); + const ledger = Ledger.open(dir); + const call: ToolCall = async (tool, args) => { + const fn = script[tool]; + if (!fn) throw new ToolError(tool, "not scripted"); + return fn(args); + }; + const wl = parseWatchlist({ version: 1, name: "t", aois: [aoi] }); + const r = await sweep({ watchlists: [wl], rules: RULES, ledger, journal: new Journal(join(dir, "watch")), call, now: "2026-09-26T12:00:00Z", hasKey: () => true }); + return ledger.get(r.created[0]!)!; + }; + const fm = mockFetch(() => new Response("{}", { status: 200 })); + t.after(fm.restore); + + geeEnv(t, true); + const f = await run(); + const values = f.evidence[0]!.values!; + assert.ok(Math.abs(values.watch_area_converted_pct! - 57.1) < 0.3); + for (const v of Object.values(values)) assert.equal(typeof v, "number"); + assert.equal(values.living_value_usd_yr, Math.round(38.2 * BIOMES.tropical_forest.usdPerHaYr.mid), "lost area still valued as forest"); + assert.match(f.context?.notes?.join(" ") ?? "", /The watch area is 57\.\d % converted land \(MapBiomas 2024/); + + delete process.env.GEE_SERVICE_ACCOUNT_JSON; + const g = await run(); + assert.equal(g.evidence[0]!.values!.watch_area_converted_pct, undefined); + assert.doesNotMatch(g.context?.notes?.join(" ") ?? "", /converted land/); +}); diff --git a/test/news.test.ts b/test/news.test.ts new file mode 100644 index 0000000..3581642 --- /dev/null +++ b/test/news.test.ts @@ -0,0 +1,154 @@ +// "In the news": the GDELT DOC 2.0 client (fetch-mocked against a response recorded live on +// 2026-09-27 — deliberately a noisy one), query building from real ledger AOI names, the +// title relevance filter, caching/pacing/budget/rate-limit behaviour, and the rendered section +// in the static case page. Never touches the network. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdtempSync, readFileSync, writeFileSync, mkdirSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { gdeltArticles, gdeltUrl, newsPlace, newsQuery, parseArticles, type NewsItem, type NewsSubject } from "../src/clients/gdelt.js"; +import { Ledger } from "../src/ledger/store.js"; +import { seedDemo } from "../src/ledger/cli.js"; +import type { Finding } from "../src/ledger/schema.js"; +import { exportSite } from "../src/watch/export.js"; +import { newsForCases, relevant } from "../src/watch/news.js"; +import { CallBudget, gdeltCapFromEnv } from "../src/watch/quota.js"; +import { NEWS_NOTE, newsHtml } from "../src/watch/site-render.js"; +import { mockFetch, textResponse } from "./helpers.js"; + +const RAW = readFileSync(new URL("./fixtures/gdelt-doc-california-fire-2026-09-27.json", import.meta.url), "utf8"); +const subj = (name: string, rule: string, params: Record = {}): NewsSubject => ({ rule: { name: rule, params }, aoi: { name }, title: "" }); + +test("newsPlace: strips tile/registered-site bookkeeping, parentheses and admin tails", () => { + assert.equal(newsPlace(subj("Flare field near Eleme, Rivers (Nigeria) — 20 registered sites", "flaring")), "Eleme"); + assert.equal(newsPlace(subj("Mavinga National Park (AGO) — tile 3/4", "fires_in_protected")), "Mavinga National Park"); + assert.equal(newsPlace(subj("Peixoto de Azevedo, Mato Grosso (Brazil) — tile 2/2", "forest_loss")), "Peixoto de Azevedo"); + assert.equal(newsPlace(subj("Rumaila field (Basra, Iraq)", "flaring")), "Rumaila field"); + assert.equal(newsPlace(subj("World: tree cover loss", "indicator_trend")), null); + assert.equal(newsPlace(subj("Arctic sea ice", "indicator_threshold")), "Arctic"); +}); + +test("newsQuery: place phrase AND OR-ed topic keywords; no topic or place → null", () => { + assert.equal(newsQuery(subj("Galápagos Marine Reserve", "mpa_fishing")), `"Galápagos Marine Reserve" ("illegal fishing" OR "fishing fleet" OR "fishing vessels")`); + assert.equal(newsQuery(subj("Lahore (Pakistan)", "indicator_threshold", { indicator: "air_quality" })), `"Lahore" (smog OR "air pollution" OR "air quality")`); + assert.equal(newsQuery(subj("Arctic sea ice", "indicator_threshold", { indicator: "sea_ice" })), `"Arctic" "sea ice"`); + assert.equal(newsQuery(subj("Somewhere", "indicator_trend")), null); + const u = new URL(gdeltUrl("x y")); + assert.equal(u.origin + u.pathname, "https://api.gdeltproject.org/api/v2/doc/doc"); + assert.deepEqual([u.searchParams.get("mode"), u.searchParams.get("format"), u.searchParams.get("timespan"), u.searchParams.get("sort")], ["ArtList", "json", "7d", "hybridrel"]); +}); + +test("parseArticles: keeps only headline metadata, normalises seendate", () => { + const items = parseArticles(JSON.parse(RAW)); + assert.equal(items.length, 5); + assert.deepEqual(Object.keys(items[0]!).sort(), ["domain", "language", "seendate", "sourcecountry", "title", "url"]); + assert.equal(items[1]!.seendate, "2026-09-27T09:30:00Z"); + assert.equal(items[1]!.domain, "newstribune.com"); + assert.deepEqual(parseArticles({ articles: [{ title: "x", url: "javascript:alert(1)" }, { title: "", url: "https://a" }] }), []); +}); + +test("gdeltArticles: UA + timeout; empty body → []; plain-text rate notice → 429, not retried", async (t) => { + let reply = RAW; + const m = mockFetch(() => textResponse(reply)); + t.after(m.restore); + assert.equal((await gdeltArticles(`"California" wildfire`)).length, 5); + assert.match(m.calls[0]!.headers["user-agent"]!, /earthdeck-news/); + reply = ""; + assert.deepEqual(await gdeltArticles("q"), []); + reply = "Please limit requests to one every 5 seconds or contact …"; + await assert.rejects(gdeltArticles("q"), (e: { status?: number }) => e.status === 429); + assert.equal(m.calls.length, 3, "one request per call — no retry"); +}); + +test("relevant: the noisy live fixture mostly falls away — only titles naming the place or topic survive", () => { + const f = { ...subj("California", "fires_in_protected"), findingId: "x", status: "confirmed" } as unknown as Finding; + const kept = relevant(f, parseArticles(JSON.parse(RAW))); + assert.deepEqual(kept.map((k) => k.domain), ["newstribune.com"]); // "California oldest … winery" — place match; still noise, hence the note +}); + +const item = (title: string): NewsItem => ({ title, url: `https://news.example/${encodeURIComponent(title)}`, domain: "news.example", seendate: "2026-09-26T10:00:00Z", language: "English", sourcecountry: "Brazil" }); +const finding = (id: string, status: string, name = "Peixoto de Azevedo, Mato Grosso (Brazil)"): Finding => + ({ findingId: id, status, rule: { name: "forest_loss", version: "1.0", params: {} }, aoi: { name }, title: "t" }) as unknown as Finding; + +test("newsForCases: decided cases only, 12 h cache, budget cap, stop on rate limit, stale cache survives", async () => { + const dir = mkdtempSync(join(tmpdir(), "earthdeck-news-")); + const queries: string[] = []; + let fail = false; + const fetchArticles = async (q: string) => { + queries.push(q); + if (fail) throw Object.assign(new Error("GDELT rate limit (429)"), { status: 429 }); + return [item("Deforestation surges in Peixoto de Azevedo"), item("Unrelated football result"), ...Array.from({ length: 6 }, (_, i) => item(`Logging raid ${i}`))]; + }; + const fs = [finding("a", "published"), finding("b", "candidate"), finding("c", "false_positive"), finding("d", "confirmed", "Novo Progresso, Pará (Brazil)")]; + const now = new Date("2026-09-27T12:00:00Z"); + const r1 = await newsForCases(fs, { cacheDir: dir, budget: new CallBudget(40), now, fetchArticles, minIntervalMs: 0 }); + assert.deepEqual([...r1.keys()], ["a", "d"]); + assert.equal(r1.get("a")!.length, 5, "capped at 5"); + assert.ok(!r1.get("a")!.some((n) => /football/.test(n.title)), "off-topic titles dropped"); + assert.equal(queries.length, 2); + assert.ok(existsSync(join(dir, "a.json"))); + + // Within 12 h: served from cache, no calls. + await newsForCases(fs, { cacheDir: dir, budget: new CallBudget(40), now: new Date(now.getTime() + 3600_000), fetchArticles, minIntervalMs: 0 }); + assert.equal(queries.length, 2); + + // Stale + rate-limited: first call 429 → budget stops → both keep their stale cached headlines. + fail = true; + const logs: string[] = []; + const budget = new CallBudget(40); + const r3 = await newsForCases(fs, { cacheDir: dir, budget, now: new Date(now.getTime() + 13 * 3600_000), fetchArticles, minIntervalMs: 0, log: (s) => logs.push(s) }); + assert.equal(queries.length, 3, "no second call after a rate limit"); + assert.ok(budget.halted); + assert.equal(r3.size, 2); + assert.ok(logs.some((l) => /rate limit/.test(l))); + + // Budget 0 → cache only. + fail = false; + await newsForCases(fs, { cacheDir: dir, budget: new CallBudget(0), now: new Date(now.getTime() + 13 * 3600_000), fetchArticles, minIntervalMs: 0 }); + assert.equal(queries.length, 3); +}); + +test("gdeltCapFromEnv: default 40, env override, rejects garbage", () => { + assert.equal(gdeltCapFromEnv({}), 40); + assert.equal(gdeltCapFromEnv({ EARTHDECK_MAX_GDELT_CALLS: "3" }), 3); + assert.throws(() => gdeltCapFromEnv({ EARTHDECK_MAX_GDELT_CALLS: "-1" })); +}); + +test("newsHtml: escaped headline links with rel=noopener nofollow + the context note; empty → nothing", () => { + assert.equal(newsHtml([]), ""); + assert.equal(newsHtml(undefined), ""); + assert.equal(newsHtml([{ ...item("x"), url: "javascript:alert(1)" }]), ""); + const h = newsHtml([item(` fire`)]); + assert.match(h, /In the news/); + assert.match(h, /rel="noopener nofollow"/); + assert.doesNotMatch(h, / { + const m = mockFetch(() => { + throw new Error("network must not be touched"); + }); + t.after(m.restore); + const ledgerDir = mkdtempSync(join(tmpdir(), "earthdeck-news-ledger-")); + seedDemo(Ledger.open(ledgerDir)); + const PUB = "01994a2e-0000-7000-8000-00000000d001"; + const tmp = mkdtempSync(join(tmpdir(), "earthdeck-news-site-")); + + const r0 = await exportSite({ out: join(tmp, "s0"), ledgerDir, siteDir: null, pulse: "off" }); + assert.equal(r0.news, 0); + assert.equal(existsSync(join(tmp, "s0", "api", "news")), false); + assert.doesNotMatch(readFileSync(join(tmp, "s0", "watch", "case", PUB, "index.html"), "utf8"), /In the news/); + + mkdirSync(join(ledgerDir, "news"), { recursive: true }); + writeFileSync(join(ledgerDir, "news", `${PUB}.json`), JSON.stringify({ fetchedAt: "2026-01-01T00:00:00Z", query: "old", items: [item("Deforestation in São Félix do Xingu")] })); + const r1 = await exportSite({ out: join(tmp, "s1"), ledgerDir, siteDir: null, pulse: "off", news: "cache" }); + assert.equal(r1.news, 1); + const api = JSON.parse(readFileSync(join(tmp, "s1", "api", "news", `${PUB}.json`), "utf8")); + assert.equal(api.items.length, 1); + const page = readFileSync(join(tmp, "s1", "watch", "case", PUB, "index.html"), "utf8"); + assert.match(page, /In the news[\s\S]*Deforestation in São Félix do Xingu/); + assert.equal(m.calls.length, 0); +}); diff --git a/test/replies.test.ts b/test/replies.test.ts new file mode 100644 index 0000000..83eefea --- /dev/null +++ b/test/replies.test.ts @@ -0,0 +1,294 @@ +// The public reply wall, offline: intake validation (every rejection rule), IP hashing (the raw +// IP is never stored), the reviewer verdict parser, the analyst-side review over a local mirror +// (accepted → public + a valid `commented` ledger event; rejected → rejected/, never shown), the +// export of public replies, and the runner's S3 ↔ local mirror. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { seedDemo } from "../src/ledger/cli.js"; +import { eventPayload } from "../src/ledger/schema.js"; +import { Ledger } from "../src/ledger/store.js"; +import { DAILY_CAP, handleReply, ipHash, stripHtml, ulid, type IntakeDeps } from "../src/replies/intake.js"; +import { parseVerdict, readPublicReplies, reviewReplies } from "../src/replies/review.js"; +import type { JsonCallResult } from "../src/analyst/anthropic.js"; +import { caseIndexFrom, repliesRelPath } from "../src/runner/core.js"; +import { exportSite } from "../src/watch/export.js"; + +const PUB_ID = "01994a2e-0000-7000-8000-00000000d001"; +const IP = "203.0.113.77"; +const SALT = "test-salt"; +const GOOD = "The river bank here was cleared in August; I walk past it every week."; + +function memDeps(o: { salt?: string | null; ids?: string[] } = {}) { + const objects = new Map(); + let n = 0; + const deps: IntakeDeps = { + store: { get: async (k) => objects.get(k) ?? null, put: async (k, b) => void objects.set(k, b) }, + salt: async () => (o.salt === undefined ? SALT : o.salt), + caseIds: async () => new Set(o.ids ?? [PUB_ID]), + now: () => new Date("2026-09-27T10:00:00Z"), + id: () => ulid(Date.parse("2026-09-27T10:00:00Z") + n++), + }; + return { deps, objects }; +} +const post = (body: unknown, ip = IP) => ({ method: "POST", path: "/reply", body: typeof body === "string" ? body : JSON.stringify(body), ip }); +const inbox = (objects: Map) => [...objects.keys()].filter((k) => k.startsWith("replies/inbox/")); + +test("intake: a good reply is stored in the inbox with a salted IP hash — never the IP", async () => { + const { deps, objects } = memDeps(); + const r = await handleReply(post({ caseId: PUB_ID, text: `${GOOD}`, role: "resident" }), deps); + assert.equal(r.status, 202); + assert.match(r.body.id!, /^[0-9A-HJKMNP-TV-Z]{26}$/); + const keys = inbox(objects); + assert.deepEqual(keys, [`replies/inbox/${PUB_ID}/${r.body.id}.json`]); + const raw = objects.get(keys[0]!)!.toString("utf8"); + const stored = JSON.parse(raw) as Record; + assert.deepEqual(Object.keys(stored).sort(), ["caseId", "ipHash", "receivedAt", "role", "text"]); + assert.equal(stored.text, GOOD, "HTML stripped"); + assert.equal(stored.ipHash, ipHash(IP, SALT)); + for (const [k, v] of objects) assert.ok(!v.toString("utf8").includes(IP) && !k.includes(IP), `${k} holds the raw IP`); + assert.equal(stored.role, "resident"); +}); + +test("ipHash: salted, stable, 64 hex; a different salt or IP gives a different hash", () => { + assert.match(ipHash(IP, SALT), /^[0-9a-f]{64}$/); + assert.equal(ipHash(IP, SALT), ipHash(` ${IP} `, SALT)); + assert.notEqual(ipHash(IP, SALT), ipHash(IP, "other")); + assert.notEqual(ipHash(IP, SALT), ipHash("203.0.113.78", SALT)); +}); + +test("intake: every rejection rule, and nothing stored for any of them", async () => { + const cases: [string, ReturnType, number, string][] = [ + ["path", { ...post({ caseId: PUB_ID, text: GOOD }), path: "/other" }, 404, "path"], + ["method", { ...post({ caseId: PUB_ID, text: GOOD }), method: "GET" }, 405, "method"], + ["too large", post(JSON.stringify({ caseId: PUB_ID, text: "x".repeat(9000) })), 413, "too_large"], + ["bad json", post("{not json"), 400, "bad_json"], + ["array body", post("[1]"), 400, "bad_json"], + ["bad case id", post({ caseId: "../../etc", text: GOOD }), 400, "bad_case"], + ["bad role", post({ caseId: PUB_ID, text: GOOD, role: "ceo" }), 400, "bad_role"], + ["too short", post({ caseId: PUB_ID, text: "Looks wrong." }), 400, "too_short"], + ["short after stripping HTML", post({ caseId: PUB_ID, text: "
    hi
    " }), 400, "too_short"], + ["too long", post({ caseId: PUB_ID, text: "a ".repeat(1100) }), 400, "too_long"], + ["email", post({ caseId: PUB_ID, text: `${GOOD} Write me: someone.else@example.org` }), 400, "contact_info"], + ["obfuscated email", post({ caseId: PUB_ID, text: `${GOOD} someone (at) example.org` }), 400, "contact_info"], + ["@handle", post({ caseId: PUB_ID, text: `${GOOD} ask @river_watch_42` }), 400, "contact_info"], + ["phone", post({ caseId: PUB_ID, text: `${GOOD} Call +55 (91) 98765-4321` }), 400, "phone"], + ["url", post({ caseId: PUB_ID, text: `${GOOD} see https://example.org/photos` }), 400, "link"], + ["bare domain", post({ caseId: PUB_ID, text: `${GOOD} photos at cheap-pills.shop` }), 400, "link"], + ["www", post({ caseId: PUB_ID, text: `${GOOD} www.example` }), 400, "link"], + ["unknown case", post({ caseId: "01994a2e-0000-7000-8000-00000000ffff", text: GOOD }), 404, "unknown_case"], + ]; + for (const [name, req, status, error] of cases) { + const { deps, objects } = memDeps(); + const r = await handleReply(req, deps); + assert.equal(r.status, status, name); + assert.equal(r.body.error, error, name); + assert.ok(r.body.message, `${name}: a plain-language message`); + assert.equal(inbox(objects).length, 0, `${name}: nothing stored`); + } +}); + +test("intake: dates and measurements are not phone numbers", async () => { + const { deps } = memDeps(); + const r = await handleReply(post({ caseId: PUB_ID, text: "Cleared between 2026-08-01 and 2026-09-15, about 38.2 ha, 420 alerts." }), deps); + assert.equal(r.status, 202, JSON.stringify(r.body)); +}); + +test("intake: honeypot filled → a fake 202 and nothing stored", async () => { + const { deps, objects } = memDeps(); + const r = await handleReply(post({ caseId: PUB_ID, text: GOOD, website: "http://spam" }), deps); + assert.equal(r.status, 202); + assert.equal(objects.size, 0); +}); + +test("intake: per-IP daily cap, counted under the hash; other IPs unaffected", async () => { + const { deps, objects } = memDeps(); + for (let i = 0; i < DAILY_CAP; i++) assert.equal((await handleReply(post({ caseId: PUB_ID, text: GOOD }), deps)).status, 202); + const r = await handleReply(post({ caseId: PUB_ID, text: GOOD }), deps); + assert.equal(r.status, 429); + assert.equal(r.body.error, "rate_limited"); + assert.equal(inbox(objects).length, DAILY_CAP); + assert.equal((await handleReply(post({ caseId: PUB_ID, text: GOOD }, "198.51.100.1"), deps)).status, 202); + assert.ok([...objects.keys()].some((k) => k === `replies/rate/2026-09-27/${ipHash(IP, SALT)}.json`)); +}); + +test("intake: no salt → closed (503), nothing stored", async () => { + const { deps, objects } = memDeps({ salt: null }); + const r = await handleReply(post({ caseId: PUB_ID, text: GOOD }), deps); + assert.equal(r.status, 503); + assert.equal(objects.size, 0); +}); + +test("stripHtml + ulid", () => { + assert.equal(stripHtml("a b & c\n\n\n\nd"), "a b & c\n\nd"); + const a = ulid(1_000, Buffer.alloc(10)); + const b = ulid(2_000, Buffer.alloc(10, 255)); + assert.equal(a.length, 26); + assert.ok(a < b, "sortable by time"); +}); + +test("parseVerdict: strict shape; any flag forces a reject", () => { + assert.deepEqual(parseVerdict({ accept: true, reason: "On topic.", flags: [] }), { accept: true, reason: "On topic.", flags: [] }); + assert.deepEqual(parseVerdict({ accept: true, reason: "ok", flags: ["names_person"] }), { accept: false, reason: "ok", flags: ["names_person"] }); + assert.equal(parseVerdict({ accept: "yes", reason: "x", flags: [] }), null); + assert.equal(parseVerdict({ accept: true, reason: "", flags: [] }), null); + assert.equal(parseVerdict({ accept: true, reason: "x", flags: ["rude"] }), null); + assert.equal(parseVerdict({ accept: true, reason: "x", flags: [], extra: 1 }), null); + assert.equal(parseVerdict([true]), null); + assert.equal(parseVerdict(null), null); +}); + +function fakeCall(verdicts: unknown[], calls: string[] = []) { + return async (_system: string, user: string): Promise => { + calls.push(user); + const data = verdicts.shift(); + return { data, text: JSON.stringify(data), model: "claude-sonnet-5", usage: { input_tokens: 900, output_tokens: 60 }, costUsd: 0.0024, ms: 5, requestSha256: "0".repeat(64), responseSha256: "1".repeat(64) }; + }; +} + +function mirror(replies: { caseId: string; text: string; role?: string }[]): { dir: string; ids: string[] } { + const dir = mkdtempSync(join(tmpdir(), "earthdeck-replies-")); + const ids: string[] = []; + replies.forEach((r, i) => { + const id = ulid(Date.parse("2026-09-27T10:00:00Z") + i); + ids.push(id); + mkdirSync(join(dir, "inbox", r.caseId), { recursive: true }); + writeFileSync(join(dir, "inbox", r.caseId, `${id}.json`), JSON.stringify({ caseId: r.caseId, text: r.text, role: r.role ?? "resident", receivedAt: "2026-09-27T10:00:00.000Z", ipHash: "a".repeat(64) })); + }); + return { dir, ids }; +} + +test("reviewReplies: accepted → public/ (no ipHash) + a valid signed `commented` event; rejected → rejected/ with the verdict", async () => { + const lDir = mkdtempSync(join(tmpdir(), "earthdeck-replies-ledger-")); + const ledger = Ledger.open(lDir); + seedDemo(ledger); + const candidate = ledger.list().find((f) => f.status === "candidate")!; + const { dir, ids } = mirror([ + { caseId: PUB_ID, text: GOOD }, + { caseId: PUB_ID, text: "Buy cheap watches, best prices anywhere in the region!" }, + { caseId: candidate.findingId, text: GOOD }, + ]); + const before = ledger.get(PUB_ID)!; + const calls: string[] = []; + const r = await reviewReplies({ + dir, + ledger, + reviewer: "claude-sonnet-5", + call: fakeCall([{ accept: true, reason: "A first-hand, on-topic observation.", flags: [] }, { accept: false, reason: "Advertising.", flags: ["spam"] }], calls), + }); + assert.deepEqual(r.accepted, [ids[0]]); + assert.deepEqual(r.rejected, [ids[1], ids[2]]); + assert.equal(r.left, 0); + assert.equal(calls.length, 2, "a reply on a non-public case costs no model call"); + assert.match(calls[0]!, /The reply \(writer says they are: resident\)/); + + const pub = JSON.parse(readFileSync(join(dir, "public", PUB_ID, `${ids[0]}.json`), "utf8")) as Record; + assert.deepEqual(Object.keys(pub).sort(), ["caseId", "id", "receivedAt", "role", "text"]); + const rej = JSON.parse(readFileSync(join(dir, "rejected", PUB_ID, `${ids[1]}.json`), "utf8")) as { verdict: { flags: string[] }; reviewedBy: string }; + assert.deepEqual(rej.verdict.flags, ["spam"]); + assert.equal(rej.reviewedBy, "model:claude-sonnet-5"); + assert.ok(existsSync(join(dir, "rejected", candidate.findingId, `${ids[2]}.json`))); + assert.ok(!existsSync(join(dir, "inbox", PUB_ID, `${ids[0]}.json`))); + + const after = ledger.get(PUB_ID)!; + assert.equal(after.status, before.status, "a comment changes no status"); + assert.equal(after.eventCount, before.eventCount + 1); + const entries = readFileSync(join(lDir, "entries.jsonl"), "utf8").trim().split("\n"); + const last = JSON.parse(entries[entries.length - 1]!) as { payload: string }; + const ev = eventPayload.parse((JSON.parse(Buffer.from(last.payload, "base64").toString("utf8")) as { predicate: unknown }).predicate) as Extract, { kind: "commented" }>; + assert.equal(ev.kind, "commented"); + assert.equal(ev.actor, "model:claude-sonnet-5"); + assert.equal(ev.reply.id, ids[0]); + assert.ok(!JSON.stringify(ev).includes("river bank"), "only the text hash is signed"); + assert.deepEqual(readPublicReplies(dir, PUB_ID).map((x) => x.id), [ids[0]]); +}); + +test("ledger: `commented` only on public cases, only from a model:/reviewer: actor, never flagged", () => { + const ledger = Ledger.open(mkdtempSync(join(tmpdir(), "earthdeck-replies-ledger-"))); + seedDemo(ledger); + const candidate = ledger.list().find((f) => f.status === "candidate")!; + const ev = (findingId: string, actor = "model:claude-sonnet-5", flags: string[] = []) => ({ + kind: "commented" as const, + findingId, + actor, + reply: { id: ulid(), role: "resident" as const, receivedAt: "2026-09-27T10:00:00Z", textSha256: "a".repeat(64) }, + verdict: { accept: true as const, reason: "ok", flags }, + }); + assert.throws(() => ledger.append(ev(candidate.findingId)), /only taken on public cases/); + assert.throws(() => ledger.append(ev(PUB_ID, "system:forest_loss@1.0")), /model: or reviewer:/); + assert.throws(() => ledger.append(ev(PUB_ID, "model:x", ["spam"]))); + assert.doesNotThrow(() => ledger.append(ev(PUB_ID))); +}); + +test("reviewReplies: invalid model output → rejected (never shown); a call error leaves it in the inbox", async () => { + const ledger = Ledger.open(mkdtempSync(join(tmpdir(), "earthdeck-replies-ledger-"))); + seedDemo(ledger); + const { dir, ids } = mirror([{ caseId: PUB_ID, text: GOOD }, { caseId: PUB_ID, text: GOOD }]); + let n = 0; + const r = await reviewReplies({ + dir, + ledger, + reviewer: "claude-sonnet-5", + call: async (s, u) => { + if (n++ === 0) return fakeCall([{ accept: true }])(s, u); + throw new Error("Anthropic API 529"); + }, + }); + assert.deepEqual(r.rejected, [ids[0]]); + assert.equal(r.errors.length, 1); + assert.equal(r.left, 1); + assert.ok(existsSync(join(dir, "inbox", PUB_ID, `${ids[1]}.json`))); +}); + +test("export: public replies render under the case (+ api/replies/.json) with the form mount; no raw IP, no ipHash, no @", async () => { + const lDir = mkdtempSync(join(tmpdir(), "earthdeck-replies-ledger-")); + seedDemo(Ledger.open(lDir)); + const repliesDir = mkdtempSync(join(tmpdir(), "earthdeck-replies-")); + const id = ulid(Date.parse("2026-09-27T10:00:00Z")); + mkdirSync(join(repliesDir, "public", PUB_ID), { recursive: true }); + writeFileSync(join(repliesDir, "public", PUB_ID, `${id}.json`), JSON.stringify({ id, caseId: PUB_ID, text: "Line one x\nline two of what I see here.", role: "resident", receivedAt: "2026-09-27T10:00:00.000Z" })); + const out = join(mkdtempSync(join(tmpdir(), "earthdeck-replies-out-")), "site"); + await exportSite({ out, ledgerDir: lDir, baseUrl: null, siteDir: null, pulse: "off", repliesDir, replyUrl: "https://abc123.lambda-url.us-east-1.on.aws/", trustFile: join(lDir, "none.md") }); + + const api = JSON.parse(readFileSync(join(out, "api", "replies", `${PUB_ID}.json`), "utf8")) as { replies: Record[] }; + assert.equal(api.replies.length, 1); + assert.deepEqual(Object.keys(api.replies[0]!).sort(), ["id", "receivedAt", "role", "text"]); + const html = readFileSync(join(out, "watch", "case", PUB_ID, "index.html"), "utf8"); + assert.match(html, /Lives nearby/); + assert.match(html, /Line one <b>x<\/b>
    line two/); + assert.match(html, /read and accepted by a second AI model/); + assert.match(html, /class="reply-box" data-case="[^"]+" data-endpoint="https:\/\/abc123\.lambda-url\.us-east-1\.on\.aws\/reply"/); + assert.match(html, /Know this place\? Say what you see\. Replies are checked before they appear\. No account, no email\./); + assert.match(html, /Replies are open on the interactive site/); + assert.ok(!html.slice(html.indexOf("Reply<\/a>/.test(html)); + // A non-public case takes no replies. + const cand = readFileSync(join(out, "watch", "index.html"), "utf8"); + assert.ok(cand.length > 0); +}); + +test("export: without --reply-url there is no form (and no endpoint anywhere)", async () => { + const lDir = mkdtempSync(join(tmpdir(), "earthdeck-replies-ledger-")); + seedDemo(Ledger.open(lDir)); + const out = join(mkdtempSync(join(tmpdir(), "earthdeck-replies-out-")), "site"); + await exportSite({ out, ledgerDir: lDir, baseUrl: null, siteDir: null, pulse: "off", repliesDir: join(lDir, "nope"), trustFile: join(lDir, "none.md") }); + const html = readFileSync(join(out, "watch", "case", PUB_ID, "index.html"), "utf8"); + assert.ok(!html.includes("reply-box")); + assert.match(html, /No replies yet\./); + await assert.rejects(exportSite({ out, ledgerDir: lDir, baseUrl: null, siteDir: null, pulse: "off", replyUrl: "http://insecure.example", trustFile: join(lDir, "none.md") }), /https/); +}); + +test("runner: reply keys map safely; the case index holds public cases only", () => { + assert.equal(repliesRelPath(`replies/inbox/${PUB_ID}/01K66Z2ZQ0000000000000000Z.json`), `inbox/${PUB_ID}/01K66Z2ZQ0000000000000000Z.json`); + assert.equal(repliesRelPath("replies/rate/2026-09-27/abc.json"), null); + assert.equal(repliesRelPath("replies/cases.json"), null); + assert.equal(repliesRelPath("replies/inbox/../x/01K66Z2ZQ0000000000000000Z.json"), null); + assert.equal(repliesRelPath("replies/secret/a/01K66Z2ZQ0000000000000000Z.json"), null); + const idx = caseIndexFrom(JSON.stringify({ cases: [{ id: "a", status: "published" }, { id: "b", status: "candidate" }, { id: "c", status: "notified" }] }), ["published", "notified"]); + assert.deepEqual(idx, { ids: ["a", "c"] }); +}); diff --git a/test/runner.test.ts b/test/runner.test.ts index 558b4e3..ef21e52 100644 --- a/test/runner.test.ts +++ b/test/runner.test.ts @@ -4,7 +4,7 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { appendFileSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { @@ -30,6 +30,7 @@ import { type ObjectStore, type RunnerConfig, type RunnerDeps, + sitePruneKeys, } from "../src/runner/core.js"; test("parsePayload accepts the scheduled shapes (object or JSON string)", () => { @@ -58,12 +59,15 @@ test("stepsFor + cliArgs map payloads to CLI invocations", () => { delete process.env.EARTHDECK_CONTACT; assert.deepEqual(cliArgs({ job: "export", dryRun: false }, "/tmp/site"), ["watch", "export", "--out", "/tmp/site", "--trust", "TRUST.md"]); process.env.EARTHDECK_SITE_URL = "https://example.org"; - process.env.EARTHDECK_CONTACT = "me@example.org"; - assert.deepEqual(cliArgs({ job: "export", dryRun: false }, "/tmp/site"), ["watch", "export", "--out", "/tmp/site", "--base-url", "https://example.org", "--contact", "me@example.org", "--trust", "TRUST.md"]); + process.env.EARTHDECK_CONTACT = "me@example.org"; // never forwarded: the site is anonymous + process.env.EARTHDECK_REPLY_URL = "https://abc.lambda-url.us-east-1.on.aws/"; + assert.deepEqual(cliArgs({ job: "export", dryRun: false }, "/tmp/site", "/tmp/replies"), ["watch", "export", "--out", "/tmp/site", "--base-url", "https://example.org", "--reply-url", "https://abc.lambda-url.us-east-1.on.aws/", "--replies", "/tmp/replies", "--trust", "TRUST.md"]); + assert.deepEqual(cliArgs({ job: "analyst", dryRun: false }, "/tmp/site", "/tmp/replies"), ["analyst", "--once", "--replies", "/tmp/replies"]); delete process.env.EARTHDECK_SITE_URL; delete process.env.EARTHDECK_CONTACT; + delete process.env.EARTHDECK_REPLY_URL; const all = stepsFor({ job: "all" }); - assert.deepEqual(all.map((s) => s.watchlist ?? s.job), ["amazon", "congo-borneo", "controls", "methane", "flaring", "analyst", "export"]); + assert.deepEqual(all.map((s) => s.watchlist ?? s.job), ["amazon", "congo-borneo", "controls", "methane", "flaring", "indicators", "weather", "good-news", "marine", "analyst", "export"]); assert.ok(all.every((s) => !s.dryRun)); }); @@ -339,9 +343,9 @@ test("parsePayload: generated lists, all-generated/all-handwritten, shard, timeB test("cliArgs: watchlist targets map to --watchlist paths; shard and budget pass through", () => { assert.deepEqual(watchlistPaths("all-generated"), ["watchlists/generated"]); assert.deepEqual(watchlistPaths("generated/methane-basins"), ["watchlists/generated/methane-basins.json"]); - assert.deepEqual(watchlistPaths("all-handwritten"), ["watchlists/amazon.json", "watchlists/congo-borneo.json", "watchlists/controls.json", "watchlists/methane.json", "watchlists/flaring.json"]); + assert.deepEqual(watchlistPaths("all-handwritten"), ["watchlists/amazon.json", "watchlists/congo-borneo.json", "watchlists/controls.json", "watchlists/methane.json", "watchlists/flaring.json", "watchlists/indicators.json", "watchlists/weather.json", "watchlists/good-news.json", "watchlists/marine.json"]); assert.deepEqual(cliArgs({ job: "sweep", watchlist: "all-generated", shard: "2/8", timeBudgetSec: 681, dryRun: false }, "/s"), ["watch", "--once", "--watchlist", "watchlists/generated", "--shard", "2/8", "--time-budget", "681"]); - assert.equal(cliArgs({ job: "sweep", watchlist: "all-handwritten", dryRun: true }, "/s").filter((a) => a === "--watchlist").length, 5); + assert.equal(cliArgs({ job: "sweep", watchlist: "all-handwritten", dryRun: true }, "/s").filter((a) => a === "--watchlist").length, 9); assert.deepEqual(stepsFor({ job: "sweep", watchlist: "all-generated", shard: "1/8", timeBudgetSec: 100 }), [{ job: "sweep", watchlist: "all-generated", shard: "1/8", timeBudgetSec: 100, dryRun: false }]); }); @@ -388,3 +392,93 @@ test("infra: every schedule Input is a valid payload; 8 shards + hand-written + assert.equal(inputs.length, 11); assert.match(yaml, /EARTHDECK_MAX_ANALYST_CASES: "10"/); }); + +test("analyst: reply inbox is mirrored down, moves are synced back only after the ledger upload; export writes the case index", async () => { + const A = "01K66Z2ZQ0000000000000000A"; + const B = "01K66Z2ZQ0000000000000000B"; + const C = "01K66Z2ZQ0000000000000000C"; + const h = harness({ + help: "earthdeck analyst --once\nearthdeck watch export", + job: (args, dir) => { + if (args[0] !== "analyst") return 0; + const rd = args[args.indexOf("--replies") + 1]!; + assert.ok(existsSync(join(rd, "inbox", "case-1", `${A}.json`))); + assert.ok(!existsSync(join(rd, "public")), "the analyst mirror holds the inbox only"); + rmSync(join(rd, "inbox", "case-1", `${A}.json`)); + rmSync(join(rd, "inbox", "case-1", `${B}.json`)); + mkdirSync(join(rd, "public", "case-1"), { recursive: true }); + writeFileSync(join(rd, "public", "case-1", `${A}.json`), "{}"); + mkdirSync(join(rd, "rejected", "case-1"), { recursive: true }); + writeFileSync(join(rd, "rejected", "case-1", `${B}.json`), "{}"); + appendEntry(dir, "commented"); + return 0; + }, + }); + h.cfg.repliesDir = join(h.cfg.siteDir, "..", "replies"); + await h.store.put("state", "ledger/entries.jsonl", Buffer.from("e1\n")); + for (const id of [A, B, C]) await h.store.put("state", `replies/inbox/case-1/${id}.json`, Buffer.from("{}")); + await h.store.put("state", "replies/public/case-0/01K66Z2ZQ0000000000000000Z.json", Buffer.from("{}")); + const r = await runPayload({ job: "analyst" }, h.cfg, h.deps); + assert.equal(r.ok, true, JSON.stringify(r.steps)); + assert.match(r.steps[0]!.reason ?? "", /replies: 2 written, 2 inbox removed/); + const keys = (await h.store.list("state", "replies/")).sort(); + assert.deepEqual(keys, [`replies/inbox/case-1/${C}.json`, `replies/public/case-0/01K66Z2ZQ0000000000000000Z.json`, `replies/public/case-1/${A}.json`, `replies/rejected/case-1/${B}.json`]); + + // A refused ledger upload leaves the inbox untouched. + const h2 = harness({ help: "earthdeck analyst --once", verifyExit: 1, job: (args) => (args[0] === "analyst" ? (rmSync(join(args[args.indexOf("--replies") + 1]!, "inbox"), { recursive: true }), 0) : 0) }); + h2.cfg.repliesDir = join(h2.cfg.siteDir, "..", "replies"); + await h2.store.put("state", `replies/inbox/case-1/${A}.json`, Buffer.from("{}")); + await runPayload({ job: "analyst" }, h2.cfg, h2.deps); + assert.deepEqual(await h2.store.list("state", "replies/"), [`replies/inbox/case-1/${A}.json`]); + + // Export: public replies mirrored down; the intake's case index written from api/map.json. + const h3 = harness({ + help: "earthdeck analyst --once\nearthdeck watch export", + job: (args, _dir, site) => { + const rd = args[args.indexOf("--replies") + 1]!; + assert.ok(existsSync(join(rd, "public", "case-0", "01K66Z2ZQ0000000000000000Z.json"))); + mkdirSync(join(site, "api"), { recursive: true }); + writeFileSync(join(site, "api", "map.json"), JSON.stringify({ cases: [{ id: "case-0", status: "published" }, { id: "case-9", status: "candidate" }] })); + return 0; + }, + }); + h3.cfg.repliesDir = join(h3.cfg.siteDir, "..", "replies"); + await h3.store.put("state", "replies/public/case-0/01K66Z2ZQ0000000000000000Z.json", Buffer.from("{}")); + const r3 = await runPayload({ job: "export" }, h3.cfg, h3.deps); + assert.equal(r3.ok, true, JSON.stringify(r3.steps)); + assert.deepEqual(JSON.parse(h3.store.text("state", "replies/cases.json")!), { ids: ["case-0"] }); + for (const x of [h, h2, h3]) x.cleanup(); +}); + +test("infra: reply wall — Function URL (auth NONE, CORS site origin only), least-privilege role, URL fed to the export", () => { + const yaml = readFileSync("infra/earthdeck.yaml", "utf8"); + assert.match(yaml, /Handler: dist\/runner\/reply-lambda\.handler/); + assert.match(yaml, /AuthType: NONE\n\s+Cors:\n\s+AllowOrigins: \[!Sub "https:\/\/\$\{DomainName\}"\]\n\s+AllowMethods: \[POST\]/); + assert.match(yaml, /Action: s3:PutObject\n\s+Resource: !Sub \$\{StateBucket\.Arn\}\/replies\/inbox\/\*/); + assert.match(yaml, /EARTHDECK_REPLY_URL: !GetAtt ReplyFunctionUrl\.FunctionUrl/); + assert.match(yaml, /ReplyUrl:\n\s+Condition: WithFunction/); + const role = yaml.slice(yaml.indexOf(" ReplyRole:"), yaml.indexOf(" ReplyFunction:")); + assert.ok(!/s3:DeleteObject|s3:ListBucket|GetParametersByPath|ledger/.test(role), "the public intake cannot read the ledger or other secrets"); +}); + +test("export: deletes stale api/ and watch/ objects, never ledger/, other prefixes or assets", async () => { + const h = harness({ + help: "earthdeck watch export --out DIR", + job: (_a, _dir, site) => { + mkdirSync(join(site, "api/replies"), { recursive: true }); + writeFileSync(join(site, "index.html"), "

    hi

    "); + writeFileSync(join(site, "api/replies/keep.json"), "{}"); + return 0; + }, + }); + for (const k of ["api/replies/gone.json", "watch/case/old/index.html", "watch/assets/app-Old.js", "ledger/entries.jsonl", "og-old.png", "api/replies/keep.json"]) await h.store.put("site", k, Buffer.from("x")); + const r = await runPayload({ job: "export" }, h.cfg, h.deps); + assert.equal(r.ok, true); + assert.equal(r.steps[0]!.filesDeleted, 2); + const keys = [...h.store.objects.keys()]; + assert.ok(!keys.includes("site/api/replies/gone.json") && !keys.includes("site/watch/case/old/index.html")); + for (const k of ["site/watch/assets/app-Old.js", "site/ledger/entries.jsonl", "site/og-old.png", "site/api/replies/keep.json"]) assert.ok(keys.includes(k), k); + assert.equal(h.counts().invalidations, 1); + assert.deepEqual(sitePruneKeys(["api/a", "apix/b", "watch/../ledger/x", "ledger/y"], new Set()), ["api/a"]); + h.cleanup(); +}); diff --git a/test/scale.test.ts b/test/scale.test.ts index 1a16bd7..3d105d9 100644 --- a/test/scale.test.ts +++ b/test/scale.test.ts @@ -17,7 +17,7 @@ import { mockFetch } from "./helpers.js"; const NOW = "2026-09-26T12:00:00Z"; const DAY = "2026-09-26"; -const CAPS: QuotaCaps = { cdse: 60, gfw: 400, firms: 300, analystCases: 10, analystUsd: 3, perRule: { METHANE_ANOMALY: { cdse: 10 } } }; +const CAPS: QuotaCaps = { cdse: 60, gfw: 400, firms: 300, gfw_fishing: 200, analystCases: 10, analystUsd: 3, perRule: { METHANE_ANOMALY: { cdse: 10 } } }; /** n quiet fire AOIs (one fires_in call each when quiet). */ function fireList(n: number, prefix = "a"): Watchlist { diff --git a/test/site-export.test.ts b/test/site-export.test.ts index 42eb3f0..9bb1f3e 100644 --- a/test/site-export.test.ts +++ b/test/site-export.test.ts @@ -185,6 +185,15 @@ test("export writes a self-contained, relative, server-rendered site", async () for (const k of ["Cases published", "False alarms we caught", "Last check", "Latest cases", "How the planet is doing", "Being checked", "34 hectares — about 48 football fields"]) { assert.ok(landing.includes(k), `landing lacks ${k}`); } + // The map is the product: a full-screen hero with the panel's five modes, all server-rendered + // (no-JS readers get every pane, stacked), and a light below-the-fold section for crawlers. + for (const m of ["cases", "planet", "live", "metrics", "about"]) { + assert.ok(landing.includes(`id="tab-${m}" href="#pane-${m}"`) && landing.includes(`id="pane-${m}"`), `landing lacks the ${m} mode`); + } + assert.ok(landing.includes('
    ')); + assert.ok(landing.includes('id="challenge"'), "the Reply link still lands somewhere"); + assert.ok(landing.includes('
    ') < page.indexOf("`)); // The plain part comes first; ids, rule names and the proof only inside the closed details block. const tech = page.indexOf('
    page.indexOf("What would change our mind") && !page.includes('