Backend & API · reference for roles A, B, C · architecture revised 29 Sep · API aligned with the web app 6 Oct · subscriber notifications 9 Oct

Five deterministic jobs, two services

Observation (Himawari-9, GK2A), baselines (NASA POWER + thermal baseline) and the rule engine (MAUT + neighbour support) run as Cloud Run jobs. The ADK agent lives in the asapify-agent service and is called only for AWAS clusters; it fetches VIIRS at that moment (on demand). The asapify-api service serves operators and subscribers; once an operator publishes, the message reaches the inbox and Telegram DMs of that province's subscribers through the asapify-notify worker. Code on this page is a 💡 starting point; ⚠️ parts are checked in Sprint 0.

01 · Who reads and writes what

Seven components, one image

The wiring diagram is in Plan 03 (schematic B). Keep this table at hand while writing code.

ComponentTriggerReadsWritesCalls
asapify-build (job)manual, onceBIG KHG, data/ref/provinces.geojson, WorldCover (EE)peat/pixels.parquet, neighbors8, neighbors_r5, power_cellsEarth Engine
asapify-ingest-himawari (job)Scheduler */10 20-23,0-4NOAA noaa-himawari9, peat/himawari/…/HHMM.parquet, raw/himawari/manifest/, runs—
asapify-ingest-gk2a (job)Scheduler */10 20-23,0-4NOAA noaa-gk2a-pds, peat/gk2a/…/HHMM.parquet, raw/gk2a/manifest/, runs—
asapify-environment (job)Scheduler 0 12 * * *NASA POWER, himawari/, gk2a/, score/ (frozen pixels)environment/power/, environment/thermal/, environment/bias/, raw/power/—
asapify-evaluate (job)Scheduler 5-59/10 20-23,0-4himawari/, gk2a/, environment/, peat/, score/ 3 nightsscore/…/HHMM.parquet, Firestore clusters, runsasapify-agent: POST /verify (AWAS only), POST /cluster-closed
asapify-agent (service, private)POST from evaluate or apiclusters, score/, NASA FIRMS, NASA GIBS, NOAA Himawaricrops/, raw/firms/, verifications, alerts.status (close), audit_logGemini, Telegram (operator group)
asapify-api (service)operator and subscriber web requests; Telegram webhookscore/ (grid), clusters, verifications, notification_recipientsalerts, audit_log, notification_inbox, notification_jobsCloud Tasks (send queue), asapify-agent (re-verification)
asapify-notify (service, private)Cloud Tasks (one task per job), Scheduler sweep every minutenotification_jobs, notification_inbox, notification_recipientsjob status, notification_inbox (resumed fan-out)Telegram (subscriber DMs), FCM (exercise push)
02 · Conventions

Apply to every job and endpoint

Base path
Operator API: /api/v1, through Firebase Hosting (same origin as the web app). Agent: /verify on the private Cloud Run URL.
Format
UTF-8 JSON, coordinates [lon, lat]. The web map uses a compact format: a static pixel index once (/operator/pixels), then one status letter per cell (S, N, W, A). For 10k cells that is ≈ 23 KB raw / 11 KB gzip, against ≈ 1.9 MB / 83 KB for GeoJSON. GeoJSON points stay available (format=geojson, the default) for other tools.
Time
ISO 8601. Store UTC, display WIB. slot = the 10-minute scan time in UTC.
IDs
pixel p{row}_{col} on the 0.02° Sumatra + Kalimantan grid (1,225 × 620, origin 94.9° E / 6.2° N, row 0 in the north); cluster C-{MMDD}-{nnn}; verification {cluster_id}_{slot:%Y%m%dT%H%M}
Status
SAFE, NO_OBSERVATION, WATCH, AWAS (upper case, exactly)
Operator auth
Firebase ID token, claim role = "operator"
Internal auth
OIDC from sa-jobs or sa-api to asapify-agent (Cloud Run IAM run.invoker)
Replay
jobs: --as-of or env AS_OF; endpoints: as_of; response header X-Asapify-As-Of
Errors
{"error": {"code": "...", "message": "..."}}. code is stable; the web app writes its own message from code in the operator's language (EN/ID). message (Indonesian) shows only when the web app does not know the code yet.
Language
Agent text is sent in both languages (finding + finding_en, summary_id + summary_en) so a screen never mixes languages. Alert message text (inbox and Telegram DM) stays in Indonesian.
03 · Endpoints

asapify-api and asapify-agent

MethodPathAuthPurpose
asapify-api · public (after /api/v1)
GET/health, /metapublicliveness; latest slot per satellite, night/day, replay status, range of archive nights that can be opened (nights.first–nights.last)
asapify-api · operator
GET/operator/pixelsoperatorstatic peat pixel index: version, grid origin, 0.02° step, rows, columns and province code per cell. Its order is the cell index in every compact response. Downloaded once; send ETag + Cache-Control
GET/operator/grid?as_of=, &format=compactoperatorstatus of every peat pixel for the latest night slot ≤ as_of. Default GeoJSON points (status, utility, n_sat, cluster_id, province). format=compact (used by the web app): a status string with one letter per cell, utility as base64 Uint8 (round(U × 250), 255 = null), and active clusters → cell indices
GET/operator/grid/night?night=operator54 status strings (compact format) for one night, 20:00–04:50 WIB, plus the clusters that were AWAS in any slot that night → cell indices. One request for the slot player and for archive nights. Slots after as_of or without data = null
GET/operator/nights?month=operatorone row per archive night in that month: night, has_data, awas_clusters. Fills the night calendar (faded date = no data, dot = AWAS clusters)
GET/operator/basemaps?as_of=operatorraster basemap options from the backend, e.g. NASA GIBS VIIRS true colour for the as_of date (tile template, tile size, max zoom, attribution, EN/ID label). Empty array = street and plain maps only
GET/operator/clusters?state=active, ?night=operatorAWAS clusters + latest verification + decision. With night=YYYY-MM-DD (archive night): clusters that were AWAS in any slot that night, active or closed (first_awas_at ≤ night end and last_awas_at ≥ night start); state is ignored
GET/operator/clusters/{id}operator3-night utility series, MAUT attributes at the trigger slot with their measured numbers (attribute_details), neighbour grid, verification + tool trace, signed image URLs with the crop bbox, and per-cell brightness temperatures behind the thermal image (images[].thermal)
POST/operator/clusters/{id}/verifyoperatorrequest re-verification; forwarded to the agent (respects the 6 h cooldown unless force=true)
POST/operator/clusters/{id}/decisionoperatorpublish (message text; the decision, audit entry and alert are saved first, then inbox entries and a queue are written for each subscriber of that province, 50 per batch; the subscriber count never fails a decision) / reject (reason required)
GET/operator/alerts?status=operatorpublished alerts + queue summary
POST/operator/alerts/{id}/closeoperatorearly close by an operator: inbox entries get the SELESAI label, unsent jobs are cancelled (automatic through agent /cluster-closed when a cluster closes)
GET/operator/alerts/{id}/deliveriesoperatorsend status per channel per subscriber (pending, sending, accepted, failed, unknown, blocked, cancelled, simulated) + the recipient's confirmation time. accepted = the provider took it, not that it was read ✅
asapify-api · subscribers (Google account with a verified email, no role)
GET/notifications/settingsuserpreferences (provinces, channels, consent, exercises), linked Telegram / registered push device, channel list with on/off state, mode dry_run / live ✅
PUT/notifications/preferencesuserbody {provinces, channels, consent, exercises}; consent = true needs at least one province; unsubscribing = consent = false ✅
POST/notifications/device, DELETEuserregister / remove one push token (FCM, including Web Push) per account ✅
POST/notifications/telegram-linkusersingle-use deep link t.me/<bot>?start=<code>, valid for 10 minutes; only a hash of the code is stored ✅
GET/notifications/inboxuserthe account's last 50 messages: text, province, purpose (emergency / exercise), published_at, expires_at, acknowledged_at ✅
POST/notifications/inbox/{id}/ackuserconfirm receipt; idempotent; another account's ID → 404. Opening the link alone does not count as a confirmation ✅
POST/notifications/telegram-webhookTelegram secretcalled by Telegram, not the browser. Header X-Telegram-Bot-Api-Secret-Token; only accepts /start <code> from a private chat to link an account; never replies ✅
public bucket · static files for map layers (not endpoints)
FILElayers/peat_pixels.geojsonpublicprocessed peat boundary (KHG ∩ 15 provinces − built-up), simplified; written by asapify-build
FILElayers/provinces.geojsonpublicthe 15 Sumatra + Kalimantan provinces (BPS code, name), simplified to ≈ 90 KB (≈ 30 KB gzip); used for province lines and the selected-province highlight. geoBoundaries IDN ADM1, ODbL
asapify-agent · internal (private Cloud Run URL)
POST/verifyOIDC sa-jobs / sa-apibody {"cluster_id", "trigger_slot", "force": false}; runs the agent, saves verifications, posts to the operator group. Response 202 + verification_id
POST/cluster-closedOIDC sa-jobsbody {"cluster_id"}; deterministic code (no Gemini): if an alert was published for that cluster, set alerts.status = closed, label the inbox entries SELESAI and cancel unsent jobs
asapify-notify · internal (private Cloud Run URL, same image as asapify-api)
POST/_internal/notifications/dispatchOIDC sa-taskbody {"job_id"} from Cloud Tasks: claim one job, re-check consent, confirmation and expiry, send, save the status. A timeout = unknown, never resent automatically ✅
POST/_internal/notifications/sweepOIDC sa-taskCloud Scheduler every minute: resume interrupted fan-outs (alerts.fanout = pending), re-queue pending jobs, mark sending > 5 min as unknown ✅

The full schema of every response (fields, types, required, JSON examples) is in the API contract tab of the web app (/kontrak-api, public, EN/ID). Its examples come from the same mock data the screens show.

04 · Examples

The agreed data shapes

Fictional data.

GET /api/v1/operator/clusters/C-0924-002200
{
  "id": "C-0924-002",
  "state": "active",
  "province": "62",
  "rep_pixel": "p420_950",
  "centroid": [113.92, -2.21],
  "pixels": ["p420_950", "p420_951", "p421_950", "p419_951"],
  "trigger_slot": "2023-09-24T15:10:00Z",
  "utility_score": 0.73,
  "neighbour_support": 0.375,
  "attributes": {"u_H": 1.0, "u_G": 1.0, "u_LST": 0.5,
                 "u_SAT": 0.0, "u_T": 0.67},
  "attribute_details": {
    "u_H": {"value": 18.6, "unit": "K", "scale": [6, 14],
            "parts": [{"key": "b07", "value": 318.2, "unit": "K", "abs": true},
                      {"key": "bg_dt", "value": 4.1, "unit": "K"}]},
    "u_T": {"value": 2, "unit": "malam", "scale": [0, 3], "parts": []}
  },
  "n_sat": 2,
  "series": [{"slot": "2023-09-23T15:00:00Z", "U": 0.38, "status": "WATCH"},
             {"slot": "2023-09-24T15:10:00Z", "U": 0.73, "status": "AWAS"}],
  "neighbours": [{"dir": "n", "state": "anomaly", "u0": 0.62}, …],
  "verification": {
    "result": "strong_evidence",
    "viirs_within_2km_48h": 1,
    "tool_calls": 5,
    "at": "2023-09-24T15:14:00Z",
    "images": [{"source": "himawari_image", "url": "https://…",
                "bbox": [113.72, -2.41, 114.12, -2.01],
                "thermal": {"cols": 20, "rows": 20, "bands": […]}}, …]
  },
  "decision": null
}
GET /api/v1/operator/grid?format=compact200
{ "pixels_version": "2023-09-v1",
  "slot": "2023-09-24T15:10:00Z",
  "n_sat": 2,
  "status": "SSSWSNNSAAS…",   # one letter per cell, order of /operator/pixels
  "utility": "Mjw8RlB…",      # base64 Uint8: round(U × 250), 255 = null
  "clusters": {"C-0924-002": [1204, 1205, 1287, 1288]} }
POST …/C-0924-002/decisionrequest
{
  "action": "publish",
  "caption_id": "AWAS · Kalimantan Tengah …",
  "reason": null
}
Response201
{ "action": "publish", "by": "operator@contoh.id",
  "at": "2023-09-24T15:30:00Z", "reason": null,
  "alert_id": "A-0924-001", "telegram": null,
  "notifications": {"state": "outbox_saved",
                    "recipients": 2, "jobs": 4},
  "queue": {"state": "accepted", "count": 4} }
Error · 409response
{ "error": { "code": "ALREADY_DECIDED",
  "message": "Kelompok ini sudah diterbitkan oleh operator lain." } }
05 · Data model

Time series in Storage, decisions in Firestore

Cloud Storage (Parquet unless stated otherwise)
PathContents
peat/pixels.parquetpixel_id, row, col, lat, lon, peat_frac, built_frac, kode_khg, province (11–19, 21, 61–65), cell_id
peat/neighbors8.parquet, neighbors_r5.parquet, power_cells.parquetpixel_id, neighbor_ids[]; cell_id, lat, lon, n_pixels
himawari/YYYY/MM/DD/HHMM.parquetpixel_id, mir (B07), win (B14), cloud
gk2a/YYYY/MM/DD/HHMM.parquetpixel_id, mir (SW038), win (IR105), cloud
environment/power/YYYYMMDD.parquetcell_id, hour_utc, ts_base, t2m_base, n_days
environment/thermal/{sat}/YYYYMMDD.parquetpixel_id, hour_utc, median, mad, n_obs, frozen
environment/bias/YYYYMMDD.parquetpixel_id, hour_utc, b_lst
score/YYYY/MM/DD/HHMM.parquetpixel_id, timestamp, himawari_score, gk2a_score, z_rel_h, z_rel_g, lst, sat, d_lst, d_sat, u_lst, u_sat, u_t, utility_score, neighbour_support, n_sat, status, cluster_id
crops/{pixel_id}/{timestamp}_{source}.pngVIIRS and Himawari images for the agent and the UI; thermal PNGs use a fixed hot-channel colour scale of 270–340 K (the same as the web legend)
crops/{pixel_id}/{timestamp}_thermal.jsonbrightness temperature per 0.02° cell behind the thermal crop: bbox, 20 × 20 cells, channels B07/B14 (Himawari) and SW038/IR105 (GK2A), kelvin to 1 decimal, null = cloudy. Served as images[].thermal ⚠️
raw/{source}/…per-slot source file manifests (JSON), POWER cache per cell, FIRMS cache per box
layers/*.geojson (public bucket)peat_pixels.geojson and provinces.geojson for the web map layers; read by the browser directly (CORS)
Firestore
CollectionContents
clusterspixels, rep_pixel, centroid, province, utility_max, neighbour_support, first_awas_at, last_awas_at, last_verified_at, state (active/closed)
verificationsschema-locked agent output, tool trace, model, validator_ok
alertscluster_id, caption, published_by/at, status (active/closed), purpose (emergency/exercise), expires_at, fanout (pending/done), notifications {state, recipients, jobs}
notification_recipientsper subscriber (ID = hash of the UID): provinces, channels, consent, exercises, Telegram chat_id and push token (never sent to the browser)
notification_inboxone document per alert × subscriber: text, province, purpose, expires_at (1 h), acknowledged_at
notification_jobsper-channel outbox: status, error, attempts, not_before, provider_id; deterministic IDs, only ever created
notification_devices, notification_telegram_chatsowner of each push token / Telegram chat, so one device or chat cannot be linked to two accounts
runslog of every job run: slot, n_sat, count per status, latency, missing files
audit_logevery operator action, agent call and bot message
05b · Sumatra + Kalimantan region ✅

One grid, fifteen provinces, peat pixels only

Every job, the backtest and the UI use the same constants from jobs/lib/region.py.

Region constantsjobs/lib/region.py
from pyresample import create_area_def

# lon_min, lat_min, lon_max, lat_max (WGS84)
MONITOR_BBOX  = (94.9, -6.2, 119.4, 6.2)    # Sumatra + Kalimantan (grid origin 94.9 E / 6.2 N)
BACKTEST_BBOX = (113.5, -2.6, 114.3, -1.9)  # Central Kalimantan sub-area (main)
BACKTEST_BBOX_SUMSEL = (105.2, -3.7, 106.0, -3.0)  # OKI, South Sumatra (planned)
GRID_DEG = 0.02                             # 1,225 columns × 620 rows
NIGHT_UTC = range(13, 21)                   # 20:00–04:00 WIB (Sumatra is also WIB)

PROVINCES = {                               # BPS codes
    "11": "Aceh", "12": "Sumatera Utara", "13": "Sumatera Barat",
    "14": "Riau", "15": "Jambi", "16": "Sumatera Selatan",
    "17": "Bengkulu", "18": "Lampung",
    "19": "Kepulauan Bangka Belitung", "21": "Kepulauan Riau",
    "61": "Kalimantan Barat",   "62": "Kalimantan Tengah",
    "63": "Kalimantan Selatan", "64": "Kalimantan Timur",
    "65": "Kalimantan Utara",
}

AREA = create_area_def("sumkal_002", "EPSG:4326",
                       area_extent=MONITOR_BBOX, resolution=GRID_DEG)

def pixel_id(row: int, col: int) -> str:
    return f"p{row}_{col}"                  # row 0 = north

Why the bbox alone is not enough

  • The MONITOR_BBOX box also covers Peninsular Malaysia, Singapore, Sarawak, Sabah, Brunei, the western tip of Java and part of the West Sulawesi coast.
  • KHG covers Indonesia only, so Malaysia, Singapore and Brunei drop out automatically. Java and Sulawesi are removed with the province filter (codes 11–19, 21, 61–65).
  • The per-pixel province column also decides which subscribers receive the alert (subscribers choose provinces).
Full grid
1,225 × 620 = ~760 thousand cells
Peat pixels
rough estimate ~20–25 thousand ⚠️ (count in A1)
NASA POWER cells
0.5° × 0.625°; an estimated 250–400 cells contain peat ⚠️
Per slot
2 small Parquet files (hundreds of KB), 1 per satellite
Peat mask: KHG + provinces + built-upjobs/build_peat_mask.py
import geopandas as gpd, numpy as np, requests
from rasterio import features, transform
from jobs.lib.region import MONITOR_BBOX, GRID_DEG, AREA, pixel_id

KHG = ("https://kspservices.big.go.id/satupeta/rest/services/PUBLIK/"
       "SUMBER_DAYA_ALAM_DAN_LINGKUNGAN/MapServer/37/query")

def fetch_khg(bbox):
    feats, off = [], 0
    while True:                                 # max 1,000 features/request
        r = requests.get(KHG, timeout=120, params={
            "where": "1=1", "outFields": "kode_khg", "f": "geojson",
            "geometry": ",".join(map(str, bbox)),
            "geometryType": "esriGeometryEnvelope", "inSR": 4326,
            "outSR": 4326, "resultOffset": off, "resultRecordCount": 1000})
        page = r.json()["features"]; feats += page
        if len(page) < 1000: return gpd.GeoDataFrame.from_features(feats, crs=4326)
        off += 1000

def fraction(gdf, sub=10):                      # area fraction per 0.02° cell
    h, w = AREA.shape
    t = transform.from_bounds(*MONITOR_BBOX, w * sub, h * sub)
    fine = features.rasterize(gdf.geometry, (h * sub, w * sub), transform=t)
    return fine.reshape(h, sub, w, sub).mean(axis=(1, 3))

khg  = fetch_khg(MONITOR_BBOX).make_valid()
prov = gpd.read_file("data/ref/provinces.geojson")   # 15 provinces, Runbook S0-8
peat_frac  = fraction(khg.clip(prov))
built_frac = np.load("data/ref/built_frac_002.npy")

keep = (peat_frac >= 0.5) & (built_frac < 0.2)
rows, cols = np.nonzero(keep)
lon, lat = AREA.get_lonlats()
df = gpd.GeoDataFrame({
    "pixel_id": [pixel_id(r, c) for r, c in zip(rows, cols)],
    "row": rows, "col": cols,
    "lat": lat[rows, cols], "lon": lon[rows, cols],
    "peat_frac": peat_frac[rows, cols], "built_frac": built_frac[rows, cols],
}, geometry=gpd.points_from_xy(lon[rows, cols], lat[rows, cols]), crs=4326)
df = (df.sjoin(prov[["code", "geometry"]]).drop(columns="index_right")
        .rename(columns={"code": "province"}))
df = df.sjoin(khg[["kode_khg", "geometry"]], how="left")
df.drop(columns=["geometry", "index_right"]).to_parquet(
    f"gs://{DATA_BUCKET}/peat/pixels.parquet")
Built-up fraction (once)jobs/build_built_frac.py
import ee, numpy as np, requests, io
from jobs.lib.region import MONITOR_BBOX, GRID_DEG

ee.Initialize(project=PROJECT_ID)
T = [GRID_DEG, 0, MONITOR_BBOX[0], 0, -GRID_DEG, MONITOR_BBOX[3]]
built = (ee.ImageCollection("ESA/WorldCover/v200").first().eq(50)
         .reduceResolution(ee.Reducer.mean(), maxPixels=65535)
         .reproject(crs="EPSG:4326", crsTransform=T))
url = built.getDownloadURL({"region": ee.Geometry.Rectangle(list(MONITOR_BBOX)),
                            "crs": "EPSG:4326", "format": "NPY", "crsTransform": T})
arr = np.load(io.BytesIO(requests.get(url).content))
np.save("data/ref/built_frac_002.npy", arr["Map"].astype("float32"))
Neighbours + POWER cells (once)jobs/build_neighbors.py, build_power_cells.py
peat = pd.read_parquet(f"gs://{DATA_BUCKET}/peat/pixels.parquet")
idx = {(r, c): p for p, r, c in zip(peat.pixel_id, peat.row, peat.col)}

def around(r, c, k):        # k=1 → 8 directions; k=5 → 5-cell radius
    return [idx[(r+i, c+j)] for i in range(-k, k+1) for j in range(-k, k+1)
            if (i or j) and (r+i, c+j) in idx and (k == 1 or i*i + j*j <= k*k)]

for k, name in ((1, "neighbors8"), (5, "neighbors_r5")):
    pd.DataFrame({"pixel_id": peat.pixel_id,
                  "neighbor_ids": [around(r, c, k) for r, c in zip(peat.row, peat.col)]}
                 ).to_parquet(f"gs://{DATA_BUCKET}/peat/{name}.parquet")

# NASA POWER cell (GEOS-IT 0.5° × 0.625°)
peat["cell_lat"] = (peat.lat / 0.5).round() * 0.5
peat["cell_lon"] = (peat.lon / 0.625).round() * 0.625
peat["cell_id"] = [f"c{a:+.1f}_{o:.3f}" for a, o in zip(peat.cell_lat, peat.cell_lon)]
cells = (peat.groupby("cell_id")
             .agg(lat=("cell_lat", "first"), lon=("cell_lon", "first"),
                  n_pixels=("pixel_id", "size")).reset_index())
05c · Observation: Himawari-9 and GK2A

Two readers, one output format

Both ingests write the same columns (pixel_id, mir, win, cloud), so the rule engine never needs to know which satellite it reads. Only night slots (13:00–20:50 UTC) are processed.

Himawari-9 (segments)jobs/lib/himawari.py
import os, s3fs
from satpy import Scene
from jobs.lib.region import AREA

fs = s3fs.S3FileSystem(anon=True)
SEGMENTS = ("S0510", "S0610")              # ⚠️ checked in S0-7

def list_scan(slot):                       # slot: UTC datetime, multiple of 10 minutes
    d = f"noaa-himawari9/AHI-L1b-FLDK/{slot:%Y/%m/%d/%H%M}"
    return [f for f in fs.ls(d)
            if any(f"_{b}_" in f for b in ("B07", "B14"))
            and any(s in f for s in SEGMENTS)]      # 4 files

def read_scan(files, tmp):
    local = []
    for f in files:
        p = os.path.join(tmp, os.path.basename(f)); fs.get(f, p); local.append(p)
    scn = Scene(reader="ahi_hsd", filenames=local)  # .DAT.bz2 ⚠️
    scn.load(["B07", "B14"], calibration="brightness_temperature")
    g = scn.resample(AREA, resampler="nearest", radius_of_influence=5000)
    return g["B07"].values, g["B14"].values        # mir, win (445 × 545, K)
GK2A (full disk)jobs/lib/gk2a.py
import os, s3fs
from satpy import Scene
from jobs.lib.region import AREA

fs = s3fs.S3FileSystem(anon=True)
CHANNELS = ("sw038", "ir105")

def list_scan(slot):                       # archive starts 16 Feb 2023
    d = f"noaa-gk2a-pds/AMI/L1B/FD/{slot:%Y%m/%d/%H}"
    return [f"{d}/gk2a_ami_le1b_{ch}_fd020ge_{slot:%Y%m%d%H%M}.nc"
            for ch in CHANNELS]            # 2 files × ~30 MB

def read_scan(files, tmp):
    local = []
    for f in files:
        p = os.path.join(tmp, os.path.basename(f)); fs.get(f, p); local.append(p)
    scn = Scene(reader="ami_l1b", filenames=local)
    scn.load(["SW038", "IR105"], calibration="brightness_temperature")
    g = scn.resample(AREA, resampler="nearest", radius_of_influence=5000)
    for p in local: os.remove(p)           # do not keep the full disk
    return g["SW038"].values, g["IR105"].values
Shared thermal featuresjobs/lib/features.py
CLOUD_K = 270.0                              # window channel < 270 K = cloud

def to_features(mir, win, peat):
    r, c = peat.row.values, peat.col.values
    df = pd.DataFrame({"pixel_id": peat.pixel_id.values,
                       "mir": mir[r, c], "win": win[r, c]})
    df["cloud"] = (df.win < CLOUD_K) | df.win.isna()
    return df                                # → {sat}/YYYY/MM/DD/HHMM.parquet
05d · Baselines: NASA POWER and the thermal baseline

What "normal" looks like for each night hour

NASA POWER hourly data arrive ~1.5 days late and are coarse (0.5° × 0.625°), so they serve as a 30-day median per hour, not as tonight's value. There is no area endpoint for hourly data: one request per cell.

NASA POWERjobs/lib/power.py
URL = "https://power.larc.nasa.gov/api/temporal/hourly/point"

def fetch_cell(lat, lon, start, end):
    r = httpx.get(URL, timeout=120, params={
        "parameters": "TS,T2M", "community": "RE",
        "latitude": lat, "longitude": lon,
        "start": f"{start:%Y%m%d}", "end": f"{end:%Y%m%d}",
        "format": "JSON", "time-standard": "UTC"})
    p = r.json()["properties"]["parameter"]
    df = pd.DataFrame({"ts": p["TS"], "t2m": p["T2M"]}).replace(-999.0, np.nan)
    df.index = pd.to_datetime(df.index, format="%Y%m%d%H", utc=True)
    return df + 273.15                       # °C → K

def power_baseline(raw, as_of, days=30):     # raw: cell_id, time, ts, t2m
    w = raw[(raw.time > as_of - pd.Timedelta(days=days)) & (raw.time <= as_of)]
    w = w[w.time.dt.hour.isin(range(13, 21))]
    g = w.assign(hour_utc=w.time.dt.hour).groupby(["cell_id", "hour_utc"])
    return pd.DataFrame({"ts_base": g.ts.median(), "t2m_base": g.t2m.median(),
                         "n_days": g.ts.count()}).reset_index()
Thermal baseline and LST biasjobs/lib/baseline.py
def thermal_baseline(feats, as_of, nights=30, frozen_ids=(), prev=None):
    # feats: pixel_id, slot, mir, cloud from one satellite, 30 nights ≤ as_of
    f = feats[~feats.cloud].assign(hour_utc=feats.slot.dt.hour)
    g = f.groupby(["pixel_id", "hour_utc"]).mir
    base = pd.DataFrame({"median": g.median(),
                         "mad": g.apply(lambda x: (x - x.median()).abs().median()),
                         "n_obs": g.size()}).reset_index()
    base["frozen"] = base.pixel_id.isin(frozen_ids)
    if prev is not None:                     # WATCH/AWAS pixels keep the old rows
        base = pd.concat([base[~base.frozen],
                          prev[prev.pixel_id.isin(frozen_ids)].assign(frozen=True)])
    return base

def lst_bias(win_max, power, cells):
    # b_LST = 30-night median of (win_max − ts_base) per pixel per hour
    d = (win_max.merge(cells, on="pixel_id")
                .merge(power, on=["cell_id", "hour_utc"]))
    d["x"] = d.win_max - d.ts_base
    return d.groupby(["pixel_id", "hour_utc"]).x.median().rename("b_lst")
05e · Rule engine: MAUT + neighbour support

Pure functions, one dict for every number

The numbers are exactly Plan 05. Change only W, RAMP and T, then record it in WORKLOG section 7.

Utilityjobs/lib/maut.py
import numpy as np

W    = {"H": .25, "G": .25, "LST": .10, "SAT": .05, "T": .15, "N": .20}
RAMP = {"H": (2.0, 4.0), "G": (2.0, 4.0), "LST": (1.0, 4.0), "SAT": (0.0, 3.0)}

def ramp(x, a, b):
    return np.clip((x - a) / (b - a), 0.0, 1.0)   # NaN stays NaN

def attributes(zrel_h, zrel_g, d_lst, d_sat, k_nights):
    return {"H": ramp(zrel_h, *RAMP["H"]), "G": ramp(zrel_g, *RAMP["G"]),
            "LST": ramp(d_lst, *RAMP["LST"]), "SAT": ramp(d_sat, *RAMP["SAT"]),
            "T": np.minimum(k_nights / 3.0, 1.0)}

def weighted(u, keys):                    # weights normalised over available attributes
    num = sum(np.where(np.isnan(u[k]), 0, u[k]) * W[k] for k in keys)
    den = sum(np.where(np.isnan(u[k]), 0, W[k]) for k in keys)
    return np.where(den > 0, num / np.where(den > 0, den, 1), np.nan)

def u0(u):
    return weighted(u, ["H", "G", "LST", "SAT", "T"])

def utility(u, u_n):
    return weighted({**u, "N": u_n}, ["H", "G", "LST", "SAT", "T", "N"])
Neighboursjobs/lib/neighbours.py
def support(u0: pd.Series, nbr8: pd.DataFrame) -> pd.Series:
    # u0: index pixel_id; nbr8: pixel_id, neighbor_ids[]
    def one(ids):
        v = u0.reindex(ids).dropna()          # observed neighbours only
        return float((v >= 0.5).mean()) if len(v) else 0.0
    return pd.Series(nbr8.neighbor_ids.map(one).values, index=nbr8.pixel_id)
Statusjobs/lib/status.py
T = {"awas_u": 0.65, "awas_n": 0.25, "watch_u": 0.30}

def classify(U, u_n, agree, n_sat):
    return np.select(
        [n_sat == 0,
         (U >= T["awas_u"]) & (u_n >= T["awas_n"]) & agree,
         U >= T["watch_u"]],
        ["NO_OBSERVATION", "AWAS", "WATCH"], default="SAFE")
# agree = u_H ≥ 0.5 and u_G ≥ 0.5, each in ≥ 1 slot within 60 minutes
Order inside jobs/evaluate.py: read slot features → anomaly.zscore per satellite → ΔLST, ΔSAT → maut.attributes → u0 → neighbours.support → utility → status.classify → write score/ → cluster.label → POST /verify for new clusters.
06 · ADK agent

On-demand verification; limits live in the tool layer

✅ ADK built-in loop, called per AWAS cluster. Output goes through save_verification, which validates the schema; there is no status or level field.

Agent definitionagent/agent.py
from google.adk.agents import Agent

INSTRUCTION = """
You verify AWAS thermal anomalies on Indonesian peatland.
The rule engine has already identified the coordinate as AWAS.
Your task is verification, not detection.
1. Read the candidate context (get_pixel_context).
2. Retrieve the latest VIIRS detections around the coordinate
   (get_latest_viirs).
3. Retrieve the latest VIIRS true-colour image (fetch_viirs_image)
   and a Himawari image of the same area (fetch_himawari_image).
4. Look for visible smoke or other visual evidence consistent
   with smouldering or fire activity near the marker.
5. result = strong_evidence if smoke is visible within 5 km, or
   get_latest_viirs reports within_2km > 0. Otherwise inconclusive.
   Absence of visible smoke is never a negative.
6. Never change the rule-engine status. Every number in your
   summary must come from a tool result.
7. Finish with save_verification.
"""

verifier = Agent(
    name="asapify_verifier",
    model=os.environ["GEMINI_MODEL"],
    instruction=INSTRUCTION,
    tools=[get_pixel_context, get_latest_viirs, fetch_viirs_image,
           fetch_himawari_image, save_verification],
)
Schema and guardrailsagent/schema.py
class Evidence(BaseModel):
    source: Literal["rule_engine", "viirs_firms",
                    "viirs_image", "himawari_image"]
    finding: str = Field(max_length=200)      # Indonesian
    finding_en: str = Field(max_length=200)   # the same finding for the English UI
    observed_at: str | None = None
    age_h: float | None = None

class Verification(BaseModel):
    model_config = ConfigDict(extra="forbid")
    cluster_id: str
    pixel_id: str
    result: Literal["strong_evidence", "inconclusive"]
    smoke_visible: bool | None
    viirs_within_2km_48h: int = Field(ge=0)
    evidence: list[Evidence] = Field(min_length=1)
    summary_id: str = Field(max_length=500)
    summary_en: str = Field(max_length=500)
    # no status or level field

MAX_TOOL_CALLS = 8

def save_verification(result: dict) -> dict:
    """Validate schema + rules:
    - viirs_within_2km_48h must equal the get_latest_viirs result
    - viirs_within_2km_48h > 0  →  result must be strong_evidence
    - every number in summary_* exists in a tool result
    Return {"ok": true} or {"ok": false, "errors": [...]}"""
VIIRS from FIRMS (on demand)agent/tools/viirs.py
FIRMS = "https://firms.modaps.eosdis.nasa.gov/api/area/csv/{k}/{src}/{w},{s},{e},{n}/{days}"
SATS = ("VIIRS_SNPP", "VIIRS_NOAA20", "VIIRS_NOAA21")

def get_latest_viirs(lat: float, lon: float, as_of: str,
                     radius_km: float = 10, hours: int = 48) -> dict:
    t = parse_utc(as_of); d = radius_km / 111
    recent = (now_utc() - t).days <= 7          # NRT; otherwise the SP archive
    rows = []
    for sat in SATS:
        src = f"{sat}_NRT" if recent else f"{sat}_SP"
        url = FIRMS.format(k=MAP_KEY, src=src, w=lon-d, s=lat-d, e=lon+d, n=lat+d, days=2)
        if not recent:
            url += f"/{t - timedelta(days=1):%Y-%m-%d}"   # ⚠️ meaning of the date: S0-6
        try: rows.append(read_csv(cached_get(url)).assign(src=src))
        except SourceUnavailable: continue       # e.g. NOAA21 SP not available yet
    df = pd.concat(rows)
    df["time_utc"] = to_utc(df.acq_date, df.acq_time)
    df = df[(df.time_utc > t - timedelta(hours=hours)) & (df.time_utc <= t)]
    df["distance_km"] = haversine(lat, lon, df.latitude, df.longitude)
    df = df[df.distance_km <= radius_km].sort_values("distance_km")
    return {"detections": df[["src", "time_utc", "daynight", "confidence",
                              "frp", "distance_km"]].to_dict("records"),
            "within_2km": int((df.distance_km <= 2).sum())}
VIIRS image from GIBSagent/tools/viirs_image.py
GIBS = "https://gibs.earthdata.nasa.gov/wms/epsg4326/best/wms.cgi"
LAYERS = [f"{s}_CorrectedReflectance_TrueColor"
          for s in ("VIIRS_NOAA21", "VIIRS_NOAA20", "VIIRS_SNPP")]

def fetch_viirs_image(lat: float, lon: float, as_of: str,
                      half_deg: float = 0.2) -> dict:
    t = parse_utc(as_of)
    for back in range(0, 4):                     # WIB date of as_of, back ≤ 3 days
        day = (t + timedelta(hours=7)).date() - timedelta(days=back)
        for layer in LAYERS:
            r = httpx.get(GIBS, timeout=60, params={
                "SERVICE": "WMS", "REQUEST": "GetMap", "VERSION": "1.3.0",
                "LAYERS": layer, "CRS": "EPSG:4326",
                "BBOX": f"{lat-half_deg},{lon-half_deg},{lat+half_deg},{lon+half_deg}",
                "WIDTH": 512, "HEIGHT": 512, "FORMAT": "image/jpeg",
                "TIME": f"{day:%Y-%m-%d}"})
            img = Image.open(io.BytesIO(r.content))
            if np.asarray(img).std() < 3: continue    # blank / no data
            png = draw_marker(img, radius_km=5)       # dot + 5 km circle
            path = save_crop(png, pixel_id, t, "viirs")
            return {"path": path, "signed_url": sign(path, hours=1),
                    "layer": layer, "date": str(day),
                    "age_h": hours_since(day, local_time="13:30", tz="+07:00", now=t)}
    return {"none": True, "reason": "no image in the last 3 days"}
06b · Telegram bot and subscriber channels ✅

A group for operators, DMs for subscribers

Plain HTTP to the Bot API (httpx), no bot framework. asapify-agent sends the verification summary to the operator group. Published alerts no longer go to provincial groups: asapify-api writes an inbox entry for every subscriber who chose that province, and the asapify-notify worker sends a text Telegram DM (team decision of 9 Oct, code in ktp-asapify-be).

Subscriber DM (worker)asapify_api/notification_delivery.py
TG = f"https://api.telegram.org/bot{TOKEN}"

r = client.post(f"{TG}/sendMessage", json={
    "chat_id": profile["telegram_chat_id"],
    "text": text_message(inbox),     # plain text, HTML stripped
    "link_preview_options": {"is_disabled": True},
    "reply_markup": {"inline_keyboard": [[{
        "text": "Buka & konfirmasi diterima",
        "url": f"{ORIGIN}/notifikasi?open={inbox['id']}"}]]}})
# ok + message_id   → accepted (not "read")
# 4xx               → failed
# timeout / 5xx     → unknown, never resent automatically
Linking an account to Telegramflow
# 1. web: POST /notifications/telegram-link
#    → t.me/<bot>?start=<code> (10 min, single use)
# 2. the subscriber presses Start in the bot
# 3. Telegram → POST /notifications/telegram-webhook
#    secret token header; private chats only
# 4. the API stores chat_id on the subscriber profile

curl -s "https://api.telegram.org/bot$TOKEN/setWebhook" \
  -d url="https://<HOSTING>/api/v1/notifications/telegram-webhook" \
  -d secret_token="$WEBHOOK_SECRET" \
  -d allowed_updates='["message"]'
The webhook only links accounts: it never replies and never takes a chat target from the browser. The operator group still uses sendPhoto with a chat_id recorded once.
FCM / Web Push is for exercises and non-emergency messages only: FCM policy forbids emergency use, so real AWAS alerts are blocked at three layers (planning, claiming, adapter). WhatsApp, SMS, email, LoRa and Bluetooth are stored as choices and do not send yet.
07 · Jobs

Steps inside each job

asapify-ingest-himawari / -gk2a · */10 at night
  1. Pick the slot: AS_OF rounded down to a multiple of 10 minutes; process that slot + any missing night slot from the last 60 minutes. Outside 13:00–20:50 UTC: exit without action.
  2. list_scan(slot); if files are incomplete, record it in runs (pending) and exit. The next cycle retries.
  3. read_scan → 0.02° grid → to_features (peat pixels only).
  4. Write {sat}/YYYY/MM/DD/HHMM.parquet (idempotent: overwrite) and the source file manifest in raw/{sat}/manifest/.
  5. Record latency (slot time vs the file's LastModified) in runs.
asapify-evaluate · minutes 5, 15, … at night
  1. Pick the latest slot where both satellites are present; if one satellite is > 40 minutes late, run with one satellite (n_sat = 1). Skip slots already in runs.
  2. Read the latest thermal baseline, LST bias and POWER from environment/.
  3. Compute z, ΔLST, ΔSAT, attributes, U0, u_N, U, status (05e). Write score/.
  4. Label AWAS clusters (cluster.label), update clusters, close clusters without AWAS for 3 valid nights, then POST $AGENT_URL/cluster-closed so any published alert is marked SELESAI.
  5. For new clusters, or when the last verification is > 6 h old: POST $AGENT_URL/verify with an OIDC token.
asapify-environment · daily 12:00 WIB
  1. For each cell in peat/power_cells.parquet: request the days missing from raw/power/{cell_id}.parquet (0.2 s pause between requests).
  2. power_baseline → environment/power/YYYYMMDD.parquet.
  3. thermal_baseline per satellite from 30 nights of himawari/ and gk2a/; WATCH/AWAS pixels are frozen.
  4. lst_bias → environment/bias/YYYYMMDD.parquet.
asapify-build · once
  1. build_built_frac (Earth Engine WorldCover).
  2. build_peat_mask (BIG KHG + provinces + built_frac).
  3. build_neighbors (8 directions, radius 5) and build_power_cells.

The backtest backfill uses the same image and ingest code: python -m jobs.backfill --sat … --start … --end … --step 10|20 --night-only, run as an 8-task Cloud Run job.

08 · Repo

Monorepo layout

Monorepoasapify/
asapify/
├─ WORKLOG.md, Dockerfile, .gcloudignore, requirements.lock
├─ infra/ env.sh, set_role.py, lifecycle.json
├─ shared/ telegram.py, auth.py, storage.py      # used by agent and api
├─ agent/                    # Cloud Run service asapify-agent
│  ├─ main.py (POST /verify), agent.py, schema.py, validator.py, run.py, evaluate.py
│  ├─ tools/ context.py, viirs.py, viirs_image.py, himawari_image.py
│  └─ tests/ test_viirs.py, test_viirs_image.py, test_validator.py
├─ api/                      # Cloud Run service asapify-api
│  ├─ main.py
│  └─ routers/ public.py, operator.py
├─ jobs/                     # Cloud Run jobs, one image
│  ├─ ingest.py (--sat himawari|gk2a), evaluate.py, environment.py   # scheduled
│  ├─ build_all.py, build_built_frac.py, build_peat_mask.py,
│  │  build_neighbors.py, build_power_cells.py                       # once
│  ├─ backfill.py, replay.py, calibrate.py                           # backtest
│  ├─ lib/ region.py, himawari.py, gk2a.py, features.py, power.py, baseline.py,
│  │       anomaly.py, maut.py, neighbours.py, status.py, cluster.py
│  └─ tests/ test_features.py, test_himawari.py, test_gk2a.py, test_power.py,
│            test_baseline.py, test_maut.py, test_status.py, test_cluster.py
├─ notebooks/ backtest.ipynb   # lead time: first VIIRS − first AWAS
├─ scripts/ e2e.sh
├─ data/ref/                   # KHG, provinces, built_frac (no secrets)
├─ data/local/                 # raw, not committed
├─ docs/                       # proof of done: png, csv, log
└─ (web app in the ktp-asapify-fe repo: React 19 + Vite + MapLibre 6)

This is the planned monorepo. What is built so far lives in the team repo ktp-asapify-be: asapify_api/ (operator API + Notification Engine), gcp/ (deploy scripts), tools/ (publish snapshot, set operator); the pipeline and agent are still experimental.

09 · Errors

What happens when something fails

EventBehaviour
One satellite's scan is not available yetIngest exits without action; evaluate waits up to 40 minutes, then runs with one satellite (n_sat = 1, AWAS impossible).
Both satellites missing or corruptEvery pixel is NO_OBSERVATION for that slot; recorded in runs.
NASA POWER fails / is lateEnvironment uses the latest available POWER baseline (max 3 days); older than that → u_LST and u_SAT are dropped (NaN) and the weights are normalised.
FIRMS or GIBS failsThe tool returns an error; the agent continues with the evidence it has and the result is inconclusive, noting the failed source.
Gemini fails or the tool limit is reachedThe verification is saved as inconclusive with validator_failed / tool_limit; the operator can request re-verification.
Two operators decide at the same timeFirestore transaction; the second gets 409 ALREADY_DECIDED and the web app shows the decision already saved.
Archive night without data/operator/nights sends has_data = false (a faded date in the calendar); /operator/grid/night sends every slot as null and the web app shows every pixel as unobserved with a banner.
A send fails or is uncertain (429, network, worker died)The decision and inbox stay saved. 4xx = failed; a timeout or a worker dying after the claim = unknown, never resent automatically. The operator sees per-channel status at /deliveries.