Safety, dispatch, fleet, simulation and vitals
Safety policy (safety/policy.py, thresholds in config/policy.yaml)
The policy is a deterministic layer between AI triage and the optimiser. It never lowers acuity: it raises severity floors, adds mandatory capabilities, and decides when a human must authorise. Downstream code always uses policy.effective_assessment, never the raw triage.
| Rule | Trigger | Effect |
|---|---|---|
| R1 red-flag floor | A red-flag concept (ontology) asserted with probability ≥ red_flag_presence (0.5) | Critical label and floor; P(critical) raised to ≥ critical_floor_mass (0.8) with red_flag_floor_mode: overwrite (default), distribution left for J with action |
| R1a red flag = action | A red-flag concept with ≥ red_flag_action_min_support (1) verified samples (support k/n) | ALS, dispatched now (red_flag_dispatch_now:<concept>), even below T_prov |
| R2 red-flag doubt | Red flag only weakly supported (≥ red_flag_doubt 0.2) or marked uncertain | ALS sent, human verifies |
| R3 abstain / silent | No model output or empty transcript | Fail safe: ALS, human required |
| R4 low confidence | low_confidence.mode: near_threshold (default): |p − T_prov| ≤ band (0.05) or normalised entropy of the severity distribution ≥ max_entropy (0.9); min_confidence: confidence < min_confidence (0.6) | Human required |
| R5 split vote | P(critical) and P(non_urgent) both ≥ split_vote_mass (0.2) | Contradictory reading, human |
| R6 contradiction | A concept both asserted and denied across samples | Human |
| R7 hallucination guard | More than max_rejected_share (30%) of LLM findings failed the evidence check | Low evidence quality, human |
| R8 location unverified | Address not resolved to a confident point | Human confirms the location (awaiting_location) |
| R9 mandatory capability | Critical mass, or red flags with ontology capabilities | ALS; plus CARDIAC / TRAUMA / OB as required |
| R10 escalation phrase (v2) | A non-negated high-risk phrase in the caller's words (config/escalation_phrases.yaml) that triage did not assert | ALS, dispatched now, human verifies (never lowers anything) |
| R11 language review (v2) | A red-flag finding resting on unsettled transliteration, ASR hypotheses disagree, IndicXlit unavailable, ≥ 30% uncertain spans | Dispatched now, human confirms with the caller (ALS for the red-flag case) |
| R12 floor without LLM | Triage abstained and R10 fired | Severity floored at critical |
| R13 conscious state | The structured conscious state disagrees with the findings | Human (unresponsive also adds ALS and is dispatched now) |
| R14 flagged caller | The caller is flagged for earlier prank / abusive calls (platform/callers.py) | Human authorises; never refuses the call |
| R15 caller cannot speak | The caller pressed SOS and could not talk (app no-speech timeout, or "I can't talk") | silent_call + ALS, human verifies; the ambulance goes now (provisional) whatever triage read |
| R16 risk factors | age_65_plus, age_under_5, multiple_patients (review_priority_risk_factors) | risk_factor:<x>, explain.review_priority = high (also set by red flags and escalation phrases); never a gate by itself |
Ambulance tiers (ops/tiers.py, tables ambulance_tiers + severity_tiers, seeded from config/fleet.yaml, edited in the admin portal). After the policy, the call's severity looks up the least capable tier that may answer it, and that tier's equipment is added to the requirements (only added: it can never lower what the policy demands). A unit's tier comes from what it carries:
| Tier | Name | A unit qualifies when it carries | Fleet |
|---|---|---|---|
| 1 | Critical care | ALS and cardiac or trauma kit | ALS_CARDIAC, ALS_TRAUMA |
| 2 | Advanced life support | ALS | ALS |
| 3 | Basic life support | BLS | BLS |
| Severity | Least tier (default) | Why |
|---|---|---|
| critical | 2 | ALS at least; tier 1 kit when the emergency is cardiac or trauma (R9 adds CARDIAC / TRAUMA) |
| urgent | 3 | Any ambulance |
| non_urgent | 3 | Any ambulance |
| unknown | 3 | No reading yet: ALS is held back (als_reserve_no_signal); R3 / R10 add ALS on red flags |
The incident records what it needed (tier: {severity, min_tier, name, added}), and /state gives each unit its tier.
Human in the loop (research §9)
Three zones, with p = P(critical) + P(unknown) after the policy:
| Zone | When | What happens |
|---|---|---|
| Auto-dispatch | No review trigger | Committed at once (actor auto) |
| Provisional dispatch | A review trigger, and p ≥ provisional_dispatch_p_critical (T_prov 0.15) or a dispatch-now rule (R1/R1a red flag, R10, R11, R13 unresponsive) | Committed at once (actor auto-provisional, flag provisional_dispatch); the dispatcher verifies after. verify_by_ts = now + provisional_verify_sec (120 s, informational) |
| Hold | A review trigger and p < T_prov | pending_approval with hold_deadline_ts = now + hold_timeout_sec (240 s) |
- T_prov 0.15 comes from the cost ratio C_FP / (C_FP + C_FN): deployed top-priority PPV of 8–27% implies T ≈ 0.08–0.25. One critical vote in five (P(critical) 0.23) is sent provisionally, not held.
- Every hold is time-boxed. The sim loop calls
OpsController.expire_holds()next to the offer expiry (wall clock, about once a second while the sim runs). Past the deadline the recommended response is committed exactly as Approve would, with actorhold-timeout(audit and eventdispatch.hold_timeout). If those units were taken meanwhile the engine decides again; with nothing free the call stays with the dispatcher. Approve, Override, cancel and any commit clear the deadline. A re-triage of a held call keeps the original deadline. Holds without an engine recommendation (run card,ops/manual.py) and non-medical SOS holds have no deadline.dispatch.pending_approvalcarrieshold_deadline_tsandhold_timeout_sec; the incident summary carrieshold_deadline_tsandverify_by_ts. - Monitoring:
GET /api/ops/metrics/hitl(ops/hitl_metrics.py) reports auto / provisional / held counts and rates, review rate, hold-timeout rate, override rate (overridden / (approved + overridden)) and median / p90 time to dispatch, overall and by language and channel. Sensitivity and PPV for life-threatening calls arenull: no clinical outcome is recorded yet (a disposition says only genuine / prank / duplicate ...).
Caller location (ops/locating.py, config/locating.yaml)
Every incident records where its location came from (location_source) and every fix offered (location_history,
including the ones not applied and why):
| Source | From | Verified |
|---|---|---|
gps | The phone's own fix (SOS, app) | Yes |
network | A device fix coarser than network_accuracy_m (150 m) | Up to network_verified_max_m (1 km); coarser = R8, a person confirms. A landmark the gazetteer is sure of replaces it |
address | What the caller said or typed, through the gazetteer / Nominatim | As the geocoder scored it (gazetteer ≥ 88) |
manual_pin | The caller tapped the map (app, /caller "my location is wrong", /l/ link page) | Yes |
link | Browser location on the /l/<token> page texted to the caller | As network when coarse |
sms | Coordinates or a maps link in an SMS | Yes |
dispatcher | POST /incidents/{id}/location | Yes |
Precedence (uc.md case 14, the emergency may not be where the phone is): dispatcher > caller pin / link / SMS >
phone fix / geocoder; the newest of equals wins. A landmark typed in the app's landmark field that the gazetteer
verifies replaces the phone's fix when it is more than stated_overrides_device_m (500 m) away
(location_conflict). A lower-ranked fix is never dropped silently: it stays in the history, and a caller pin held
behind a dispatcher's pin is shown to the dispatcher (location_review). A new location before dispatch restarts
dispatch; units already driving are re-routed when it moved more than reroute_min_m and the reassignment check runs
(scoring unchanged).
Fallbacks: a call whose location is missing or unverified gets a location-request SMS when a number is known
(/l/<incident>.<caller token>: share location, drop a pin, or type a landmark); dispatch texts the tracking link,
the callsign and the crew's number (PUT /units/{id}/contact, never prefilled). A silent call (R3) is never closed
or treated as spam: it stays awaiting_location / pending_approval, is flagged silent_call for the dispatcher,
and gets a "we could not hear you" SMS with the link; a voice call that ends without a word after
silent_call_min_sec still opens an incident. The web caller line has a keypad (1 ambulance, 2 police, 3 fire,
0 can't talk) that posts a short message. A silent SOS escalates on its own: in the citizen app the AI call after
an SOS counts seconds with no caller speech (agent speech not counted); from sos_silence.warn_after_s (20 s,
config/app.yaml) it counts down on screen ("I can talk" stops it), and at escalate_after_s (30 s), or at once on
"I can't talk", it repeats the SOS with cannot_speak. The server (ops/locating.py::caller_cannot_speak) adds
config/field_ops.yaml silent_sos.agencies (medical + police) to the call and pages them, flags it silent
(incident.silent_call), texts the location link when the number is known, and re-assesses it under R15, so a
police-only SOS's held ambulance is released too. The call stays open, on the earpiece. A voice call that joins an
incident and ends without a caller word is flagged silent_call too (no paging). SMS go through VAAZHVU_SMS_URL, else they are simulated and labelled so.
Not built: telecom / AML network location for ordinary phone calls (no TN feed exists), and a real carrier gateway.
Risk dispatch (dispatch/risk.py, parameters in config/dispatch.yaml)
For an incident with severity distribution p_s, the engine enumerates response bundles a:
- each feasible ambulance alone (the nearest
max_ambulances, 8, by ETA); - a police or fire first responder plus an ALS ambulance;
- two ambulances.
It pairs each bundle with its best receiving hospitals h and scores the pair as
J(a, h) = R_s[H_s(a, h)] + F(a, h)
- H_s(a, h): expected adverse outcomes if the true class is s. It is a cumulative hazard, λ_s × (W_s(a) + θ × (scene time + T_h)).
- λ_s =
hazard_per_min: critical 0.10/min (cardiac-arrest survival falls ~5.5 points/min untreated, Larsen 1993), urgent 0.01, non-urgent 0.002. Each value's prior, range, source and status is inparameter_sources. - W_s(a), the response-phase wait, is averaged over the condition-group belief p_c (
triage/conditions.py: arrest, ACS, stroke, trauma, respiratory, obstetric, toxicology, burns, other, from the verified findings). The clock runs at full rate until the first unit able to give early care arrives, then at (1 − κ_c) until capable care (capable_for[s], ALS for critical) arrives. κ_c comes fromconfig/destination.yamlby condition and by what the unit can do (early_care): for an arrest, CPR alone averts 0.42 and CPR + AED 0.62 of the decline (derived from Larsen 1993); for stroke, STEMI and the rest it is 0 until calibrated. BLS ambulances earn it too, so BLS 4 min + ALS 9 min beats ALS alone for a suspected arrest and not for a stroke (research §6.5). - If no unit in the bundle is capable, capable care arrives at first arrival +
request_delay_sec(60 s, the crew assesses and asks for backup) + the backup's ETA. - T_h, the expected time to definitive care via h, = drive + (1 − static × live) × (
secondary_transfer_sec+ the OSRM drive from h to the nearest fully capable hospital) + static × live × (1 − acceptance) × (redirect_sec+ that drive).secondary_transfer_secis 82 min, the lowest measured door-in-door-out median; it replaced a flat 40-minute penalty.specialty_en_route_effectis 0 (no evidence for it).
- λ_s =
- R_s is the risk measure (
risk_measure): mean + ρ·std with ρ =risk_aversion(0.5) by default, or CVaR_α (the mean harm of the worst 1 − α of the probability mass). Choosing it is a governance decision. - F(a, h): future cost. For every zone, it is the marginal delay to the next ALS or any-ambulance response while the bundle is busy, weighted by zone demand, severity mix and busy time. It comes from the OSRM duration matrix. Busy time includes the drive to h and back plus the ER's reported handover wait, so a far hospital pays its coverage cost. A
responder_costis added per first responder. - Hard constraints: units must be idle; the transport unit must be an ambulance; policy-mandated ALS must be in the bundle. If no ALS is free, the engine degrades: the best available response plus a recorded backup.
Condition model (config/destination.yaml, mode: shadow). A fuller objective is scored next to the live J for every bundle, and the decision logs what it would have chosen in baselines.condition_model. It uses a per-condition response hazard and θ (θ ≈ 0 for arrest), harm per minute to definitive care (STEMI ~0.015 pp/min, stroke ~0.09 pp/min), guideline windows (STEMI 120 min, thrombolysis 4.5 h) with a penalty when missed, condition-specific door-in-door-out, stabilise-then-transfer plans (permitted freely in extremis or when the window cannot be met directly, otherwise only past a margin) and a condition-specific ALS constraint (kept hard for arrest, respiratory, ACS and undifferentiated calls; soft for stroke and trauma, where ALS showed no benefit). It does not act until clinicians sign it off (mode: active).
The decision stores:
- the chosen bundle and hospital;
- every alternative with its harm, coverage cost and arrival times;
- the nearest-unit baseline and why it was rejected (capability mismatch, worse expected harm, coverage depletion);
- the objective breakdown.
With VAAZHVU_SCORER_URL set, the Go scorer (services/dispatch-scorer/risk.go) recomputes J and the decision records remote_scorer_agrees.
Evaluation (scripts/eval_dispatch.py, method in Dispatch evaluation). Outcomes are scored by an independent truth model (backend/app/eval/truth.py). It uses published curves: Larsen arrest survival with CPR / AED / ACLS timed by which unit arrives, De Luca STEMI ischaemic time, Emberson / HERMES stroke, and no response-time effect for trauma. The hospital and secondary-transfer legs are included. It never uses the engine's λ / θ / κ, which the earlier harm metric did (docs/eval/RESULTS.md, kept in the repository for the record).
On 10 seeds × 150 calls with Haversine routing (eval/dispatch_outcomes_2026-10-04.md), the full engine (R4) is not better than nearest-capable dispatch: +0.6 ± 0.7 adverse outcomes per 1000 calls with calibrated triage, −0.2 ± 0.5 with miscalibrated triage. Both beat plain nearest-unit / nearest-hospital dispatch by about 2–3 per 1000.
--sweep varies each parameter in parameter_sources across its range and reports how often decisions flip (Sensitivity sweep). That gives the calibration priority list: zone demand, risk aversion, handover time, the critical share of the mix and θ come first.
Hospital choice
Candidates. The nearest candidates.nearest (25) receiving hospitals by straight line, plus, for each needed service, the nearest per_need (4) hospitals that have it within max_km, plus the onward-transfer targets. The 25-nearest window alone held no cath lab for some Chennai zones. One OSRM table call covers them, and a second gives the drive from each candidate to the nearest fully capable hospitals (the onward leg).
Needs. An emergency department plus every specialty the required crew capabilities imply (CARDIAC → cath lab, TRAUMA → trauma care, OB → obstetrics). All of them count: a cardiac + trauma patient needs both. The condition model adds condition needs (stroke unit, burns, anti-snake venom, scorpion care, toxicology, paediatric).
Readiness r = static × live × acceptance (config/destination.yaml readiness):
- static: the source's confidence (verified record 1.0, registry 0.95, unverified hospital record 0.9, LLM profile = its own confidence, applied only to specialty claims) ×
absent_prior(0.3) for each needed service the record or profile does not list. A hospital nobody has profiled is not capable (unknown_prior0.1); it used to count as a capable ED. - live: ED diverting → 0, restricted → 0.5, a diverted service → 0. A report fades back towards "available" with a 45-minute half-life (
status_reported_at), because status reports are often wrong or overridden. - acceptance: 1 − 0.6 × ER load (0.3 for time-critical services). Load fades to 0.5 as the report ages.
Admissibility (admissibility, needs validation with TN Health / EMRI). J optimises among admissible hospitals:
- government hospitals;
- any hospital for a life-threatening medico-legal case (road accident, burns, poisoning, assault), under the legal duty to stabilise (TN Clinical Establishments Act 2018 s.5-B);
- NK-48 empanelled hospitals for road accidents;
- CMCHIS empanelled hospitals when the patient holds CMCHIS;
- any private hospital the patient or family consented to (
POST /incidents/{id}/consent,POST /units/{id}/consent); - hospitals with unknown ownership (most mapped hospitals).
A private, non-empanelled hospital without consent is not used, and the explanation names it when it would have been best. Cost and preference never enter J.
Live updates. The ER board declares diversion, load, ed_status, handover_wait_min and services_unavailable (cath lab, CT, ICU … not available now) (POST /hospitals/{id}/status, or the ER command interface's POST /hospitals/{id}/resources). A declaration re-evaluates patients already on their way. Hospital records (ops/hospital_records.py) correct capabilities, with an audit trail, and keep the ER's declarations across restarts. The ER board's own terms map onto the same fields (hospital_records.apply_record):
- ED status accepting / limited / diversion / unavailable →
ed_statusopen / restricted / diverting / diverting; 0 free ER beds reported → restricted; - cath lab declared not available now, or every specialist that stands for a service declared unavailable (
config/er_board.yamlspecialist_services: cardiology for the cath lab, surgery / orthopaedics for trauma, obstetrics) → that service inservices_unavailable.
The ER cannot receive. An ER that answers "Cannot receive" for a patient (on the ER board, or by phone through ops/outreach.py) is left out of that patient's ranking (rank_hospitals(exclude=)), and the patient goes to the next hospital.
In extremis en route (extremis). Each vitals reading is checked for: SBP < 90, shock index > 1, SpO2 < 90 % on oxygen, AVPU V/P/U, GCS ≤ 8, arrest, or NEWS2 ≥ 7, rising, with the planned hospital > 15 min away. If two readings in a row meet one (one reading for an arrest), and the nearest stabilising ED is at least 5 min nearer than the planned hospital, the unit is diverted there (destination.divert_in_extremis). The crew or dispatcher puts the planned hospital back with one tap (POST /units/{id}/destination). At handover, the onward transfer to the planned hospital is requested automatically as an emergency inter-facility transfer (transfer.onward_requested), which the receiving ER accepts or declines. The rule only escalates: the decision is never re-taken on later readings.
Unit acceptance: offer → accept (ops/offers.py, config/dispatch.yaml acceptance)
The engine's choice is unchanged; this sits between the commit and the drive.
commit ─┬─ crew present ──> offered (unit `assigned`, held, not moving) ─┬─ accept ──> accepted: drive starts (`enroute`)
│ ├─ decline ─> declined ┐
│ └─ timeout ─> expired ┴─> unit released (available),
│ decision stale, re-dispatch
└─ no crew (simulated) ──> accepted at once, by "auto (simulated)" without the refusers
- Who must accept: a unit with a crew actually present: a signed-in crew session bound to the unit, or live device GPS. A simulated unit with nobody on it accepts at once, so the simulator behaves as before. Police / fire answer through their own agency requests.
- State:
inc.offers[unit] = {state, offered_ts, expires_ts, responded_ts, by, role, reason}; unit statuses are unchanged (an offered unit isassigned)./stateunits carryoffer; the crew assignment carriesoffer(andnextis withheld while offered). - Decline / timeout (
timeout_sec, wall clock, checked by the sim loop): the unit is released where it is (it never moved),dispatch.stalemarks the decision stale, and the engine decides again with every unit that declined or let this job's offer expire shown to it as unavailable (OpsController._recommend(exclude=…); scoring is untouched). If the transport unit refuses while another ambulance is already on the job, that one becomes the transport. With nobody left, the call goes to the dispatcher (no_unit_accepted). - Late acceptance: the first-choice unit accepts after its offer expired. If the replacement has not accepted yet, the late unit takes the job. If the replacement accepted, switch back only when the late unit arrives at least
late_switch.min_eta_gain_secsooner (routing ETA vs the replacement's remaining drive) and the replacement accepted at mostmax_progress_secago and is not on scene; otherwise thank and release the late unit.unit.late_acceptrecords the decision, the ETA gain and the progress either way. Answers more thanwindow_secafter the expiry are not considered. - Crew apps: web
/ambulanceand iOS VaazhvuCrew show the offer with a countdown, Accept (primary) and Decline with a reason (config/app.yaml decline_reasons); answers go through the offline outbox. A status step (on_scene) on an open offer accepts it first, so a replayed tap is not lost. - Events:
unit.offered,unit.accepted,unit.declined,offer.expired,dispatch.stale,dispatch.reassigned(withexcluded),unit.late_accept. - Not done: the ALS backup sent after an escalation (
_commit_backup) and police / fire responders are not offered; they are dispatched directly as before.
Manual dispatch fallback (ops/manual.py)
- Engine failure: if the dispatch engine raises (anything but "no unit free"), component
dispatch_engineis degraded (ops.degraded, banner in the terminal;ops.recoveredon its next good decision) and the call is held inpending_approvalwith a run card. - Manual mode: a supervisor (
dispatch.manual) switches it on withPOST /api/ops/manual-mode; every new call is then held with a run card and the engine is not consulted. The mode survives a restart; the terminal shows a MANUAL DISPATCH banner. Calls held while it was on stay with the dispatcher when it is switched off. - Run card (computed without the engine): the nearest available ambulances by straight-line distance with capabilities, tier and whether they carry what the call needs, and the nearest emergency departments (
manual_runcardinconfig/dispatch.yamlsets how many). The dispatcher commits with the override endpoint; the hospital defaults to the card's nearest.
Fleet placement (ops/fleet.py, config/fleet.yaml)
- Fleet: 20 ambulances (4 ALS-cardiac, 3 ALS-trauma, 4 ALS, 9 BLS), 8 police patrols and all OSM fire stations as first responders.
- Bases are solved, not chosen. The model is MEXCLP (maximum expected covering location, Daskin 1983), solved with OR-Tools CP-SAT:
- candidate bases are the 4,189 hospitals profiled (by an LLM, from OSM names and tags) as having an emergency department;
- demand points are the 656 OSM localities, weighted by locality counts (no call history);
- coverage means an OSRM drive time ≤ 8 min, with a busy fraction of 0.35, counted up to the 3rd covering unit. The plan records
coverage_matrix; the committed plan isosrm(94.05% of demand covered).
- Placement order: ALS units are placed first, then BLS around them.
- Output:
data/fleet_plan.json(make fleet-plan). - Formulation, solver limits and the joint-dispatch CP-SAT model: Optimisation (OR-Tools).
- Fleet sources (
ops/fleet_sources.py): live units come fromSimulatedPlanSource(this plan, standing in for the state fleet),RegistrySource(private ambulances approved from/onboard) andCadAvlSource(the slot for an authorised EMRI CAD/AVL feed;VAAZHVU_AVL_URL/_TOKEN, polls{id, type, capabilities, lat, lon, status, ts}; no-op without the env).VAAZHVU_FLEET_SOURCESpicks them (defaultplan,registry, plusavlwhen its URL is set). Feed positions go through the crew-GPS path; feed status never overrides a unit Vaazhvu has committed. - Unit types (
unit_typesinconfig/fleet.yaml): BLS, ALS, ALS_CARDIAC, ALS_TRAUMA, NLS (neonatal: new capabilityNLS), FRB (first-responder bike), ARV (adult retrieval, inter-facility), 4WD, AUTO. Tier still comes from capabilities (NLS → 3, ARV → 2). FRB does not transport patients and is never loaded as a live unit: the engine treats everyemsunit as transport; using bikes as first responders, or IFT-only routing for ARV, is a change to the dispatch objective. Hospital protocol fields (ownership, NK-48, CMCHIS) and the new care classes are data on the hospital; hospital selection does not read them yet.
Simulation (ops/sim.py)
- Clock: a simulated clock (
simulation.speed, 3 simulated seconds per wall-clock second). - Movement:
- a committed unit gets a track (OSRM route geometry with its duration) and moves along it;
- arrivals fire
unit.on_scene/unit.at_hospital/unit.available; - after a handover, units return to base or to a redeployment target.
- Traffic: a disruption (
POST /traffic, e.g. waterlogging) is snapped to the road it is on (OSRMnearest;routing/traffic.py). A closure blocks only routes that run along that road through the point, so a unit on a parallel street is not slowed; a slowdown adds delay only for the stretch on that road. Affected units get the fastest OSRM alternative that avoids it (unit.rerouted); if none exists the route is flaggedno-detourand the console says so. Without OSRM the old circle model applies. - Failures:
POST /units/{id}/failtakes a unit out of service and re-dispatches its incident.unit_failures_per_hourinjects random breakdowns. - Coverage: after every commit, zones whose ALS or any-unit response time exceeds the target raise a
coverage.alert, with a redeploy recommendation (Apply redeployment). Zone demand is a next-hour forecast (ops/forecast.py): the static OSM share, shifted toward zones with recent calls (half-life and prior weight inconfig/dispatch.yamlforecast; the hour-of-day profile is flat until a sourced one exists). The search tries the worst gaps × nearest idle units (coverage_search) with one OSRM table call. Dispatch's own coverage cost uses the same forecast. - Duplicate calls: a call within
clustering.radius_m/window_secof an open incident that shares a finding is linked to it (no second ambulance; its words re-triage the first incident). The dispatcher can split it (POST /incidents/{id}/unlink) or merge one by hand (/link). - Distances shown for each option are OSRM road distances (
table_distances), matching the road ETA.
Traffic police, green corridors and other agencies (ops/traffic_police.py, config/field_ops.yaml)
- SOS emergency types: the caller picks medical / police / fire (several allowed; default medical) on the web
questionnaire, the iOS SOS and
POST /intake/sos|text(emergency_types). Police and fire are paged at intake, before triage, through the sameagency_requesta dispatcher uses (actorcaller); their board shows the SOS fix until triage resolves the place. The only change to dispatch: when the caller chose only non-medical types and triage found no medical finding (no concept needing a crew capability, no red flag, no escalation floor), the recommendation is computed as usual but held (pending_approval, flagnon_medical_sos). Scoring is unchanged and one approval sends the recommended ambulance. - Green corridor: when an ambulance starts a leg matching
traffic_police.purposesand the call's severity is inseverities(default:to_hospital,critical;all_transports: truefor every EMS transport), a corridor request is raised with the route, ETA and junctions, and agencytrafficis paged on the incident. Traffic police (roletraffic,/agency?a=traffic) accept it naming the officer / unit, or decline with a reason. A re-route updates it; arrival, a new leg, a breakdown or the incident closing ends it. A dispatcher can ask for one on any call (command "Ask traffic police for a green corridor",POST /traffic/corridors). - Junctions: the GIS has no traffic-signal layer, so junctions are named OSM junction landmarks within
junction_match_mof the route plus route vertices turning byturn_degor more (labelledroute_turn: a candidate, not a known signal), one permin_gap_m. - Junction alerts: every unit position (simulator tick, crew GPS) is checked against the unit's open corridor;
within
junction_alert_m(200 m) a junction is alerted once per trip (traffic.junction_alertwith distance and ETA). WithVAAZHVU_MSIREN_URL(+VAAZHVU_MSIREN_TOKEN) each alert is POSTed to Chennai Traffic Police's mSiren; the payload is our own shape, unverified against the live system. Without it the alerts are labelledsimulated: trueand nothing leaves the server. - Traffic-aware routing (Mappls): with
VAAZHVU_MAPPLS_KEY(+VAAZHVU_MAPPLS_URL,VAAZHVU_MAPPLS_RESOURCE, defaultroute_traffic)default_routing()putsrouting/mappls.pyin front: route ETA with live traffic and thedistance_matrix_traffictable, falling back to OSRM (or Haversine) on any failure. Unverified against the live API (no key was available; tested against mocked responses only). With Mappls in front, closures use the radius model, since road snapping talks to OSRM. Without the key nothing changes. - Hotspots (
ops/hotspots.py): grid cells (hotspots.cell_m) over stored incidents (pranks / duplicates left out) and imported crash history (crash_history,scripts/import_irad.py), with peak hours, weekday, month and season.GET /hotspots/suggestionscompares each with the fleet's bases against the response target and the zone forecast (read fromops/forecast.py, not changed) and writes plain advice (standby point at peak hours when no base reaches it in time). Advice only: nothing moves a unit. Map layer "hotspots" in the terminal (Shift+L); Admin › Hotspots.
Vitals and NEWS2 (vitals/physiology.py, vitals/news2.py)
- Monitor: when a unit reaches the patient, a
PatientMonitorstarts. A latent physiological state follows the severity class (stabilising under care, bytreated_hazard_factor). - Signals: NeuroKit2 synthesises ECG, PPG and respiration signals, and HR, SpO₂ and RR are measured back from them, like a real monitor.
- NEWS2 (Royal College of Physicians 2017) is computed on every reading, from the crew app, the monitor or the API.
- Rising risk band (
patient.deteriorated) triggers:- re-triage (
triage.escalated); - re-optimisation: a better hospital, or an ALS backup if a BLS crew is with a now-critical patient;
- a renewed hospital alert.
- re-triage (
- FHIR: each reading is sent to HAPI FHIR as LOINC vital-sign Observations in a transaction bundle.
- Correction (
vitals/corrections.py): the crew can mark a reading entered-in-error with a reason. It stays in the record, is left out of NEWS2, the RTS and "latest", NEWS2 is refolded from the valid readings in order, and its FHIR Observations are re-sent with statusentered-in-error. An escalation it already caused is not reverted (the policy never lowers acuity on its own);vitals.voidedtells the dispatcher.
GCS, Revised Trauma Score and incident type (display only)
- RTS (
vitals/rts.py, Champion et al. 1989): with GCS (total, or eye + verbal + motor), systolic BP and respiratory rate on one reading, each coded 0-4; RTS = 0.9368·GCSc + 0.7326·SBPc + 0.2908·RRc (0-7.84) and T-RTS = the sum (0-12). Without all three it isincompletewith the missing inputs; a missing input is never assumed normal. Shown on the crew app, the dispatcher's incident, the ER board and the ERC board. - Incident type (
triage/incident_type.py): the TAEI category (trauma, cardiac/MI, stroke, burns, poisoning, paediatric, snakebite, scorpion sting, plus obstetric and medical_other), derived from the evidence-checked findings and the model's structured patient age, never from raw text.suggested_capabilitieslists the ER services usually wanted, for people to read. - Neither feeds dispatch. The RTS and the incident type are not inputs of J(a), the safety policy, hospital ranking or capability constraints. Spec 16.4 asks for the GCS/SBP/RR score in the formula; that change belongs to the dispatch objective's owners and is not made here (the data is on every reading for them to use).
Trip log and time norms (ops/trips.py)
One record per ambulance per incident, written by listening to the bus: stage times (dispatched, accepted, departed
from base or elsewhere, on scene, departed scene, at hospital, cleared, back at base), the crew's odometer readings,
km estimated from the driven share of each route leg, receiving-hospital changes, police / fire remarks and crew
remarks. Stage durations use the simulation clock (equal to the wall clock in production, simulation.speed 1) and
are compared with time_norms in config/dispatch.yaml. Those norms are draft placeholders, not values from the
TAEI manual or the 108 service agreement; a within / over badge is a reminder until they are checked. The norms
feed no scoring.
Non-emergency referral and inter-facility transfers (ops/referrals.py)
- Helplines: a call the policy left non-urgent with confidence ≥
non_emergency.min_confidence, no red flag and no high-risk phrase can be referred to a line inconfig/region.yamlhelplines(the mother-and-infant drop-back and health-advice lines); the caller gets the number and the call closes asadvice. Policy rules are unchanged. - IFT: a referring hospital asks, the receiving hospital accepts on its ER board, and only then is an
iftincident created (location = referring hospital, destination = accepting hospital, locked against re-ranking in_choice_holds). Units come from the normal dispatch path as a black box with the triage built from the referral (urgency → severity, needed ambulance capability; confidence 1.0, labelled a clinician's assessment). Planned transfers queue until at leastift.min_free_unitsambulances (min_free_alsALS) would stay free.