HAK-16 commited on
Commit
1ffd0a4
·
verified ·
1 Parent(s): 1741cfc

Initial deploy

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +12 -0
  2. .gitignore +31 -0
  3. .python-version +1 -0
  4. Dockerfile +40 -0
  5. README.md +13 -4
  6. cloudbuild.yaml +30 -0
  7. pyproject.toml +31 -0
  8. src/backend/__init__.py +1 -0
  9. src/backend/agents/__init__.py +1 -0
  10. src/backend/agents/analysis.py +166 -0
  11. src/backend/agents/detection.py +228 -0
  12. src/backend/agents/pipeline.py +315 -0
  13. src/backend/agents/planning.py +284 -0
  14. src/backend/agents/simulation.py +343 -0
  15. src/backend/core/__init__.py +1 -0
  16. src/backend/core/auth.py +31 -0
  17. src/backend/core/config.py +59 -0
  18. src/backend/core/constants.py +75 -0
  19. src/backend/core/firebase.py +67 -0
  20. src/backend/core/model.py +69 -0
  21. src/backend/core/runner.py +135 -0
  22. src/backend/core/tools.py +83 -0
  23. src/backend/main.py +59 -0
  24. src/backend/models/__init__.py +1 -0
  25. src/backend/models/agent_result.py +46 -0
  26. src/backend/models/escalation.py +36 -0
  27. src/backend/models/risk.py +55 -0
  28. src/backend/models/signal.py +70 -0
  29. src/backend/models/simulation.py +123 -0
  30. src/backend/models/trace.py +35 -0
  31. src/backend/routes/__init__.py +1 -0
  32. src/backend/routes/auth.py +108 -0
  33. src/backend/routes/crises.py +12 -0
  34. src/backend/routes/crisis.py +122 -0
  35. src/backend/routes/crowd_verification.py +133 -0
  36. src/backend/routes/report.py +183 -0
  37. src/backend/routes/trace.py +24 -0
  38. src/backend/routes/weather.py +46 -0
  39. src/backend/services/__init__.py +1 -0
  40. src/backend/services/cnic.py +102 -0
  41. src/backend/services/crowd_verification.py +217 -0
  42. src/backend/services/fcm.py +162 -0
  43. src/backend/services/firestore.py +91 -0
  44. src/backend/services/maps.py +111 -0
  45. src/backend/services/ngo_escalation.py +218 -0
  46. src/backend/services/radius_query.py +85 -0
  47. src/backend/services/risk_tiering.py +163 -0
  48. src/backend/services/signal_aggregator.py +78 -0
  49. src/backend/services/social_feed.py +116 -0
  50. src/backend/services/trace.py +166 -0
.dockerignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ .env
5
+ .env.*
6
+ *.json
7
+ !pyproject.toml
8
+ .mypy_cache/
9
+ .pytest_cache/
10
+ scripts/
11
+ .python-version
12
+ cloudbuild.yaml
.gitignore ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ── Python ────────────────────────────────────────────────────────────
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ *.egg-info/
7
+ dist/
8
+ build/
9
+
10
+ # ── Virtual environment ──────────────────────────────────────────────
11
+ .venv/
12
+
13
+ # ── Environment secrets ──────────────────────────────────────────────
14
+ .env
15
+ .env.local
16
+ .env.*.local
17
+ .secrets
18
+
19
+ # ── Firebase service account key ─────────────────────────────────────
20
+ *.json
21
+ !pyproject.toml
22
+
23
+ # ── IDE ───────────────────────────────────────────────────────────────
24
+ .vscode/
25
+ .idea/
26
+ *.swp
27
+ *.swo
28
+
29
+ # ── OS ────────────────────────────────────────────────────────────────
30
+ .DS_Store
31
+ Thumbs.db
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.11
Dockerfile ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ── Stage 1: Build ────────────────────────────────────────────────────
2
+ FROM python:3.11-slim AS builder
3
+
4
+ # Install uv
5
+ COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv
6
+
7
+ WORKDIR /app
8
+
9
+ # Copy dependency manifests first (Docker layer caching)
10
+ COPY pyproject.toml uv.lock ./
11
+
12
+ # Install production dependencies only — frozen ensures lockfile is respected
13
+ RUN uv sync --frozen --no-dev --no-install-project
14
+
15
+ # Copy application source
16
+ COPY src/ src/
17
+ COPY README.md ./
18
+
19
+ # Install the project itself
20
+ RUN uv sync --frozen --no-dev
21
+
22
+ # ── Stage 2: Runtime ──────────────────────────────────────────────────
23
+ FROM python:3.11-slim
24
+
25
+ # UV is needed at runtime for 'uv run'
26
+ COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv
27
+
28
+ WORKDIR /app
29
+
30
+ # Copy the entire virtual environment and source from builder
31
+ COPY --from=builder /app /app
32
+
33
+ # Port is supplied by the host (Cloud Run: 8080, HF Spaces: 7860).
34
+ # Default to 8080 for local runs when PORT is unset.
35
+ ENV PORT=8080
36
+
37
+ EXPOSE ${PORT}
38
+
39
+ # Shell form so ${PORT} is expanded at runtime by the host environment.
40
+ CMD ["sh", "-c", "uv run uvicorn backend.main:app --host 0.0.0.0 --port ${PORT:-8080}"]
README.md CHANGED
@@ -1,10 +1,19 @@
1
  ---
2
- title: Ciro Backend
3
- emoji: 🏢
4
  colorFrom: red
5
- colorTo: blue
6
  sdk: docker
 
7
  pinned: false
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: CIRO Backend
3
+ emoji: 🚨
4
  colorFrom: red
5
+ colorTo: yellow
6
  sdk: docker
7
+ app_port: 7860
8
  pinned: false
9
  ---
10
 
11
+ # CIRO Backend
12
+
13
+ Crisis Intelligence & Response Orchestrator — agentic AI backend (FastAPI).
14
+
15
+ - `GET /` → service status
16
+ - `GET /health` → readiness probe
17
+ - `GET /docs` → OpenAPI docs
18
+
19
+ Configuration is supplied via HF Space secrets (see `.env.example`).
cloudbuild.yaml ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ steps:
2
+ # Build the container image
3
+ - name: 'gcr.io/cloud-builders/docker'
4
+ args: ['build', '-t', 'gcr.io/$PROJECT_ID/ciro-backend:$COMMIT_SHA', '.']
5
+
6
+ # Push the container image to Container Registry
7
+ - name: 'gcr.io/cloud-builders/docker'
8
+ args: ['push', 'gcr.io/$PROJECT_ID/ciro-backend:$COMMIT_SHA']
9
+
10
+ # Deploy container image to Cloud Run
11
+ - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
12
+ entrypoint: gcloud
13
+ args:
14
+ - 'run'
15
+ - 'deploy'
16
+ - 'ciro-backend'
17
+ - '--image'
18
+ - 'gcr.io/$PROJECT_ID/ciro-backend:$COMMIT_SHA'
19
+ - '--region'
20
+ - 'us-central1'
21
+ - '--platform'
22
+ - 'managed'
23
+ - '--allow-unauthenticated'
24
+ - '--port'
25
+ - '8080'
26
+ - '--set-env-vars'
27
+ - 'ENVIRONMENT=production'
28
+
29
+ images:
30
+ - 'gcr.io/$PROJECT_ID/ciro-backend:$COMMIT_SHA'
pyproject.toml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "backend"
3
+ version = "0.1.0"
4
+ description = "Crisis Intelligence & Response Orchestrator — agentic AI backend"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Muhammad Fasih", email = "161964251+HafizFasih@users.noreply.github.com" }
8
+ ]
9
+ requires-python = ">=3.11"
10
+ dependencies = [
11
+ "fastapi>=0.136.1",
12
+ "firebase-admin>=7.4.0",
13
+ "httpx>=0.28.1",
14
+ "openai-agents>=0.17.2",
15
+ "pydantic-settings>=2.14.1",
16
+ "python-dotenv>=1.2.2",
17
+ "uvicorn[standard]>=0.47.0",
18
+ ]
19
+
20
+ [project.scripts]
21
+ backend = "backend:main"
22
+
23
+ [build-system]
24
+ requires = ["uv_build>=0.11.7,<0.12.0"]
25
+ build-backend = "uv_build"
26
+
27
+ [dependency-groups]
28
+ dev = [
29
+ "pytest>=9.0.3",
30
+ "pytest-asyncio>=1.3.0",
31
+ ]
src/backend/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """CIRO Backend — Crisis Intelligence & Response Orchestrator."""
src/backend/agents/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Agents module — one file per agent (detection, analysis, planning, simulation)
src/backend/agents/analysis.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Situation Analysis Agent — second reasoning stage of the CIRO pipeline.
3
+
4
+ Responsibility
5
+ --------------
6
+ Given the detection verdict, the assigned risk tier, and the raw signals,
7
+ this agent determines "how bad is it and why". It estimates severity (1-5),
8
+ identifies what is impacted, and produces a plain-language explanation for
9
+ a human coordinator.
10
+
11
+ Output contract
12
+ ---------------
13
+ Returns a `SituationReport` Pydantic model via the SDK's structured-output path.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from datetime import datetime, timezone
19
+ from typing import Literal
20
+
21
+ from agents import Agent
22
+ from pydantic import BaseModel, ConfigDict, Field
23
+
24
+ from backend.core.model import get_gemini_model
25
+ from backend.core.runner import run_agent
26
+ from backend.models.agent_result import AgentResult
27
+ from backend.models.risk import RiskTieringResult
28
+ from backend.models.signal import CrisisSignal
29
+ from backend.agents.detection import DetectionOutput
30
+
31
+
32
+ class SituationReport(BaseModel):
33
+ """Structured response shape the analysis agent must return."""
34
+
35
+ model_config = ConfigDict(extra="forbid")
36
+
37
+ severity: int = Field(ge=1, le=5)
38
+ severity_label: Literal["minor", "moderate", "serious", "severe", "catastrophic"]
39
+ affected_population_estimate: str
40
+ impacts: list[str] = Field(default_factory=list)
41
+ confidence: float = Field(ge=0.0, le=1.0)
42
+ explanation: str
43
+ missing_info: list[str] = Field(default_factory=list)
44
+ timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
45
+
46
+
47
+ _INSTRUCTIONS = """\
48
+ You are a crisis situation analyst for Pakistani urban areas (Islamabad, Karachi, Lahore).
49
+ You receive: the type of crisis detected, the location, the assigned risk level, the initial confidence score, and all raw signals.
50
+
51
+ Your job is to:
52
+ 1. Estimate severity on a scale of 1 (minor) to 5 (catastrophic).
53
+ 2. Assign the corresponding severity_label ("minor", "moderate", "serious", "severe", "catastrophic").
54
+ 3. Identify who and what is impacted (e.g. traffic blocked, residents trapped, power lines down). List these explicitly.
55
+ 4. Estimate the affected population in plain language (e.g. "500-1000 residents", "commuters on Main Highway").
56
+ 5. Explain your reasoning in plain language that a non-technical coordinator can understand. Do not use JSON or technical jargon in the explanation.
57
+ 6. Re-evaluate confidence based on cross-signal analysis.
58
+ 7. Flag any missing information that would change the assessment.
59
+
60
+ Severity Scale Reference:
61
+ 1 - Minor: Light rain causing slow traffic, localized issue. No disruption requiring response.
62
+ 2 - Moderate: Traffic congestion (even severe jams), road blockage where vehicles can be rerouted, minor infrastructure impact. No casualties, no physical blockage.
63
+ 3 - Serious: Flash flood with vehicles actually stranded, road physically impassable (debris, water level), localized property damage. A traffic jam — however severe — is NOT severity 3 unless there is confirmed physical damage or casualties.
64
+ 4 - Severe: Flooding with confirmed casualties risk, fire actively spreading, building collapse risk, large area impacted.
65
+ 5 - Catastrophic: Building collapse with casualties, mass casualty event, multi-zone systemic failure.
66
+
67
+ Calibration rules (apply strictly):
68
+ - traffic_jam, rainfall, road_blockage: severity MUST be 1 or 2 unless confirmed casualties or physical destruction are explicitly stated. Congestion — even "completely jammed for 40+ minutes" — is at most severity 2. Speculation about a possible accident does NOT justify severity 3+.
69
+ - flood: severity 3 when vehicles are physically stranded and road is impassable; severity 4 when casualties risk is confirmed or area is large.
70
+ - fire: any active fire requiring emergency services (fire brigade called, smoke visible from far, multiple reports) is severity 4 by default. Severity 3 only for a small isolated fire that is already being managed. Fire spreads fast — treat active fires as severe.
71
+ - accident, building_collapse: severity 3–5 based on confirmed casualties, structural damage, and area of impact.
72
+
73
+ Be specific to the Pakistani urban context — reference local infrastructure, population density patterns, and common constraints.
74
+ Return the result strictly as the SituationReport schema.
75
+ """
76
+
77
+ analysis_agent = Agent(
78
+ name="situation_analysis_agent",
79
+ instructions=_INSTRUCTIONS,
80
+ model=get_gemini_model(),
81
+ output_type=SituationReport,
82
+ )
83
+
84
+
85
+ def _format_inputs(
86
+ signals: list[CrisisSignal],
87
+ detection: DetectionOutput,
88
+ risk: RiskTieringResult,
89
+ ) -> str:
90
+ """Render the inputs as a structured prompt for the agent."""
91
+ lines: list[str] = [
92
+ "### Detection Verdict ###",
93
+ f"Crisis Type: {detection.crisis_type}",
94
+ f"Location: {detection.location_label} ({detection.coordinates})",
95
+ f"Detection Confidence: {detection.confidence:.2f}",
96
+ f"Detection Reasoning: {detection.reasoning}",
97
+ "",
98
+ "### Risk Assessment ###",
99
+ f"Risk Level: {risk.risk_level}",
100
+ f"Risk Reasoning: {risk.reasoning}",
101
+ "",
102
+ f"### Raw Signals ({len(signals)}) ###",
103
+ ]
104
+
105
+ for idx, sig in enumerate(signals, start=1):
106
+ lat, lon = sig.coordinates if sig.coordinates else (0.0, 0.0)
107
+ lines.append(
108
+ f"Signal #{idx}\n"
109
+ f" source: {sig.source}\n"
110
+ f" trust_weight: {sig.trust_weight}\n"
111
+ f" signal_type_hint: {sig.signal_type}\n"
112
+ f" location: {sig.location_label} ({lat:.4f}, {lon:.4f})\n"
113
+ f" severity_hint: {sig.severity_hint}\n"
114
+ f" observed_at: {sig.timestamp.isoformat()}\n"
115
+ f" text: {sig.raw_text or '(none)'}\n"
116
+ )
117
+
118
+ lines.append(
119
+ "Synthesize this information and return a complete SituationReport. "
120
+ "Your explanation must be clear and actionable for a coordinator."
121
+ )
122
+ return "\n".join(lines)
123
+
124
+
125
+ def _synthetic_no_crisis_analysis(reason: str) -> AgentResult:
126
+ """Build an AgentResult representing 'no crisis' without calling Gemini."""
127
+ out = SituationReport(
128
+ severity=1,
129
+ severity_label="minor",
130
+ affected_population_estimate="None",
131
+ impacts=[],
132
+ confidence=1.0,
133
+ explanation=reason,
134
+ missing_info=[],
135
+ )
136
+ return AgentResult(
137
+ agent_name=analysis_agent.name,
138
+ success=True,
139
+ output=out.model_dump(),
140
+ reasoning=reason,
141
+ confidence=1.0,
142
+ )
143
+
144
+
145
+ async def run_analysis(
146
+ signals: list[CrisisSignal],
147
+ detection: DetectionOutput,
148
+ risk: RiskTieringResult,
149
+ ) -> AgentResult:
150
+ """Run the situation analysis agent over the detected crisis.
151
+
152
+ Args:
153
+ signals: The list of `CrisisSignal` instances.
154
+ detection: The `DetectionOutput` from Phase 5.
155
+ risk: The `RiskTieringResult` from Phase 6.
156
+
157
+ Returns:
158
+ An `AgentResult` whose `output` is a `SituationReport` dict.
159
+ """
160
+ if not detection.crisis_detected:
161
+ return _synthetic_no_crisis_analysis(
162
+ "No crisis detected in the previous stage; analysis skipped."
163
+ )
164
+
165
+ prompt = _format_inputs(signals, detection, risk)
166
+ return await run_agent(analysis_agent, prompt)
src/backend/agents/detection.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Crisis Detection Agent — first reasoning stage of the CIRO pipeline.
3
+
4
+ Responsibility
5
+ --------------
6
+ Given a list of `CrisisSignal` instances aggregated by Phase 4, decide:
7
+
8
+ 1. Is a crisis occurring at all?
9
+ 2. If yes, which type (from a closed taxonomy)?
10
+ 3. Where exactly? (location label + coordinates, copied — never
11
+ invented — from the signals).
12
+ 4. How confident is the agent?
13
+
14
+ This agent is intentionally narrow. It does *not* estimate severity (Phase 7),
15
+ classify risk tier (Phase 6), or plan a response (Phase 8). Keeping the
16
+ detection step single-purpose is a deliberate context-isolation choice
17
+ (see the multi-agent-patterns skill) — the prompt and tool surface stay
18
+ small, so the model stays accurate.
19
+
20
+ Output contract
21
+ ---------------
22
+ The agent returns a `DetectionOutput` Pydantic model via the SDK's
23
+ structured-output path (`output_type=DetectionOutput`). The base runner
24
+ wraps it into an `AgentResult` with `output = DetectionOutput.model_dump()`,
25
+ which is what downstream pipeline stages read.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ from typing import Literal
31
+
32
+ from agents import Agent
33
+ from pydantic import BaseModel, ConfigDict, Field
34
+
35
+ from backend.core.model import get_gemini_model
36
+ from backend.core.runner import run_agent
37
+ from backend.models.agent_result import AgentResult
38
+ from backend.models.signal import CrisisSignal
39
+
40
+
41
+ # Closed taxonomy. Keeping this as a Literal is what lets the SDK reject
42
+ # free-form crisis types ("Flooding", "WaterAccumulation") at schema level.
43
+ CrisisType = Literal[
44
+ "flood",
45
+ "fire",
46
+ "accident",
47
+ "traffic_jam",
48
+ "rainfall",
49
+ "heatwave",
50
+ "infrastructure",
51
+ ]
52
+
53
+
54
+ class DetectionOutput(BaseModel):
55
+ """Structured response shape the detection agent must return.
56
+
57
+ Field semantics
58
+ ---------------
59
+ crisis_detected
60
+ Binary verdict. If False, every other field describing a crisis
61
+ must be None (the agent is told this explicitly in the prompt).
62
+
63
+ crisis_type
64
+ Closed-taxonomy label. None iff crisis_detected is False.
65
+
66
+ location_label / coordinates
67
+ Copied verbatim from the most-credible signal that named a
68
+ location. NEVER invented. If no signal contains a recognizable
69
+ location, both are None even when a crisis is detected.
70
+
71
+ confidence
72
+ Self-reported, in [0, 1]. Higher weight should track higher
73
+ signal trust_weight and stronger inter-signal agreement.
74
+
75
+ reasoning
76
+ One short paragraph in plain language. Rendered directly in
77
+ the agent-trace UI for end users, so it must read like an
78
+ explanation, not a JSON dump.
79
+
80
+ supporting_signals
81
+ Short references to the specific signals that drove the verdict
82
+ — e.g. `'social_media: "G-10 mein pani bhar gaya hai..."'`.
83
+ Used for the trace UI and for downstream debugging.
84
+ """
85
+
86
+ # Forbid extra fields so the SDK enforces strict structured output.
87
+ model_config = ConfigDict(extra="forbid")
88
+
89
+ crisis_detected: bool
90
+ crisis_type: CrisisType | None = None
91
+ location_label: str | None = None
92
+ coordinates: tuple[float, float] | None = None
93
+ confidence: float = Field(ge=0.0, le=1.0)
94
+ reasoning: str
95
+ supporting_signals: list[str] = Field(default_factory=list)
96
+
97
+
98
+ # ── Agent definition ──────────────────────────────────────────────────────
99
+
100
+ _INSTRUCTIONS = """\
101
+ You are CIRO's crisis detection agent for Pakistani urban areas
102
+ (Islamabad, Karachi, Lahore). You receive a structured list of signals
103
+ aggregated from weather APIs, simulated social-media posts, and
104
+ CNIC-verified in-app reports. Each signal is tagged with its `source`,
105
+ its `trust_weight` in [0, 1], a `signal_type`, an optional location, an
106
+ optional severity hint, and the raw text (which may be Urdu, English,
107
+ or mixed).
108
+
109
+ Your job is to decide:
110
+
111
+ 1. Whether a crisis is currently occurring.
112
+ 2. If yes, which type — strictly one of:
113
+ flood, fire, accident, traffic_jam, rainfall, heatwave, infrastructure.
114
+ 3. Where exactly — copy the most precise `location_label` and
115
+ `coordinates` from the signals. Never invent a location.
116
+ 4. How confident you are, in [0, 1].
117
+
118
+ Rules:
119
+ - Signals with higher `trust_weight` are stronger evidence. A single
120
+ app_report (trust=1.0) confirming a flood outweighs three
121
+ social_media posts (trust=0.5) that disagree. Use the provided
122
+ weights as data — do not assume fixed weights of your own.
123
+ - Handle Urdu, English, and mixed-language input natively. Do not
124
+ translate in your reasoning — just understand and classify.
125
+ - If the signals do not consistently support a crisis (e.g. benign
126
+ weather + no eyewitness reports), set `crisis_detected=False` and
127
+ leave `crisis_type`, `location_label`, and `coordinates` as null.
128
+ Confidence in that case is your confidence in the *no-crisis*
129
+ verdict.
130
+ - NEVER invent a location. If no signal contains a recognizable
131
+ location, set `location_label=null` and `coordinates=null`, even
132
+ when a crisis is detected.
133
+ - `supporting_signals` must reference the actual signals you used,
134
+ each as a short string like
135
+ 'social_media (trust=0.5): "G-10 mein pani bhar gaya hai..."'
136
+ - `reasoning` must be one short paragraph in plain language. It is
137
+ shown directly to end-users in the live agent-trace UI, so write
138
+ it like an explanation, not a JSON dump.
139
+
140
+ Return the result strictly as the `DetectionOutput` schema. Do not add
141
+ prose outside the schema.
142
+ """
143
+
144
+
145
+ detection_agent = Agent(
146
+ name="crisis_detection_agent",
147
+ instructions=_INSTRUCTIONS,
148
+ model=get_gemini_model(),
149
+ output_type=DetectionOutput,
150
+ )
151
+
152
+
153
+ # ── Helpers ───────────────────────────────────────────────────────────────
154
+
155
+
156
+ def _format_signals(signals: list[CrisisSignal]) -> str:
157
+ """Render the signal list as a structured prompt for the agent.
158
+
159
+ The format is deliberately verbose-but-uniform: each signal occupies
160
+ a fixed-key block. The agent reasons over this directly; no
161
+ serialization tricks needed at the model end.
162
+ """
163
+ lines: list[str] = [f"You have received {len(signals)} signal(s):\n"]
164
+ for idx, sig in enumerate(signals, start=1):
165
+ lat, lon = sig.coordinates
166
+ lines.append(
167
+ f"Signal #{idx}\n"
168
+ f" source: {sig.source}\n"
169
+ f" trust_weight: {sig.trust_weight}\n"
170
+ f" signal_type_hint: {sig.signal_type}\n"
171
+ f" location: {sig.location_label} ({lat:.4f}, {lon:.4f})\n"
172
+ f" severity_hint: {sig.severity_hint}\n"
173
+ f" observed_at: {sig.timestamp.isoformat()}\n"
174
+ f" text: {sig.raw_text or '(none)'}\n"
175
+ )
176
+ lines.append(
177
+ "Reason across these signals and return a DetectionOutput. "
178
+ "Remember: do not invent a location, and use trust_weight as "
179
+ "the strength of each piece of evidence."
180
+ )
181
+ return "\n".join(lines)
182
+
183
+
184
+ def _synthetic_no_crisis(reason: str) -> AgentResult:
185
+ """Build an AgentResult representing 'no crisis' without calling Gemini.
186
+
187
+ Used when there are zero signals to reason about — saving a model
188
+ round-trip while keeping the same contract every other stage expects.
189
+ """
190
+ out = DetectionOutput(
191
+ crisis_detected=False,
192
+ confidence=1.0,
193
+ reasoning=reason,
194
+ supporting_signals=[],
195
+ )
196
+ return AgentResult(
197
+ agent_name=detection_agent.name,
198
+ success=True,
199
+ output=out.model_dump(),
200
+ reasoning=reason,
201
+ confidence=1.0,
202
+ )
203
+
204
+
205
+ # ── Public entry point ────────────────────────────────────────────────────
206
+
207
+
208
+ async def run_detection(signals: list[CrisisSignal]) -> AgentResult:
209
+ """Run the detection agent over an aggregated signal list.
210
+
211
+ Args:
212
+ signals: The list returned by `aggregate_signals(...)` — or any
213
+ list of `CrisisSignal` instances, including a hand-built
214
+ list for tests or for raw app-report submissions.
215
+
216
+ Returns:
217
+ An `AgentResult` whose `output` is a `DetectionOutput` dict.
218
+ Never raises — any underlying SDK failure collapses to
219
+ `success=False` via the base runner.
220
+ """
221
+ if not signals:
222
+ return _synthetic_no_crisis(
223
+ "No signals were provided to the detection agent — "
224
+ "treating as no crisis."
225
+ )
226
+
227
+ prompt = _format_signals(signals)
228
+ return await run_agent(detection_agent, prompt)
src/backend/agents/pipeline.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CIRO multi-agent pipeline — top-level orchestrator.
3
+
4
+ Architecture: supervisor-style sequential pipeline.
5
+
6
+ Phase 4: aggregate CrisisSignal list (NOT done here — handled by
7
+ services/signal_aggregator.py before this function is called)
8
+ │
9
+ ▼
10
+ Phase 5: [Detection] ──► if crisis_detected=False → stop, return
11
+ │
12
+ ▼
13
+ Phase 6: [Risk Tier] ──► deterministic, no LLM (rule-based)
14
+ │
15
+ ▼
16
+ Phase 10:[Crowd Verif]──► medium/high only; FCM prompts to nearby
17
+ │ users. Non-blocking — pipeline continues.
18
+ ▼
19
+ Phase 7: [Analysis] ──► severity, impacts, confidence (LLM)
20
+ Phase 8: [Planning] ──► response plan + Maps routes (LLM + tool)
21
+ Phase 11:[NGO Escal] ──► severity threshold check; real FCM to NGO
22
+ │ devices if confirmed + severity ≥ 3.
23
+ ▼
24
+ Phase 12: [Simulation] (placeholder)
25
+
26
+ Each stage produces an `AgentResult`. The trace accumulates every result
27
+ in execution order — that's what the in-app agent-trace timeline renders.
28
+
29
+ Why sequential supervisor and not swarm/handoff: the CIRO flow has fixed
30
+ dependency-ordered shape. You cannot plan an action before you know the
31
+ risk tier; you cannot tier risk before detection has produced a verdict.
32
+ A swarm pattern would add coordination overhead with no upside.
33
+
34
+ Avoiding the "telephone game" problem (see multi-agent-patterns skill):
35
+ downstream stages get the previous stage's `output` dict verbatim, not a
36
+ paraphrase. No supervisor LLM re-summarizes intermediate results.
37
+ """
38
+
39
+ from __future__ import annotations
40
+
41
+ import logging
42
+ from typing import Any
43
+
44
+ from pydantic import ValidationError
45
+
46
+ from backend.agents.analysis import SituationReport, run_analysis
47
+ from backend.agents.detection import DetectionOutput, run_detection
48
+ from backend.agents.planning import run_planning
49
+ from backend.core.runner import run_agent
50
+ from backend.models.agent_result import AgentResult
51
+ from backend.models.risk import RiskTieringResult
52
+ from backend.models.signal import CrisisSignal
53
+ from backend.services.risk_tiering import RISK_TIER_AGENT_NAME, run_risk_tiering
54
+
55
+ logger = logging.getLogger(__name__)
56
+
57
+
58
+ # ── Phase 10: crowd verification helper ──────────────────────────────────────
59
+
60
+
61
+ async def _run_crowd_verification(
62
+ crisis_id: str,
63
+ detection_output: DetectionOutput,
64
+ signals: list[CrisisSignal],
65
+ ) -> AgentResult:
66
+ """Send FCM verification prompts to nearby users and return a trace entry.
67
+
68
+ Non-blocking: the pipeline does not wait for crowd responses. Responses
69
+ arrive asynchronously via POST /api/crisis/{crisis_id}/verify. A failed
70
+ dispatch is logged but never crashes the pipeline (FCM is best-effort).
71
+ """
72
+ from backend.services.crowd_verification import send_verification_prompts # local import avoids circular dep
73
+
74
+ coords = detection_output.coordinates
75
+ if coords is None and signals:
76
+ coords = signals[0].coordinates
77
+
78
+ if coords is None:
79
+ return AgentResult(
80
+ agent_name="crowd_verification",
81
+ success=False,
82
+ output={"error": "NO_COORDINATES"},
83
+ reasoning="Cannot dispatch verification prompts — no coordinates in detection output or signals.",
84
+ confidence=0.0,
85
+ )
86
+
87
+ lat, lon = coords
88
+ location = detection_output.location_label or "unknown location"
89
+ crisis_type = detection_output.crisis_type or "unknown"
90
+
91
+ try:
92
+ prompt_result = await send_verification_prompts(
93
+ crisis_id=crisis_id,
94
+ crisis_type=crisis_type,
95
+ location_label=location,
96
+ lat=lat,
97
+ lon=lon,
98
+ )
99
+ return AgentResult(
100
+ agent_name="crowd_verification",
101
+ success=True,
102
+ output={**prompt_result, "status": "pending"},
103
+ reasoning=(
104
+ f"Verification prompts sent to {prompt_result['users_notified']} of "
105
+ f"{prompt_result['users_found']} nearby users within 1 km of {location}. "
106
+ "Awaiting crowd responses before emergency dispatch."
107
+ ),
108
+ confidence=1.0,
109
+ )
110
+ except Exception as exc: # noqa: BLE001
111
+ logger.warning("Crowd verification dispatch failed for crisis %s: %s", crisis_id, exc)
112
+ return AgentResult(
113
+ agent_name="crowd_verification",
114
+ success=False,
115
+ output={"error": "DISPATCH_FAILED", "detail": str(exc)},
116
+ reasoning=f"FCM dispatch failed: {exc}. Pipeline continues without crowd verification.",
117
+ confidence=0.0,
118
+ )
119
+
120
+
121
+ # ── Phase 11: NGO escalation helper ──────────────────────────────────────────
122
+
123
+
124
+ async def _run_ngo_escalation(
125
+ crisis_id: str | None,
126
+ detection_output: DetectionOutput,
127
+ situation_report: SituationReport,
128
+ planning_output: dict[str, Any],
129
+ ) -> AgentResult:
130
+ """Evaluate NGO escalation threshold and dispatch alerts if warranted.
131
+
132
+ Fetches the current verification_result from Firestore when a crisis_id
133
+ is available. Without a crisis_id the escalation always returns
134
+ not-escalated (no persisted document to check or update).
135
+ """
136
+ from backend.services.ngo_escalation import run_escalation # local import avoids circular dep
137
+
138
+ verification_result = "inconclusive"
139
+ if crisis_id:
140
+ from backend.core.firebase import get_async_db
141
+ db = get_async_db()
142
+ doc = await db.collection("crises").document(crisis_id).get()
143
+ if doc.exists:
144
+ verification_result = doc.to_dict().get("verification_result") or "inconclusive"
145
+
146
+ plan_summary: str = planning_output.get("plan_summary") or ""
147
+
148
+ escalation = await run_escalation(
149
+ crisis_id=crisis_id or "no_crisis_id",
150
+ crisis_type=detection_output.crisis_type or "unknown",
151
+ location_label=detection_output.location_label or "unknown",
152
+ severity=situation_report.severity,
153
+ response_plan_summary=plan_summary,
154
+ verification_result=verification_result,
155
+ )
156
+ return AgentResult(
157
+ agent_name="ngo_escalation",
158
+ success=True,
159
+ output=escalation.model_dump(),
160
+ reasoning=escalation.reason,
161
+ confidence=1.0,
162
+ )
163
+
164
+
165
+ # ── Pipeline entry point ──────────────────────────────────────────────────────
166
+
167
+
168
+ def _serialize(final: AgentResult, trace: list[AgentResult]) -> dict[str, Any]:
169
+ """Pack the pipeline result into the shape FastAPI returns to clients."""
170
+ return {
171
+ "final": final.model_dump(mode="json"),
172
+ "trace": [r.model_dump(mode="json") for r in trace],
173
+ }
174
+
175
+
176
+ async def run_pipeline(signals: list[CrisisSignal], crisis_id: str | None = None) -> dict[str, Any]:
177
+ """Run the full CIRO agent pipeline against an aggregated signal list.
178
+
179
+ Args:
180
+ signals: The list returned by `aggregate_signals(...)`. Empty list
181
+ is a valid input — the detection agent will short-circuit
182
+ with `crisis_detected=False` without burning a model call.
183
+ crisis_id: Firestore document ID of the persisted crisis, if any.
184
+ When provided and the crisis is medium/high risk, Phase 10
185
+ crowd verification prompts are sent to nearby users. When None
186
+ (e.g. the demo /api/crisis/analyze route), crowd verification
187
+ is skipped — the trace still records the risk tier verdict.
188
+
189
+ Returns:
190
+ A dict with two keys:
191
+ * `final` — the final stage's `AgentResult` (mode='json').
192
+ When the pipeline stops early on no-crisis, this is
193
+ the detection result itself.
194
+ * `trace` — every `AgentResult` produced along the way, in
195
+ execution order. Renders as the agent-trace timeline.
196
+ """
197
+ trace: list[AgentResult] = []
198
+
199
+ # ── Stage 1: detection ───────────────────────────────────────────────
200
+ detection_result = await run_detection(signals)
201
+ trace.append(detection_result)
202
+
203
+ # Detection failed (SDK exception, validation error, etc.) — stop.
204
+ if not detection_result.success:
205
+ return _serialize(detection_result, trace)
206
+
207
+ # No crisis → graceful stop. No further agents run.
208
+ if not detection_result.output.get("crisis_detected"):
209
+ return _serialize(detection_result, trace)
210
+
211
+ # ── Stage 2: risk tiering (deterministic — no LLM) ───────────────────
212
+ # Re-validate the detection dict back into its Pydantic shape before
213
+ # passing it to the classifier. Validation should always succeed here
214
+ # (detection just produced it), but if structured output ever drifts
215
+ # we want a clean error rather than a KeyError further downstream.
216
+ try:
217
+ detection_output = DetectionOutput.model_validate(detection_result.output)
218
+ except ValidationError as exc:
219
+ failure = AgentResult(
220
+ agent_name=RISK_TIER_AGENT_NAME,
221
+ success=False,
222
+ output={"error": "INVALID_DETECTION_OUTPUT"},
223
+ reasoning=f"Detection output failed schema validation: {exc}",
224
+ confidence=0.0,
225
+ )
226
+ trace.append(failure)
227
+ return _serialize(failure, trace)
228
+
229
+ risk_result = run_risk_tiering(detection_output)
230
+ trace.append(risk_result)
231
+
232
+ # Validate risk tiering output before any downstream stage reads it.
233
+ try:
234
+ risk_tiering_output = RiskTieringResult.model_validate(risk_result.output)
235
+ except ValidationError as exc:
236
+ failure = AgentResult(
237
+ agent_name="situation_analysis_agent",
238
+ success=False,
239
+ output={"error": "INVALID_RISK_TIERING_OUTPUT"},
240
+ reasoning=f"Risk tiering output failed schema validation: {exc}",
241
+ confidence=0.0,
242
+ )
243
+ trace.append(failure)
244
+ return _serialize(failure, trace)
245
+
246
+ # ── Stage 2.5: crowd verification (Phase 10) ─────────────────────────
247
+ # Runs only for medium/high-risk crises AND only when the caller has
248
+ # persisted a crisis document (crisis_id provided). Non-blocking: the
249
+ # pipeline does not wait for crowd responses — they arrive async via
250
+ # POST /api/crisis/{crisis_id}/verify.
251
+ if risk_tiering_output.requires_crowd_verification and crisis_id:
252
+ cv_result = await _run_crowd_verification(
253
+ crisis_id=crisis_id,
254
+ detection_output=detection_output,
255
+ signals=signals,
256
+ )
257
+ trace.append(cv_result)
258
+
259
+ # ── Stage 3: situation analysis (Phase 7) ────────────────────────────
260
+
261
+ analysis_result = await run_analysis(signals, detection_output, risk_tiering_output)
262
+ trace.append(analysis_result)
263
+
264
+ if not analysis_result.success:
265
+ return _serialize(analysis_result, trace)
266
+
267
+ # ── Stage 4: action planning (Phase 8) ───────────────────────────────
268
+ try:
269
+ situation_report = SituationReport.model_validate(analysis_result.output)
270
+ except ValidationError as exc:
271
+ failure = AgentResult(
272
+ agent_name="action_planning_agent",
273
+ success=False,
274
+ output={"error": "INVALID_SITUATION_REPORT"},
275
+ reasoning=f"Situation report failed schema validation: {exc}",
276
+ confidence=0.0,
277
+ )
278
+ trace.append(failure)
279
+ return _serialize(failure, trace)
280
+
281
+ planning_result = await run_planning(detection_output, risk_tiering_output, situation_report)
282
+ trace.append(planning_result)
283
+
284
+ if not planning_result.success:
285
+ return _serialize(planning_result, trace)
286
+
287
+ # ── Stage 5: NGO escalation (Phase 11) ───────────────────────────────
288
+ # Runs for medium/high risk crises only. Checks Firestore for the
289
+ # current verification_result — if "confirmed" and severity ≥ 3, fires
290
+ # real FCM to registered NGO devices. Always adds a trace entry.
291
+ escalation_result: AgentResult | None = None
292
+ if risk_tiering_output.requires_crowd_verification:
293
+ escalation_result = await _run_ngo_escalation(
294
+ crisis_id=crisis_id,
295
+ detection_output=detection_output,
296
+ situation_report=situation_report,
297
+ planning_output=planning_result.output,
298
+ )
299
+ trace.append(escalation_result)
300
+
301
+ # ── Stage 6: simulation (Phase 12) ───────────────────────────────────
302
+ # Terminal stage — simulates plan execution, builds before/after state,
303
+ # assembles the dispatch ticket, and fires WhatsApp emergency dispatch.
304
+ from backend.agents.simulation import run_simulation # local import avoids circular dep
305
+ simulation_result = await run_simulation(
306
+ detection_output=detection_output,
307
+ situation_report=situation_report,
308
+ planning_output=planning_result.output,
309
+ risk_tiering_output=risk_tiering_output,
310
+ escalation_output=escalation_result.output if escalation_result else {},
311
+ crisis_id=crisis_id,
312
+ )
313
+ trace.append(simulation_result)
314
+
315
+ return _serialize(simulation_result, trace)
src/backend/agents/planning.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Action Planning Agent — third reasoning stage of the CIRO pipeline.
3
+
4
+ Responsibility
5
+ --------------
6
+ Given the detection verdict, risk tier, and situation report, generate a
7
+ concrete, prioritized response plan. For flood/traffic crises, fetches real
8
+ alternate routes from Google Maps via the fetch_routes_tool before finalising
9
+ the plan.
10
+
11
+ Output contract
12
+ ---------------
13
+ Returns a `ResponsePlan` Pydantic model via the SDK's structured-output path.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import logging
20
+ from typing import Literal
21
+
22
+ from agents import Agent, function_tool
23
+ from pydantic import BaseModel, ConfigDict, Field
24
+
25
+ from backend.agents.analysis import SituationReport
26
+ from backend.agents.detection import DetectionOutput
27
+ from backend.core.model import get_gemini_model
28
+ from backend.core.runner import run_agent
29
+ from backend.models.agent_result import AgentResult
30
+ from backend.models.risk import RiskTieringResult
31
+ from backend.services.maps import RouteOption
32
+ from backend.services.maps import fetch_routes as _fetch_routes_impl
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+
37
+ # ── Output schemas ────────────────────────────────────────────────────────
38
+
39
+
40
+ class ActionItem(BaseModel):
41
+ """A single response action in the plan."""
42
+
43
+ model_config = ConfigDict(extra="forbid")
44
+
45
+ action: str
46
+ assigned_to: str
47
+ priority: Literal["critical", "high", "medium"]
48
+
49
+
50
+ class ResponsePlan(BaseModel):
51
+ """Full coordinated response plan produced by the planning agent."""
52
+
53
+ model_config = ConfigDict(extra="forbid")
54
+
55
+ immediate_actions: list[ActionItem] = Field(default_factory=list)
56
+ short_term_actions: list[ActionItem] = Field(default_factory=list)
57
+ route_options: list[RouteOption] = Field(default_factory=list)
58
+ recommended_route: RouteOption | None = None
59
+ resources_needed: list[str] = Field(default_factory=list)
60
+ estimated_response_time: str
61
+ plan_summary: str
62
+ confidence: float = Field(default=0.8, ge=0.0, le=1.0)
63
+
64
+
65
+ # ── Maps function tool ────────────────────────────────────────────────────
66
+
67
+
68
+ async def _fetch_routes_tool_impl(origin: str, destination: str) -> str:
69
+ """Business logic for fetch_routes_tool — separated for unit testing."""
70
+ routes = await _fetch_routes_impl(origin, destination)
71
+ if not routes:
72
+ return json.dumps({
73
+ "routes": [],
74
+ "count": 0,
75
+ "status": "NO_ROUTES",
76
+ "suggestion": (
77
+ "No routes returned — GOOGLE_MAPS_API_KEY may be unset or the "
78
+ "address format may be invalid. Use Pakistani sector format: "
79
+ "'G-10 Markaz, Islamabad'. Proceed with plan_summary noting "
80
+ "that alternate route data is unavailable."
81
+ ),
82
+ })
83
+ return json.dumps({
84
+ "routes": [r.model_dump() for r in routes],
85
+ "count": len(routes),
86
+ "status": "OK",
87
+ })
88
+
89
+
90
+ @function_tool
91
+ async def fetch_routes_tool(origin: str, destination: str) -> str:
92
+ """Fetch real alternate route options from the Google Maps Directions API.
93
+
94
+ Use when:
95
+ - The crisis type is flood, traffic_jam, or road_blockage.
96
+ - Vehicles need to be rerouted around the affected area.
97
+ - The response plan must name specific alternate roads.
98
+
99
+ Do NOT use for:
100
+ - Fire-only or building_collapse scenarios where traffic rerouting
101
+ is not the primary response action.
102
+ - When the crisis has no road-access impact.
103
+
104
+ Args:
105
+ origin: Starting point as Pakistani address or "lat,lon" string.
106
+ Example: "G-10 Markaz, Islamabad" or "33.6844,73.0479".
107
+ destination: End point that bypasses the affected area.
108
+ Example: "F-10 Markaz, Islamabad" or "Kashmir Highway, Islamabad".
109
+
110
+ Returns:
111
+ JSON with:
112
+ routes: list of {summary, distance_km, duration_minutes, polyline, is_recommended}
113
+ count: number of routes
114
+ status: "OK" | "NO_ROUTES"
115
+ On failure includes a suggestion field to guide plan fallback.
116
+ """
117
+ return await _fetch_routes_tool_impl(origin, destination)
118
+
119
+
120
+ # ── Agent definition ──────────────────────────────────────────────────────
121
+
122
+
123
+ _INSTRUCTIONS = """\
124
+ You are a crisis response planner for Pakistani urban areas (Islamabad, Karachi, Lahore).
125
+ You receive the full situational picture: crisis type, location, risk level, severity (1-5), a plain-language situation summary, and — for traffic/flood crises — pre-fetched alternate route data.
126
+
127
+ Your job is to produce a ResponsePlan with:
128
+
129
+ 1. immediate_actions (0-5 min): critical interventions that prevent escalation right now.
130
+ 2. short_term_actions (5-30 min): follow-up coordination, resource staging, public alerts.
131
+ 3. resources_needed: specific units, e.g. "2 fire trucks from F-11 station", "Rescue 1122 ambulance", "traffic wardens at G-9 Markaz".
132
+ 4. estimated_response_time: realistic for Pakistani emergency services (police ~8 min, fire brigade ~15 min, Rescue 1122 ~10 min in major cities).
133
+ 5. route_options + recommended_route: copy the routes exactly from the "### Available Routes ###" section of the input if provided. Set recommended_route to the one with is_recommended=true. If no routes are provided, leave both as empty/null and note this in plan_summary.
134
+ 6. plan_summary: one clear paragraph a non-technical coordinator can act on. No JSON, no jargon.
135
+ 7. confidence: your confidence in this plan (0.0-1.0).
136
+
137
+ Be specific to the Pakistani context: name real roads (Margalla Road, Kashmir Highway, Islamabad Expressway, Khayaban-e-Iqbal), real services (Islamabad Police, CDA, Rescue 1122), and sector names.
138
+ Return the result strictly as the ResponsePlan schema.
139
+ """
140
+
141
+ # Note: tools are NOT registered here — Gemini's OpenAI-compat endpoint does not
142
+ # support function calling + JSON-mode structured output simultaneously.
143
+ # Routes are pre-fetched in run_planning() and injected into the prompt.
144
+ planning_agent = Agent(
145
+ name="action_planning_agent",
146
+ instructions=_INSTRUCTIONS,
147
+ model=get_gemini_model(),
148
+ output_type=ResponsePlan,
149
+ )
150
+
151
+
152
+ # ── Input formatting ──────────────────────────────────────────────────────
153
+
154
+
155
+ # Crisis types that benefit from traffic rerouting.
156
+ _REROUTE_TYPES: frozenset[str] = frozenset({"flood", "traffic_jam", "road_blockage"})
157
+
158
+ # General Islamabad bypass destination used when fetching alternate routes.
159
+ # Routes are fetched from the crisis location → this point, giving the Maps
160
+ # API enough geographic distance to return meaningful alternatives.
161
+ _ISLAMABAD_DESTINATION = "Zero Point Interchange, Islamabad"
162
+
163
+
164
+ def _format_inputs(
165
+ detection: DetectionOutput,
166
+ risk: RiskTieringResult,
167
+ analysis: SituationReport,
168
+ routes: list[RouteOption],
169
+ ) -> str:
170
+ """Render upstream pipeline context as a structured planning prompt."""
171
+ lines: list[str] = [
172
+ "### Crisis Context ###",
173
+ f"Crisis Type : {detection.crisis_type}",
174
+ f"Location : {detection.location_label} ({detection.coordinates})",
175
+ f"Detection Conf : {detection.confidence:.2f}",
176
+ "",
177
+ "### Risk Assessment ###",
178
+ f"Risk Level : {risk.risk_level}",
179
+ f"Requires Emergency Services: {risk.requires_emergency_services}",
180
+ f"Requires Crowd Verification: {risk.requires_crowd_verification}",
181
+ f"Auto Response Actions : {risk.auto_response_actions or 'none'}",
182
+ "",
183
+ "### Situation Report ###",
184
+ f"Severity : {analysis.severity}/5 ({analysis.severity_label})",
185
+ f"Affected Pop : {analysis.affected_population_estimate}",
186
+ f"Impacts : {', '.join(analysis.impacts)}",
187
+ f"Confidence : {analysis.confidence:.2f}",
188
+ f"Summary : {analysis.explanation}",
189
+ f"Missing Info : {', '.join(analysis.missing_info) if analysis.missing_info else 'none'}",
190
+ ]
191
+
192
+ if routes:
193
+ lines += ["", f"### Available Routes ({len(routes)}) ###"]
194
+ for r in routes:
195
+ lines.append(
196
+ f" - summary={r.summary!r} distance_km={r.distance_km}"
197
+ f" duration_minutes={r.duration_minutes}"
198
+ f" polyline={r.polyline!r}"
199
+ f" is_recommended={r.is_recommended}"
200
+ )
201
+ lines.append(
202
+ "Copy these routes verbatim into route_options. Set recommended_route "
203
+ "to the entry where is_recommended=true."
204
+ )
205
+ else:
206
+ lines += [
207
+ "",
208
+ "### Available Routes ###",
209
+ "No route data available (Maps API key unset or unavailable).",
210
+ "Set route_options=[] and recommended_route=null. Note this in plan_summary.",
211
+ ]
212
+
213
+ lines.append("")
214
+ lines.append("Generate a complete ResponsePlan based on the above.")
215
+ return "\n".join(lines)
216
+
217
+
218
+ # ── Synthetic shortcut ────────────────────────────────────────────────────
219
+
220
+
221
+ def _synthetic_no_crisis_plan(reason: str) -> AgentResult:
222
+ """Return a trivial no-action plan without consuming a Gemini call."""
223
+ plan = ResponsePlan(
224
+ immediate_actions=[],
225
+ short_term_actions=[],
226
+ route_options=[],
227
+ recommended_route=None,
228
+ resources_needed=[],
229
+ estimated_response_time="N/A",
230
+ plan_summary=reason,
231
+ confidence=1.0,
232
+ )
233
+ return AgentResult(
234
+ agent_name=planning_agent.name,
235
+ success=True,
236
+ output=plan.model_dump(),
237
+ reasoning=reason,
238
+ confidence=1.0,
239
+ )
240
+
241
+
242
+ # ── Pipeline entry point ──────────────────────────────────────────────────
243
+
244
+
245
+ async def run_planning(
246
+ detection: DetectionOutput,
247
+ risk: RiskTieringResult,
248
+ analysis: SituationReport,
249
+ ) -> AgentResult:
250
+ """Run the action planning agent.
251
+
252
+ Pre-fetches alternate routes from Google Maps for traffic-impacted crisis
253
+ types and injects them into the prompt before calling Gemini. This avoids
254
+ the Gemini compatibility limitation where function calling and JSON-mode
255
+ structured output cannot be used together.
256
+
257
+ Args:
258
+ detection: Phase 5 detection verdict.
259
+ risk: Phase 6 risk tier result.
260
+ analysis: Phase 7 situation report.
261
+
262
+ Returns:
263
+ An `AgentResult` whose `output` is a `ResponsePlan` dict.
264
+ """
265
+ if not detection.crisis_detected:
266
+ return _synthetic_no_crisis_plan(
267
+ "No crisis detected in the previous stage; planning skipped."
268
+ )
269
+
270
+ # Pre-fetch routes for crisis types that involve traffic rerouting.
271
+ routes: list[RouteOption] = []
272
+ if detection.crisis_type in _REROUTE_TYPES and detection.coordinates:
273
+ lat, lon = detection.coordinates
274
+ origin = f"{lat},{lon}"
275
+ routes = await _fetch_routes_impl(origin, _ISLAMABAD_DESTINATION)
276
+ logger.info(
277
+ "Pre-fetched %d route(s) for %s crisis at %s",
278
+ len(routes),
279
+ detection.crisis_type,
280
+ detection.location_label,
281
+ )
282
+
283
+ prompt = _format_inputs(detection, risk, analysis, routes)
284
+ return await run_agent(planning_agent, prompt)
src/backend/agents/simulation.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Simulation Agent — Phase 12 (final pipeline stage).
3
+
4
+ Responsibility
5
+ --------------
6
+ Takes the response plan from Phase 8 and simulates its execution in a
7
+ mock environment, producing the before/after state comparison and dispatch
8
+ ticket that the mobile app's outcome visualization screen renders.
9
+
10
+ Architecture notes (multi-agent-patterns)
11
+ -----------------------------------------
12
+ This is the terminal stage of the sequential supervisor pipeline. It
13
+ receives verbatim outputs from detection, analysis, and planning — no
14
+ paraphrasing, no supervisor synthesis. The agent only reasons about AFTER
15
+ state and outcomes; before-state and dispatch-ticket are constructed
16
+ deterministically so they are always consistent and predictable.
17
+
18
+ Tool design (tool-design skill)
19
+ --------------------------------
20
+ This agent has no function tools — pure reasoning over provided context.
21
+ Adding tools would add coordination overhead with no upside: the simulation
22
+ is a one-shot structured-output call. The rich prompt context is sufficient.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import logging
28
+ import random
29
+ from datetime import datetime, timezone
30
+ from typing import Any
31
+
32
+ from agents import Agent
33
+ from pydantic import ValidationError
34
+
35
+ from backend.agents.analysis import SituationReport
36
+ from backend.agents.detection import DetectionOutput
37
+ from backend.core.model import get_gemini_model
38
+ from backend.core.runner import run_agent
39
+ from backend.models.agent_result import AgentResult
40
+ from backend.models.risk import RiskTieringResult
41
+ from backend.models.simulation import (
42
+ DispatchTicket,
43
+ DispatchedUnit,
44
+ SimulationAgentOutput,
45
+ SimulationResult,
46
+ SystemState,
47
+ )
48
+ from backend.services.whatsapp import dispatch_emergency_whatsapp
49
+
50
+ logger = logging.getLogger(__name__)
51
+
52
+
53
+ # ── Deterministic helpers ─────────────────────────────────────────────────────
54
+
55
+
56
+ # Severity → before-state congestion level (phase doc table).
57
+ _SEVERITY_TO_CONGESTION = {
58
+ 1: "light",
59
+ 2: "moderate",
60
+ 3: "heavy",
61
+ 4: "severe",
62
+ 5: "severe",
63
+ }
64
+
65
+ # Standard Pakistani emergency units per crisis type.
66
+ _EMERGENCY_UNITS: dict[str, list[dict]] = {
67
+ "flood": [
68
+ {"service": "Rescue 1122", "units": 2, "eta_minutes": 8},
69
+ {"service": "Islamabad Police (15)", "units": 1, "eta_minutes": 5},
70
+ {"service": "EDHI Ambulance", "units": 1, "eta_minutes": 12},
71
+ ],
72
+ "fire": [
73
+ {"service": "Islamabad Fire Brigade", "units": 2, "eta_minutes": 6},
74
+ {"service": "Rescue 1122", "units": 1, "eta_minutes": 8},
75
+ {"service": "Islamabad Police (15)", "units": 1, "eta_minutes": 5},
76
+ ],
77
+ "accident": [
78
+ {"service": "EDHI Ambulance", "units": 2, "eta_minutes": 7},
79
+ {"service": "Islamabad Police (15)", "units": 1, "eta_minutes": 5},
80
+ {"service": "Rescue 1122", "units": 1, "eta_minutes": 10},
81
+ ],
82
+ "building_collapse": [
83
+ {"service": "Rescue 1122", "units": 3, "eta_minutes": 8},
84
+ {"service": "Islamabad Fire Brigade", "units": 1, "eta_minutes": 6},
85
+ {"service": "EDHI Ambulance", "units": 2, "eta_minutes": 7},
86
+ ],
87
+ "heatwave": [
88
+ {"service": "EDHI Ambulance", "units": 2, "eta_minutes": 10},
89
+ {"service": "CDA Emergency Services", "units": 1, "eta_minutes": 15},
90
+ ],
91
+ "infrastructure": [
92
+ {"service": "CDA Emergency Services", "units": 2, "eta_minutes": 12},
93
+ {"service": "Islamabad Police (15)", "units": 1, "eta_minutes": 5},
94
+ ],
95
+ "infrastructure_failure": [
96
+ {"service": "CDA Emergency Services", "units": 2, "eta_minutes": 12},
97
+ {"service": "Islamabad Police (15)", "units": 1, "eta_minutes": 5},
98
+ ],
99
+ }
100
+
101
+
102
+ def build_before_state(situation_report: SituationReport) -> SystemState:
103
+ """Construct the pre-response system state from the situation report.
104
+
105
+ Deterministic: severity maps directly to congestion level and area
106
+ status per the phase doc specification. All counters start at zero
107
+ (nothing has been deployed yet).
108
+ """
109
+ return SystemState(
110
+ congestion_level=_SEVERITY_TO_CONGESTION.get(situation_report.severity, "heavy"),
111
+ affected_area_status="crisis active",
112
+ vehicles_rerouted=0,
113
+ emergency_units_deployed=0,
114
+ citizens_alerted=0,
115
+ ngos_activated=0,
116
+ )
117
+
118
+
119
+ def build_dispatch_ticket(
120
+ crisis_id: str,
121
+ detection_output: DetectionOutput,
122
+ situation_report: SituationReport,
123
+ risk_tiering_output: RiskTieringResult,
124
+ ) -> DispatchTicket | None:
125
+ """Build the emergency dispatch ticket, or None for low-risk crises.
126
+
127
+ Returns None when `requires_emergency_services=False` (traffic jam,
128
+ rainfall, road_blockage) — these crises use automated rerouting only.
129
+ """
130
+ if not risk_tiering_output.requires_emergency_services:
131
+ return None
132
+
133
+ crisis_type = detection_output.crisis_type or "unknown"
134
+ raw_units = _EMERGENCY_UNITS.get(crisis_type, _EMERGENCY_UNITS["flood"])
135
+ units = [DispatchedUnit(**u) for u in raw_units]
136
+
137
+ year = datetime.now(timezone.utc).year
138
+ ticket_num = random.randint(1000, 9999) # noqa: S311 — demo ID, not security-critical
139
+
140
+ return DispatchTicket(
141
+ ticket_id=f"CIR-{year}-{ticket_num:04d}",
142
+ status="DISPATCHED",
143
+ crisis_id=crisis_id,
144
+ crisis_type=crisis_type,
145
+ location_label=detection_output.location_label or "unknown",
146
+ severity=situation_report.severity,
147
+ units_dispatched=units,
148
+ issued_at=datetime.now(timezone.utc),
149
+ )
150
+
151
+
152
+ # ── Agent definition ──────────────────────────────────────────────────────────
153
+
154
+
155
+ _INSTRUCTIONS = """\
156
+ You are a crisis response simulation engine for Pakistani urban areas
157
+ (Islamabad, Karachi, Lahore).
158
+
159
+ You receive:
160
+ - A detected crisis (type, location, severity 1-5)
161
+ - A situation report (impacts, affected population)
162
+ - A response plan (immediate and short-term actions, resources needed)
163
+ - The BEFORE state of the affected area (congestion, status)
164
+ - Number of NGOs already alerted
165
+
166
+ Your job is to simulate the execution of the response plan and produce
167
+ the AFTER state plus a list of executed actions with realistic outcomes.
168
+
169
+ Rules:
170
+ 1. AFTER state must show meaningful improvement from BEFORE:
171
+ - congestion_level must decrease (e.g. severe → heavy or moderate)
172
+ - affected_area_status must improve (crisis active → contained or resolved)
173
+ - vehicles_rerouted, emergency_units_deployed, citizens_alerted must be > 0
174
+ 2. actions_executed must list at least 3 actions from the plan with:
175
+ - realistic simulated_effect in Pakistani urban context
176
+ - plausible duration_minutes (5–60)
177
+ - status: "completed" for immediate actions, "in_progress" for short-term
178
+ 3. Use Pakistani emergency services where relevant:
179
+ Rescue 1122, Islamabad Police (15), EDHI, CDA, Islamabad Fire Brigade
180
+ 4. Estimates must be plausible — not "100% resolved" or absurd numbers
181
+ 5. ngos_activated in AFTER state must equal the provided NGO count
182
+ 6. outcome_summary must be plain English readable by a non-technical coordinator
183
+
184
+ Return strictly as SimulationAgentOutput. Do not add prose outside the schema.
185
+ """
186
+
187
+ simulation_agent = Agent(
188
+ name="simulation_agent",
189
+ instructions=_INSTRUCTIONS,
190
+ model=get_gemini_model(),
191
+ output_type=SimulationAgentOutput,
192
+ )
193
+
194
+
195
+ # ── Prompt formatter ──────────────────────────────────────────────────────────
196
+
197
+
198
+ def _format_simulation_prompt(
199
+ detection_output: DetectionOutput,
200
+ situation_report: SituationReport,
201
+ planning_output: dict[str, Any],
202
+ before: SystemState,
203
+ ngos_activated: int,
204
+ ) -> str:
205
+ """Format all pipeline context into a single structured prompt for the agent.
206
+
207
+ Passes verbatim outputs from previous stages — no paraphrasing (avoids
208
+ the telephone-game problem described in the multi-agent-patterns skill).
209
+ """
210
+ immediate = planning_output.get("immediate_actions", [])
211
+ short_term = planning_output.get("short_term_actions", [])
212
+ resources = planning_output.get("resources_needed", [])
213
+
214
+ lines = [
215
+ f"CRISIS: {detection_output.crisis_type} at {detection_output.location_label}",
216
+ f"SEVERITY: {situation_report.severity}/5 ({situation_report.severity_label})",
217
+ f"AFFECTED: {situation_report.affected_population_estimate}",
218
+ "",
219
+ "IMPACTS:",
220
+ *[f" - {impact}" for impact in situation_report.impacts],
221
+ "",
222
+ "BEFORE STATE:",
223
+ f" congestion_level: {before.congestion_level}",
224
+ f" affected_area_status: {before.affected_area_status}",
225
+ f" vehicles_rerouted: 0, emergency_units_deployed: 0, citizens_alerted: 0",
226
+ f" ngos_activated: 0",
227
+ "",
228
+ "NGOS ALREADY ALERTED: " + str(ngos_activated),
229
+ "",
230
+ "IMMEDIATE ACTIONS:",
231
+ *[f" [{i+1}] {a}" for i, a in enumerate(immediate)],
232
+ "",
233
+ "SHORT-TERM ACTIONS:",
234
+ *[f" [{i+1}] {a}" for i, a in enumerate(short_term)],
235
+ "",
236
+ "RESOURCES NEEDED:",
237
+ *[f" - {r}" for r in resources],
238
+ "",
239
+ f"PLANNED RESPONSE TIME: {planning_output.get('estimated_response_time', 'unknown')}",
240
+ "",
241
+ "Simulate the execution of this plan. Produce the AFTER state showing "
242
+ "meaningful improvements, list each executed action with its effect, "
243
+ "and write a plain-English outcome_summary for the crisis coordinator.",
244
+ ]
245
+ return "\n".join(lines)
246
+
247
+
248
+ # ── Public entry point ───────────────────���────────────────────────────────────
249
+
250
+
251
+ async def run_simulation(
252
+ detection_output: DetectionOutput,
253
+ situation_report: SituationReport,
254
+ planning_output: dict[str, Any],
255
+ risk_tiering_output: RiskTieringResult,
256
+ escalation_output: dict[str, Any],
257
+ crisis_id: str | None = None,
258
+ ) -> AgentResult:
259
+ """Run the simulation agent and return an AgentResult wrapping SimulationResult.
260
+
261
+ Args:
262
+ detection_output: Validated detection agent output.
263
+ situation_report: Validated situation analysis output.
264
+ planning_output: Raw dict of the planning agent's ResponsePlan.
265
+ risk_tiering_output: Risk tier — determines dispatch_ticket presence.
266
+ escalation_output: Raw dict of the NGO escalation result (may be empty
267
+ for low-risk crises that skipped Phase 11).
268
+ crisis_id: Firestore document ID, used in the dispatch ticket.
269
+
270
+ Returns:
271
+ AgentResult whose output is SimulationResult.model_dump(mode="json").
272
+ Never raises — any failure collapses to success=False.
273
+ """
274
+ # Build deterministic parts before calling the LLM.
275
+ before = build_before_state(situation_report)
276
+ dispatch = build_dispatch_ticket(
277
+ crisis_id=crisis_id or "DEMO",
278
+ detection_output=detection_output,
279
+ situation_report=situation_report,
280
+ risk_tiering_output=risk_tiering_output,
281
+ )
282
+ ngos_activated: int = len(escalation_output.get("ngos_alerted") or [])
283
+
284
+ prompt = _format_simulation_prompt(
285
+ detection_output=detection_output,
286
+ situation_report=situation_report,
287
+ planning_output=planning_output,
288
+ before=before,
289
+ ngos_activated=ngos_activated,
290
+ )
291
+
292
+ # Run the LLM agent.
293
+ agent_result = await run_agent(simulation_agent, prompt)
294
+ if not agent_result.success:
295
+ return agent_result
296
+
297
+ # Reconstruct structured output from the raw dict the runner stored.
298
+ try:
299
+ sim_output = SimulationAgentOutput.model_validate(agent_result.output)
300
+ except ValidationError as exc:
301
+ return AgentResult(
302
+ agent_name="simulation_agent",
303
+ success=False,
304
+ output={"error": "INVALID_SIMULATION_OUTPUT", "raw": agent_result.output},
305
+ reasoning=f"Simulation output failed schema validation: {exc}",
306
+ confidence=0.0,
307
+ )
308
+
309
+ # Assemble the final SimulationResult.
310
+ sim_result = SimulationResult(
311
+ before=before,
312
+ after=sim_output.after,
313
+ actions_executed=sim_output.actions_executed,
314
+ dispatch_ticket=dispatch,
315
+ outcome_summary=sim_output.outcome_summary,
316
+ time_to_resolution_estimate=sim_output.time_to_resolution_estimate,
317
+ )
318
+
319
+ # WhatsApp emergency dispatch — real side effect, non-fatal.
320
+ if dispatch:
321
+ units_summary = "\n".join(
322
+ f" - {u.service}: {u.units} unit(s), ETA {u.eta_minutes} min"
323
+ for u in dispatch.units_dispatched
324
+ )
325
+ try:
326
+ await dispatch_emergency_whatsapp(
327
+ ticket_id=dispatch.ticket_id,
328
+ crisis_type=dispatch.crisis_type,
329
+ location=detection_output.location_label or "",
330
+ severity=situation_report.severity,
331
+ units_summary=units_summary,
332
+ affected_population=situation_report.affected_population_estimate,
333
+ )
334
+ except Exception as exc: # noqa: BLE001
335
+ logger.warning("WhatsApp dispatch failed (non-fatal): %s", exc)
336
+
337
+ return AgentResult(
338
+ agent_name="simulation_agent",
339
+ success=True,
340
+ output=sim_result.model_dump(mode="json"),
341
+ reasoning=sim_output.reasoning,
342
+ confidence=sim_output.confidence,
343
+ )
src/backend/core/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Core module — config loader, constants, shared utilities
src/backend/core/auth.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import Depends, HTTPException, status
2
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
3
+ from firebase_admin import auth as firebase_auth
4
+
5
+ security = HTTPBearer()
6
+
7
+ async def get_current_user(
8
+ credentials: HTTPAuthorizationCredentials = Depends(security)
9
+ ) -> dict:
10
+ """
11
+ Extracts and verifies the Firebase JWT token from the Authorization header.
12
+ Returns a dictionary containing 'uid' and optionally 'phone_number'.
13
+ """
14
+ token = credentials.credentials
15
+ try:
16
+ # Verify the token against Firebase. This checks signature and expiration.
17
+ # It automatically uses the initialized Firebase app.
18
+ decoded = firebase_auth.verify_id_token(token)
19
+ return {
20
+ "uid": decoded["uid"],
21
+ "phone_number": decoded.get("phone_number"),
22
+ }
23
+ except Exception as e:
24
+ # The phase definition specifies returning a specific message on expiry/invalid token
25
+ # but Firebase exception might be more specific. We'll return a general message
26
+ # mentioning "Token expired" or invalid as requested.
27
+ raise HTTPException(
28
+ status_code=status.HTTP_401_UNAUTHORIZED,
29
+ detail="Token expired — please re-authenticate" if "expired" in str(e).lower() else "Invalid or expired token",
30
+ headers={"WWW-Authenticate": "Bearer"},
31
+ )
src/backend/core/config.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CIRO Backend — Application Configuration
3
+
4
+ All environment variables are loaded from .env via pydantic-settings.
5
+ Import `settings` (the singleton instance), never the class directly.
6
+ """
7
+
8
+ import os
9
+
10
+ from pydantic_settings import BaseSettings, SettingsConfigDict
11
+
12
+
13
+ class Settings(BaseSettings):
14
+ """Typed, validated application settings loaded from environment variables."""
15
+
16
+ model_config = SettingsConfigDict(
17
+ env_file=".env",
18
+ env_file_encoding="utf-8",
19
+ case_sensitive=False,
20
+ extra="ignore",
21
+ )
22
+
23
+ # ── LLM / Agent Keys ─────────────────────────────────────────────
24
+ gemini_api_key: str = ""
25
+ openai_api_key: str = ""
26
+
27
+ # ── Google Maps ───────────────────────────────────────────────────
28
+ google_maps_api_key: str = ""
29
+
30
+ # ── Weather ───────────────────────────────────────────────────────
31
+ openweathermap_api_key: str = ""
32
+
33
+ # ── Firebase ──────────────────────────────────────────────────────
34
+ firebase_credentials_path: str = ""
35
+
36
+ # ── WhatsApp (Meta Cloud API — test mode) ─────────────────────────
37
+ whatsapp_token: str = ""
38
+ whatsapp_phone_id: str = ""
39
+ whatsapp_fire_brigade_number: str = ""
40
+ whatsapp_police_number: str = ""
41
+ whatsapp_ambulance_number: str = ""
42
+
43
+ # ── Application ───────────────────────────────────────────────────
44
+ environment: str = "development"
45
+ debug: bool = False
46
+ port: int = 8080
47
+
48
+ def __init__(self, **kwargs):
49
+ super().__init__(**kwargs)
50
+ # Bridge pydantic-settings → os.environ for third-party SDKs
51
+ # (OpenAI Agents SDK reads OPENAI_API_KEY from os.environ)
52
+ if self.openai_api_key and not os.environ.get("OPENAI_API_KEY"):
53
+ os.environ["OPENAI_API_KEY"] = self.openai_api_key
54
+ if self.gemini_api_key and not os.environ.get("GEMINI_API_KEY"):
55
+ os.environ["GEMINI_API_KEY"] = self.gemini_api_key
56
+
57
+
58
+ # Global settings instance — import this, not the class
59
+ settings = Settings()
src/backend/core/constants.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Hard-coded constants for CIRO's deterministic decision logic.
3
+
4
+ What lives here
5
+ ---------------
6
+ Constants that are NOT meant to be tuned per request or per environment —
7
+ they encode product decisions about how CIRO classifies and responds to
8
+ crises. Putting them in one module keeps risk-tiering, planning, and
9
+ the UI in lockstep about which types map to which tier.
10
+
11
+ What does NOT live here
12
+ -----------------------
13
+ Environment-driven config (API keys, feature flags, ports) — that
14
+ belongs in `core/config.py` (pydantic-settings). If a value is something
15
+ ops would change, it goes there, not here.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ # ── Risk tiering ──────────────────────────────────────────────────────────
21
+ #
22
+ # These sets define the response path a crisis takes after detection:
23
+ #
24
+ # LOW_RISK_TYPES → automated response (reroute, alert), no humans
25
+ # MEDIUM_HIGH_RISK_TYPES → requires crowd verification before any
26
+ # emergency dispatch
27
+ #
28
+ # Crisis types not in either set are treated as MEDIUM by the classifier
29
+ # (fail-safe default — never silently skip verification for an unknown
30
+ # type).
31
+
32
+ LOW_RISK_TYPES: frozenset[str] = frozenset({
33
+ "traffic_jam",
34
+ "rainfall",
35
+ "road_blockage",
36
+ })
37
+
38
+ MEDIUM_HIGH_RISK_TYPES: frozenset[str] = frozenset({
39
+ "flood",
40
+ "fire",
41
+ "accident",
42
+ "building_collapse",
43
+ "infrastructure_failure",
44
+ "infrastructure", # alias used by the detection taxonomy
45
+ "heatwave",
46
+ })
47
+
48
+ # Confidence threshold below which a high-risk crisis is downgraded to
49
+ # medium. The intent: "we are not confident enough to skip crowd
50
+ # verification, but we are confident enough to investigate further."
51
+ # Hard-coded — not configurable per request, per the phase doc's
52
+ # architectural constraint.
53
+ CONFIDENCE_THRESHOLD: float = 0.6
54
+
55
+
56
+ # ── NGO escalation ────────────────────────────────────────────────────────
57
+ #
58
+ # Severity score (1-5, from SituationReport) at or above which a confirmed
59
+ # crisis is escalated to registered NGOs. Hard-coded per the phase doc.
60
+
61
+ NGO_ESCALATION_THRESHOLD: int = 3
62
+
63
+ # Maps crisis type to the NGO categories that are relevant for that type.
64
+ # An NGO matches when it has at least one category from this list AND its
65
+ # coverage_areas overlap with the crisis location. Any crisis type not in
66
+ # this map is treated as requiring "disaster_relief" as a fallback.
67
+ NGO_CRISIS_TYPE_MAP: dict[str, list[str]] = {
68
+ "flood": ["disaster_relief", "rescue"],
69
+ "fire": ["fire_rescue", "medical"],
70
+ "accident": ["medical", "rescue"],
71
+ "building_collapse": ["rescue", "disaster_relief", "medical"],
72
+ "heatwave": ["medical", "community_welfare"],
73
+ "infrastructure_failure": ["disaster_relief"],
74
+ "infrastructure": ["disaster_relief"], # detection-agent alias
75
+ }
src/backend/core/firebase.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import logging
4
+ import firebase_admin
5
+ from firebase_admin import credentials, firestore_async
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ def init_firebase():
10
+ """Initializes the Firebase Admin SDK singleton.
11
+
12
+ Credential resolution order:
13
+ 1. FIREBASE_CREDENTIALS_JSON — full service-account JSON as a string
14
+ (used on HF Spaces, where no key file can be committed).
15
+ 2. FIREBASE_CREDENTIALS_PATH — path to a service-account JSON file.
16
+ 3. Application default credentials (Cloud Run / gcloud).
17
+ """
18
+ if not firebase_admin._apps:
19
+ cred_json = os.getenv("FIREBASE_CREDENTIALS_JSON", "").strip()
20
+ cred_path = os.getenv("FIREBASE_CREDENTIALS_PATH", "serviceAccountKey.json")
21
+ try:
22
+ if cred_json:
23
+ cred = credentials.Certificate(json.loads(cred_json))
24
+ firebase_admin.initialize_app(cred)
25
+ logger.info("Firebase initialized from FIREBASE_CREDENTIALS_JSON env var.")
26
+ elif os.path.exists(cred_path):
27
+ cred = credentials.Certificate(cred_path)
28
+ firebase_admin.initialize_app(cred)
29
+ logger.info(f"Firebase initialized with credentials at {cred_path}")
30
+ else:
31
+ firebase_admin.initialize_app()
32
+ logger.warning(f"Credentials not found at {cred_path}, falling back to default application credentials.")
33
+ except Exception as e:
34
+ logger.error(f"Failed to initialize Firebase: {e}")
35
+ raise
36
+
37
+ def get_async_db():
38
+ """Returns the asynchronous Firestore client."""
39
+ from google.cloud import firestore
40
+ import firebase_admin
41
+ import os
42
+
43
+ app = firebase_admin.get_app()
44
+ cred = app.credential.get_credential()
45
+ db_id = os.getenv("FIRESTORE_DATABASE_ID", "default")
46
+
47
+ return firestore.AsyncClient(
48
+ project=app.project_id,
49
+ credentials=cred,
50
+ database=db_id
51
+ )
52
+
53
+ def get_db():
54
+ """Returns the synchronous Firestore client."""
55
+ from google.cloud import firestore
56
+ import firebase_admin
57
+ import os
58
+
59
+ app = firebase_admin.get_app()
60
+ cred = app.credential.get_credential()
61
+ db_id = os.getenv("FIRESTORE_DATABASE_ID", "default")
62
+
63
+ return firestore.Client(
64
+ project=app.project_id,
65
+ credentials=cred,
66
+ database=db_id
67
+ )
src/backend/core/model.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gemini ↔ OpenAI Agents SDK bridge.
3
+
4
+ Why this exists
5
+ ---------------
6
+ CIRO standardizes on the OpenAI Agents SDK for orchestration (tracing, tool
7
+ calls, handoffs) but uses Google Gemini as the underlying LLM. Gemini exposes
8
+ an OpenAI-compatible REST surface at
9
+ `https://generativelanguage.googleapis.com/v1beta/openai/`, so we plug it in
10
+ as a custom `AsyncOpenAI` client wrapped by `OpenAIChatCompletionsModel`.
11
+
12
+ Every agent in the project imports `get_gemini_model()` from here. That keeps
13
+ model selection, base_url, and API-key wiring in one place — swap the model
14
+ ID once and every agent inherits the change.
15
+ """
16
+
17
+ from functools import lru_cache
18
+
19
+ from agents import OpenAIChatCompletionsModel
20
+ from openai import AsyncOpenAI
21
+
22
+ from backend.core.config import settings
23
+
24
+ # Gemini's OpenAI-compatible endpoint. Documented at:
25
+ # https://ai.google.dev/gemini-api/docs/openai
26
+ GEMINI_BASE_URL = "https://generativelanguage.googleapis.com/v1beta/openai/"
27
+
28
+ # Default model for every CIRO agent. `gemini-2.5-flash` is the cheap/fast tier
29
+ # and is sufficient for the hackathon's reasoning workloads. Phase-specific
30
+ # agents can override by passing `model=` to `get_gemini_model()`.
31
+ # (Note: `gemini-2.0-flash` was the original choice but is no longer issued to
32
+ # new API keys — use 2.5-flash going forward.)
33
+ DEFAULT_GEMINI_MODEL = "gemini-2.5-flash"
34
+
35
+
36
+ @lru_cache(maxsize=1)
37
+ def _gemini_client() -> AsyncOpenAI:
38
+ """Singleton AsyncOpenAI client pointed at Gemini.
39
+
40
+ Cached so we reuse a single underlying httpx connection pool across every
41
+ agent invocation in the process.
42
+ """
43
+ if not settings.gemini_api_key:
44
+ raise RuntimeError(
45
+ "GEMINI_API_KEY is not set. Add it to backend/.env before running "
46
+ "any agent — see backend/.env.example."
47
+ )
48
+
49
+ return AsyncOpenAI(
50
+ base_url=GEMINI_BASE_URL,
51
+ api_key=settings.gemini_api_key,
52
+ )
53
+
54
+
55
+ def get_gemini_model(model: str = DEFAULT_GEMINI_MODEL) -> OpenAIChatCompletionsModel:
56
+ """Return an SDK-ready model object backed by Gemini.
57
+
58
+ Args:
59
+ model: Gemini model ID (defaults to `gemini-2.0-flash`). Use a stronger
60
+ model like `gemini-2.0-pro` for higher-stakes reasoning stages
61
+ (planning, analysis) if quality demands it.
62
+
63
+ Returns:
64
+ An `OpenAIChatCompletionsModel` instance ready to pass to `Agent(model=...)`.
65
+ """
66
+ return OpenAIChatCompletionsModel(
67
+ model=model,
68
+ openai_client=_gemini_client(),
69
+ )
src/backend/core/runner.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Base agent runner — the single entry point every CIRO agent runs through.
3
+
4
+ Why this is the only way to run an agent
5
+ ----------------------------------------
6
+ Letting each phase call `Runner.run(...)` directly would mean each phase
7
+ re-implements its own error boundary, its own trace logging, its own
8
+ JSON parsing, and its own AgentResult assembly. By funneling everything
9
+ through `run_agent()`:
10
+
11
+ • every step in the pipeline yields a uniformly-shaped `AgentResult`,
12
+ • exceptions never escape into FastAPI route handlers (they collapse
13
+ into `success=False` results instead),
14
+ • the agent-trace timeline in the UI gets consistent data without
15
+ special-casing per stage.
16
+
17
+ The runner itself is intentionally stateless — all context is passed
18
+ explicitly so the same function can serve the synchronous pipeline,
19
+ streaming endpoints, and tests.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from datetime import datetime, timezone
25
+ from typing import Any
26
+
27
+ from agents import Agent, Runner
28
+ from pydantic import BaseModel, ValidationError
29
+
30
+ from backend.models.agent_result import AgentResult
31
+
32
+
33
+ def _coerce_output(
34
+ final_output: Any,
35
+ fallback_reasoning: str,
36
+ ) -> tuple[dict[str, Any], str, float]:
37
+ """Normalize whatever the agent returned into (output, reasoning, confidence).
38
+
39
+ Agents may return:
40
+ * a Pydantic model (when `output_type=...` is configured) — preferred,
41
+ * a dict (loose structured output),
42
+ * a plain string (e.g. the dummy/test agent).
43
+
44
+ We always end up with a dict for `output`, leaving `reasoning` either as
45
+ the model-provided field or the fallback text the runner generated.
46
+ """
47
+ if isinstance(final_output, BaseModel):
48
+ data = final_output.model_dump()
49
+ reasoning = str(data.get("reasoning") or fallback_reasoning)
50
+ confidence = float(data.get("confidence") or 0.0)
51
+ return data, reasoning, confidence
52
+
53
+ if isinstance(final_output, dict):
54
+ reasoning = str(final_output.get("reasoning") or fallback_reasoning)
55
+ confidence = float(final_output.get("confidence") or 0.0)
56
+ return final_output, reasoning, confidence
57
+
58
+ # Plain string / other — wrap so AgentResult.output stays a dict.
59
+ return {"text": str(final_output)}, fallback_reasoning, 0.0
60
+
61
+
62
+ async def run_agent(
63
+ agent: Agent[Any],
64
+ input: str | list[dict[str, Any]],
65
+ *,
66
+ context: Any = None,
67
+ max_turns: int = 10,
68
+ ) -> AgentResult:
69
+ """Run a single agent and return its result in canonical `AgentResult` form.
70
+
71
+ This is the function every pipeline stage calls. It never raises — any
72
+ exception from the SDK collapses into `AgentResult(success=False, ...)`
73
+ so the orchestrator can decide whether to continue or short-circuit.
74
+
75
+ Args:
76
+ agent: A configured `agents.Agent` (model, instructions, tools,
77
+ optional `output_type` for structured outputs).
78
+ input: Either a string prompt or a list of `{"role", "content"}`
79
+ message dicts for multi-turn input.
80
+ context: Optional user-defined context object that tools receive
81
+ through `RunContextWrapper`. The runner does not inspect it.
82
+ max_turns: Safety cap on tool-call → model round-trips. 10 is fine
83
+ for every current CIRO agent.
84
+
85
+ Returns:
86
+ An `AgentResult` describing what the agent did. On failure,
87
+ `success=False` and `reasoning` carries the exception message.
88
+ """
89
+ started_at = datetime.now(timezone.utc)
90
+
91
+ try:
92
+ run_result = await Runner.run(
93
+ agent,
94
+ input,
95
+ context=context,
96
+ max_turns=max_turns,
97
+ )
98
+ except Exception as exc: # noqa: BLE001 — boundary; collapse all failures.
99
+ return AgentResult(
100
+ agent_name=agent.name,
101
+ success=False,
102
+ output={"error": exc.__class__.__name__},
103
+ reasoning=f"Agent run failed: {exc}",
104
+ confidence=0.0,
105
+ timestamp=started_at,
106
+ )
107
+
108
+ fallback_reasoning = (
109
+ f"{agent.name} produced output without an explicit reasoning field."
110
+ )
111
+ output, reasoning, confidence = _coerce_output(
112
+ run_result.final_output,
113
+ fallback_reasoning=fallback_reasoning,
114
+ )
115
+
116
+ try:
117
+ return AgentResult(
118
+ agent_name=agent.name,
119
+ success=True,
120
+ output=output,
121
+ reasoning=reasoning,
122
+ confidence=confidence,
123
+ timestamp=datetime.now(timezone.utc),
124
+ )
125
+ except ValidationError as exc:
126
+ # The agent returned something that violates the AgentResult shape
127
+ # (e.g. confidence > 1). Treat as a soft failure rather than 500-ing.
128
+ return AgentResult(
129
+ agent_name=agent.name,
130
+ success=False,
131
+ output={"error": "INVALID_AGENT_OUTPUT", "raw": output},
132
+ reasoning=f"Output failed AgentResult validation: {exc}",
133
+ confidence=0.0,
134
+ timestamp=datetime.now(timezone.utc),
135
+ )
src/backend/core/tools.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tool registration pattern for CIRO agents.
3
+
4
+ This module owns the *pattern* for tool registration, not the tools themselves.
5
+ Each downstream phase ships its own tools:
6
+
7
+ Phase 4 weather_api / social_feed
8
+ Phase 8 maps_directions / dispatch_actions
9
+ Phase 10 fcm_push / firestore_lookup
10
+
11
+ …and registers them by exporting a `@function_tool`-decorated function from
12
+ its module. The pipeline picks which subset to hand to each agent at call time
13
+ (see `agents/pipeline.py`). There is intentionally no global tool registry —
14
+ keeping the surface explicit per agent reduces the "which tool do I pick?"
15
+ ambiguity that hurts model accuracy in multi-tool setups.
16
+
17
+ Conventions every CIRO tool must follow
18
+ ---------------------------------------
19
+ 1. **Verb-first name.** `get_weather`, `fetch_routes`, `send_push` — not
20
+ `weather` or `routes`. Verbs make the agent's tool-selection step
21
+ unambiguous.
22
+ 2. **Docstring shape: what / when / args / returns / errors.** The decorator
23
+ feeds the docstring straight to the LLM as the tool description, so
24
+ treat it as prompt engineering, not API docs.
25
+ 3. **Return JSON strings, not Python objects.** The SDK serializes whatever
26
+ you return, but explicit `json.dumps()` keeps the agent-visible payload
27
+ deterministic and lets you embed `error` + `suggestion` fields for
28
+ recovery (see `_ping_impl` below).
29
+ 4. **Separate `_impl` from the decorated wrapper** for any tool with real
30
+ business logic. Lets unit tests call `_impl` directly without going
31
+ through the SDK.
32
+
33
+ The dummy `ping` tool below is the reference implementation. Copy its shape
34
+ when you add a real tool.
35
+ """
36
+
37
+ import json
38
+
39
+ from agents import function_tool
40
+
41
+
42
+ # ── Reference dummy tool ──────────────────────────────────────────────────
43
+ #
44
+ # `ping` exists to (a) document the convention above and (b) give the Phase 3
45
+ # smoke test a deterministic tool to invoke without touching any external API.
46
+ # Real tools (weather, maps, FCM) will replace it from their own modules.
47
+
48
+
49
+ async def _ping_impl(message: str) -> str:
50
+ """Pure logic for `ping` — separated so it can be unit-tested without
51
+ going through the OpenAI Agents SDK.
52
+ """
53
+ if not message:
54
+ return json.dumps(
55
+ {
56
+ "error": "INVALID_INPUT",
57
+ "message": "message must be a non-empty string",
58
+ "suggestion": "Call ping again with a short non-empty message.",
59
+ }
60
+ )
61
+
62
+ return json.dumps({"echo": message, "status": "ok"})
63
+
64
+
65
+ @function_tool
66
+ async def ping(message: str) -> str:
67
+ """Echo a short message back. Reference tool used to verify the agent
68
+ pipeline is wired up correctly.
69
+
70
+ Use when:
71
+ - You are explicitly asked to verify tool calling works.
72
+ - You need a no-op tool to confirm an agent can invoke external code.
73
+ Do NOT use this for any real crisis reasoning.
74
+
75
+ Args:
76
+ message: Any short non-empty string. The tool echoes it back verbatim.
77
+
78
+ Returns:
79
+ JSON string of the form `{"echo": "<message>", "status": "ok"}`,
80
+ or `{"error": "INVALID_INPUT", "message": ..., "suggestion": ...}`
81
+ if `message` was empty.
82
+ """
83
+ return await _ping_impl(message)
src/backend/main.py ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CIRO Backend — FastAPI Application Entry Point
3
+
4
+ Run locally:
5
+ uv run uvicorn backend.main:app --reload
6
+ """
7
+
8
+ from contextlib import asynccontextmanager
9
+ from fastapi import FastAPI
10
+ from fastapi.middleware.cors import CORSMiddleware
11
+
12
+ from backend.core.config import settings
13
+ from backend.core.firebase import init_firebase
14
+ from backend.routes import auth, crises, crisis, crowd_verification, report, trace, weather
15
+
16
+ @asynccontextmanager
17
+ async def lifespan(app: FastAPI):
18
+ init_firebase()
19
+ yield
20
+
21
+ app = FastAPI(
22
+ title="CIRO Backend",
23
+ description="Crisis Intelligence & Response Orchestrator — agentic AI backend",
24
+ version="0.1.0",
25
+ debug=settings.debug,
26
+ lifespan=lifespan,
27
+ redoc_url="/redoc",
28
+ docs_url="/docs",
29
+ )
30
+
31
+ # ── CORS ──────────────────────────────────────────────────────────────
32
+ app.add_middleware(
33
+ CORSMiddleware,
34
+ allow_origins=["*"], # Tighten in production
35
+ allow_credentials=True,
36
+ allow_methods=["*"],
37
+ allow_headers=["*"],
38
+ )
39
+
40
+ # ── Routers ───────────────────────────────────────────────────────────
41
+ app.include_router(crises.router)
42
+ app.include_router(crisis.router)
43
+ app.include_router(trace.router)
44
+ app.include_router(report.router)
45
+ app.include_router(auth.router)
46
+ app.include_router(weather.router)
47
+ app.include_router(crowd_verification.router)
48
+
49
+ # ── Health Check ──────────────────────────────────────────────────────
50
+ @app.get("/")
51
+ async def root():
52
+ """Root endpoint — HF Spaces health-checks GET /."""
53
+ return {"status": "ok", "service": "ciro-backend"}
54
+
55
+
56
+ @app.get("/health")
57
+ async def health():
58
+ """Readiness probe for Cloud Run and local dev verification."""
59
+ return {"status": "ok"}
src/backend/models/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Models module — Pydantic request/response schemas
src/backend/models/agent_result.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ AgentResult — the canonical contract every agent in the CIRO pipeline returns.
3
+
4
+ Why this exists
5
+ ---------------
6
+ The pipeline (detection → analysis → planning → simulation) chains heterogeneous
7
+ agents together. Each stage feeds the next, and the agent-trace UI renders every
8
+ step uniformly. To keep that working, every agent — regardless of what it does —
9
+ must produce the same outer shape. That shape is `AgentResult`.
10
+
11
+ `output` is intentionally a free-form dict so individual agents can return their
12
+ own domain payload (detection verdict, risk tier, action plan, etc.) without
13
+ having to grow this base schema each time a new agent ships.
14
+ """
15
+
16
+ from datetime import datetime, timezone
17
+ from typing import Any
18
+
19
+ from pydantic import BaseModel, Field
20
+
21
+
22
+ class AgentResult(BaseModel):
23
+ """Uniform output every CIRO agent must produce.
24
+
25
+ Attributes:
26
+ agent_name: Stable identifier of the agent that produced this result
27
+ (e.g. "detection_agent"). Used in trace logs + downstream routing.
28
+ success: True iff the agent completed without raising. A `success=False`
29
+ result still carries `reasoning` describing why it failed so the
30
+ pipeline can short-circuit gracefully.
31
+ output: Free-form domain payload produced by the agent. Each agent
32
+ documents its own output keys in its own module.
33
+ reasoning: Plain-language explanation of how the agent reached its
34
+ decision. Surfaced directly in the in-app agent-trace timeline.
35
+ confidence: Self-reported confidence in `output`, clamped to [0, 1].
36
+ Downstream stages (risk tiering, crowd verification) use this.
37
+ timestamp: When the result was finalized (UTC). Used for ordering
38
+ steps in the trace log.
39
+ """
40
+
41
+ agent_name: str
42
+ success: bool
43
+ output: dict[str, Any] = Field(default_factory=dict)
44
+ reasoning: str = ""
45
+ confidence: float = Field(default=0.0, ge=0.0, le=1.0)
46
+ timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
src/backend/models/escalation.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ EscalationResult — output contract for Phase 11's NGO escalation service.
3
+
4
+ Consumed by:
5
+ Phase 12 for simulation context
6
+ Phase 13 agent trace log (ngos_alerted field)
7
+ Mobile agent-trace timeline (escalation step)
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from pydantic import BaseModel, ConfigDict
13
+
14
+
15
+ class EscalationResult(BaseModel):
16
+ """Outcome of the NGO escalation evaluation for a confirmed crisis.
17
+
18
+ Attributes:
19
+ escalated: True iff at least one NGO FCM notification was sent.
20
+ reason: One sentence explaining why escalation did or did not
21
+ fire. Rendered in the agent-trace UI.
22
+ ngos_alerted: Names of NGOs that received a push notification.
23
+ Empty when escalated=False.
24
+ severity_score: The SituationReport.severity value evaluated against
25
+ the threshold.
26
+ threshold_used: The NGO_ESCALATION_THRESHOLD constant in effect when
27
+ this result was produced.
28
+ """
29
+
30
+ model_config = ConfigDict(frozen=True, extra="forbid")
31
+
32
+ escalated: bool
33
+ reason: str
34
+ ngos_alerted: list[str]
35
+ severity_score: int
36
+ threshold_used: int
src/backend/models/risk.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ RiskTieringResult — output contract for Phase 6's classifier.
3
+
4
+ This is the second structured payload the pipeline produces (after
5
+ DetectionOutput from Phase 5). It is consumed by:
6
+
7
+ Phase 7 to scope severity analysis (only run analysis for med/high)
8
+ Phase 8 to shape the response plan (different actions per tier)
9
+ Phase 10 to decide whether to fan out crowd-verification pushes
10
+
11
+ Like DetectionOutput, this model is frozen + extra="forbid" so the
12
+ classifier (and any future LLM-backed variant) can't silently grow the
13
+ schema. Frozen also signals that once tiering is decided for a given
14
+ crisis, downstream agents do not retro-edit it.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Literal
20
+
21
+ from pydantic import BaseModel, ConfigDict, Field
22
+
23
+ RiskLevel = Literal["low", "medium", "high"]
24
+
25
+
26
+ class RiskTieringResult(BaseModel):
27
+ """Classification outcome from `services.risk_tiering.classify_risk`.
28
+
29
+ Attributes:
30
+ risk_level: The tier the crisis falls into. Drives every downstream
31
+ routing decision in the pipeline.
32
+ requires_crowd_verification: Whether radius-based push notifications
33
+ should be sent to nearby app users before contacting emergency
34
+ services. True for medium/high and unknown types; False for low.
35
+ requires_emergency_services: Whether the crisis is one that
36
+ ultimately needs an emergency dispatch (after verification, if
37
+ verification is required). Phase 8's planning agent owns the
38
+ actual dispatch decision; this flag is just the eligibility
39
+ signal.
40
+ auto_response_actions: Actions that can fire immediately without
41
+ human confirmation — populated only for low-risk crises
42
+ (e.g. ["reroute_traffic", "send_area_alert"]). Always [] for
43
+ medium/high.
44
+ reasoning: One short sentence explaining why this tier was chosen.
45
+ Rendered in the agent-trace UI alongside the LLM agents'
46
+ reasoning fields.
47
+ """
48
+
49
+ model_config = ConfigDict(frozen=True, extra="forbid")
50
+
51
+ risk_level: RiskLevel
52
+ requires_crowd_verification: bool
53
+ requires_emergency_services: bool
54
+ auto_response_actions: list[str] = Field(default_factory=list)
55
+ reasoning: str
src/backend/models/signal.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CrisisSignal — the canonical input shape every downstream agent reads.
3
+
4
+ Why this exists
5
+ ---------------
6
+ CIRO ingests evidence from three very different sources (weather APIs,
7
+ simulated social media posts, CNIC-verified in-app reports). The detection
8
+ agent in Phase 5 cannot afford to grow source-specific branches; it needs a
9
+ single Pydantic shape it can iterate over.
10
+
11
+ Trust weights are deliberately fixed constants set at the source level, not
12
+ computed dynamically. The detection agent uses `trust_weight` directly when
13
+ folding multi-source signals into a confidence score.
14
+
15
+ CrisisSignal instances are **immutable** after creation (frozen=True).
16
+ Downstream agents read signals; they never mutate them — the aggregator is
17
+ the only place a signal is allowed to come into existence.
18
+ """
19
+
20
+ from datetime import datetime, timezone
21
+ from typing import Literal
22
+
23
+ from pydantic import BaseModel, ConfigDict, Field
24
+
25
+ SignalSource = Literal["weather", "social_media", "app_report"]
26
+ SignalType = Literal["rainfall", "flood", "fire", "traffic", "report"]
27
+ SeverityHint = Literal["heavy", "moderate", "light"]
28
+
29
+
30
+ # Trust weights are intentionally part of the model module so every consumer
31
+ # imports the same constants. Do not redefine these elsewhere.
32
+ TRUST_WEIGHT_APP_REPORT = 1.0 # CNIC-verified, accountable
33
+ TRUST_WEIGHT_WEATHER = 0.7 # authoritative but indirect (atmospheric)
34
+ TRUST_WEIGHT_SOCIAL_MEDIA = 0.5 # eyewitness but unverified
35
+
36
+
37
+ class CrisisSignal(BaseModel):
38
+ """A single piece of evidence about a possibly-emerging crisis.
39
+
40
+ Attributes:
41
+ source: Which ingestion channel produced this signal.
42
+ trust_weight: How much downstream reasoning should weight this signal,
43
+ in [0.0, 1.0]. Set per-source (see constants above); do not invent
44
+ new values per signal.
45
+ raw_text: Original natural-language content (post body, report
46
+ description). `None` for pure sensor signals like weather where
47
+ there is no human-authored text.
48
+ location_label: Human-readable area name, e.g. "G-10, Islamabad".
49
+ Used in the UI trace + by the analysis agent for spatial reasoning.
50
+ coordinates: (lat, lon) in WGS84. Used by the crowd-verification
51
+ radius query in Phase 10.
52
+ signal_type: Coarse category for downstream routing. Limited to the
53
+ crisis taxonomy CIRO actually responds to.
54
+ severity_hint: Optional source-level hint at intensity. Detection
55
+ agent treats it as input, not as ground truth.
56
+ timestamp: When the signal was observed (UTC).
57
+ """
58
+
59
+ # frozen=True → CrisisSignal acts as a value object; agents can't mutate
60
+ # them mid-pipeline. Enforces the "read-only after aggregation" rule.
61
+ model_config = ConfigDict(frozen=True)
62
+
63
+ source: SignalSource
64
+ trust_weight: float = Field(ge=0.0, le=1.0)
65
+ raw_text: str | None = None
66
+ location_label: str
67
+ coordinates: tuple[float, float]
68
+ signal_type: SignalType
69
+ severity_hint: SeverityHint | None = None
70
+ timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
src/backend/models/simulation.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Simulation schemas — output contract for Phase 12's simulation agent.
3
+
4
+ SimulationResult is the final output of the entire CIRO pipeline. It is
5
+ consumed by:
6
+ Phase 13 agent trace log
7
+ Mobile outcome visualization screen (before/after + actions)
8
+ Mobile Maps screen bottom sheet (dispatch_ticket)
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from datetime import datetime, timezone
14
+ from typing import Literal
15
+
16
+ from pydantic import BaseModel, ConfigDict, Field
17
+
18
+
19
+ CongestionLevel = Literal["severe", "heavy", "moderate", "light", "clear"]
20
+ AreaStatus = Literal["crisis active", "contained", "resolved"]
21
+ ActionStatus = Literal["completed", "in_progress", "pending"]
22
+
23
+
24
+ class SystemState(BaseModel):
25
+ """Snapshot of the crisis area before or after response execution."""
26
+
27
+ model_config = ConfigDict(extra="forbid")
28
+
29
+ congestion_level: CongestionLevel
30
+ affected_area_status: AreaStatus
31
+ vehicles_rerouted: int = Field(ge=0)
32
+ emergency_units_deployed: int = Field(ge=0)
33
+ citizens_alerted: int = Field(ge=0)
34
+ ngos_activated: int = Field(ge=0)
35
+
36
+
37
+ class ExecutedAction(BaseModel):
38
+ """A single response action from the plan, with its simulated outcome."""
39
+
40
+ model_config = ConfigDict(extra="forbid")
41
+
42
+ action: str
43
+ assigned_to: str
44
+ status: ActionStatus
45
+ simulated_effect: str
46
+ duration_minutes: int = Field(ge=0)
47
+
48
+
49
+ class DispatchedUnit(BaseModel):
50
+ """One emergency service unit dispatched to the crisis."""
51
+
52
+ model_config = ConfigDict(extra="forbid")
53
+
54
+ service: str
55
+ units: int = Field(ge=1)
56
+ eta_minutes: int = Field(ge=1)
57
+
58
+
59
+ class DispatchTicket(BaseModel):
60
+ """Structured emergency dispatch record shown on the Maps screen bottom sheet.
61
+
62
+ Generated deterministically for medium/high-risk crises that require
63
+ emergency services. None for low-risk crises (traffic jam, rainfall,
64
+ road_blockage).
65
+ """
66
+
67
+ model_config = ConfigDict(extra="forbid")
68
+
69
+ ticket_id: str # e.g. "CIR-2025-0047"
70
+ status: str # "DISPATCHED"
71
+ crisis_id: str
72
+ crisis_type: str
73
+ location_label: str
74
+ severity: int = Field(ge=1, le=5)
75
+ units_dispatched: list[DispatchedUnit]
76
+ issued_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
77
+
78
+
79
+ class SimulationResult(BaseModel):
80
+ """Full output of the simulation agent — final stage of the CIRO pipeline.
81
+
82
+ Attributes:
83
+ before: System state at crisis onset (deterministic).
84
+ after: System state after response execution (LLM).
85
+ actions_executed: Each plan action with its simulated effect (LLM).
86
+ dispatch_ticket: Emergency dispatch record; None for low-risk crises.
87
+ outcome_summary: Plain-English paragraph describing what happened.
88
+ time_to_resolution_estimate: e.g. "25–40 minutes".
89
+ """
90
+
91
+ model_config = ConfigDict(extra="forbid")
92
+
93
+ before: SystemState
94
+ after: SystemState
95
+ actions_executed: list[ExecutedAction]
96
+ dispatch_ticket: DispatchTicket | None
97
+ outcome_summary: str
98
+ time_to_resolution_estimate: str
99
+
100
+
101
+ # ── Agent output shape (subset of SimulationResult) ───────────────────────────
102
+ #
103
+ # The simulation agent generates only the variable parts — `before` and
104
+ # `dispatch_ticket` are constructed deterministically and injected by
105
+ # `run_simulation()` before the final SimulationResult is assembled.
106
+
107
+
108
+ class SimulationAgentOutput(BaseModel):
109
+ """Structured output contract for the simulation agent itself.
110
+
111
+ `before` and `dispatch_ticket` are excluded because they are built
112
+ deterministically from SituationReport severity and crisis type — the
113
+ agent should not invent ticket IDs or severity mappings.
114
+ """
115
+
116
+ model_config = ConfigDict(extra="forbid")
117
+
118
+ after: SystemState
119
+ actions_executed: list[ExecutedAction]
120
+ outcome_summary: str
121
+ time_to_resolution_estimate: str
122
+ reasoning: str
123
+ confidence: float = Field(default=0.8, ge=0.0, le=1.0)
src/backend/models/trace.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Agent trace schemas — Phase 13.
3
+
4
+ AgentTrace is the complete pipeline reasoning record for a single crisis event.
5
+ Persisted to Firestore agent_logs and served via GET /api/crisis/{id}/trace,
6
+ which powers the in-app reasoning timeline on AgentTraceScreen.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from datetime import datetime, timezone
12
+ from typing import Literal
13
+
14
+ from pydantic import BaseModel, Field
15
+
16
+
17
+ class AgentTraceStep(BaseModel):
18
+ step_number: int
19
+ agent_name: str
20
+ action: str
21
+ reasoning: str
22
+ confidence: float | None
23
+ output_summary: str
24
+ timestamp: datetime
25
+
26
+
27
+ FinalOutcome = Literal["responded", "denied", "inconclusive", "low_risk_auto"]
28
+
29
+
30
+ class AgentTrace(BaseModel):
31
+ crisis_id: str
32
+ steps: list[AgentTraceStep]
33
+ total_duration_seconds: float
34
+ final_outcome: FinalOutcome
35
+ created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
src/backend/routes/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Routes module — API route handlers added per feature in subsequent phases
src/backend/routes/auth.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Authentication routes — CNIC verification.
3
+
4
+ POST /api/auth/verify-cnic
5
+ First protected call after phone auth. Links the authenticated
6
+ Firebase uid to a user-provided CNIC and creates the Firestore
7
+ user record. Requires a valid Firebase JWT.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from fastapi import APIRouter, Depends, HTTPException, status
13
+ from pydantic import BaseModel
14
+
15
+ from backend.core.auth import get_current_user
16
+ from backend.services.cnic import validate_cnic_format
17
+ from backend.services.firestore import firestore_service
18
+
19
+ router = APIRouter(prefix="/api/auth", tags=["Auth"])
20
+
21
+
22
+ class CnicVerifyRequest(BaseModel):
23
+ cnic: str
24
+ name: str
25
+
26
+
27
+ class RegisterTokenRequest(BaseModel):
28
+ cnic: str
29
+ token: str
30
+
31
+
32
+ @router.post("/verify-cnic")
33
+ async def verify_cnic(
34
+ payload: CnicVerifyRequest,
35
+ user: dict = Depends(get_current_user),
36
+ ) -> dict:
37
+ """Link an authenticated Firebase uid to a CNIC and create a user record.
38
+
39
+ - Any well-formatted CNIC (XXXXX-XXXXXXX-X) is accepted — no external
40
+ NADRA lookup is performed for the demo.
41
+ - If the CNIC is already registered to the same uid, returns the
42
+ existing record (idempotent).
43
+ - If the CNIC is registered to a *different* uid, returns 409.
44
+ """
45
+ if not validate_cnic_format(payload.cnic):
46
+ raise HTTPException(
47
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
48
+ detail="Invalid CNIC format. Expected XXXXX-XXXXXXX-X (digits only).",
49
+ )
50
+
51
+ existing = await firestore_service.get_user(payload.cnic)
52
+ if existing:
53
+ if existing.get("uid") != user["uid"]:
54
+ raise HTTPException(
55
+ status_code=status.HTTP_409_CONFLICT,
56
+ detail="This CNIC is already registered to another account.",
57
+ )
58
+ return {
59
+ "message": "CNIC already verified",
60
+ "cnic": payload.cnic,
61
+ "verified": True,
62
+ }
63
+
64
+ await firestore_service.create_user({
65
+ "cnic": payload.cnic,
66
+ "uid": user["uid"],
67
+ "phone_number": user.get("phone_number"),
68
+ "name": payload.name,
69
+ "role": "citizen",
70
+ "verified": True,
71
+ "strike_count": 0,
72
+ "blacklisted": False,
73
+ "warned": False,
74
+ "fcm_token": None,
75
+ })
76
+
77
+ return {
78
+ "message": "CNIC verified successfully",
79
+ "cnic": payload.cnic,
80
+ "verified": True,
81
+ }
82
+
83
+
84
+ @router.post("/register-token")
85
+ async def register_fcm_token(
86
+ payload: RegisterTokenRequest,
87
+ user: dict = Depends(get_current_user),
88
+ ) -> dict:
89
+ """Store or update the FCM device token for an authenticated user.
90
+
91
+ Called on app launch (after CNIC verification) and whenever the token
92
+ refreshes. The CNIC in the body is cross-validated against the uid in
93
+ the Firebase JWT to prevent token hijacking.
94
+ """
95
+ existing = await firestore_service.get_user(payload.cnic)
96
+ if not existing:
97
+ raise HTTPException(
98
+ status_code=status.HTTP_404_NOT_FOUND,
99
+ detail="User not found. Complete CNIC verification first.",
100
+ )
101
+ if existing.get("uid") != user["uid"]:
102
+ raise HTTPException(
103
+ status_code=status.HTTP_403_FORBIDDEN,
104
+ detail="CNIC does not match the authenticated user.",
105
+ )
106
+
107
+ await firestore_service.update_user(payload.cnic, {"fcm_token": payload.token})
108
+ return {"message": "FCM token registered", "cnic": payload.cnic}
src/backend/routes/crises.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Depends
2
+ from backend.core.auth import get_current_user
3
+
4
+ router = APIRouter(prefix="/api/crises", tags=["Crises"])
5
+
6
+ @router.get("/active")
7
+ async def get_active_crises(user: dict = Depends(get_current_user)):
8
+ """
9
+ Returns a list of active crises.
10
+ Requires a valid Firebase JWT token.
11
+ """
12
+ return {"message": "Authenticated successfully", "user": user, "data": []}
src/backend/routes/crisis.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ POST /api/crisis/analyze — main pipeline entry point.
3
+
4
+ This is the route the mobile app and demo scripts hit. It accepts one of
5
+ three input shapes and runs the full pipeline starting from the detection
6
+ agent:
7
+
8
+ 1. {"scenario": "g10_flood"} ← simplest demo
9
+ Uses the scenario's baked-in coordinates + location_label and runs
10
+ the aggregator. Best for the hackathon demo.
11
+
12
+ 2. {"scenario": "g10_flood", "lat": …, "lon": …, "location_label": …}
13
+ Override coordinates while still pulling social-media posts from a
14
+ named scenario. Useful when the same scenario is replayed in a
15
+ different location.
16
+
17
+ 3. {"signals": [CrisisSignal, …]}
18
+ Bypass the aggregator entirely. Used by tests and (in Phase 9) by
19
+ the CNIC-verified report path that hands its own signal in directly.
20
+
21
+ Returns the pipeline result envelope:
22
+
23
+ {
24
+ "final": AgentResult of the last stage,
25
+ "trace": [AgentResult, …] ← every stage in execution order
26
+ }
27
+
28
+ Auth: deliberately unprotected for the hackathon demo. Phase 9 will
29
+ add CNIC checks for the report-driven entry path.
30
+ """
31
+
32
+ import uuid
33
+
34
+ from fastapi import APIRouter, HTTPException
35
+ from pydantic import BaseModel, model_validator
36
+
37
+ from backend.agents.pipeline import run_pipeline
38
+ from backend.models.agent_result import AgentResult
39
+ from backend.models.signal import CrisisSignal
40
+ from backend.services.firestore import firestore_service
41
+ from backend.services.signal_aggregator import aggregate_signals
42
+ from backend.services.social_feed import SCENARIOS
43
+ from backend.services.trace import assemble_trace, save_trace
44
+
45
+ router = APIRouter(prefix="/api/crisis", tags=["Crisis"])
46
+
47
+
48
+ class AnalyzeRequest(BaseModel):
49
+ """Input shape for POST /api/crisis/analyze.
50
+
51
+ Either `scenario` or `signals` must be set (validated below). All
52
+ other fields are optional refinements of the scenario path.
53
+ """
54
+
55
+ scenario: str | None = None
56
+ lat: float | None = None
57
+ lon: float | None = None
58
+ location_label: str | None = None
59
+ signals: list[CrisisSignal] | None = None
60
+
61
+ @model_validator(mode="after")
62
+ def _require_scenario_or_signals(self) -> "AnalyzeRequest":
63
+ if not self.scenario and not self.signals:
64
+ raise ValueError("Provide either 'scenario' or 'signals'.")
65
+ return self
66
+
67
+
68
+ @router.post("/analyze")
69
+ async def analyze_crisis(payload: AnalyzeRequest) -> dict:
70
+ """Run the CIRO agent pipeline for one analysis request."""
71
+
72
+ # Path A: signals passed directly — bypass the aggregator.
73
+ if payload.signals:
74
+ signals = payload.signals
75
+
76
+ # Path B: scenario-driven — pull weather + social via the aggregator.
77
+ else:
78
+ assert payload.scenario is not None # guaranteed by the validator
79
+ bundle = SCENARIOS.get(payload.scenario)
80
+ if bundle is None:
81
+ raise HTTPException(
82
+ status_code=400,
83
+ detail=(
84
+ f"Unknown scenario {payload.scenario!r}. "
85
+ f"Available: {list(SCENARIOS.keys())}"
86
+ ),
87
+ )
88
+
89
+ lat = payload.lat if payload.lat is not None else bundle["coordinates"][0]
90
+ lon = payload.lon if payload.lon is not None else bundle["coordinates"][1]
91
+ location_label = payload.location_label or bundle["location_label"]
92
+
93
+ signals = await aggregate_signals(
94
+ scenario=payload.scenario,
95
+ lat=lat,
96
+ lon=lon,
97
+ location_label=location_label,
98
+ )
99
+
100
+ crisis_id = str(uuid.uuid4())
101
+ result = await run_pipeline(signals, crisis_id=None)
102
+
103
+ # Assemble and persist the trace so mobile AgentTraceScreen can poll it.
104
+ trace_results = [AgentResult.model_validate(r) for r in result.get("trace", [])]
105
+ if trace_results:
106
+ trace = assemble_trace(crisis_id, trace_results)
107
+ try:
108
+ await save_trace(trace)
109
+ except Exception:
110
+ pass # Non-fatal — trace save failure must not block the API response.
111
+
112
+ result["crisis_id"] = crisis_id
113
+ return result
114
+
115
+
116
+ @router.get("/{crisis_id}")
117
+ async def get_crisis(crisis_id: str) -> dict:
118
+ """Return the full crisis document from Firestore for the mobile map screen."""
119
+ doc = await firestore_service.get_crisis(crisis_id)
120
+ if not doc:
121
+ raise HTTPException(status_code=404, detail=f"Crisis '{crisis_id}' not found.")
122
+ return doc
src/backend/routes/crowd_verification.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Crowd verification routes — Phase 10.
3
+
4
+ POST /api/users/register-token — register FCM device token + last location
5
+ POST /api/crisis/{crisis_id}/verify — submit a crowd verification response
6
+
7
+ CNIC is ALWAYS resolved server-side from the authenticated JWT uid.
8
+ It is never accepted from the request body.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from fastapi import APIRouter, Depends, HTTPException, status
14
+ from google.cloud.firestore import SERVER_TIMESTAMP
15
+ from pydantic import BaseModel
16
+
17
+ from backend.core.auth import get_current_user
18
+ from backend.core.firebase import get_async_db
19
+ from backend.services.cnic import get_user_by_uid
20
+ from backend.services.crowd_verification import process_verification_response
21
+ from backend.services.ngo_escalation import escalate_confirmed_crisis
22
+
23
+ router = APIRouter(tags=["Crowd Verification"])
24
+
25
+ _VALID_RESPONSES = frozenset({"confirm", "deny", "help"})
26
+
27
+
28
+ # ── POST /api/users/register-token ───────────────────────────────────────────
29
+
30
+
31
+ class RegisterTokenRequest(BaseModel):
32
+ fcm_token: str
33
+ lat: float | None = None
34
+ lon: float | None = None
35
+
36
+
37
+ @router.post("/api/users/register-token")
38
+ async def register_fcm_token(
39
+ payload: RegisterTokenRequest,
40
+ user: dict = Depends(get_current_user),
41
+ ) -> dict:
42
+ """Store the device's FCM registration token and optional last location.
43
+
44
+ Called on app launch or whenever the FCM token rotates. The token is
45
+ required for crowd verification prompts. The location field is used by
46
+ the radius query to identify nearby users when a crisis is detected.
47
+
48
+ Both `lat` and `lon` must be provided together — one without the other
49
+ leaves `last_location` unchanged.
50
+ """
51
+ user_record = await get_user_by_uid(user["uid"])
52
+ if not user_record:
53
+ raise HTTPException(
54
+ status_code=status.HTTP_403_FORBIDDEN,
55
+ detail="Account not found. Please verify your CNIC first.",
56
+ )
57
+
58
+ updates: dict = {
59
+ "fcm_token": payload.fcm_token,
60
+ "token_updated_at": SERVER_TIMESTAMP,
61
+ }
62
+ if payload.lat is not None and payload.lon is not None:
63
+ updates["last_location"] = {"lat": payload.lat, "lon": payload.lon}
64
+
65
+ db = get_async_db()
66
+ await db.collection("users").document(user_record["cnic"]).update(updates)
67
+ return {"message": "Token registered successfully"}
68
+
69
+
70
+ # ── POST /api/crisis/{crisis_id}/verify ──────────────────────────────────────
71
+
72
+
73
+ class VerifyRequest(BaseModel):
74
+ response: str # "confirm" | "deny" | "help"
75
+
76
+
77
+ @router.post("/api/crisis/{crisis_id}/verify")
78
+ async def verify_crisis(
79
+ crisis_id: str,
80
+ payload: VerifyRequest,
81
+ user: dict = Depends(get_current_user),
82
+ ) -> dict:
83
+ """Submit a crowd verification response for a medium/high-risk crisis.
84
+
85
+ Response values:
86
+ confirm — crisis is visible at your location; supports emergency dispatch
87
+ deny — no crisis visible; contributes to a potential false-report
88
+ penalty on the original reporter once the denial threshold
89
+ (≤30% confirmation rate) is reached
90
+ help — crisis is confirmed AND you are willing to assist on-ground;
91
+ counted as a confirmation and records your CNIC in
92
+ crisis.helpers for volunteer coordination
93
+
94
+ Returns the current verdict and running totals:
95
+ {"verdict": "confirmed"|"denied"|"inconclusive",
96
+ "confirmations": int, "denials": int}
97
+ """
98
+ if payload.response not in _VALID_RESPONSES:
99
+ raise HTTPException(
100
+ status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
101
+ detail=f"response must be one of: {sorted(_VALID_RESPONSES)}",
102
+ )
103
+
104
+ user_record = await get_user_by_uid(user["uid"])
105
+ if not user_record:
106
+ raise HTTPException(
107
+ status_code=status.HTTP_403_FORBIDDEN,
108
+ detail="Account not found. Please verify your CNIC first.",
109
+ )
110
+
111
+ if user_record.get("blacklisted"):
112
+ raise HTTPException(
113
+ status_code=status.HTTP_403_FORBIDDEN,
114
+ detail="Your account has been permanently blocked.",
115
+ )
116
+
117
+ try:
118
+ result = await process_verification_response(
119
+ crisis_id=crisis_id,
120
+ cnic=user_record["cnic"],
121
+ response=payload.response,
122
+ )
123
+ except ValueError as exc:
124
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc))
125
+
126
+ # Primary escalation trigger: the moment a crisis is confirmed by the
127
+ # crowd, fire NGO alerts immediately so judges see the notification land
128
+ # on the NGO device in real time during the demo.
129
+ if result["verdict"] == "confirmed":
130
+ escalation = await escalate_confirmed_crisis(crisis_id)
131
+ result["escalation"] = escalation.model_dump()
132
+
133
+ return result
src/backend/routes/report.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ POST /api/report — CNIC-verified in-app crisis report endpoint.
3
+
4
+ This is the only route through which app reports enter the pipeline.
5
+ Trust weight is 1.0 (highest) because every submission is tied to an
6
+ accountable, verified CNIC.
7
+
8
+ Security invariant: CNIC is ALWAYS resolved server-side from the
9
+ authenticated uid. It is never accepted from the request body.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from datetime import datetime, timezone
15
+
16
+ from fastapi import APIRouter, Depends, HTTPException, status
17
+ from google.cloud.firestore import SERVER_TIMESTAMP
18
+ from pydantic import BaseModel
19
+
20
+ from backend.agents.pipeline import run_pipeline
21
+ from backend.core.auth import get_current_user
22
+ from backend.models.agent_result import AgentResult
23
+ from backend.models.signal import TRUST_WEIGHT_APP_REPORT, CrisisSignal
24
+ from backend.services.cnic import get_user_by_uid
25
+ from backend.services.firestore import firestore_service
26
+ from backend.services.trace import assemble_trace, save_trace
27
+
28
+ router = APIRouter(prefix="/api/report", tags=["Report"])
29
+
30
+
31
+ class ReportRequest(BaseModel):
32
+ description: str
33
+ crisis_type: str # stored in Firestore; pipeline detects from text
34
+ location_label: str
35
+ lat: float
36
+ lon: float
37
+
38
+
39
+ @router.post("")
40
+ async def submit_report(
41
+ payload: ReportRequest,
42
+ user: dict = Depends(get_current_user),
43
+ ) -> dict:
44
+ """Submit a CNIC-verified crisis report and trigger the agent pipeline.
45
+
46
+ - CNIC is resolved from the JWT uid — never from the request body.
47
+ - Blacklisted users receive 403 before any processing.
48
+ - The report is stored in Firestore and handed to the pipeline as an
49
+ app_report signal with trust_weight=1.0.
50
+ """
51
+ uid = user["uid"]
52
+
53
+ # Resolve CNIC server-side — security invariant.
54
+ user_record = await get_user_by_uid(uid)
55
+ if not user_record:
56
+ raise HTTPException(
57
+ status_code=status.HTTP_403_FORBIDDEN,
58
+ detail="Account not found. Please verify your CNIC first.",
59
+ )
60
+
61
+ if not user_record.get("verified"):
62
+ raise HTTPException(
63
+ status_code=status.HTTP_403_FORBIDDEN,
64
+ detail="CNIC not verified. Please complete verification before submitting reports.",
65
+ )
66
+
67
+ if user_record.get("blacklisted"):
68
+ raise HTTPException(
69
+ status_code=status.HTTP_403_FORBIDDEN,
70
+ detail="Your account has been permanently blocked due to repeated false reports.",
71
+ )
72
+
73
+ cnic = user_record["cnic"]
74
+
75
+ # Persist the report in Firestore before touching the pipeline.
76
+ stored = await firestore_service.create_crisis({
77
+ "reporter_cnic": cnic,
78
+ "reporter_uid": uid,
79
+ "description": payload.description,
80
+ "crisis_type": payload.crisis_type,
81
+ "location_label": payload.location_label,
82
+ "lat": payload.lat,
83
+ "lon": payload.lon,
84
+ "source": "app_report",
85
+ "status": "submitted",
86
+ "created_at": SERVER_TIMESTAMP,
87
+ })
88
+ crisis_id: str = stored["crisis_id"]
89
+
90
+ # Build the highest-trust signal and run the pipeline.
91
+ signal = CrisisSignal(
92
+ source="app_report",
93
+ trust_weight=TRUST_WEIGHT_APP_REPORT,
94
+ raw_text=payload.description,
95
+ location_label=payload.location_label,
96
+ coordinates=(payload.lat, payload.lon),
97
+ signal_type="report",
98
+ timestamp=datetime.now(timezone.utc),
99
+ )
100
+
101
+ pipeline_result = await run_pipeline([signal], crisis_id=crisis_id)
102
+
103
+ # Assemble and persist the agent trace for AgentTraceScreen.
104
+ trace_results = [AgentResult.model_validate(r) for r in pipeline_result.get("trace", [])]
105
+ if trace_results:
106
+ try:
107
+ await save_trace(assemble_trace(crisis_id, trace_results))
108
+ except Exception:
109
+ pass # Non-fatal — trace save must not block the report response.
110
+
111
+ # Persist analysis + planning outputs on the crisis doc so that the
112
+ # verify route can trigger NGO escalation with the correct severity and
113
+ # plan summary when a user confirms the crisis later.
114
+ severity: int = 0
115
+ plan_summary: str = ""
116
+ route_options: list = []
117
+ recommended_route: dict | None = None
118
+ dispatch_ticket: dict | None = None
119
+ sim_before: dict | None = None
120
+ sim_after: dict | None = None
121
+ risk_level: str = "medium"
122
+ requires_emergency_services: bool = False
123
+ detected_lat: float | None = None
124
+ detected_lon: float | None = None
125
+ detected_location_label: str | None = None
126
+ crisis_type_detected: str | None = None
127
+ confidence: float = 0.0
128
+
129
+ for stage in pipeline_result.get("trace", []):
130
+ name = stage.get("agent_name", "")
131
+ out = stage.get("output", {})
132
+ if name == "crisis_detection_agent":
133
+ coords = out.get("coordinates")
134
+ if isinstance(coords, (list, tuple)) and len(coords) >= 2:
135
+ detected_lat = float(coords[0])
136
+ detected_lon = float(coords[1])
137
+ crisis_type_detected = out.get("crisis_type")
138
+ confidence = float(out.get("confidence") or 0.0)
139
+ detected_location_label = out.get("location_label")
140
+ elif name == "risk_tier_classifier":
141
+ risk_level = str(out.get("risk_level") or "medium")
142
+ requires_emergency_services = bool(out.get("requires_emergency_services", False))
143
+ elif name == "situation_analysis_agent":
144
+ severity = int(out.get("severity") or 0)
145
+ elif name == "action_planning_agent":
146
+ plan_summary = str(out.get("plan_summary") or "")
147
+ route_options = out.get("route_options") or []
148
+ recommended_route = out.get("recommended_route")
149
+ elif name == "simulation_agent":
150
+ dispatch_ticket = out.get("dispatch_ticket")
151
+ sim_before = out.get("before")
152
+ sim_after = out.get("after")
153
+
154
+ crisis_update: dict = {
155
+ "severity": severity,
156
+ "response_plan_summary": plan_summary,
157
+ "risk_level": risk_level,
158
+ "requires_emergency_services": requires_emergency_services,
159
+ "confidence": confidence,
160
+ "crisis_type_detected": crisis_type_detected,
161
+ "route_options": route_options,
162
+ }
163
+ if recommended_route is not None:
164
+ crisis_update["recommended_route"] = recommended_route
165
+ if dispatch_ticket is not None:
166
+ crisis_update["dispatch_ticket"] = dispatch_ticket
167
+ if sim_before is not None:
168
+ crisis_update["sim_before"] = sim_before
169
+ if sim_after is not None:
170
+ crisis_update["sim_after"] = sim_after
171
+ if detected_lat is not None and detected_lon is not None:
172
+ crisis_update["detected_lat"] = detected_lat
173
+ crisis_update["detected_lon"] = detected_lon
174
+ if detected_location_label:
175
+ crisis_update["detected_location_label"] = detected_location_label
176
+
177
+ await firestore_service.update_crisis(crisis_id, crisis_update)
178
+
179
+ return {
180
+ "crisis_id": crisis_id,
181
+ "message": "Report submitted successfully",
182
+ "pipeline": pipeline_result,
183
+ }
src/backend/routes/trace.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ GET /api/crisis/{crisis_id}/trace — agent trace endpoint.
3
+
4
+ Returns the full AgentTrace for a given crisis_id. Polled by the mobile app
5
+ to render the live reasoning timeline on AgentTraceScreen.
6
+ """
7
+
8
+ from fastapi import APIRouter, HTTPException
9
+
10
+ from backend.services.trace import get_trace
11
+
12
+ router = APIRouter(prefix="/api/crisis", tags=["Crisis"])
13
+
14
+
15
+ @router.get("/{crisis_id}/trace")
16
+ async def get_crisis_trace(crisis_id: str) -> dict:
17
+ """Return the agent reasoning trace for a completed pipeline run."""
18
+ trace = await get_trace(crisis_id)
19
+ if trace is None:
20
+ raise HTTPException(
21
+ status_code=404,
22
+ detail=f"No trace found for crisis {crisis_id!r}.",
23
+ )
24
+ return trace.model_dump(mode="json")
src/backend/routes/weather.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ GET /api/weather — live atmospheric signal for a single coordinate.
3
+
4
+ This route exists to satisfy the Phase 4 Definition of Done:
5
+
6
+ "GET /weather?lat=33.7&lon=73.0 returns a valid CrisisSignal with live
7
+ OWM data."
8
+
9
+ It is intentionally a thin shell over `services.weather.fetch_weather_signal`
10
+ so the downstream pipeline and this HTTP surface share the exact same
11
+ normalization path. If the OWM call fails (no key, network error, bad
12
+ response), the endpoint returns 503 — the response payload itself stays
13
+ schema-clean because we never want to leak half-built signals to clients.
14
+ """
15
+
16
+ from fastapi import APIRouter, HTTPException, Query
17
+
18
+ from backend.models.signal import CrisisSignal
19
+ from backend.services.weather import fetch_weather_signal
20
+
21
+ router = APIRouter(prefix="/api/weather", tags=["Signals"])
22
+
23
+
24
+ @router.get("", response_model=CrisisSignal)
25
+ async def get_weather_signal(
26
+ lat: float = Query(..., ge=-90.0, le=90.0, description="Latitude in WGS84"),
27
+ lon: float = Query(..., ge=-180.0, le=180.0, description="Longitude in WGS84"),
28
+ location_label: str | None = Query(
29
+ default=None,
30
+ description=(
31
+ "Optional human-readable area name (e.g. 'G-10, Islamabad'). "
32
+ "If omitted, OpenWeatherMap's city name is used."
33
+ ),
34
+ ),
35
+ ) -> CrisisSignal:
36
+ """Fetch a single normalized weather `CrisisSignal` for (lat, lon)."""
37
+ signal = await fetch_weather_signal(lat, lon, location_label=location_label)
38
+ if signal is None:
39
+ raise HTTPException(
40
+ status_code=503,
41
+ detail=(
42
+ "Weather signal unavailable — check OPENWEATHERMAP_API_KEY "
43
+ "or upstream OpenWeatherMap availability."
44
+ ),
45
+ )
46
+ return signal
src/backend/services/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # Services module — external API clients (weather, maps, FCM, Firestore, WhatsApp)
src/backend/services/cnic.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CNIC verification and fake-report accountability service.
3
+
4
+ Domain ownership
5
+ ----------------
6
+ - CNIC format validation
7
+ - User lookup by Firebase uid
8
+ - Atomic strike increment + state transitions (warned → blacklisted)
9
+
10
+ Strike state machine
11
+ --------------------
12
+ 0-2 → strike_recorded (silent)
13
+ 3 → warned=True (FCM warning sent by Phase 10)
14
+ 4+ → blacklisted=True (FCM blacklist sent by Phase 10)
15
+
16
+ The transition logic lives here; FCM dispatch lives in Phase 10. This
17
+ module only updates Firestore state and returns the action taken.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import re
23
+
24
+ from google.cloud.firestore import FieldFilter, async_transactional
25
+
26
+ from backend.core.firebase import get_async_db
27
+
28
+ CNIC_PATTERN = re.compile(r"^\d{5}-\d{7}-\d$")
29
+
30
+
31
+ def validate_cnic_format(cnic: str) -> bool:
32
+ """Return True iff `cnic` matches the Pakistani XXXXX-XXXXXXX-X format."""
33
+ return bool(CNIC_PATTERN.match(cnic))
34
+
35
+
36
+ async def get_user_by_uid(uid: str) -> dict | None:
37
+ """Fetch the user record whose `uid` field matches the given Firebase uid.
38
+
39
+ The Firestore `users` collection is keyed by CNIC, so this is a query
40
+ rather than a direct document lookup.
41
+
42
+ Returns:
43
+ User dict with a `cnic` key added (the document ID), or None if no
44
+ matching record exists.
45
+ """
46
+ db = get_async_db()
47
+ query = db.collection("users").where(filter=FieldFilter("uid", "==", uid))
48
+ async for doc in query.stream():
49
+ return {"cnic": doc.id, **doc.to_dict()}
50
+ return None
51
+
52
+
53
+ # ── Atomic strike increment ────────────────────────────────────────────────
54
+ #
55
+ # Defined at module level so @async_transactional can wrap it correctly.
56
+ # The decorator handles retry on contention — the function body must be
57
+ # idempotent with respect to Firestore writes.
58
+
59
+ @async_transactional
60
+ async def _apply_strike(transaction, user_ref) -> dict:
61
+ """Transactional inner function — must only be called via record_false_report."""
62
+ snap = await user_ref.get(transaction=transaction)
63
+ if not snap.exists:
64
+ raise ValueError(f"User document {user_ref.id!r} not found in Firestore")
65
+
66
+ data = snap.to_dict()
67
+ new_count = (data.get("strike_count") or 0) + 1
68
+
69
+ updates: dict = {"strike_count": new_count}
70
+ if new_count == 3:
71
+ updates["warned"] = True
72
+ action = "warned"
73
+ elif new_count >= 4:
74
+ updates["blacklisted"] = True
75
+ action = "blacklisted"
76
+ else:
77
+ action = "strike_recorded"
78
+
79
+ transaction.update(user_ref, updates)
80
+ return {"action": action, "strike_count": new_count}
81
+
82
+
83
+ async def record_false_report(cnic: str) -> dict:
84
+ """Atomically increment the strike count for a CNIC and apply state transitions.
85
+
86
+ Uses a Firestore transaction so concurrent calls cannot produce a
87
+ split-brain where the counter and the flags disagree.
88
+
89
+ Args:
90
+ cnic: The document ID of the user in the `users` collection.
91
+
92
+ Returns:
93
+ {"action": "strike_recorded" | "warned" | "blacklisted",
94
+ "strike_count": <new value>}
95
+
96
+ Raises:
97
+ ValueError: If no user document exists for `cnic`.
98
+ """
99
+ db = get_async_db()
100
+ user_ref = db.collection("users").document(cnic)
101
+ transaction = db.transaction()
102
+ return await _apply_strike(transaction, user_ref)
src/backend/services/crowd_verification.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Crowd verification orchestrator — Phase 10.
3
+
4
+ Owns:
5
+ - Sending FCM verification prompts to nearby users (via radius query)
6
+ - Storing crowd responses on the crisis Firestore document
7
+ - Evaluating confirmation/denial counts to produce a verdict
8
+ - Calling record_false_report() on the original reporter for denied verdicts
9
+ - Dispatching FCM warning/blacklist notices when those strikes land
10
+
11
+ Does NOT own:
12
+ - Strike rules (services/cnic.py — Phase 9)
13
+ - NGO escalation (Phase 11)
14
+ - Map display of helper locations (mobile Phase 5)
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import logging
20
+
21
+ from google.cloud.firestore import SERVER_TIMESTAMP
22
+
23
+ from backend.core.firebase import get_async_db
24
+ from backend.services.cnic import record_false_report
25
+ from backend.services.fcm import send_blacklist_notice, send_strike_warning, send_verification_prompt
26
+ from backend.services.radius_query import DEFAULT_RADIUS_KM, get_users_within_radius
27
+
28
+ logger = logging.getLogger(__name__)
29
+
30
+ CONFIRMATION_THRESHOLD: float = 0.6
31
+ DENIAL_THRESHOLD: float = 0.3
32
+
33
+
34
+ # ── Pure decision function (no I/O — fully unit-testable) ────────────────────
35
+
36
+
37
+ def evaluate_verification(confirmations: int, denials: int) -> str:
38
+ """Return the crowd verification verdict from raw response counts.
39
+
40
+ Rules (single source of truth):
41
+ total == 0 → "inconclusive"
42
+ confirmation_rate >= 0.6 → "confirmed"
43
+ confirmation_rate <= 0.3 → "denied"
44
+ between thresholds → "inconclusive"
45
+
46
+ Args:
47
+ confirmations: Count of "confirm" + "help" responses received.
48
+ denials: Count of "deny" responses received.
49
+
50
+ Returns:
51
+ One of: "confirmed", "denied", "inconclusive".
52
+ """
53
+ total = confirmations + denials
54
+ if total == 0:
55
+ return "inconclusive"
56
+ rate = confirmations / total
57
+ if rate >= CONFIRMATION_THRESHOLD:
58
+ return "confirmed"
59
+ if rate <= DENIAL_THRESHOLD:
60
+ return "denied"
61
+ return "inconclusive"
62
+
63
+
64
+ # ── Outbound: fan out prompts to nearby users ─────────────────────────────────
65
+
66
+
67
+ async def send_verification_prompts(
68
+ crisis_id: str,
69
+ crisis_type: str,
70
+ location_label: str,
71
+ lat: float,
72
+ lon: float,
73
+ radius_km: float = DEFAULT_RADIUS_KM,
74
+ ) -> dict:
75
+ """Query users within radius and fire FCM verification prompts to each one.
76
+
77
+ Initialises the crisis document's verification counters on Firestore so
78
+ the verify endpoint can do atomic increments against a known baseline.
79
+
80
+ Args:
81
+ crisis_id: Firestore document ID of the crisis.
82
+ crisis_type: Human-readable crisis label (e.g. "flood").
83
+ location_label: Human-readable area name shown in the notification.
84
+ lat: Crisis latitude.
85
+ lon: Crisis longitude.
86
+ radius_km: Search radius. Defaults to DEFAULT_RADIUS_KM (1 km).
87
+
88
+ Returns:
89
+ {"users_found": int, "users_notified": int}
90
+ """
91
+ nearby = await get_users_within_radius(lat, lon, radius_km)
92
+ notified = 0
93
+ for user in nearby:
94
+ ok = await send_verification_prompt(
95
+ token=user.fcm_token,
96
+ crisis_id=crisis_id,
97
+ crisis_type=crisis_type,
98
+ location=location_label,
99
+ )
100
+ if ok:
101
+ notified += 1
102
+
103
+ db = get_async_db()
104
+ await db.collection("crises").document(crisis_id).update({
105
+ "verification_status": "pending",
106
+ "users_notified": notified,
107
+ "confirmations": 0,
108
+ "denials": 0,
109
+ "helpers": [],
110
+ "verification_sent_at": SERVER_TIMESTAMP,
111
+ })
112
+
113
+ logger.info(
114
+ "Crowd verification: notified %d/%d users near crisis %s",
115
+ notified, len(nearby), crisis_id,
116
+ )
117
+ return {"users_found": len(nearby), "users_notified": notified}
118
+
119
+
120
+ # ── Inbound: handle a user's verification response ────────────────────────────
121
+
122
+
123
+ async def process_verification_response(
124
+ crisis_id: str,
125
+ cnic: str,
126
+ response: str,
127
+ ) -> dict:
128
+ """Store a crowd verification response and re-evaluate the verdict.
129
+
130
+ Args:
131
+ crisis_id: Firestore document ID of the crisis being verified.
132
+ cnic: Responding user's CNIC (resolved server-side from JWT).
133
+ response: One of "confirm", "deny", "help".
134
+ "help" = confirm + volunteer to assist on-ground.
135
+
136
+ Returns:
137
+ {"verdict": str, "confirmations": int, "denials": int}
138
+
139
+ Side effects:
140
+ - Updates crisis.confirmations / crisis.denials / crisis.helpers
141
+ - Updates crisis.verification_result
142
+ - On "denied" verdict: calls record_false_report() on the original
143
+ reporter and dispatches the appropriate FCM notice (warning or
144
+ blacklist) if a state transition occurs.
145
+
146
+ Raises:
147
+ ValueError: If no crisis document exists for `crisis_id`.
148
+ """
149
+ db = get_async_db()
150
+ crisis_ref = db.collection("crises").document(crisis_id)
151
+ doc = await crisis_ref.get()
152
+ if not doc.exists:
153
+ raise ValueError(f"Crisis {crisis_id!r} not found in Firestore")
154
+
155
+ data = doc.to_dict()
156
+ confirmations: int = data.get("confirmations", 0)
157
+ denials: int = data.get("denials", 0)
158
+ helpers: list[str] = list(data.get("helpers", []))
159
+ reporter_cnic: str | None = data.get("reporter_cnic")
160
+
161
+ if response == "confirm":
162
+ confirmations += 1
163
+ await crisis_ref.update({"confirmations": confirmations})
164
+ elif response == "deny":
165
+ denials += 1
166
+ await crisis_ref.update({"denials": denials})
167
+ elif response == "help":
168
+ confirmations += 1
169
+ if cnic not in helpers:
170
+ helpers.append(cnic)
171
+ await crisis_ref.update({"confirmations": confirmations, "helpers": helpers})
172
+
173
+ verdict = evaluate_verification(confirmations, denials)
174
+ await crisis_ref.update({
175
+ "verification_result": verdict,
176
+ "verification_updated_at": SERVER_TIMESTAMP,
177
+ })
178
+
179
+ if verdict == "denied" and reporter_cnic:
180
+ await _handle_denied_verdict(reporter_cnic)
181
+
182
+ return {"verdict": verdict, "confirmations": confirmations, "denials": denials}
183
+
184
+
185
+ async def _handle_denied_verdict(reporter_cnic: str) -> None:
186
+ """Record a false report strike and dispatch FCM notice if warranted.
187
+
188
+ Only sends a notification when the strike causes a state transition
189
+ (warned or blacklisted). Silent strikes (1 and 2) produce no FCM.
190
+ """
191
+ try:
192
+ strike_result = await record_false_report(reporter_cnic)
193
+ except ValueError as exc:
194
+ logger.warning("record_false_report failed for %s: %s", reporter_cnic, exc)
195
+ return
196
+
197
+ action = strike_result.get("action")
198
+ logger.info("False report strike for %s: %s (count=%s)", reporter_cnic, action, strike_result.get("strike_count"))
199
+
200
+ if action not in ("warned", "blacklisted"):
201
+ return
202
+
203
+ db = get_async_db()
204
+ user_doc = await db.collection("users").document(reporter_cnic).get()
205
+ if not user_doc.exists:
206
+ return
207
+
208
+ token: str | None = user_doc.to_dict().get("fcm_token")
209
+ if not token:
210
+ return
211
+
212
+ if action == "warned":
213
+ # strikes_remaining = how many more before blacklist (always 1 at count=3)
214
+ strikes_remaining = 4 - strike_result["strike_count"]
215
+ await send_strike_warning(token=token, strikes_remaining=strikes_remaining)
216
+ elif action == "blacklisted":
217
+ await send_blacklist_notice(token=token)
src/backend/services/fcm.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FCM Notification Service — single source of truth for all push notifications.
3
+
4
+ All notification types (verification prompts, area alerts, strike warnings,
5
+ blacklist notices) are dispatched through this module. No other module should
6
+ call firebase_admin.messaging directly.
7
+
8
+ Failure policy: a failed FCM send is logged and returns False — it must
9
+ never crash the pipeline. FCM is best-effort for the demo.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import asyncio
15
+ import logging
16
+
17
+ from firebase_admin import messaging
18
+
19
+ logger = logging.getLogger(__name__)
20
+
21
+
22
+ async def send_notification(
23
+ token: str,
24
+ title: str,
25
+ body: str,
26
+ data: dict[str, str] | None = None,
27
+ ) -> bool:
28
+ """Send a push notification to a single device token.
29
+
30
+ Args:
31
+ token: FCM device registration token.
32
+ title: Notification title shown on the device.
33
+ body: Notification body text.
34
+ data: Optional key-value payload delivered alongside the visual
35
+ notification. All values must be strings (FCM requirement).
36
+
37
+ Returns:
38
+ True on success, False on any failure (token invalid, quota, etc.).
39
+ """
40
+ if not token:
41
+ logger.warning("send_notification called with empty token — skipped")
42
+ return False
43
+
44
+ message = messaging.Message(
45
+ notification=messaging.Notification(title=title, body=body),
46
+ data={k: str(v) for k, v in (data or {}).items()},
47
+ token=token,
48
+ )
49
+
50
+ try:
51
+ # messaging.send() is synchronous — run in thread to stay non-blocking.
52
+ await asyncio.to_thread(messaging.send, message)
53
+ return True
54
+ except messaging.UnregisteredError:
55
+ logger.warning("FCM token unregistered — device removed app: %.20s…", token)
56
+ return False
57
+ except Exception as exc: # noqa: BLE001
58
+ logger.warning("FCM send failed: %s", exc)
59
+ return False
60
+
61
+
62
+ async def send_verification_prompt(
63
+ token: str,
64
+ crisis_id: str,
65
+ crisis_type: str,
66
+ location: str,
67
+ ) -> bool:
68
+ """Ask a nearby user to confirm or deny a reported crisis.
69
+
70
+ Payload delivered to the mobile app:
71
+ type = "verification_prompt"
72
+ crisis_id = <crisis document ID>
73
+ crisis_type = e.g. "flood"
74
+ """
75
+ return await send_notification(
76
+ token=token,
77
+ title="Crisis reported near you",
78
+ body=f"A {crisis_type} has been reported near {location}. Can you confirm?",
79
+ data={
80
+ "type": "verification_prompt",
81
+ "crisis_id": crisis_id,
82
+ "crisis_type": crisis_type,
83
+ },
84
+ )
85
+
86
+
87
+ async def send_area_alert(
88
+ token: str,
89
+ crisis_type: str,
90
+ location: str,
91
+ action: str,
92
+ ) -> bool:
93
+ """Notify a user that a crisis is active in their area."""
94
+ return await send_notification(
95
+ token=token,
96
+ title=f"Crisis alert: {crisis_type} in {location}",
97
+ body=action,
98
+ data={"type": "area_alert", "crisis_type": crisis_type},
99
+ )
100
+
101
+
102
+ async def send_strike_warning(token: str, strikes_remaining: int) -> bool:
103
+ """Warn a user that they are close to being blacklisted."""
104
+ return await send_notification(
105
+ token=token,
106
+ title="False report warning",
107
+ body=(
108
+ f"Warning: you have received {3 - strikes_remaining + 1} false report "
109
+ "strikes. One more false report will permanently block your account."
110
+ ),
111
+ data={"type": "strike_warning"},
112
+ )
113
+
114
+
115
+ async def send_blacklist_notice(token: str) -> bool:
116
+ """Notify a user that their account has been permanently blocked."""
117
+ return await send_notification(
118
+ token=token,
119
+ title="Account blocked",
120
+ body="Your account has been permanently blocked due to repeated false reports.",
121
+ data={"type": "blacklist_notice"},
122
+ )
123
+
124
+
125
+ async def send_ngo_alert(
126
+ token: str,
127
+ crisis_id: str,
128
+ crisis_type: str,
129
+ location: str,
130
+ severity: int,
131
+ response_plan_summary: str,
132
+ ) -> bool:
133
+ """Dispatch a real-time escalation alert to an NGO device.
134
+
135
+ This is a real notification to a real device — it is NOT simulated.
136
+ The NGO representative's device receives the push; tapping it opens
137
+ the crisis detail screen (handled by the mobile FCM handler).
138
+
139
+ Payload delivered to the app:
140
+ type = "ngo_escalation"
141
+ crisis_id = <crisis document ID>
142
+ crisis_type = e.g. "flood"
143
+ location = human-readable area name
144
+ severity = stringified int (FCM data values must be strings)
145
+ response_plan_summary = short summary of the planned response
146
+ """
147
+ return await send_notification(
148
+ token=token,
149
+ title="\U0001f6a8 Crisis Alert — Response Required",
150
+ body=(
151
+ f"Confirmed {crisis_type} in {location}. "
152
+ f"Severity: {severity}/5. {response_plan_summary}"
153
+ ),
154
+ data={
155
+ "type": "ngo_escalation",
156
+ "crisis_id": crisis_id,
157
+ "crisis_type": crisis_type,
158
+ "location": location,
159
+ "severity": str(severity),
160
+ "response_plan_summary": response_plan_summary,
161
+ },
162
+ )
src/backend/services/firestore.py ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Dict, Any, List, Optional
2
+ from fastapi import HTTPException
3
+ from google.cloud.firestore import AsyncClient, SERVER_TIMESTAMP, ArrayUnion, FieldFilter
4
+ from backend.core.firebase import get_async_db
5
+
6
+ class FirestoreService:
7
+ @property
8
+ def db(self) -> AsyncClient:
9
+ return get_async_db()
10
+
11
+ async def get_user(self, cnic: str) -> Optional[Dict[str, Any]]:
12
+ doc_ref = self.db.collection("users").document(cnic)
13
+ doc = await doc_ref.get()
14
+ if doc.exists:
15
+ return doc.to_dict()
16
+ return None
17
+
18
+ async def create_user(self, data: Dict[str, Any]) -> Dict[str, Any]:
19
+ cnic = data.get("cnic")
20
+ if not cnic:
21
+ raise ValueError("CNIC is required to create a user.")
22
+ doc_ref = self.db.collection("users").document(cnic)
23
+ await doc_ref.set(data)
24
+ return data
25
+
26
+ async def update_user(self, cnic: str, data: Dict[str, Any]) -> Dict[str, Any]:
27
+ doc_ref = self.db.collection("users").document(cnic)
28
+ doc = await doc_ref.get()
29
+ if not doc.exists:
30
+ raise HTTPException(status_code=404, detail="User not found")
31
+ await doc_ref.update(data)
32
+ return {"cnic": cnic, **data}
33
+
34
+ async def create_crisis(self, data: Dict[str, Any]) -> Dict[str, Any]:
35
+ crisis_id = data.get("crisis_id")
36
+ if not crisis_id:
37
+ _, doc_ref = await self.db.collection("crises").add(data)
38
+ data["crisis_id"] = doc_ref.id
39
+ await doc_ref.update({"crisis_id": doc_ref.id})
40
+ else:
41
+ doc_ref = self.db.collection("crises").document(crisis_id)
42
+ await doc_ref.set(data)
43
+ return data
44
+
45
+ async def get_crisis(self, crisis_id: str) -> Optional[Dict[str, Any]]:
46
+ doc_ref = self.db.collection("crises").document(crisis_id)
47
+ doc = await doc_ref.get()
48
+ if doc.exists:
49
+ return doc.to_dict()
50
+ return None
51
+
52
+ async def update_crisis(self, crisis_id: str, data: Dict[str, Any]) -> Dict[str, Any]:
53
+ doc_ref = self.db.collection("crises").document(crisis_id)
54
+ doc = await doc_ref.get()
55
+ if not doc.exists:
56
+ raise HTTPException(status_code=404, detail="Crisis not found")
57
+ await doc_ref.update(data)
58
+ return {"crisis_id": crisis_id, **data}
59
+
60
+ async def get_ngos_for_area(self, area: str, crisis_type: str) -> List[Dict[str, Any]]:
61
+ ngos_ref = self.db.collection("ngos")
62
+ query = (
63
+ ngos_ref
64
+ .where(filter=FieldFilter("coverage_areas", "array_contains", area))
65
+ .where(filter=FieldFilter("active", "==", True))
66
+ )
67
+
68
+ results = []
69
+ async for doc in query.stream():
70
+ data = doc.to_dict()
71
+ if crisis_type in data.get("crisis_types", []):
72
+ results.append({"ngo_id": doc.id, **data})
73
+ return results
74
+
75
+ async def append_agent_log(self, crisis_id: str, step: Dict[str, Any]) -> bool:
76
+ log_ref = self.db.collection("agent_logs").document(crisis_id)
77
+ doc = await log_ref.get()
78
+
79
+ if not doc.exists:
80
+ await log_ref.set({
81
+ "crisis_id": crisis_id,
82
+ "steps": [step],
83
+ "created_at": SERVER_TIMESTAMP
84
+ })
85
+ else:
86
+ await log_ref.update({
87
+ "steps": ArrayUnion([step])
88
+ })
89
+ return True
90
+
91
+ firestore_service = FirestoreService()
src/backend/services/maps.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Google Maps Directions API client.
3
+
4
+ Failure policy
5
+ --------------
6
+ Any error returns [] — a maps miss must never crash the pipeline. The
7
+ planning agent falls back to a plan without concrete route data and notes
8
+ the absence in plan_summary.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+
15
+ import httpx
16
+ from pydantic import BaseModel, ConfigDict
17
+
18
+ from backend.core.config import settings
19
+
20
+ logger = logging.getLogger(__name__)
21
+
22
+ DIRECTIONS_BASE_URL = "https://maps.googleapis.com/maps/api/directions/json"
23
+ MAPS_TIMEOUT_SECONDS = 8.0
24
+
25
+
26
+ class RouteOption(BaseModel):
27
+ """A single route returned by the Google Maps Directions API."""
28
+
29
+ model_config = ConfigDict(extra="forbid")
30
+
31
+ summary: str
32
+ distance_km: float
33
+ duration_minutes: int
34
+ polyline: str
35
+ is_recommended: bool = False
36
+
37
+
38
+ async def fetch_routes(
39
+ origin: str,
40
+ destination: str,
41
+ *,
42
+ avoid_area: str | None = None,
43
+ ) -> list[RouteOption]:
44
+ """Fetch up to 3 alternate routes from the Directions API.
45
+
46
+ Args:
47
+ origin: Starting point as Pakistani address or "lat,lon".
48
+ destination: End point that bypasses the affected area.
49
+ avoid_area: Textual description of the crisis area — logged for
50
+ context only. The Directions API does not support arbitrary
51
+ coordinate avoidance, so alternatives=true is used instead.
52
+
53
+ Returns:
54
+ Up to 3 RouteOption objects sorted by duration ascending, with
55
+ the fastest marked is_recommended=True. Returns [] on any failure
56
+ or missing API key.
57
+ """
58
+ if not settings.google_maps_api_key:
59
+ logger.warning("GOOGLE_MAPS_API_KEY not set — skipping Maps routes")
60
+ return []
61
+
62
+ if avoid_area:
63
+ logger.info("Route fetch: %s → %s (avoiding %s)", origin, destination, avoid_area)
64
+
65
+ params: dict[str, str] = {
66
+ "origin": origin,
67
+ "destination": destination,
68
+ "alternatives": "true",
69
+ "key": settings.google_maps_api_key,
70
+ }
71
+
72
+ try:
73
+ async with httpx.AsyncClient(timeout=MAPS_TIMEOUT_SECONDS) as client:
74
+ response = await client.get(DIRECTIONS_BASE_URL, params=params)
75
+ response.raise_for_status()
76
+ payload = response.json()
77
+ except httpx.HTTPError as exc:
78
+ logger.warning("Google Maps HTTP error: %s", exc)
79
+ return []
80
+ except Exception as exc: # noqa: BLE001 — boundary; must not crash pipeline
81
+ logger.warning("Unexpected Maps error: %s", exc)
82
+ return []
83
+
84
+ if payload.get("status") != "OK":
85
+ logger.warning(
86
+ "Maps API status=%s: %s",
87
+ payload.get("status"),
88
+ payload.get("error_message", "(no detail)"),
89
+ )
90
+ return []
91
+
92
+ routes: list[RouteOption] = []
93
+ try:
94
+ for idx, route in enumerate(payload.get("routes", [])[:3]):
95
+ leg = route["legs"][0]
96
+ routes.append(RouteOption(
97
+ summary=route.get("summary") or f"Route {idx + 1}",
98
+ distance_km=round(int(leg["distance"]["value"]) / 1000, 2),
99
+ duration_minutes=round(int(leg["duration"]["value"]) / 60),
100
+ polyline=route["overview_polyline"]["points"],
101
+ ))
102
+ except (KeyError, IndexError, TypeError, ValueError) as exc:
103
+ logger.warning("Failed to parse Maps response: %s", exc)
104
+ return []
105
+
106
+ if not routes:
107
+ return []
108
+
109
+ routes.sort(key=lambda r: r.duration_minutes)
110
+ routes[0] = routes[0].model_copy(update={"is_recommended": True})
111
+ return routes
src/backend/services/ngo_escalation.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ NGO Escalation Service — Phase 11.
3
+
4
+ Owns:
5
+ - Severity threshold evaluation (NGO_ESCALATION_THRESHOLD = 3)
6
+ - NGO matching: coverage area overlap + category match
7
+ - FCM dispatch to matched NGO devices (real notification, real device)
8
+ - Persisting escalation state on the crisis Firestore document
9
+
10
+ Does NOT own:
11
+ - FCM send implementation (services/fcm.py — Phase 10)
12
+ - Severity calculation (agents/analysis.py — Phase 7)
13
+ - Emergency services dispatch (agents/planning.py — Phase 8)
14
+
15
+ Trigger points:
16
+ 1. agents/pipeline.py — after planning, checks Firestore verification_result
17
+ 2. routes/crowd_verification.py — fired immediately when verdict = "confirmed"
18
+
19
+ Path 2 is the primary demo path: the NGO notification lands in real time
20
+ the moment a nearby user confirms the crisis.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import logging
26
+
27
+ from google.cloud.firestore import FieldFilter, SERVER_TIMESTAMP
28
+
29
+ from backend.core.constants import NGO_CRISIS_TYPE_MAP, NGO_ESCALATION_THRESHOLD
30
+ from backend.core.firebase import get_async_db
31
+ from backend.models.escalation import EscalationResult
32
+ from backend.services.fcm import send_ngo_alert
33
+
34
+ logger = logging.getLogger(__name__)
35
+
36
+
37
+ # ── NGO matching helpers ──────────────────────────────────────────────────────
38
+
39
+
40
+ def _location_matches(coverage_areas: list[str], location_label: str) -> bool:
41
+ """Return True if any coverage area string appears in the location label.
42
+
43
+ Case-insensitive substring match: "G-10" matches "G-10, Islamabad".
44
+ """
45
+ loc_lower = location_label.lower()
46
+ return any(area.lower() in loc_lower for area in coverage_areas)
47
+
48
+
49
+ def _category_matches(ngo_categories: list[str], required_categories: list[str]) -> bool:
50
+ """Return True if the NGO has at least one category from required_categories."""
51
+ ngo_set = {c.lower() for c in ngo_categories}
52
+ return any(req.lower() in ngo_set for req in required_categories)
53
+
54
+
55
+ async def _query_matching_ngos(
56
+ location_label: str,
57
+ crisis_type: str,
58
+ ) -> list[dict]:
59
+ """Fetch all NGO users from Firestore and filter by coverage + category.
60
+
61
+ Firestore cannot do combined array-intersection queries, so we fetch all
62
+ role="ngo" users and filter in Python — acceptable at demo scale.
63
+
64
+ Returns:
65
+ List of matching NGO user dicts (each guaranteed to have fcm_token
66
+ and ngo_name set).
67
+ """
68
+ required_categories = NGO_CRISIS_TYPE_MAP.get(crisis_type, ["disaster_relief"])
69
+
70
+ db = get_async_db()
71
+ query = db.collection("users").where(filter=FieldFilter("role", "==", "ngo"))
72
+
73
+ matched: list[dict] = []
74
+ async for doc in query.stream():
75
+ data = doc.to_dict()
76
+ token: str | None = data.get("fcm_token")
77
+ ngo_name: str | None = data.get("ngo_name")
78
+ if not token or not ngo_name:
79
+ continue
80
+
81
+ coverage: list[str] = data.get("coverage_areas") or []
82
+ categories: list[str] = data.get("ngo_categories") or []
83
+
84
+ if _location_matches(coverage, location_label) and _category_matches(categories, required_categories):
85
+ matched.append({"fcm_token": token, "ngo_name": ngo_name})
86
+
87
+ return matched
88
+
89
+
90
+ # ── Core escalation logic ─────────────────────────────────────────────────────
91
+
92
+
93
+ async def run_escalation(
94
+ crisis_id: str,
95
+ crisis_type: str,
96
+ location_label: str,
97
+ severity: int,
98
+ response_plan_summary: str,
99
+ verification_result: str,
100
+ ) -> EscalationResult:
101
+ """Evaluate and execute NGO escalation for a crisis.
102
+
103
+ Args:
104
+ crisis_id: Firestore document ID of the crisis.
105
+ crisis_type: Detected crisis type (e.g. "flood").
106
+ location_label: Human-readable area name (e.g. "G-10, Islamabad").
107
+ severity: SituationReport.severity score (1-5).
108
+ response_plan_summary: One-sentence plan summary for the NGO notification.
109
+ verification_result: Current crowd verification status; must be
110
+ "confirmed" for escalation to proceed.
111
+
112
+ Returns:
113
+ EscalationResult describing the outcome. Never raises.
114
+ """
115
+ # Guard 1: only confirmed crises get escalated
116
+ if verification_result != "confirmed":
117
+ return EscalationResult(
118
+ escalated=False,
119
+ reason="Crisis not confirmed by crowd — escalation requires verification_result='confirmed'",
120
+ ngos_alerted=[],
121
+ severity_score=severity,
122
+ threshold_used=NGO_ESCALATION_THRESHOLD,
123
+ )
124
+
125
+ # Guard 2: severity threshold
126
+ if severity < NGO_ESCALATION_THRESHOLD:
127
+ return EscalationResult(
128
+ escalated=False,
129
+ reason=(
130
+ f"Severity {severity} is below NGO escalation threshold "
131
+ f"({NGO_ESCALATION_THRESHOLD}). No NGO alert required."
132
+ ),
133
+ ngos_alerted=[],
134
+ severity_score=severity,
135
+ threshold_used=NGO_ESCALATION_THRESHOLD,
136
+ )
137
+
138
+ # Find matching NGOs
139
+ matched = await _query_matching_ngos(location_label, crisis_type)
140
+ if not matched:
141
+ return EscalationResult(
142
+ escalated=False,
143
+ reason=f"No NGOs registered for area '{location_label}' / type '{crisis_type}'",
144
+ ngos_alerted=[],
145
+ severity_score=severity,
146
+ threshold_used=NGO_ESCALATION_THRESHOLD,
147
+ )
148
+
149
+ # Dispatch FCM to each matched NGO
150
+ alerted: list[str] = []
151
+ for ngo in matched:
152
+ ok = await send_ngo_alert(
153
+ token=ngo["fcm_token"],
154
+ crisis_id=crisis_id,
155
+ crisis_type=crisis_type,
156
+ location=location_label,
157
+ severity=severity,
158
+ response_plan_summary=response_plan_summary,
159
+ )
160
+ if ok:
161
+ alerted.append(ngo["ngo_name"])
162
+ logger.info("NGO escalation alert sent to %s for crisis %s", ngo["ngo_name"], crisis_id)
163
+ else:
164
+ logger.warning("FCM delivery failed for NGO %s (crisis %s)", ngo["ngo_name"], crisis_id)
165
+
166
+ # Persist escalation outcome on the crisis document
167
+ db = get_async_db()
168
+ await db.collection("crises").document(crisis_id).update({
169
+ "escalation_status": "escalated" if alerted else "delivery_failed",
170
+ "ngos_alerted": alerted,
171
+ "escalation_at": SERVER_TIMESTAMP,
172
+ })
173
+
174
+ if alerted:
175
+ return EscalationResult(
176
+ escalated=True,
177
+ reason=f"Escalated to {len(alerted)} NGO(s): {', '.join(alerted)}",
178
+ ngos_alerted=alerted,
179
+ severity_score=severity,
180
+ threshold_used=NGO_ESCALATION_THRESHOLD,
181
+ )
182
+ return EscalationResult(
183
+ escalated=False,
184
+ reason=f"Matched {len(matched)} NGO(s) but FCM delivery failed for all",
185
+ ngos_alerted=[],
186
+ severity_score=severity,
187
+ threshold_used=NGO_ESCALATION_THRESHOLD,
188
+ )
189
+
190
+
191
+ async def escalate_confirmed_crisis(crisis_id: str) -> EscalationResult:
192
+ """Convenience entry point called from the verify route on confirmed verdict.
193
+
194
+ Reads all needed context (crisis_type, location_label, severity,
195
+ response_plan_summary) from the Firestore crisis document, then delegates
196
+ to run_escalation(). Returns a not-escalated result gracefully if the
197
+ document is missing or incomplete.
198
+ """
199
+ db = get_async_db()
200
+ doc = await db.collection("crises").document(crisis_id).get()
201
+ if not doc.exists:
202
+ return EscalationResult(
203
+ escalated=False,
204
+ reason=f"Crisis {crisis_id!r} not found in Firestore",
205
+ ngos_alerted=[],
206
+ severity_score=0,
207
+ threshold_used=NGO_ESCALATION_THRESHOLD,
208
+ )
209
+
210
+ data = doc.to_dict()
211
+ return await run_escalation(
212
+ crisis_id=crisis_id,
213
+ crisis_type=data.get("crisis_type") or "unknown",
214
+ location_label=data.get("location_label") or "unknown",
215
+ severity=int(data.get("severity") or 0),
216
+ response_plan_summary=data.get("response_plan_summary") or "",
217
+ verification_result=data.get("verification_result") or "inconclusive",
218
+ )
src/backend/services/radius_query.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Radius-based Firestore user query for crowd verification.
3
+
4
+ Firestore lacks native geo-radius support; this module fetches all verified,
5
+ non-blacklisted users and filters in Python using the Haversine formula.
6
+ Acceptable for demo scale (hundreds of users). Production would use
7
+ GeoFirestore or server-side geo-hash indexing.
8
+
9
+ Only users who have BOTH `last_location` and `fcm_token` set are returned —
10
+ no token means we cannot notify them; no location means we cannot check their
11
+ proximity.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import math
17
+ from typing import NamedTuple
18
+
19
+ from google.cloud.firestore import FieldFilter
20
+
21
+ from backend.core.firebase import get_async_db
22
+
23
+ DEFAULT_RADIUS_KM: float = 1.0
24
+
25
+
26
+ class NearbyUser(NamedTuple):
27
+ cnic: str
28
+ fcm_token: str
29
+ distance_km: float
30
+
31
+
32
+ def _haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
33
+ """Return great-circle distance in km between two WGS-84 points."""
34
+ R = 6371.0
35
+ dlat = math.radians(lat2 - lat1)
36
+ dlon = math.radians(lon2 - lon1)
37
+ a = (
38
+ math.sin(dlat / 2) ** 2
39
+ + math.cos(math.radians(lat1))
40
+ * math.cos(math.radians(lat2))
41
+ * math.sin(dlon / 2) ** 2
42
+ )
43
+ return R * 2 * math.asin(math.sqrt(a))
44
+
45
+
46
+ async def get_users_within_radius(
47
+ lat: float,
48
+ lon: float,
49
+ radius_km: float = DEFAULT_RADIUS_KM,
50
+ ) -> list[NearbyUser]:
51
+ """Return verified app users within `radius_km` of (lat, lon).
52
+
53
+ Args:
54
+ lat: Crisis latitude in WGS-84 decimal degrees.
55
+ lon: Crisis longitude in WGS-84 decimal degrees.
56
+ radius_km: Search radius. Defaults to DEFAULT_RADIUS_KM (1 km).
57
+
58
+ Returns:
59
+ List of NearbyUser tuples sorted by distance ascending. Empty list
60
+ when no eligible users are found or Firestore returns no results.
61
+ """
62
+ db = get_async_db()
63
+ query = (
64
+ db.collection("users")
65
+ .where(filter=FieldFilter("verified", "==", True))
66
+ .where(filter=FieldFilter("blacklisted", "==", False))
67
+ )
68
+
69
+ nearby: list[NearbyUser] = []
70
+ async for doc in query.stream():
71
+ data = doc.to_dict()
72
+ token: str | None = data.get("fcm_token")
73
+ loc: dict | None = data.get("last_location")
74
+ if not token or not loc:
75
+ continue
76
+ ulat = loc.get("lat")
77
+ ulon = loc.get("lon")
78
+ if ulat is None or ulon is None:
79
+ continue
80
+ dist = _haversine(lat, lon, float(ulat), float(ulon))
81
+ if dist <= radius_km:
82
+ nearby.append(NearbyUser(cnic=doc.id, fcm_token=token, distance_km=dist))
83
+
84
+ nearby.sort(key=lambda u: u.distance_km)
85
+ return nearby
src/backend/services/risk_tiering.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Deterministic crisis risk-tier classifier.
3
+
4
+ This is the one stage of the CIRO pipeline that is *not* an LLM call.
5
+ The phase doc is explicit:
6
+
7
+ "Risk tiering is deterministic rule-based logic — fast, predictable,
8
+ testable."
9
+
10
+ Why deterministic here matters
11
+ ------------------------------
12
+ The risk tier decides whether emergency services get involved at all,
13
+ and whether to broadcast push notifications to nearby app users. We do
14
+ not want that decision varying request-to-request based on model
15
+ sampling. A rule-based classifier is faster, cheaper, and auditable.
16
+
17
+ Classification rules (single source of truth)
18
+ ---------------------------------------------
19
+ crisis_type in LOW_RISK_TYPES → "low" (regardless of confidence)
20
+ crisis_type in MEDIUM_HIGH_RISK_TYPES:
21
+ confidence >= CONFIDENCE_THRESHOLD → "high"
22
+ confidence < CONFIDENCE_THRESHOLD → "medium" (confidence cap)
23
+ crisis_type otherwise / None → "medium" (fail-safe default)
24
+
25
+ The confidence cap acts as a *ceiling* on high-risk types, not a floor
26
+ on everything. A low-confidence rainfall stays low — raising it to
27
+ medium just because confidence is low would be perverse. The cap exists
28
+ specifically to make sure we don't skip crowd verification for a
29
+ high-risk type when the agent is unsure.
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ from backend.agents.detection import DetectionOutput
35
+ from backend.core.constants import (
36
+ CONFIDENCE_THRESHOLD,
37
+ LOW_RISK_TYPES,
38
+ MEDIUM_HIGH_RISK_TYPES,
39
+ )
40
+ from backend.models.agent_result import AgentResult
41
+ from backend.models.risk import RiskTieringResult
42
+
43
+
44
+ # Actions safe to fire automatically for a low-risk crisis. The simulation
45
+ # agent (Phase 12) is what actually executes them; tiering only declares
46
+ # intent. Kept here so the list lives next to the rule that produces it.
47
+ _LOW_RISK_AUTO_ACTIONS: list[str] = ["reroute_traffic", "send_area_alert"]
48
+
49
+ RISK_TIER_AGENT_NAME = "risk_tier_classifier"
50
+
51
+
52
+ # ── Pure classifier ───────────────────────────────────────────────────────
53
+
54
+
55
+ def classify_risk(detection: DetectionOutput) -> RiskTieringResult:
56
+ """Apply the risk-tiering rules to a detection result.
57
+
58
+ Args:
59
+ detection: The structured output of Phase 5's detection agent.
60
+ This function does not re-validate that a crisis was detected —
61
+ callers (the pipeline) decide whether to even ask. If the
62
+ detection has `crisis_detected=False`, we still produce a
63
+ sensible "low" result so the function stays total.
64
+
65
+ Returns:
66
+ A `RiskTieringResult` describing the response path. Never raises.
67
+ """
68
+
69
+ # Defensive: no crisis → no need to escalate anything. The pipeline
70
+ # short-circuits before reaching here, but if a caller does invoke
71
+ # us with crisis_detected=False, return a coherent low-risk result
72
+ # rather than letting the caller see garbage.
73
+ if not detection.crisis_detected:
74
+ return RiskTieringResult(
75
+ risk_level="low",
76
+ requires_crowd_verification=False,
77
+ requires_emergency_services=False,
78
+ auto_response_actions=[],
79
+ reasoning="No crisis detected; nothing to escalate.",
80
+ )
81
+
82
+ crisis_type = detection.crisis_type
83
+ confidence = detection.confidence
84
+
85
+ # ── Low-risk path: automated response, no humans involved. ───────────
86
+ if crisis_type in LOW_RISK_TYPES:
87
+ return RiskTieringResult(
88
+ risk_level="low",
89
+ requires_crowd_verification=False,
90
+ requires_emergency_services=False,
91
+ auto_response_actions=list(_LOW_RISK_AUTO_ACTIONS),
92
+ reasoning=(
93
+ f"Crisis type {crisis_type!r} is low-risk. "
94
+ "Automated response initiated; no crowd verification or "
95
+ "emergency dispatch required."
96
+ ),
97
+ )
98
+
99
+ # ── Medium/high path with confidence cap. ────────────────────────────
100
+ if crisis_type in MEDIUM_HIGH_RISK_TYPES:
101
+ if confidence < CONFIDENCE_THRESHOLD:
102
+ return RiskTieringResult(
103
+ risk_level="medium",
104
+ requires_crowd_verification=True,
105
+ requires_emergency_services=True,
106
+ auto_response_actions=[],
107
+ reasoning=(
108
+ f"Crisis type {crisis_type!r} is high-risk but "
109
+ f"detection confidence is {confidence:.2f} "
110
+ f"(< {CONFIDENCE_THRESHOLD}); capping at medium. "
111
+ "Crowd verification required before emergency dispatch."
112
+ ),
113
+ )
114
+
115
+ return RiskTieringResult(
116
+ risk_level="high",
117
+ requires_crowd_verification=True,
118
+ requires_emergency_services=True,
119
+ auto_response_actions=[],
120
+ reasoning=(
121
+ f"Crisis type {crisis_type!r} is high-risk with "
122
+ f"confidence {confidence:.2f}. Crowd verification "
123
+ "required before emergency dispatch."
124
+ ),
125
+ )
126
+
127
+ # ── Unknown crisis type → fail-safe default. ─────────────────────────
128
+ # We never silently skip verification for an unrecognized label.
129
+ return RiskTieringResult(
130
+ risk_level="medium",
131
+ requires_crowd_verification=True,
132
+ requires_emergency_services=True,
133
+ auto_response_actions=[],
134
+ reasoning=(
135
+ f"Crisis type {crisis_type!r} is not in the known taxonomy; "
136
+ "defaulting to medium risk so crowd verification is performed."
137
+ ),
138
+ )
139
+
140
+
141
+ # ── Pipeline-facing wrapper (synthesizes an AgentResult) ─────────────────
142
+
143
+
144
+ def run_risk_tiering(detection: DetectionOutput) -> AgentResult:
145
+ """Run the classifier and wrap the result as an `AgentResult`.
146
+
147
+ The trace UI and downstream pipeline expect every stage to produce an
148
+ `AgentResult`. Since this stage is deterministic, we synthesize one:
149
+ `success=True`, `confidence=1.0`, the reasoning copied from the
150
+ classifier's verdict.
151
+
152
+ This wrapper is the only thing the pipeline imports from this module —
153
+ `classify_risk` itself stays pure so it can be unit-tested without
154
+ touching the AgentResult shape.
155
+ """
156
+ tiering = classify_risk(detection)
157
+ return AgentResult(
158
+ agent_name=RISK_TIER_AGENT_NAME,
159
+ success=True,
160
+ output=tiering.model_dump(),
161
+ reasoning=tiering.reasoning,
162
+ confidence=1.0,
163
+ )
src/backend/services/signal_aggregator.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Signal aggregator — single fan-in point for every CrisisSignal source.
3
+
4
+ Why this is a separate module
5
+ -----------------------------
6
+ The detection agent in Phase 5 calls one function and gets back a uniform,
7
+ ranked list of signals. It does not orchestrate the weather client, doesn't
8
+ know which scenario is loaded, and doesn't care whether OWM was reachable.
9
+ All of that lives here.
10
+
11
+ CNIC-verified in-app reports are deliberately NOT plumbed through this
12
+ function — Phase 9 owns their own ingestion path. The aggregator is for
13
+ non-app evidence only.
14
+
15
+ Ordering
16
+ --------
17
+ Signals are returned sorted by `trust_weight` descending, so the detection
18
+ agent processes the most credible evidence first. Ties keep their original
19
+ source order (weather before social, matching the call order below).
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import asyncio
25
+
26
+ from backend.models.signal import CrisisSignal
27
+ from backend.services.social_feed import get_social_feed
28
+ from backend.services.weather import fetch_weather_signal
29
+
30
+
31
+ async def aggregate_signals(
32
+ *,
33
+ scenario: str | None,
34
+ lat: float,
35
+ lon: float,
36
+ location_label: str | None = None,
37
+ ) -> list[CrisisSignal]:
38
+ """Collect every non-app signal for a given scenario + location.
39
+
40
+ Runs the weather fetch concurrently with social-feed lookup so the
41
+ cumulative latency is dominated by the weather API call rather than
42
+ summed.
43
+
44
+ Args:
45
+ scenario: Name of the demo scenario to pull social-media posts
46
+ for (e.g. `"g10_flood"`). Pass `None` to skip social and
47
+ return weather-only.
48
+ lat: Latitude for the weather lookup.
49
+ lon: Longitude for the weather lookup.
50
+ location_label: Optional human-readable area label passed through
51
+ to the weather signal. Social signals use the label baked
52
+ into their scenario definition.
53
+
54
+ Returns:
55
+ Combined list of `CrisisSignal`, sorted by `trust_weight`
56
+ descending. Empty list is a valid result (e.g. unknown scenario
57
+ AND weather API down).
58
+ """
59
+ # Kick both off in parallel. Each side has its own failure isolation:
60
+ # weather returns None on any error; the feed returns [] for unknown
61
+ # scenarios. So neither side can bubble an exception.
62
+ weather_task = asyncio.create_task(
63
+ fetch_weather_signal(lat, lon, location_label=location_label)
64
+ )
65
+
66
+ social_signals: list[CrisisSignal] = (
67
+ get_social_feed(scenario) if scenario else []
68
+ )
69
+ weather_signal = await weather_task
70
+
71
+ combined: list[CrisisSignal] = []
72
+ if weather_signal is not None:
73
+ combined.append(weather_signal)
74
+ combined.extend(social_signals)
75
+
76
+ # Stable sort preserves call order within a trust tier.
77
+ combined.sort(key=lambda s: s.trust_weight, reverse=True)
78
+ return combined
src/backend/services/social_feed.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Simulated social-media feed for CIRO demos.
3
+
4
+ Why simulated
5
+ -------------
6
+ The hackathon scope (see OUT_OF_SCOPE.md) explicitly rules out live
7
+ scraping of Twitter/X, Facebook, etc. Real demos need reproducible
8
+ input, so we ship a small catalogue of pre-written Urdu/English posts
9
+ keyed by named scenario.
10
+
11
+ Each scenario bundles:
12
+ • a stable `location_label` and `coordinates` (so every signal in the
13
+ scenario plausibly comes from the same area),
14
+ • a fixed `signal_type` and source-level `severity_hint`,
15
+ • a list of `posts` — natural-language strings exactly as a user
16
+ would post them.
17
+
18
+ Adding a scenario is the *only* way new social-media-style content
19
+ enters the system. There is no scraping, no live feed, no third-party
20
+ client.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ from datetime import datetime, timezone
26
+ from typing import TypedDict
27
+
28
+ from backend.models.signal import (
29
+ TRUST_WEIGHT_SOCIAL_MEDIA,
30
+ CrisisSignal,
31
+ SeverityHint,
32
+ SignalType,
33
+ )
34
+
35
+
36
+ class _Scenario(TypedDict):
37
+ location_label: str
38
+ coordinates: tuple[float, float]
39
+ signal_type: SignalType
40
+ severity_hint: SeverityHint | None
41
+ posts: list[str]
42
+
43
+
44
+ # Coordinates are deliberately approximate — exact-enough to drop a marker
45
+ # in the right sector on a map without claiming sub-block precision.
46
+ SCENARIOS: dict[str, _Scenario] = {
47
+ "g10_flood": {
48
+ "location_label": "G-10, Islamabad",
49
+ "coordinates": (33.6844, 73.0479),
50
+ "signal_type": "flood",
51
+ "severity_hint": "heavy",
52
+ "posts": [
53
+ "G-10 mein pani bhar gaya hai, gaariyan phans gayi hain",
54
+ "Flash flood on main G-10 road, cars stuck",
55
+ "Yahan pani itna zyada hai, nikal nahi saktay",
56
+ ],
57
+ },
58
+ "g18_fire": {
59
+ "location_label": "G-18, Islamabad",
60
+ "coordinates": (33.6093, 72.9213),
61
+ "signal_type": "fire",
62
+ "severity_hint": "heavy",
63
+ "posts": [
64
+ "G-18 mein aag lag gayi hai",
65
+ "Huge fire near G-18 markaz, smoke visible from far",
66
+ "Fire brigade ko bulao, G-18 main road",
67
+ ],
68
+ },
69
+ "i8_traffic": {
70
+ "location_label": "I-8 Flyover, Islamabad",
71
+ "coordinates": (33.6663, 73.0723),
72
+ "signal_type": "traffic",
73
+ "severity_hint": "moderate",
74
+ "posts": [
75
+ "I-8 flyover completely jammed, no movement for 40 mins",
76
+ "Bohat zyada traffic hai I-8 par, koi accident hua lagta hai",
77
+ ],
78
+ },
79
+ }
80
+
81
+
82
+ def list_scenarios() -> list[str]:
83
+ """Return the ids of every available demo scenario."""
84
+ return list(SCENARIOS.keys())
85
+
86
+
87
+ def get_social_feed(scenario: str) -> list[CrisisSignal]:
88
+ """Return all social-media signals for a named demo scenario.
89
+
90
+ Args:
91
+ scenario: One of the keys in `SCENARIOS` (e.g. `"g10_flood"`).
92
+
93
+ Returns:
94
+ A list of `CrisisSignal` instances with `source="social_media"`
95
+ and `trust_weight=0.5`, one per pre-written post. Returns `[]`
96
+ for unknown scenarios — callers treat that the same way they
97
+ treat a real-world feed with no matching posts.
98
+ """
99
+ bundle = SCENARIOS.get(scenario)
100
+ if bundle is None:
101
+ return []
102
+
103
+ now = datetime.now(timezone.utc)
104
+ return [
105
+ CrisisSignal(
106
+ source="social_media",
107
+ trust_weight=TRUST_WEIGHT_SOCIAL_MEDIA,
108
+ raw_text=post,
109
+ location_label=bundle["location_label"],
110
+ coordinates=bundle["coordinates"],
111
+ signal_type=bundle["signal_type"],
112
+ severity_hint=bundle["severity_hint"],
113
+ timestamp=now,
114
+ )
115
+ for post in bundle["posts"]
116
+ ]
src/backend/services/trace.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Trace service — Phase 13.
3
+
4
+ Assembles the agent reasoning trace from pipeline AgentResult outputs and
5
+ persists it to Firestore agent_logs. Provides the read path for
6
+ GET /api/crisis/{crisis_id}/trace.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from datetime import datetime, timezone
12
+
13
+ from backend.core.firebase import get_async_db
14
+ from backend.models.agent_result import AgentResult
15
+ from backend.models.trace import AgentTrace, AgentTraceStep, FinalOutcome
16
+
17
+
18
+ # Maps pipeline agent_name → human-readable action label.
19
+ _ACTION_LABELS: dict[str, str] = {
20
+ "crisis_detection_agent": "Crisis Detected",
21
+ "risk_tier_classifier": "Risk Classified",
22
+ "crowd_verification": "Verification Sent",
23
+ "situation_analysis_agent": "Situation Assessed",
24
+ "action_planning_agent": "Response Plan Generated",
25
+ "ngo_escalation": "NGOs Alerted",
26
+ "simulation_agent": "Simulation Complete",
27
+ }
28
+
29
+
30
+ def _action_label(result: AgentResult) -> str:
31
+ name = result.agent_name
32
+ if name == "crisis_detection_agent":
33
+ return "Crisis Detected" if result.output.get("crisis_detected") else "No Crisis Detected"
34
+ if name == "ngo_escalation":
35
+ ngos = result.output.get("ngos_alerted") or []
36
+ return "NGOs Alerted" if ngos else "No Escalation"
37
+ return _ACTION_LABELS.get(name, name.replace("_", " ").title())
38
+
39
+
40
+ def _output_summary(result: AgentResult) -> str:
41
+ """Derive a one-line plain-English summary from the step's output dict."""
42
+ out = result.output
43
+ name = result.agent_name
44
+
45
+ if name == "crisis_detection_agent":
46
+ if out.get("crisis_detected"):
47
+ ct = out.get("crisis_type", "unknown")
48
+ loc = out.get("location_label", "unknown location")
49
+ return f"Detected {ct} at {loc} (confidence: {result.confidence:.0%})."
50
+ return "No crisis found in incoming signals."
51
+
52
+ if name == "risk_tier_classifier":
53
+ level = out.get("risk_level", "unknown")
54
+ requires_cv = out.get("requires_crowd_verification", False)
55
+ suffix = "Crowd verification required." if requires_cv else "Auto-response triggered."
56
+ return f"Risk level: {level}. {suffix}"
57
+
58
+ if name == "crowd_verification":
59
+ if result.success:
60
+ notified = out.get("users_notified", 0)
61
+ return f"Prompts sent to {notified} nearby users. Awaiting crowd responses."
62
+ return "Crowd verification dispatch failed; pipeline continued."
63
+
64
+ if name == "situation_analysis_agent":
65
+ severity = out.get("severity", "?")
66
+ label = out.get("severity_label", "")
67
+ population = out.get("affected_population_estimate", "unknown")
68
+ return f"Severity {severity}/5 ({label}). Affected population: {population}."
69
+
70
+ if name == "action_planning_agent":
71
+ immediate = len(out.get("immediate_actions") or [])
72
+ short_term = len(out.get("short_term_actions") or [])
73
+ eta = out.get("estimated_response_time", "unknown")
74
+ return f"Plan: {immediate} immediate, {short_term} short-term actions. ETA: {eta}."
75
+
76
+ if name == "ngo_escalation":
77
+ ngos = out.get("ngos_alerted") or []
78
+ if ngos:
79
+ names_str = ", ".join(str(n) for n in ngos[:3])
80
+ return f"Escalated to {len(ngos)} NGO(s): {names_str}."
81
+ return out.get("reason") or "No escalation threshold met."
82
+
83
+ if name == "simulation_agent":
84
+ after = out.get("after") or {}
85
+ congestion = after.get("congestion_level", "unknown")
86
+ alerted = after.get("citizens_alerted", 0)
87
+ return f"Response executed. Congestion: '{congestion}', {alerted} citizens alerted."
88
+
89
+ return (result.reasoning or "Step completed.")[:120]
90
+
91
+
92
+ def _final_outcome(results: list[AgentResult]) -> FinalOutcome:
93
+ """Determine the overall pipeline outcome from the accumulated trace steps."""
94
+ names = {r.agent_name for r in results}
95
+
96
+ for r in results:
97
+ if r.agent_name == "crisis_detection_agent" and not r.output.get("crisis_detected"):
98
+ return "inconclusive"
99
+
100
+ if "simulation_agent" not in names:
101
+ return "inconclusive"
102
+
103
+ for r in results:
104
+ if r.agent_name == "risk_tier_classifier":
105
+ if not r.output.get("requires_crowd_verification"):
106
+ return "low_risk_auto"
107
+
108
+ return "responded"
109
+
110
+
111
+ def assemble_trace(crisis_id: str, results: list[AgentResult]) -> AgentTrace:
112
+ """Convert pipeline AgentResult list into a structured AgentTrace.
113
+
114
+ Step numbers are sequential in execution order. Not every pipeline step
115
+ runs for every scenario (e.g. crowd verification is medium/high only),
116
+ so step numbers reflect what actually ran.
117
+ """
118
+ steps: list[AgentTraceStep] = []
119
+ for i, r in enumerate(results, start=1):
120
+ steps.append(
121
+ AgentTraceStep(
122
+ step_number=i,
123
+ agent_name=r.agent_name,
124
+ action=_action_label(r),
125
+ reasoning=r.reasoning,
126
+ confidence=r.confidence,
127
+ output_summary=_output_summary(r),
128
+ timestamp=r.timestamp,
129
+ )
130
+ )
131
+
132
+ duration = 0.0
133
+ if len(steps) >= 2:
134
+ duration = max(
135
+ (steps[-1].timestamp - steps[0].timestamp).total_seconds(),
136
+ 0.0,
137
+ )
138
+
139
+ return AgentTrace(
140
+ crisis_id=crisis_id,
141
+ steps=steps,
142
+ total_duration_seconds=duration,
143
+ final_outcome=_final_outcome(results),
144
+ created_at=datetime.now(timezone.utc),
145
+ )
146
+
147
+
148
+ async def save_trace(trace: AgentTrace) -> None:
149
+ """Persist the assembled trace to Firestore agent_logs/{crisis_id}.
150
+
151
+ Keyed by crisis_id so the mobile app fetches it with a single document
152
+ read. Overwrites any existing trace for this crisis_id (idempotent).
153
+ """
154
+ db = get_async_db()
155
+ await db.collection("agent_logs").document(trace.crisis_id).set(
156
+ trace.model_dump(mode="json")
157
+ )
158
+
159
+
160
+ async def get_trace(crisis_id: str) -> AgentTrace | None:
161
+ """Read a trace from Firestore. Returns None if no trace exists."""
162
+ db = get_async_db()
163
+ doc = await db.collection("agent_logs").document(crisis_id).get()
164
+ if not doc.exists:
165
+ return None
166
+ return AgentTrace.model_validate(doc.to_dict())