Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CONTINUITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,11 @@ reference is [CLAUDE.md](CLAUDE.md); the phase plan is [ROADMAP.md](ROADMAP.md).
(tool `coral_bleaching` exists); second signal: SST anomaly persistence / neighbour cell.
3. **Extreme-fire rule** — global VIIRS FRP/extent anomaly vs. the same weeks in prior
years (not only inside protected areas); confirm with a later pass + burn index.
0. **Improvement rule** (queued 2026-09-26, after the flare "stopped" case type lands):
cases that open when something *gets better* — loss below the ring baseline for 90 d,
flaring down year-on-year (VNF), bleaching alert lifted, fires absent in a formerly
burning protected area — same evidence standard, tag `improvement`, shown on the
landing as good news. "A watch, not a complaint feed."
4. **Radiation** — `radiation` tool + `radiation_anomaly` rule from open ground networks:
BfS ODL (DE, open JSON), EURDEP (EU), EPA RadNet (US), Safecast (global, CC0); dose
rate vs. station baseline, confirmed by a neighbouring station or second network.
Expand Down
1 change: 1 addition & 0 deletions infra/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ hold across invocations) and set as function env vars in the template:
| Env var | Default | Counts |
| --- | --- | --- |
| `EARTHDECK_MAX_CDSE_CALLS` | 60 | `eo_compare`, `methane_plumes`, `eo_*` tool calls (1 each) |
| `EARTHDECK_MAX_<PROVIDER>_CALLS_<RULE>` | `…_CDSE_CALLS_METHANE_ANOMALY` 10 | per-rule sub-cap inside a provider's cap (rule name upper-cased, `-`→`_`); keeps methane from spending the CDSE budget forest confirmations need |
| `EARTHDECK_MAX_GFW_CALLS` | 400 | `forest_alerts` calls (1 each) |
| `EARTHDECK_MAX_FIRMS_CALLS` | 300 | FIRMS transactions: `fires_in` 1; `flaring` ⌈days/5⌉ × sources (30 d × 2 = 12) |
| `EARTHDECK_MAX_ANALYST_CASES` | 10 | findings the analyst takes on per day (also the `--max` default) |
Expand Down
2 changes: 2 additions & 0 deletions infra/earthdeck.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -380,6 +380,8 @@ Resources:
# 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"
# methane_anomaly may spend at most 10 of those; forest confirmations keep the rest.
EARTHDECK_MAX_CDSE_CALLS_METHANE_ANOMALY: "10"
EARTHDECK_MAX_GFW_CALLS: "400"
EARTHDECK_MAX_FIRMS_CALLS: "3000"
EARTHDECK_MAX_ANALYST_CASES: "10"
Expand Down
71 changes: 64 additions & 7 deletions src/analyst/analyst.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,66 @@ const REVIEWER_SYSTEM = `You are the independent second reviewer for Earth Watch

verdict: "publish" only if all of the above hold and the finding is fit for the public record; "hold" if a human should look (unclear, overclaiming, fixable); "reject" if the finding itself looks like a false positive or the AOI is a control. Give short, specific reasons.`;

export function select(ledger: AnalystLedger, max: number): { finding: Finding; needs: "narrate" | "review" }[] {
const out: { finding: Finding; needs: "narrate" | "review" }[] = [];
const confirmed = ledger.list({ status: ["confirmed"] }).sort((a, b) => (a.createdAt < b.createdAt ? 1 : -1));
for (const f of confirmed) {
if (!f.narration) out.push({ finding: f, needs: "narrate" });
else if (!f.reviews.some((r) => r.actor.startsWith("model:") && r.at >= f.narration!.at)) out.push({ finding: f, needs: "review" });
if (out.length >= max) break;
export interface Selected {
finding: Finding;
needs: "narrate" | "review";
score: number;
}

const numParam = (v: unknown, dflt: number) => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : dflt);

/**
* How surprising a finding is: the AOI-vs-ring baseline ratio (1 when absent) times a
* rule-specific boost — flaring with no registry match ×2, forest ha / minHa, methane
* anomaly ppb / minAnomalyPpb, fires detections / minDetections. Unknown rules: ×1.
*/
export function novelty(f: Finding): number {
const ratio = f.context?.baseline?.ratio;
const base = typeof ratio === "number" && ratio > 0 ? ratio : 1;
const v = Object.assign({}, ...f.evidence.map((e) => e.values ?? {})) as Record<string, number>;
const p = f.rule.params ?? {};
let boost = 1;
switch (f.rule.name) {
case "flaring":
boost = v.new_flare === 1 ? 2 : 1;
break;
case "forest_loss":
if (typeof v.ha === "number") boost = v.ha / numParam(p.minHa, 5);
break;
case "methane_anomaly":
if (typeof v.deltaPpb === "number") boost = v.deltaPpb / numParam(p.minAnomalyPpb, 20);
break;
case "fires_in_protected":
if (typeof v.detections === "number") boost = v.detections / numParam(p.minDetections, 5);
break;
}
return Math.round(base * (boost > 0 ? boost : 1) * 1000) / 1000;
}

/** 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);

/**
* 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`.
*/
export function select(ledger: AnalystLedger, max: number): Selected[] {
const review: Selected[] = [];
const groups = new Map<string, Selected[]>();
for (const f of ledger.list({ status: ["confirmed"] })) {
if (!f.narration) {
const g = groups.get(f.rule.name) ?? [];
g.push({ finding: f, needs: "narrate", score: novelty(f) });
groups.set(f.rule.name, 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));
while (out.length < max && queues.some((q) => q.length)) {
const round = queues.filter((q) => q.length).map((q) => q.shift()!).sort(byNovelty);
out.push(...round.slice(0, max - out.length));
}
return out;
}
Expand All @@ -112,6 +165,10 @@ export async function runAnalyst(o: AnalystOptions): Promise<AnalystReport> {
report.selected = work.length;
if (q && q.analystCasesLeft() === 0) 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(" · ")}`);
j("selection", { order: work.map((w) => ({ findingId: w.finding.findingId, rule: w.finding.rule.name, needs: w.needs, score: w.score })) });
}

const call = async (purpose: "narrate" | "review", findingId: string, attempt: number, model: string, system: string, user: string, jsonSchema: Record<string, unknown>): Promise<JsonCallResult> => {
try {
Expand Down
66 changes: 66 additions & 0 deletions src/clients/geo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,69 @@ export async function geocode(place: string): Promise<GeoPlace> {
center: [Number(r.lon), Number(r.lat)],
};
}

const NOMINATIM_REVERSE = "https://nominatim.openstreetmap.org/reverse";

/** Administrative areas around a point — nothing finer, so never a facility, operator or person. */
export interface AdminPlace {
county?: string;
state?: string;
country?: string;
/** ISO 3166-1 alpha-2, lower case. */
countryCode?: string;
}

/** Nominatim `reverse` URL. zoom 8 ≈ county, 5 ≈ state; coordinates rounded to 3 dp (~100 m). */
export function reverseGeocodeUrl(lat: number, lon: number, zoom = 8): string {
const r = (v: number) => String(Math.round(v * 1000) / 1000);
return `${NOMINATIM_REVERSE}?${new URLSearchParams({ lat: r(lat), lon: r(lon), zoom: String(zoom), format: "jsonv2", addressdetails: "1", "accept-language": "en" })}`;
}

/**
* Keep only admin levels from a Nominatim `reverse` answer. `name` / `display_name` and every
* non-admin address key are dropped on purpose: for an industrial point Nominatim can answer
* with the facility, i.e. an operator's name. No match ({ error }) → {}.
*/
export function parseReverseGeocode(body: unknown): AdminPlace {
const a = ((body ?? {}) as { address?: Record<string, unknown> }).address ?? {};
const s = (k: string) => (typeof a[k] === "string" && (a[k] as string).trim() ? (a[k] as string).trim() : undefined);
const out: AdminPlace = {};
const county = s("county") ?? s("state_district");
const state = s("state") ?? s("province") ?? s("region");
if (county) out.county = county;
if (state) out.state = state;
if (s("country")) out.country = s("country");
if (s("country_code")) out.countryCode = s("country_code")!.toLowerCase();
return out;
}

/** Reverse-geocode a point to its county/state/country. Nominatim ToS: ≤1 req/s — callers pace. */
export async function reverseGeocode(lat: number, lon: number, zoom = 8): Promise<AdminPlace> {
const res = await fetch(reverseGeocodeUrl(lat, lon, zoom), { headers: { "user-agent": USER_AGENT, "accept-language": "en" } });
if (!res.ok) throw new OverviewError(`Nominatim reverse geocoding failed (${res.status})`, res.status);
return parseReverseGeocode(await res.json());
}

/**
* Drop generic admin words for a readable label: "Dehloran County" → "Dehloran", "Municipio
* Ezequiel Zamora" → "Ezequiel Zamora", "Delta State" → "Delta". Kept when only a compass word
* would remain ("Eastern Province").
*/
export function shortAdmin(name: string): string {
const s = name
.replace(/\s+\((département|department|province)\)$/i, "")
.replace(/^(Municipio|Departamento|Partido|Distrito|District de|Département de|Provincia de)\s+/i, "")
.replace(/\s+(County|District|Province|Governorate|Region|Municipality|Prefecture|Oblast|Krai|Department|Regency|Division|State|Rayon|Ulus)$/i, "")
.trim();
return !s || /^(north|south|east|west|central|eastern|western|northern|southern)$/i.test(s) ? name : s;
}

/** "Dehloran, Ilam (Iran)" / "Bayelsa (Nigeria)" / null when nothing usable came back. */
export function adminLabel(p: AdminPlace | null | undefined): string | null {
if (!p) return null;
// Nominatim sometimes ignores accept-language=en for small units; a label must be readable.
const parts = [p.county, p.state].filter((x): x is string => !!x && /[A-Za-z]/.test(x)).map(shortAdmin);
const uniq = parts.filter((x, i) => parts.indexOf(x) === i);
if (!uniq.length) return p.country ?? null;
return p.country ? `${uniq.join(", ")} (${p.country})` : uniq.join(", ");
}
70 changes: 69 additions & 1 deletion src/clients/vnf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,8 @@ export interface FlareCluster {
lastNight: string;
sources: string[];
vnf?: { id: string; type: string; bcm: number; km: number } | null;
/** No VNF site within NOVEL_KM in the latest OR the previous annual summary: not in the registry. */
novel?: boolean;
}

/**
Expand Down Expand Up @@ -189,6 +191,11 @@ export function parseVnfKml(kml: string): VnfSite[] {

const vnfCache = new Map<number, Promise<VnfSite[]>>();

/** Forget the per-process VNF downloads (tests that mock EOG differently). */
export function clearVnfCache(): void {
vnfCache.clear();
}

/** The year's global flare summary (≈12 MB KML, fetched once per process and cached). */
export async function vnfAnnual(year = VNF_DEFAULT_YEAR): Promise<{ year: number; sensor: string; url: string; sites: VnfSite[] }> {
const spec = VNF_ANNUAL[year];
Expand Down Expand Up @@ -235,6 +242,40 @@ export interface FlaringOptions {
limit?: number;
}

/** New / stopped flares: a VNF site "is" a cluster when within this distance. */
export const NOVEL_KM = 2;
/** A registered site counts as stopped only if it flared at least this much in the latest year. */
export const STOPPED_MIN_BCM = 0.05;

/** A VNF site in the box that flared ≥ STOPPED_MIN_BCM in the latest year with zero FIRMS night detections within NOVEL_KM. */
export interface StoppedSite {
id: string;
type: string;
lat: number;
lon: number;
bcm: number;
}

/**
* Registered sites (≥ minBcm) with no night-time detection (any FRP) within `km` in the
* window. Null when the window holds no night detection at all in the box: then a shutdown
* cannot be told from a data gap, so nothing is claimed.
*/
export function stoppedSites(
sites: readonly VnfSite[],
dets: readonly Pick<FireDetection, "lat" | "lon" | "daynight">[],
o: { minBcm?: number; km?: number } = {},
): StoppedSite[] | null {
const night = dets.filter((d) => d.daynight === "N");
if (night.length === 0) return null;
const km = o.km ?? NOVEL_KM;
return sites
.filter((s) => s.bcm >= (o.minBcm ?? STOPPED_MIN_BCM))
.filter((s) => !night.some((d) => kmBetween(s.lat, s.lon, d.lat, d.lon) <= km))
.sort((a, b) => b.bcm - a.bcm || a.id.localeCompare(b.id))
.map(({ id, type, lat, lon, bcm }) => ({ id, type, lat, lon, bcm }));
}

export const FLARING_DEFAULTS = { days: 30, minFrp: 3, minNights: 5, clusterKm: 1, vnfYear: VNF_DEFAULT_YEAR, limit: 50 } as const;

export async function flaringReport(mapKey: string, bbox: BBox, o: FlaringOptions = {}) {
Expand Down Expand Up @@ -263,6 +304,22 @@ export async function flaringReport(mapKey: string, bbox: BBox, o: FlaringOption
const m = nearestSite(cl.lat, cl.lon, local, matchKm);
cl.vnf = m ? { id: m.site.id, type: m.site.type, bcm: m.site.bcm, km: round(m.km, 2) } : null;
}
// New: no site within NOVEL_KM in the latest AND the previous year (sites just outside the box count too).
const near = padBBox(bbox, 0.05);
const prevYear = a.year - 1 in VNF_ANNUAL ? a.year - 1 : null;
let previous: Record<string, unknown> = { available: false, reason: `no VNF annual summary for ${a.year - 1}` };
if (prevYear != null) {
try {
const p = await vnfAnnual(prevYear);
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 };
} catch (err) {
previous = { available: false, reason: err instanceof Error ? err.message : String(err) };
}
}
const stopped = stoppedSites(local, detections);
vnf = {
available: true,
product: "VNF annual global flare summary (aggregate; nightly VNF not used)",
Expand All @@ -275,6 +332,11 @@ export async function flaringReport(mapKey: string, bbox: BBox, o: FlaringOption
bcmTotal: round(local.reduce((s, x) => s + x.bcm, 0), 3),
matchKm,
matchedClusters: persistent.filter((x) => x.vnf).length,
previous,
newClusters: persistent.filter((x) => x.novel).length,
stopped: stopped
? { minBcm: STOPPED_MIN_BCM, km: NOVEL_KM, count: stopped.length, bcm: round(stopped.reduce((s, x) => s + x.bcm, 0), 3), sites: stopped.slice(0, 50) }
: { minBcm: STOPPED_MIN_BCM, km: NOVEL_KM, count: 0, bcm: 0, sites: [], note: "no night detection anywhere in the box this window — a shutdown cannot be told from a data gap" },
sites: local.slice(0, 20).map(({ id, type, lat, lon, bcm, clearObs, clearPct }) => ({ id, type, lat, lon, bcm, clearObs, clearPct })),
};
} catch (err) {
Expand Down Expand Up @@ -303,13 +365,15 @@ export async function flaringReport(mapKey: string, bbox: BBox, o: FlaringOption
href: FIRMS_HREF,
method: {
name: "flaring",
version: "1.0",
version: "1.1",
nightFilter: 'daynight == "N"',
frpFilter: `frp >= ${minFrp} MW`,
night: "local solar night (UTC + lon/15 h − 12 h), so one night's passes count once",
clustering: `leader clustering by descending FRP, radius ${clusterKm} km`,
persistence: `cluster lit on >= ${minNights} distinct nights of the ${days}-day window`,
vnfMatch: `nearest VNF annual site within ${matchKm} km of the cluster centroid`,
newFlare: `persistent cluster with no VNF site within ${NOVEL_KM} km in the latest or the previous annual summary`,
stopped: `VNF site (≥ ${STOPPED_MIN_BCM} BCM in the latest year) with no night detection of any FRP within ${NOVEL_KM} km in the window`,
},
retrievedAt: new Date().toISOString(),
caveat:
Expand All @@ -325,6 +389,10 @@ function round(v: number, dp: number): number {
return Math.round(v * f) / f;
}

function padBBox([w, s, e, n]: BBox, deg: number): BBox {
return [w - deg, s - deg, e + deg, n + deg];
}

function toNum(s: string | undefined): number | null {
if (s == null) return null;
const n = Number(s);
Expand Down
Loading
Loading