Backend & API · pegangan Peran A, B, C · arsitektur revisi 29 Sep · API disamakan dengan web 6 Okt · notifikasi pelanggan 9 Okt

Lima job deterministik, dua service

Observasi (Himawari-9, GK2A), baseline (NASA POWER + baseline termal), dan rule engine (MAUT + neighbour support) berjalan sebagai Cloud Run job. Agen ADK tinggal di service asapify-agent dan hanya dipanggil untuk kelompok AWAS; ia mengambil VIIRS saat itu juga (on-demand). Service asapify-api melayani web operator dan pelanggan; setelah operator menerbitkan, pesan masuk ke inbox dan DM Telegram pelanggan provinsi itu lewat worker asapify-notify. Kode di halaman ini 💡 titik awal; bagian ⚠️ dicek di Sprint 0.

01 · Siapa membaca dan menulis apa

Tujuh komponen, satu image

Gambar sambungannya ada di Rencana 03 (skematik B). Tabel ini untuk dipegang saat menulis kode.

KomponenPemicuMembacaMenulisMemanggil
asapify-build (job)manual, sekaliBIG 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/ (piksel beku)environment/power/, environment/thermal/, environment/bias/, raw/power/—
asapify-evaluate (job)Scheduler 5-59/10 20-23,0-4himawari/, gk2a/, environment/, peat/, score/ 3 malamscore/…/HHMM.parquet, Firestore clusters, runsasapify-agent: POST /verify (hanya AWAS), POST /cluster-closed
asapify-agent (service, privat)POST dari evaluate atau apiclusters, score/, NASA FIRMS, NASA GIBS, NOAA Himawaricrops/, raw/firms/, verifications, alerts.status (tutup), audit_logGemini, Telegram (grup operator)
asapify-api (service)request web operator dan pelanggan; webhook Telegramscore/ (grid), clusters, verifications, notification_recipientsalerts, audit_log, notification_inbox, notification_jobsCloud Tasks (antrean kirim), asapify-agent (verifikasi ulang)
asapify-notify (service, privat)Cloud Tasks (satu task per job), Scheduler sweep tiap menitnotification_jobs, notification_inbox, notification_recipientsstatus job, notification_inbox (fan-out lanjutan)Telegram (DM pelanggan), FCM (push simulasi)
02 · Konvensi

Berlaku di semua job dan endpoint

Base path
API operator: /api/v1, lewat Firebase Hosting (satu origin dengan web). Agen: /verify di URL Cloud Run privat.
Format
JSON UTF-8, koordinat [lon, lat]. Peta web memakai format ringkas: indeks piksel statis sekali (/operator/pixels), lalu satu huruf status per sel (S, N, W, A). Untuk 10 ribu sel ≈ 23 KB mentah / 11 KB gzip, dibanding GeoJSON ≈ 1,9 MB / 83 KB. GeoJSON titik tetap tersedia (format=geojson, default) untuk alat lain.
Waktu
ISO 8601. Simpan UTC, tampilkan WIB. slot = waktu scan 10 menit UTC.
ID
piksel p{row}_{col} di grid 0,02° Sumatra + Kalimantan (1.225 × 620, asal 94,9° BT / 6,2° LU, baris 0 di utara); kelompok C-{MMDD}-{nnn}; verifikasi {cluster_id}_{slot:%Y%m%dT%H%M}
Status
SAFE, NO_OBSERVATION, WATCH, AWAS (huruf besar, persis)
Auth operator
Firebase ID token, claim role = "operator"
Auth pelanggan
Firebase ID token akun Google dengan email terverifikasi, tanpa role. Hanya untuk /notifications/*; tidak membuka peta atau keputusan
Auth internal
OIDC dari sa-jobs atau sa-api ke asapify-agent (Cloud Run IAM run.invoker)
Replay
job: --as-of atau env AS_OF; endpoint: as_of; header respons X-Asapify-As-Of
Galat
{"error": {"code": "...", "message": "..."}}. code stabil; web menulis pesannya sendiri dari code dalam bahasa operator (EN/ID). message (Bahasa Indonesia) hanya tampil bila code belum dikenal web.
Bahasa
Teks agen dikirim dua bahasa (finding + finding_en, summary_id + summary_en) supaya layar tidak mencampur bahasa. Teks pesan peringatan (inbox dan DM Telegram) tetap Bahasa Indonesia.
03 · Endpoint

asapify-api dan asapify-agent

MetodePathAuthFungsi
asapify-api · umum (setelah /api/v1)
GET/health, /metapublikcek hidup; slot terakhir per satelit, malam/siang, status replay, rentang malam arsip yang bisa dibuka (nights.first–nights.last)
asapify-api · operator
GET/operator/pixelsoperatorindeks piksel gambut statis: version, asal grid, langkah 0,02°, baris, kolom, dan kode provinsi per sel. Urutannya menjadi indeks sel di semua respons ringkas. Diunduh sekali; kirim ETag + Cache-Control
GET/operator/grid?as_of=, &format=compactoperatorstatus semua piksel gambut untuk slot malam terakhir ≤ as_of. Default GeoJSON titik (status, utility, n_sat, cluster_id, province). format=compact (dipakai web): string status satu huruf per sel, utility base64 Uint8 (round(U × 250), 255 = null), dan kelompok aktif → indeks sel
GET/operator/grid/night?night=operator54 string status (format ringkas) untuk satu malam, 20.00–04.50 WIB, plus kelompok yang AWAS di salah satu slot malam itu → indeks sel. Satu permintaan untuk pemutar slot dan malam arsip. Slot setelah as_of atau tanpa data = null
GET/operator/nights?month=operatorsatu baris per malam arsip dalam bulan itu: night, has_data, awas_clusters. Mengisi kalender malam (tanggal pudar = tanpa data, titik = ada kelompok AWAS)
GET/operator/basemaps?as_of=operatorpilihan peta dasar raster dari BE, mis. citra VIIRS true colour NASA GIBS tanggal as_of (template tile, ukuran tile, zoom maksimum, atribusi, label ID/EN). Array kosong = hanya peta jalan dan polos
GET/operator/clusters?state=active, ?night=operatordaftar kelompok AWAS + hasil verifikasi terakhir + keputusan. Dengan night=YYYY-MM-DD (malam arsip): kelompok yang AWAS di salah satu slot malam itu, aktif maupun ditutup (first_awas_at ≤ akhir malam dan last_awas_at ≥ awal malam); state diabaikan
GET/operator/clusters/{id}operatorderet utility 3 malam, atribut MAUT slot pemicu beserta angka terukurnya (attribute_details), grid tetangga, verifikasi + jejak tool, signed URL citra dengan bbox crop, dan suhu kecerahan per sel di balik citra termal (images[].thermal)
POST/operator/clusters/{id}/verifyoperatorminta verifikasi ulang; diteruskan ke agen (hormati 6 jam kecuali force=true)
POST/operator/clusters/{id}/decisionoperatorpublish (teks pesan; keputusan, audit dan alert tersimpan dulu, lalu inbox dan antrean ditulis per pelanggan provinsi itu, 50 per batch; jumlah pelanggan tidak pernah menggagalkan keputusan) / reject (alasan wajib)
GET/operator/alerts?status=operatorperingatan terbit + ringkasan antrean
POST/operator/alerts/{id}/closeoperatortutup lebih awal oleh operator: inbox berlabel SELESAI, job yang belum terkirim batal (otomatis lewat agent /cluster-closed saat kelompok ditutup)
GET/operator/alerts/{id}/deliveriesoperatorstatus kirim per kanal per pelanggan (pending, sending, accepted, failed, unknown, blocked, cancelled, simulated) + waktu konfirmasi penerima. accepted = diterima penyedia, belum berarti dibaca ✅
asapify-api · pelanggan (akun Google dengan email terverifikasi, tanpa role)
GET/notifications/settingspenggunapreferensi (provinsi, kanal, persetujuan, simulasi), Telegram tertaut / perangkat push terdaftar, daftar kanal beserta status aktif, mode dry_run / live ✅
PUT/notifications/preferencespenggunabody {provinces, channels, consent, exercises}; consent = true wajib minimal satu provinsi; berhenti berlangganan = consent = false ✅
POST/notifications/device, DELETEpenggunadaftar / lepas satu token push (FCM, termasuk Web Push) per akun ✅
POST/notifications/telegram-linkpenggunadeep link t.me/<bot>?start=<kode> sekali pakai, berlaku 10 menit; hanya hash kode yang disimpan ✅
GET/notifications/inboxpengguna50 pesan terakhir milik akun: teks, provinsi, purpose (emergency / exercise), published_at, expires_at, acknowledged_at ✅
POST/notifications/inbox/{id}/ackpenggunakonfirmasi diterima; idempoten; ID milik akun lain → 404. Membuka tautan saja tidak dihitung konfirmasi ✅
POST/notifications/telegram-webhooksecret Telegramdipanggil Telegram, bukan browser. Header X-Telegram-Bot-Api-Secret-Token; hanya menerima /start <kode> dari chat privat untuk menautkan akun; tidak membalas ✅
bucket publik · file statis untuk lapisan peta (bukan endpoint)
FILElayers/peat_pixels.geojsonpublikbatas gambut yang diproses (KHG ∩ 15 provinsi − area terbangun), disederhanakan; ditulis asapify-build
FILElayers/provinces.geojsonpublik15 provinsi Sumatra + Kalimantan (kode BPS, nama), disederhanakan ±90 KB (±30 KB gzip); dipakai garis provinsi dan sorotan provinsi terpilih. geoBoundaries IDN ADM1, ODbL
asapify-agent · internal (URL Cloud Run privat)
POST/verifyOIDC sa-jobs / sa-apibody {"cluster_id", "trigger_slot", "force": false}; jalankan agen, simpan verifications, kirim ke grup operator. Respons 202 + verification_id
POST/cluster-closedOIDC sa-jobsbody {"cluster_id"}; kode deterministik (tanpa Gemini): bila ada alert terbit untuk kelompok itu, set alerts.status = closed, beri label SELESAI di inbox, batalkan job yang belum terkirim
asapify-notify · internal (URL Cloud Run privat, image yang sama dengan asapify-api)
POST/_internal/notifications/dispatchOIDC sa-taskbody {"job_id"} dari Cloud Tasks: klaim satu job, cek ulang persetujuan, konfirmasi dan masa berlaku, kirim, simpan status. Timeout = unknown, tidak dikirim ulang otomatis ✅
POST/_internal/notifications/sweepOIDC sa-taskCloud Scheduler tiap menit: lanjutkan fan-out yang terputus (alerts.fanout = pending), antrekan ulang job pending, tandai sending > 5 menit sebagai unknown ✅

Skema lengkap tiap respons (field, tipe, wajib, contoh JSON) ada di tab Kontrak API aplikasi web (/kontrak-api, publik, EN/ID). Contoh di sana diambil dari data mock yang sama dengan yang tampil di layar.

04 · Contoh

Bentuk data yang disepakati

Data fiktif.

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…",   # satu huruf per sel, urutan /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
}
Respons201
{ "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} }
Galat · 409response
{ "error": { "code": "ALREADY_DECIDED",
  "message": "Kelompok ini sudah diterbitkan oleh operator lain." } }
05 · Model data

Deret waktu di Storage, keputusan di Firestore

Cloud Storage (Parquet, kecuali disebut lain)
PathIsi
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}.pngcitra VIIRS dan Himawari untuk agen dan UI; PNG termal memakai skala warna tetap kanal panas 270–340 K (sama dengan legenda web)
crops/{pixel_id}/{timestamp}_thermal.jsonsuhu kecerahan per sel 0,02° di balik crop termal: bbox, 20 × 20 sel, kanal B07/B14 (Himawari) dan SW038/IR105 (GK2A), kelvin 1 desimal, null = berawan. Disajikan sebagai images[].thermal ⚠️
raw/{source}/…manifest file sumber per slot (JSON), cache POWER per sel, cache FIRMS per kotak
layers/*.geojson (bucket publik)peat_pixels.geojson dan provinces.geojson untuk lapisan peta web; dibaca browser langsung (CORS)
Firestore
KoleksiIsi
clusterspixels, rep_pixel, centroid, province, utility_max, neighbour_support, first_awas_at, last_awas_at, last_verified_at, state (active/closed)
verificationsoutput agen schema-locked, jejak tool, 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 pelanggan (ID = hash UID): provinsi, kanal, consent, exercises, Telegram chat_id dan token push (tidak pernah dikirim ke browser)
notification_inboxsatu dokumen per alert × pelanggan: teks, provinsi, purpose, expires_at (1 jam), acknowledged_at
notification_jobsoutbox per kanal: status, error, attempts, not_before, provider_id; ID deterministik, hanya di-create
notification_devices, notification_telegram_chatspemilik token push / chat Telegram, agar satu perangkat atau chat tidak tertaut ke dua akun
runslog tiap eksekusi job: slot, n_sat, jumlah per status, latensi, file hilang
audit_logsetiap aksi operator, panggilan agen, dan pesan bot
05b · Wilayah Sumatra + Kalimantan ✅

Satu grid, lima belas provinsi, hanya piksel gambut

Semua job, backtest, dan UI memakai konstanta yang sama dari jobs/lib/region.py.

Konstanta wilayahjobs/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 (asal grid 94,9 BT / 6,2 LU)
BACKTEST_BBOX = (113.5, -2.6, 114.3, -1.9)  # sub-area Kalteng (utama)
BACKTEST_BBOX_SUMSEL = (105.2, -3.7, 106.0, -3.0)  # OKI, Sumsel (direncanakan)
GRID_DEG = 0.02                             # 1.225 kolom × 620 baris
NIGHT_UTC = range(13, 21)                   # 20.00–04.00 WIB (Sumatra juga WIB)

PROVINCES = {                               # kode BPS
    "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}"                  # baris 0 = utara

Kenapa bbox saja tidak cukup

  • Kotak MONITOR_BBOX ikut mencakup Semenanjung Malaysia, Singapura, Sarawak, Sabah, Brunei, ujung barat Jawa, dan sebagian pantai Sulawesi Barat.
  • KHG hanya berisi Indonesia, jadi Malaysia, Singapura, dan Brunei otomatis keluar. Jawa dan Sulawesi dikeluarkan dengan filter provinsi (kode 11–19, 21, 61–65).
  • Kolom province per piksel juga menentukan pelanggan yang menerima peringatan (pelanggan memilih provinsi).
Grid penuh
1.225 × 620 = ~760 ribu sel
Piksel gambut
perkiraan kasar ~20–25 ribu ⚠️ (hitung di A1)
Sel NASA POWER
0,5° × 0,625°; perkiraan 250–400 sel berisi gambut ⚠️
Per slot
2 file Parquet kecil (ratusan KB), 1 per satelit
Peat mask: KHG + provinsi + terbangunjobs/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:                                 # maks 1.000 fitur/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):                      # fraksi luas per sel 0,02°
    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 provinsi, 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")
Fraksi terbangun (sekali)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"))
Tetangga + sel POWER (sekali)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 arah; k=5 → radius 5 sel
    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")

# sel NASA POWER (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 · Observasi: Himawari-9 dan GK2A

Dua pembaca, satu format keluaran

Kedua ingest menulis kolom yang sama (pixel_id, mir, win, cloud), jadi rule engine tidak perlu tahu satelit mana yang dibaca. Hanya slot malam (13.00–20.50 UTC) yang diproses.

Himawari-9 (segmen)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")              # ⚠️ dicek di S0-7

def list_scan(slot):                       # slot: datetime UTC, kelipatan 10 menit
    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 file

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):                       # arsip mulai 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 file × ~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)           # jangan simpan full disk
    return g["SW038"].values, g["IR105"].values
Fitur termal bersamajobs/lib/features.py
CLOUD_K = 270.0                              # kanal jendela < 270 K = awan

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 · Baseline: NASA POWER dan baseline termal

Yang "normal" untuk tiap jam malam

NASA POWER hourly terlambat ~1,5 hari dan kasar (0,5° × 0,625°), jadi dipakai sebagai median 30 hari per jam, bukan nilai malam ini. Tidak ada endpoint wilayah untuk data jam-an: satu request per sel.

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()
Baseline termal dan bias LSTjobs/lib/baseline.py
def thermal_baseline(feats, as_of, nights=30, frozen_ids=(), prev=None):
    # feats: pixel_id, slot, mir, cloud dari satu satelit, 30 malam ≤ 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:                     # piksel WATCH/AWAS pakai baris lama
        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 = median 30 malam dari (win_max − ts_base) per piksel per jam
    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

Fungsi murni, satu dict untuk semua angka

Angka persis Rencana 05. Ubah hanya di W, RAMP, dan T, lalu catat di WORKLOG bagian 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 tetap 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):                    # bobot dinormalisasi atas atribut ada
    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"])
Tetanggajobs/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()          # hanya tetangga teramati
        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 dan u_G ≥ 0,5, masing-masing ≥ 1 slot dalam 60 menit
Urutan di jobs/evaluate.py: baca fitur slot → anomaly.zscore per satelit → ΔLST, ΔSAT → maut.attributes → u0 → neighbours.support → utility → status.classify → tulis score/ → cluster.label → POST /verify untuk kelompok baru.
06 · Agen ADK

Verifikasi on-demand; batas di lapisan tool

✅ Built-in loop ADK, dipanggil per kelompok AWAS. Output lewat save_verification yang memvalidasi skema; tidak ada field status atau level.

Definisi agenagent/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],
)
Skema dan pagaragent/schema.py
class Evidence(BaseModel):
    source: Literal["rule_engine", "viirs_firms",
                    "viirs_image", "himawari_image"]
    finding: str = Field(max_length=200)      # Bahasa Indonesia
    finding_en: str = Field(max_length=200)   # temuan yang sama untuk UI bahasa Inggris
    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)
    # tidak ada field status atau level

MAX_TOOL_CALLS = 8

def save_verification(result: dict) -> dict:
    """Validasi skema + aturan:
    - viirs_within_2km_48h harus sama dengan hasil get_latest_viirs
    - viirs_within_2km_48h > 0  →  result wajib strong_evidence
    - setiap angka di summary_* ada di hasil tool
    Kembalikan {"ok": true} atau {"ok": false, "errors": [...]}"""
VIIRS dari 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; selain itu arsip SP
    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}"   # ⚠️ arti tanggal: S0-6
        try: rows.append(read_csv(cached_get(url)).assign(src=src))
        except SourceUnavailable: continue       # mis. NOAA21 SP belum ada
    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())}
Citra VIIRS dari 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):                     # tanggal WIB as_of, mundur ≤ 3 hari
        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    # kosong / tanpa data
            png = draw_marker(img, radius_km=5)       # titik + lingkaran 5 km
            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": "tidak ada citra 3 hari terakhir"}
06b · Bot Telegram dan kanal pelanggan ✅

Grup untuk operator, DM untuk pelanggan

HTTP langsung ke Bot API (httpx), tanpa framework bot. asapify-agent mengirim ringkasan verifikasi ke grup operator. Peringatan yang diterbitkan tidak lagi dikirim ke grup provinsi: asapify-api menulis inbox per pelanggan yang memilih provinsi itu, lalu worker asapify-notify mengirim DM Telegram teks (keputusan tim 9 Okt, kode di ktp-asapify-be).

DM pelanggan (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),     # teks polos, HTML dibuang
    "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 (bukan "dibaca")
# 4xx               → failed
# timeout / 5xx     → unknown, tidak dikirim ulang otomatis
Menautkan akun ke Telegramalur
# 1. web: POST /notifications/telegram-link
#    → t.me/<bot>?start=<kode> (10 menit, sekali pakai)
# 2. pelanggan menekan Start di bot
# 3. Telegram → POST /notifications/telegram-webhook
#    header secret token; hanya chat privat
# 4. API menyimpan chat_id di profil pelanggan

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"]'
Webhook hanya untuk menautkan akun: tidak membalas pesan dan tidak menerima tujuan chat dari browser. Grup operator tetap memakai sendPhoto dengan chat_id yang dicatat sekali.
FCM / Web Push hanya untuk simulasi dan pesan non-darurat: kebijakan FCM melarang pemakaian darurat, jadi peringatan AWAS sungguhan diblokir di tiga lapis (rencana, klaim, adapter). WhatsApp, SMS, email, LoRa, dan Bluetooth tersimpan sebagai pilihan dan belum mengirim.
07 · Job

Langkah di setiap job

asapify-ingest-himawari / -gk2a · */10 malam
  1. Tentukan slot: AS_OF dibulatkan ke bawah ke kelipatan 10 menit; proses slot itu + slot malam yang belum ada dalam 60 menit terakhir. Di luar 13.00–20.50 UTC: selesai tanpa aksi.
  2. list_scan(slot); bila file belum lengkap, catat di runs (pending) dan selesai. Siklus berikutnya mencoba lagi.
  3. read_scan → grid 0,02° → to_features (hanya piksel gambut).
  4. Tulis {sat}/YYYY/MM/DD/HHMM.parquet (idempoten: tulis ulang) dan manifest file sumber di raw/{sat}/manifest/.
  5. Catat latensi (waktu slot vs LastModified file) di runs.
asapify-evaluate · menit 5, 15, … malam
  1. Pilih slot terbaru yang kedua satelitnya ada; bila satu satelit terlambat > 40 menit, jalan dengan satu satelit (n_sat = 1). Lewati slot yang sudah ada di runs.
  2. Baca baseline termal, bias LST, dan POWER terbaru dari environment/.
  3. Hitung z, ΔLST, ΔSAT, atribut, U0, u_N, U, status (05e). Tulis score/.
  4. Label kelompok AWAS (cluster.label), perbarui clusters, tutup kelompok tanpa AWAS 3 malam valid lalu POST $AGENT_URL/cluster-closed agar alert yang pernah diterbitkan ditandai SELESAI.
  5. Untuk kelompok baru atau verifikasi terakhir > 6 jam: POST $AGENT_URL/verify dengan token OIDC.
asapify-environment · harian 12.00 WIB
  1. Untuk tiap sel di peat/power_cells.parquet: minta hari yang belum ada di raw/power/{cell_id}.parquet (jeda 0,2 detik antar request).
  2. power_baseline → environment/power/YYYYMMDD.parquet.
  3. thermal_baseline per satelit dari 30 malam himawari/ dan gk2a/; piksel WATCH/AWAS dibekukan.
  4. lst_bias → environment/bias/YYYYMMDD.parquet.
asapify-build · sekali
  1. build_built_frac (Earth Engine WorldCover).
  2. build_peat_mask (KHG BIG + provinsi + built_frac).
  3. build_neighbors (8 arah, radius 5) dan build_power_cells.

Backfill backtest memakai image dan kode ingest yang sama: python -m jobs.backfill --sat … --start … --end … --step 10|20 --night-only, dijalankan sebagai Cloud Run job 8 task.

08 · Repo

Struktur monorepo

Monorepoasapify/
asapify/
├─ WORKLOG.md, Dockerfile, .gcloudignore, requirements.lock
├─ infra/ env.sh, set_role.py, lifecycle.json
├─ shared/ telegram.py, auth.py, storage.py      # dipakai agent dan 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, satu image
│  ├─ ingest.py (--sat himawari|gk2a), evaluate.py, environment.py   # terjadwal
│  ├─ build_all.py, build_built_frac.py, build_peat_mask.py,
│  │  build_neighbors.py, build_power_cells.py                       # sekali
│  ├─ 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: VIIRS pertama − AWAS pertama
├─ scripts/ e2e.sh
├─ data/ref/                   # KHG, provinsi, built_frac (tanpa rahasia)
├─ data/local/                 # mentah, tidak di-commit
├─ docs/                       # bukti selesai: png, csv, log
└─ (web di repo ktp-asapify-fe: React 19 + Vite + MapLibre 6)

Rancangan monorepo. Yang sudah dibangun ada di repo tim ktp-asapify-be: asapify_api/ (API operator + Notification Engine), gcp/ (skrip deploy), tools/ (publish snapshot, set operator); pipeline dan agen masih eksperimen.

09 · Galat

Yang terjadi saat sesuatu gagal

KejadianPerilaku
Scan satu satelit belum tersediaIngest selesai tanpa aksi; evaluate menunggu sampai 40 menit, lalu jalan dengan satu satelit (n_sat = 1, AWAS tidak mungkin).
Kedua satelit hilang atau rusakSemua piksel NO_OBSERVATION untuk slot itu; tercatat di runs.
NASA POWER gagal / terlambatEnvironment memakai baseline POWER terakhir yang ada (maks 3 hari); lebih lama → u_LST dan u_SAT dikeluarkan (NaN) dan bobot dinormalisasi.
FIRMS atau GIBS gagalTool mengembalikan galat; agen melanjutkan dengan bukti yang ada dan hasilnya inconclusive dengan catatan sumber yang gagal.
Gemini gagal atau batas tool tercapaiVerifikasi disimpan inconclusive dengan validator_failed / tool_limit; operator bisa minta verifikasi ulang.
Dua operator memutuskan bersamaanTransaksi Firestore; yang kedua mendapat 409 ALREADY_DECIDED, web menampilkan keputusan yang sudah tersimpan.
Malam arsip tanpa data/operator/nights mengirim has_data = false (tanggal pudar di kalender); /operator/grid/night mengirim semua slot null dan web menampilkan semua piksel tidak teramati dengan banner.
Kirim gagal atau tidak pasti (429, jaringan, worker mati)Keputusan dan inbox tetap tersimpan. 4xx = failed; timeout atau worker mati setelah klaim = unknown, tidak dikirim ulang otomatis. Operator melihat status per kanal di /deliveries.