abinazebinoy commited on
Commit
9f87a81
·
unverified ·
1 Parent(s): 3020619

Update Phaseroadmap with new features

Browse files
Files changed (1) hide show
  1. PHASE_ROADMAP.md +757 -261
PHASE_ROADMAP.md CHANGED
@@ -1,432 +1,928 @@
1
- # BharatGraph Complete Phase Roadmap
2
 
3
- All branches merge into `main`. Branch naming: `feature/phase-N-name` or `fix/issue-description`.
4
  Each phase has a GitHub Issue (see `issues/` directory) and a PR description template.
5
 
6
  ---
7
 
8
- ## COMPLETED PHASES
9
 
10
- ### Phase 1 Data Collection
11
- **Tag:** pre-v1 | **Branch:** `feature/phase-1-scrapers`
12
- **Summary:** Established the base scraper class with rate limiting, retry logic, and JSON output. Delivered the first 6 live scrapers (DataGov, CAG, PIB, MyNeta, MCA, GeM). Confirmed live data: DataGov returned 3,199 MGNREGA records; CAG returned 30 audit links; PIB returned 27 press release entries. All scrapers write to `data/raw/` with ISO timestamps.
13
 
14
- ### Phase 2 Data Processing
15
- **Tag:** pre-v2 | **Branch:** `feature/phase-2-processing`
16
- **Summary:** Indian name normalisation with honorific and company-prefix handling (Sh., Smt., Dr., Ltd, Pvt, LLP). Jaccard token similarity for cross-source entity resolution — prevented duplicate nodes from different datasets. Full parallel pipeline orchestrator using `concurrent.futures.ThreadPoolExecutor`. 47 records processed in 15 seconds on first run.
17
 
18
- ### Phase 3 Graph Database
19
- **Tag:** pre-v3 | **Branch:** `feature/phase-3-graph`
20
- **Summary:** Designed the Neo4j AuraDB schema with 7 node types and 6 relationship types. All MERGE operations use stable MD5 IDs derived from canonical properties — no duplicate nodes across pipeline runs. 8 pre-built Cypher query templates cover the most common investigation paths. Successfully connected to `neo4j+s://1a34e3b8.databases.neo4j.io`.
21
 
22
- ### Phase 4 FastAPI Backend
23
- **Tag:** v0.12.0 | **Branch:** `feature/phase-4-api`
24
- **Summary:** Launched the production API with FastAPI lifespan context, CORS middleware, Neo4j dependency injection, and Pydantic response models with typed source citations. Initial routes: search, profile, graph, risk. All responses include `generated_at` timestamp and source attribution for every data point.
25
 
26
- ### Phase 5 Risk Scoring Engine
27
- **Branch:** `feature/phase-5-risk`
28
- **Summary:** Composite 0–100 structural risk score combining five weighted indicators: politician–company overlap (0.35), contract concentration (0.25), audit mention frequency (0.20), asset growth anomaly (0.15), declared criminal cases (0.05). The `validate_language()` function enforces neutral analytical vocabulary across all outputs — no accusatory language passes through any API response.
29
 
30
- ### Phase 6 Expanded Data Sources (13 scrapers)
31
- **Branch:** `feature/phase-6-scrapers`
32
- **Summary:** Added ICIJ Offshore Leaks scraper using BeautifulSoup HTML parsing; Wikidata SPARQL confirmed live with Modi Q1058 and Gandhi Q10218; OpenSanctions, Lok Sabha, SEBI, Electoral Bonds. All HuggingFace models used are fully public — no gating or approval required.
33
 
34
- ### Phase 7 NLP Document Intelligence
35
- **Branch:** `feature/phase-7-nlp`
36
- **Summary:** Integrated spaCy `en_core_web_sm` for English NER. Benford's Law chi-squared test on affidavit asset figures detects non-natural digit distributions. Multilingual NER via `Davlan/bert-base-multilingual-cased-ner-hrl`. Shadow draft detector achieved 93.35% cosine alignment on test corpus using `all-MiniLM-L6-v2`.
37
 
38
- ### Phase 8 Advanced Graph Analytics
39
- **Branch:** `feature/phase-8-graph-analytics`
40
- **Summary:** NetworkX integration for betweenness centrality, PageRank, and Louvain community detection. Circular ownership detection using `simple_cycles` — confirmed 3-node ownership cycle. Ghost company scorer with GHOST_THRESHOLD=60 — returned 100/100 on test case. Shadow director detection maps hidden directors across corporate structures.
41
 
42
- ### Phase 9 Eight New Indian Sources (21 total)
43
- **Branch:** `feature/phase-9-scrapers`
44
- **Summary:** Added NJDG (39 live court records confirmed), ED, CVC, NCRB, LGD, IBBI, NGO Darpan, CPPP. All scrapers include locally-stored fallback sample data so the system continues to work if any external source is temporarily unavailable.
45
 
46
- ### Phase 10 Multi-Investigator AI Engine
47
- **Tag:** v0.10.0 | **Branch:** `feature/phase-10-multi-investigator`
48
- **Summary:** 12 parallel investigators run in `ThreadPoolExecutor`, each querying the graph independently. Synthesis logic: 3+ investigators agreeing on a finding = HIGH confidence. SHA-256 report hash is stable and unique per investigation. Forbidden-word enforcement on all text output via `validate_language()`. Investigator weights: financial (0.12), political (0.10), corporate (0.10), judicial (0.08), procurement (0.12), network (0.08), asset (0.10), international (0.10), media (0.06), historical (0.08), public_interest (0.08), doubt (0.08).
49
 
50
- ### Phase 11 Multilingual Platform (22 Languages)
51
- **Branch:** `feature/phase-11-multilingual`
52
- **Summary:** All 22 Indian scheduled languages with ISO codes and Unicode script range detection. Language auto-detection via Unicode block analysis — Devanagari → hi, Tamil → ta confirmed. Helsinki-NLP/opus-mt-en-hi for translation. Cross-script entity matching: "Modi" transliterated to 5 scripts confirmed. Risk levels pre-translated in 9 languages.
53
 
54
- ### Phase 12 PDF Dossier Generator
55
- **Branch:** `feature/phase-12-pdf-dossier`
56
- **Summary:** Jinja2 + WeasyPrint pipeline produces HTML-first dossiers with PDF generation on Linux production. Indian tricolour design system with 8 structured sections. SHA-256 integrity hash per report — tamper detection confirmed. 10,829-character report rendered on test case. Routes: `GET /export/pdf/{entity_id}`, `GET /verify/{hash}`.
57
 
58
- ### Phase 13 Production Frontend
59
- **Branch:** `feature/phase-13-frontend`
60
- **Summary:** Vanilla HTML/CSS/JS single-page application — no React, no Node.js, no build step. Works directly from `file://` protocol for offline use. D3.js force-directed knowledge graph. Dark and light theme with CSS custom properties. 5 views: home, search, entity, live feed, about.
61
 
62
- ### Phase 14 Zero Cold-Start Deployment
63
- **Tag:** v0.14.0 | **Branch:** `feature/phase-14-deployment`
64
- **Summary:** HuggingFace Spaces Docker deployment with no cold start on public spaces. Service worker cache-first strategy for static assets. GZipMiddleware achieving 60–80% compression. `POST /admin/seed` loads 10 politicians, 5 companies, 3 contracts into Neo4j. GitHub Actions workflow deploys the frontend to GitHub Pages on every push to `main`. UptimeRobot pings `/health` every 5 minutes.
65
 
66
- ### Phase 15 Mathematical Intelligence Engine
67
- **Tag:** v0.15.0 | **Branch:** `feature/phase-15-math-intelligence`
68
- **Summary:** Spectral graph analysis using the Laplacian Fiedler value (λ₁) — entities near λ₁ are graph bridges. Fourier FFT on contract amount time series detects periodic patterns (e.g. systematic quarterly spikes). 13th investigator (math, weight 0.08) integrated into the multi-investigator engine.
69
 
70
- ### Phase 16 Evidence Connection Map and Deep Investigation Engine
71
- **Tag:** v0.16.0 | **Branch:** `feature/phase-16-evidence-map`
72
- **Summary:** 6-layer recursive investigation: direct evidence → relationship expansion → structural patterns → temporal investigation → network influence → cross-source validation. Evidence panel shows WHY each entity is connected, the source document, confidence level, and 3 suggested next investigation leads. Connection mapper finds shortest paths between any two entities with relationship-level explanations on every edge. Routes: `GET /investigate/{id}`, `GET /connection-map`, `GET /node-evidence/{id}`.
73
 
74
- ### Phase 17 Security Hardening and Provenance Layer
75
- **Tag:** v0.17.0 | **Branch:** `feature/phase-17-security`
76
- **Summary:** Sliding window rate limiter — 100/min for search, 30/min for investigation, 10/min for export, 5/min for admin. IP addresses stored as SHA-256 hashes (first 16 hex chars) — never as plain text. HTTP security headers: CSP, HSTS, X-Frame-Options, X-Content-Type-Options, Referrer-Policy. Input validator detects uppercase-only Cypher injection patterns. Append-only SHA-256 hash-chained audit log at `logs/audit.jsonl`. Daily root hash anchored in a Neo4j `AuditRoot` node.
77
 
78
- ### Phase 18 Self-Learning System and Case Memory
79
- **Branch:** `feature/phase-18-self-learning`
80
- **Summary:** Schema learner detects new fields in scraper output and writes them to `pending_schema_additions.json` for human review — never auto-applies to production. Pattern learner runs weekly and discovers subgraph pattern candidates. Weight optimiser adjusts indicator weights by ±0.01 after every 3+ confirmed cases. Case memory persists investigation outcomes with reasoning paths for cross-case learning. Weekly GitHub Actions workflow.
81
 
82
- ### Phase 19 Affidavit Wealth Trajectory Engine
83
- **Tag:** v0.19.0 | **Branch:** `feature/phase-19-affidavit`
84
- **Summary:** Kalman filter constant-velocity model on 5-election asset time series. Innovation test: |z_k − H·x̂_k| > 3√S_k = anomaly. Expected growth model: initial assets + 8% FD returns + 60% salary savings. Residual ratio >2× = HIGH, >5× = VERY_HIGH unexplained wealth. Pre-election movable asset surge detection. Test result: VERY_HIGH level, ₹42.7 Cr residual (7.1×), 3 Kalman anomalies. 14th investigator (affidavit, weight 0.10). Route: `GET /affidavit/{entity_id}`.
85
 
86
- ### Phase 20 Biography Engine
87
- **Branch:** `feature/phase-20-biography`
88
- **Summary:** Chronological timeline compiled from ECI elections, GeM contracts, CAG audit mentions, NJDG court proceedings, PIB press releases, and MCA directorships. Events sorted by date, grouped by year, colour-coded by category. 5 temporal convergence window types: election+contract (90 days), election+company (180 days), audit+contract (365 days), court+company (180 days), election+audit (365 days). Neutral narrative generation with forbidden-word list and source disclaimers. Frontend: `frontend/js/timeline.js`.
89
 
90
- ### Phase 21 Benami Entity Detection
91
- **Branch:** `feature/phase-21-benami`
92
- **Summary:** 5-factor composite proxy score (0–100): director age anomaly (0.25), surname network clustering (0.25), address clustering (0.20), company formed before contract awarded (0.20), single-director structure (0.10). Thresholds: HIGH ≥ 65, MODERATE ≥ 40, LOW < 40. All 5 factors have fallback paths that return graceful results when the database is unavailable. 15th investigator (benami, weight 0.09). Route: `GET /benami/{entity_id}`.
93
 
94
- ### Phase 22 Procurement DNA, Cartel Detection, and Full Pipeline Expansion
95
- **Branch:** `feature/phase-22-procurement`
96
- **Summary:** TF-IDF cosine similarity ≥ 0.72 flags near-identical bid documents from different vendors. Cover-bid detection via price clustering (standard deviation test across vendor bids on same tender). Vendor cartel detection: award rotation pattern (equal share across vendors) and co-bidding network (same vendor pairs appearing repeatedly). Pipeline expanded to all 21 scrapers. `POST /admin/pipeline` triggers background ingestion. `GET /sources` returns record counts per dataset.
97
 
98
- ### Phase 23 Revolving Door and TBML Detection
99
- **Branch:** `feature/phase-23-conflict`
100
- **Summary:** Career transition detector: government-to-private moves within 365-day cooling-off window = flagged. Pre-employment benefit scoring: contracts awarded to a politician's future employer before their appointment. TBML indicators: contract price anomaly (2.5σ from entity mean), subcontract loop detection via Neo4j cycle queries, director changes within 90 days of contract award.
101
 
102
- ### Phase 24 Linguistic Fingerprinting
103
- **Branch:** `feature/phase-24-linguistic`
104
- **Summary:** Burrows Delta authorship attribution (Argamon's variant) using function-word frequency vectors. Template reuse detection across procurement documents via TF-IDF cosine similarity on structural elements. Ghost-writing detection by comparing speech patterns against known ministerial corpora. Route: `GET /linguistic/fingerprint/{entity_id}`.
105
 
106
- ### Phase 25 Policy-Benefit Causal Analysis
107
- **Branch:** `feature/phase-25-policy`
108
- **Summary:** Granger causality test (lag 1–6 months) between policy announcement events and company valuation changes. Transfer entropy for information-theoretic causality measurement. CACA (Confound-Adjusted Causal Attribution) scoring with cross-ministry benefit chain detection. Route: `GET /policy/causal/{entity_id}`.
109
 
110
- ### Phase 26 Adversarial Counterevidence
111
- **Branch:** `feature/phase-26-adversarial`
112
- **Summary:** Forced disproof methodology: the system actively searches for evidence contradicting its own findings before finalising a report. Competing hypothesis scorecard — each hypothesis is scored for and against. Uncertainty propagation: weak evidence reduces confidence of connected claims. Route: `GET /adversarial/{entity_id}`.
113
 
114
- ### Phase 27 Multi-Agent Debate Engine
115
- **Branch:** `feature/phase-27-debate`
116
- **Summary:** 7-agent structured 3-round debate. iMAD hesitation detection: agents that change position mid-debate signal contested evidence. Consensus scoring with explicit support / against / uncertain counts. Minority dissent findings are preserved in the final report — not suppressed. Route: `GET /debate/{entity_id}`.
117
 
118
- ### Phase 28 Dark Pattern Detection
119
- **Branch:** `feature/phase-28-dark-patterns`
120
- **Summary:** PrefixSpan sequential pattern mining on administrative event sequences. 6 pre-defined high-risk sequences including single-bidder→short-window→above-threshold and director-change→new-contract→same-buyer. Timing window significance test against baseline distribution. Route: `GET /darkpattern/{entity_id}`.
121
 
122
- ### Phase 29 UX Overhaul, Investigation Fixes, and Full i18n
123
- **Tag:** v0.29.0 | **Branch:** `feature/phase-29-ux-fixes`
124
- **Summary:** Fixed critical loading bug caused by 23 invalid `\`` and 13 invalid `\${` escape sequences injected by Python string replacement during Phase 16 development — these caused silent JS parse failure, leaving the page stuck on "Loading BharatGraph..." indefinitely. Service worker cache bumped to v3 to force invalidation of all stale cached files. Evidence panel rewritten with 4 tabs: Overview, Connections, Timeline, Investigate. Deep investigator rewritten with per-layer Neo4j sessions, confidence scoring, and richer Cypher queries. Connection mapper now returns WHY/source/next-leads on every graph edge. Seed data includes DIRECTOR_OF and WON_CONTRACT relationships. Language selector expanded to 22 Indian languages. `applyLanguage()` function rewrites the full DOM including nav links, filter buttons, headings, and search placeholder. `GET /ui-labels?lang=hi` endpoint added.
125
 
126
- ### Phase 30 Critical Bug Fix Sprint
127
- **Tag:** v0.30.0 | **Branch:** `fix/all-bugs-phase-30`
128
- **Summary:** Resolved 26 bugs covering: WebSocket deadlock (server now pushes heartbeat every 15s rather than waiting for client); health check now retries 5× with exponential backoff on HuggingFace cold start; investigation routes wrapped with try/except returning structured errors instead of raw 500s; export singleton no longer holds stale Neo4j driver; input validator no longer blocks legitimate searches containing words like "Union Bank" or "Call Centre"; audit logger hash stored per-process rather than a shared global that breaks multi-worker deployments; rate limiter has stale-window eviction to prevent memory leak; DeepInvestigator gives each of the 6 investigation layers its own Neo4j session; FindingItem description sanitized before innerHTML; profile.py duplicate fallback block removed; `ProfileResponse` Pydantic model now includes the `sources` field; service worker no longer caches API responses; fulltext index expanded from 8 to 16 node types; timeline builder audit events now pass `entity_name` not `entity_id` to the Cypher parameter.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
 
130
  ---
131
 
132
- ## PLANNED PHASES Ordered for Best Implementation Sequence
 
133
 
134
- The phases below are sequenced by dependency order: infrastructure and data quality first, then intelligence, then AI reasoning, then interfaces and operations.
 
 
135
 
136
  ---
137
 
138
- ### Phase 31 Runtime Profile and Auto-Scaling
139
- **Branch:** `feature/phase-31-runtime-profile` | **Priority:** CRITICAL — enables all subsequent phases
140
- **Issue:** `issues/031-runtime-profile.md`
141
 
142
- **Summary:** Make BharatGraph self-adapting to the hardware it runs on. At startup, detect CPU cores, RAM, GPU availability, free disk, Docker environment, and whether the database is local or remote. Assign one of three runtime profiles (low / medium / high) and apply corresponding settings for `max_workers`, `batch_size`, `graph_depth`, `investigation_layers`, `cache_ttl_seconds`, and `enable_gpu`. This means the same codebase runs well on a student laptop and scales up automatically on a government server — with zero manual configuration.
 
 
 
143
 
144
- **Files to create:** `config/runtime_profile.py`, `config/model_selector.py`, `api/routes/runtime.py`
145
- **Key algorithms:** Score-based profile assignment (cpu×2 + ram×2 + gpu×2 + disk + docker + db_location), preset dictionary lookup.
146
- **Auto-scales:** Profile decision is re-evaluated on each restart as hardware improves, the system picks a better profile automatically.
 
 
 
 
 
 
147
 
148
  ---
149
 
150
- ### Phase 32 Entity Resolution v2 Canonical Identity Engine
151
- **Branch:** `feature/phase-32-entity-resolution` | **Priority:** CRITICAL
152
- **Issue:** `issues/032-entity-resolution.md`
 
 
 
 
153
 
154
- **Summary:** The single most impactful bug in the current system is that the same real-world entity is stored under multiple Neo4j IDs across different scrapers, causing graph fragmentation where evidence chains break. This phase builds a canonical identity engine using multi-field string similarity (Jaro-Winkler + Jaccard token overlap + exact CIN/PAN match), embedding-based near-duplicate detection via sentence-transformers, and a deterministic canonical ID assignment protocol. Implements ordered entity-detector registry (inspired by Flowsint issue #45) so detector precedence can be controlled. Adds alias graphs that link every known variant of an entity name to a single canonical node without deleting source records.
 
155
 
156
- **Files to create:** `processing/entity_resolver_v2.py`, `processing/canonical_id.py`, `processing/alias_graph.py`
157
- **Impact:** Fixes broken evidence chains across all 16 node types. Every phase that reads from the graph becomes more reliable.
 
 
158
 
159
  ---
160
 
161
- ### Phase 33 Custom Graph Engine (Zero Neo4j Dependency)
162
- **Branch:** `feature/phase-33-graph-engine` | **Priority:** HIGH
163
- **Issue:** `issues/033-graph-engine.md`
 
 
164
 
165
- **Summary:** Eliminate the hard dependency on Neo4j AuraDB Free (which has a 50K node / 175K relationship limit) and replace it with a self-contained graph engine that can run locally, in Docker, or scale to millions of nodes. The engine stores the property graph as adjacency lists in memory with LevelDB/RocksDB persistence, implements HNSW-based approximate nearest neighbour search for semantic queries (M=16, ef_construction=200, ef_search=50), and provides a Cypher-compatible query layer so all existing routes continue to work without modification. Includes a Git-style version control system (GraphVersionControl) that writes a diff for every mutation — enabling replay, rollback, and anti-forensics detection. Temporal edge weight decay: confidence × e^(−λt) with per-source-type decay rates so stale evidence loses weight automatically.
 
 
 
 
 
166
 
167
- **Files to create:** `graph_engine/store.py`, `graph_engine/hnsw.py`, `graph_engine/query_planner.py`, `graph_engine/temporal.py`, `graph_engine/version_control.py`, `graph_engine/compat_layer.py`
168
- **Compatibility:** A `compat_layer.py` translates all existing Cypher calls to graph engine calls — no route changes required.
169
- **Migration:** `python -m graph_engine.migrate --from neo4j --to local` exports all nodes and edges from AuraDB and imports them into the local engine.
170
 
171
  ---
172
 
173
- ### Phase 34 Vector Search and Hybrid Retrieval
174
- **Branch:** `feature/phase-34-vector-search` | **Priority:** HIGH
175
- **Issue:** `issues/034-vector-search.md`
 
 
 
 
 
176
 
177
- **Summary:** Add semantic search alongside keyword search using FAISS or Qdrant for vector indexing. Compute sentence-transformer embeddings for all nodes and document fields during ingestion. Hybrid query execution: vector similarity + BM25 keyword ranking merged with Reciprocal Rank Fusion (RRF). This means a search for "contract irregularities Maharashtra" can find relevant audit reports even when those exact words do not appear. Implements the cost-based query planner from the graph engine: given a query, generate 5 candidate plans (graph-first, vector-first, hybrid, path-finding, fulltext), estimate execution cost for each, and execute the cheapest.
 
178
 
179
- **Files to create:** `graph_engine/vector_index.py`, `graph_engine/hybrid_search.py`, `graph_engine/query_planner.py`, `processing/embedder.py`
180
- **Models:** `sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2` (supports all 22 Indian languages).
181
 
182
  ---
183
 
184
- ### Phase 35 Plugin System and YAML-Defined Enrichers
185
- **Branch:** `feature/phase-35-plugins` | **Priority:** HIGH
186
- **Issue:** `issues/035-plugin-system.md`
187
 
188
- **Summary:** A lazy-loading plugin system (inspired by Flowsint PR #130) that lets anyone add new data sources, enrichers, or analysis modules without modifying core code. Plugins are Python packages discovered via entry-points at runtime. A YAML-based API enricher system (Flowsint issue #94) lets non-developers define new data source integrations by writing a YAML config with URL, authentication, field mappings, and rate limits — no code required. Plugins have an `EnricherABC` base class with auto-registration. Deferred Redis `connect()` avoids import-time failures.
 
189
 
190
- **Files to create:** `plugins/plugin_system.py`, `plugins/enricher_base.py`, `plugins/yaml_enricher.py`, `plugins/registry.py`
191
- **Auto-scales:** Every new data source added as a plugin is automatically discovered by the pipeline, included in `/sources`, and counted in `/stats`.
 
 
 
 
 
 
192
 
193
  ---
194
 
195
- ### Phase 36 — Sigma-Style Rule Engine
196
- **Branch:** `feature/phase-36-rule-engine` | **Priority:** HIGH
197
- **Issue:** `issues/036-rule-engine.md`
 
 
198
 
199
- **Summary:** A declarative YAML rule compiler and execution engine modelled on Sigma SIEM rules, adapted for graph-based investigation. Analysts define detection rules in YAML (entity types, relationship patterns, thresholds, evidence requirements) without writing any Python. The engine compiles rules to Cypher/graph queries and evaluates them against every new investigation. Ships with 5 built-in rules: cartel pattern detection, circular ownership, ghost company formation, revolving door violation, and politician-contractor proximity. New rules are added by dropping a YAML file into `rules/` — zero code changes.
 
 
 
 
200
 
201
- **Files to create:** `rules/rule_engine.py`, `rules/compiler.py`, `rules/built_in/cartel.yaml`, `rules/built_in/circular_ownership.yaml`, `rules/built_in/ghost_company.yaml`
 
202
 
203
  ---
204
 
205
- ### Phase 37 Job Queue and Priority Worker Pool
206
- **Branch:** `feature/phase-37-workers` | **Priority:** HIGH
207
- **Issue:** `issues/037-workers.md`
 
 
 
 
 
 
 
208
 
209
- **Summary:** Replace the current synchronous investigation pipeline with a priority job queue backed by Redis (or a lightweight in-memory queue when Redis is unavailable). Jobs have a full state machine: INIT → QUEUED → RUNNING → DONE → FAILED → DEAD_LETTER. Auto-scaler adjusts worker count based on CPU load — scales up under investigation bursts, scales down during quiet periods. Dead-letter queue holds jobs that failed 3+ times for manual review. Enables long-running investigations (multi-hop graph traversal, full 21-scraper pipeline) to run in the background without blocking the API.
 
210
 
211
- **Files to create:** `workers/job_queue.py`, `workers/worker_pool.py`, `workers/auto_scaler.py`, `workers/dead_letter.py`
 
212
 
213
  ---
214
 
215
- ### Phase 38 — DeepSeek-R1 Reasoning Integration
216
- **Branch:** `feature/phase-38-deepseek-r1` | **Priority:** HIGH
217
- **Issue:** `issues/038-deepseek-r1.md`
218
 
219
- **Summary:** Integrate DeepSeek-R1's chain-of-thought reasoning as the central synthesis engine for multi-investigator results. R1 takes the structured findings from all 15 investigators and produces a step-by-step reasoning chain that explicitly cites evidence from the graph. Anti-hallucination enforcement: R1 is constrained to reason only from verified graph evidence passed in the prompt context — it cannot invent facts. Competing hypothesis generation: R1 generates 3 competing explanations for the same evidence set and scores each. The model is accessed via the DeepSeek API (free tier available) so no GPU is required.
 
 
 
 
220
 
221
- **Files to create:** `ai/deepseek/r1_reasoner.py`, `ai/deepseek/chain_builder.py`, `ai/deepseek/anti_hallucination.py`
222
- **Integration:** Wraps `DeepInvestigator` and `MultiInvestigator` output through R1 before returning to the API.
 
 
223
 
224
  ---
225
 
226
- ### Phase 39 DeepSeek-VL2 Visual Evidence Analysis
227
- **Branch:** `feature/phase-39-deepseek-vl2` | **Priority:** MEDIUM
228
- **Issue:** `issues/039-deepseek-vl2.md`
 
229
 
230
- **Summary:** Use DeepSeek-VL2 (1B Tiny model, runs on CPU) for: (1) OCR on government document images (affidavits, audit report scans, court order photos), (2) visual inconsistency detection in submitted documents (signature mismatch, stamp placement anomalies), (3) data extraction from infographic charts in government reports. Implements DeepSeek-OCR pipeline for batch processing of PDF-attached images at ~2500 tokens/second. Cross-modal evidence linking: text findings linked to their visual source documents.
 
 
231
 
232
- **Files to create:** `ai/deepseek/vl2_processor.py`, `ai/deepseek/document_ocr.py`, `ai/forensics/visual_validator.py`
233
- **Route:** `POST /visual/analyze` accepts image URL or base64.
 
 
 
234
 
235
  ---
236
 
237
- ### Phase 40 — DeepSeek-V3 Report Generation
238
- **Branch:** `feature/phase-40-deepseek-v3` | **Priority:** HIGH
239
- **Issue:** `issues/040-deepseek-v3.md`
240
 
241
- **Summary:** Use DeepSeek-V3 to generate professional-grade investigation reports with structured sections: Executive Summary, Confirmed Evidence, Probable Indicators, Weak Signals, Risk Assessment, Timeline Reconstruction, and Legal-Safe Recommendations. Reports are generated in all 22 Indian languages using V3's multilingual capability — no separate translation step required. Report quality is graded: CONFIRMED (≥80%), PROBABLE (≥50%), WEAK (≥20%), INSUFFICIENT (<20%). All outputs are reviewed by `validate_language()` before being returned.
 
242
 
243
- **Files to create:** `ai/deepseek/v3_reporter.py`, `ai/deepseek/report_grader.py`
244
- **Integration:** Replaces and enhances `ai/dossier_generator.py`.
 
 
 
 
 
 
 
 
 
 
 
245
 
246
  ---
247
 
248
- ### Phase 41 Legal Intelligence Pipeline
249
- **Branch:** `feature/phase-41-legal-pipeline` | **Priority:** HIGH
250
- **Issue:** `issues/041-legal-pipeline.md`
 
 
251
 
252
- **Summary:** An end-to-end legal text analysis pipeline covering: IPC section classifier (maps incident descriptions to Indian Penal Code sections and punishment ranges), crime triple extractor (subject → action → object from FIR/charge sheet text), two-stage question-answering (ES retrieval + cosine similarity scoring), and multi-task predictor for charge framing suggestions. Integrates the CrimeKgAssitant open-source legal knowledge graph (GitHub: liuhuanyong/CrimeKgAssitant) and LawCrimeMining (GitHub: liuhuanyong/LawCrimeMining) datasets as reference corpora. OOV (out-of-vocabulary) repair using BK-tree approximate string matching. Minimum similarity thresholds: ES score ≥ 0.35, cosine ≥ 0.60.
 
 
 
 
 
 
253
 
254
- **Files to create:** `ai/legal/legal_pipeline.py`, `ai/legal/ipc_classifier.py`, `ai/legal/crime_triple_extractor.py`, `ai/legal/qa_engine.py`
 
 
 
255
 
256
  ---
257
 
258
- ### Phase 42 Forensic Content Intelligence
259
- **Branch:** `feature/phase-42-content-intelligence` | **Priority:** HIGH
260
- **Issue:** `issues/042-content-intelligence.md`
 
 
 
 
 
 
 
 
 
 
 
261
 
262
- **Summary:** Shannon entropy content classifier distinguishes genuine documents from fabricated ones. Chi-squared test on document structure distributions (paragraph lengths, punctuation frequencies) detects template reuse. Hash classifier against known-good and known-bad document signature databases. Perceptual hash (pHash) similarity for detecting watermarked or edited government documents. Full evidence extractor using regex patterns for PAN numbers, CIN identifiers, masked Aadhaar references, cryptocurrency wallet addresses, and Indian Rupee amounts — all extracted from raw text and linked to graph nodes automatically.
 
 
 
263
 
264
- **Files to create:** `ai/forensics/content_intelligence.py`, `ai/forensics/evidence_extractor.py`, `ai/forensics/hash_classifier.py`
265
 
266
  ---
267
 
268
- ### Phase 43 Pivot Recommendation Engine
269
- **Branch:** `feature/phase-43-pivot-engine` | **Priority:** HIGH
270
- **Issue:** `issues/043-pivot-engine.md`
271
 
272
- **Summary:** An AI-powered investigation pivot system that tells analysts their best next move. For any entity under investigation, compute a pivot score for every connected entity: PageRank × α + evidence_gap × β + log(risk_signals) × γ. The entity with the highest pivot score is the recommended next target. Inspired by OSINT investigation methodology where pivoting from one entity to a related one often unlocks a chain of evidence. Integrates with the job queue — high-priority pivots are automatically queued for background investigation.
 
 
273
 
274
- **Files to create:** `ai/pivot/recommendation_engine.py`, `ai/pivot/evidence_gap_scorer.py`
275
- **Route:** `GET /pivot/{entity_id}` returns ranked list of recommended next investigation targets.
 
 
 
 
 
 
276
 
277
  ---
278
 
279
- ### Phase 44 Geospatial Verification
280
- **Branch:** `feature/phase-44-geospatial` | **Priority:** MEDIUM
281
- **Issue:** `issues/044-geospatial.md`
 
 
282
 
283
- **Summary:** Sentinel-2 satellite imagery analysis for verifying that claimed government construction projects exist on the ground. NDVI change detection for forest diversion and mangrove destruction near infrastructure projects. Build-completion mismatch: compare claimed % completion in contract documents against observable construction progress from satellite. Contract location validation: extract GPS coordinates from contract documents and cross-reference with satellite evidence. Free Sentinel-2 data via Copernicus Open Access Hub API.
 
 
 
284
 
285
- **Files to create:** `ai/geospatial/sentinel_verifier.py`, `ai/geospatial/location_extractor.py`, `api/routes/geospatial.py`
286
- **Route:** `GET /geospatial/verify/{contract_id}`
 
 
 
 
 
 
287
 
288
  ---
289
 
290
- ### Phase 45 Provenance and Evidence Audit Layer
291
- **Branch:** `feature/phase-45-provenance` | **Priority:** HIGH
292
- **Issue:** `issues/045-provenance.md`
293
 
294
- **Summary:** Full deterministic provenance for every node, edge, and conclusion: source, timestamp, extraction method, transformation history, confidence level, and operator. Implements W3C PROV-DM model for evidence artifacts. Claim-evidence audit panel: which evidence supports vs. weakens each finding. Evidence states: CONFIRMED, PROBABLE, WEAK, REJECTED. Evidence chain export as JSON-LD using Schema.org ontology (inspired by Flowsint issue #132) — maps entities to `schema:Person`, `schema:Organization`, `schema:MoneyTransfer`, and BharatGraph-specific types. Graph mutations use enrichment IDs with input snapshots and output diffs, enabling full replay and rollback (Flowsint Graph Conductor pattern).
 
 
295
 
296
- **Files to create:** `ai/provenance_engine.py`, `ai/evidence_ranker.py`, `api/routes/provenance.py`
297
- **Routes:** `GET /export/evidence-chain/{entity_id}`, `GET /export/audit/{entity_id}`, `POST /revert/{enrichment_id}`
 
298
 
299
  ---
300
 
301
- ### Phase 46 Source Drift and Historical Analysis
302
- **Branch:** `feature/phase-46-historical` | **Priority:** HIGH
303
- **Issue:** `issues/046-historical.md`
304
 
305
- **Summary:** Detect when government records change, disappear, or are silently modified after publication. Compare current data against Wayback Machine snapshots using the CDX API. Track first-appearance dates for all claims — when a document appears that predates the entity's known history, flag it. Evidence status lifecycle: ACTIVE → MODIFIED → REMOVED → ARCHIVED. "When did this exist?" reconstruction for pages that have been taken down. Temporal edge timestamp analysis: edges that appeared and disappeared within short windows suggest data manipulation.
 
306
 
307
- **Files to create:** `ai/forensics/source_drift_detector.py`, `ai/forensics/wayback_verifier.py`, `api/routes/historical.py`
308
- **Route:** `GET /historical/{entity_id}`
 
 
 
 
 
309
 
310
  ---
311
 
312
- ### Phase 47 Predictive Risk and Lead Prioritisation
313
- **Branch:** `feature/phase-47-predict` | **Priority:** HIGH
314
- **Issue:** `issues/047-predict.md`
 
 
 
315
 
316
- **Summary:** ARIMA time series model for 6-month risk trajectory forecasting based on historical indicator trends. Random Forest ensemble trained on confirmed/unconfirmed investigation outcomes from case memory. Lead prioritisation ranking: entities are automatically sorted by: PageRank centrality × predicted risk trajectory × evidence gap × anomaly score. Analysts see the highest-value investigation targets first. Automatic "investigate next" queue populated from the ranking. Confidence intervals on all predictions.
 
 
317
 
318
- **Files to create:** `ai/forensics/risk_predictor.py`, `ai/lead_ranker.py`, `api/routes/predict.py`
319
- **Route:** `GET /predict/{entity_id}`
 
 
 
320
 
321
  ---
322
 
323
- ### Phase 48 Watchlist and Real-Time Alerts
324
- **Branch:** `feature/phase-48-watchlist` | **Priority:** MEDIUM
325
- **Issue:** `issues/048-watchlist.md`
326
 
327
- **Summary:** Persistent watchlist: analysts add entities to a watchlist and receive WebSocket push alerts when new data appears, risk scores change, new connections are formed, or audit flags appear. Diff-based alerting: "new DIRECTOR_OF relationship added to pol_003", "risk score for co_001 increased from 42 to 67". Email and webhook notification support via configurable channels. Alert rule engine: analysts define custom alert conditions in YAML without writing code. Inspired by Flowsint event timestamps issue #106 — every mutation now records when it happened so diffing is precise.
328
 
329
- **Files to create:** `api/routes/watchlist.py`, `ai/alert_engine.py`, `workers/alert_dispatcher.py`
330
- **Routes:** `POST /watchlist`, `GET /watchlist`, `GET /watchlist/alerts`, `DELETE /watchlist/{entity_id}`
 
 
 
 
 
 
 
 
 
 
 
 
 
331
 
332
  ---
333
 
334
- ### Phase 49 Observability and Pipeline Reliability
335
- **Branch:** `feature/phase-49-observability` | **Priority:** HIGH
336
- **Issue:** `issues/049-observability.md`
337
 
338
- **Summary:** Per-stage pipeline metrics: records per scraper per run, success/failure rates, latency, last-run timestamp. Prometheus-compatible `/metrics` endpoint. Stale-data detection: alert when any source has been silent for 30+ days. Ingestion validator: schema checks before any record enters the graph — malformed records are quarantined, not silently dropped. Partial-ingestion save: if the pipeline fails halfway, completed sources are preserved. Retry with exponential backoff on all scrapers. Grafana dashboard definition file included. CI/CD hardening: Bandit static analysis, Safety dependency scanner, Trivy container scanner, all blocking PR merges.
 
 
 
 
 
339
 
340
- **Files to create:** `api/middleware/metrics_collector.py`, `processing/ingestion_validator.py`, `monitoring/dashboard.py`, `deploy/ci.yml`
341
- **Routes:** `GET /admin/metrics`, `GET /admin/pipeline-health`
 
342
 
343
  ---
344
 
345
- ### Phase 50 Full 22-Language Output Engine
346
- **Branch:** `feature/phase-50-language` | **Priority:** HIGH
347
- **Issue:** `issues/050-language.md`
348
 
349
- **Summary:** Complete multilingual output for all 22 Indian scheduled languages on every API endpoint — not just the search route. Domain-specific vocabulary for government, legal, and financial terminology in each language. Language auto-detection from `Accept-Language` browser header with fallback to the query-detected language. RTL layout support for Urdu, Kashmiri, and Sindhi. All 15 UI label keys including nav, filters, buttons, and headings available in 10+ languages via `/ui-labels`. Transliteration lookup table expanded to cover all entity names in the graph across all 22 scripts.
 
350
 
351
- **Files to update:** `config/languages.py`, `ai/translator.py`, `frontend/js/app.js`
 
 
 
 
 
 
352
 
353
  ---
354
 
355
- ### Phase 51 Security Hardening v2 and PII Protection
356
- **Branch:** `feature/phase-51-security` | **Priority:** HIGH
357
- **Issue:** `issues/051-security.md`
358
 
359
- **Summary:** PII masking: automatic redaction of Aadhaar numbers, masked phone numbers, and personal financial details in all API output. Role-based access control (RBAC) with three roles: admin, analyst, viewer. Short-lived JWT access tokens (15-minute expiry) with refresh token rotation and revocation on sensitive events (Flowsint PR #135 pattern). DPDP Act 2023 compliance review. Defamation safeguard review — legal language enforcement audited. All injection attack surfaces hardened. Encryption at rest for the audit log. Penetration test script included.
 
 
360
 
361
- **Files to create:** `api/middleware/auth.py`, `api/middleware/pii_masker.py`, `api/routes/auth.py`
 
362
 
363
  ---
364
 
365
- ### Phase 52 Evidence Graph Frontend Upgrade
366
- **Branch:** `feature/phase-52-evidence-graph` | **Priority:** HIGH
367
- **Issue:** `issues/052-evidence-graph.md`
 
 
 
368
 
369
- **Summary:** New investigation UI flow: entity input → data collection progress bar (live WebSocket) → graph construction (nodes appear in real time as evidence is found) → evidence-ranked results. Clustering for large graphs (>50 nodes) using force-directed community layout. Level-of-detail rendering: distant nodes shown as circles, nearby nodes expanded to show properties. Evidence strength as edge thickness. Confidence as node opacity. Time slider for temporal graph view — watch the evidence graph build over time. Evidence status badges: CONFIRMED (green), PROBABLE (orange), WEAK (grey), REJECTED (red strikethrough). File upload support for importing external documents into an investigation (Flowsint issue #137 pattern).
 
 
 
 
 
370
 
371
  ---
372
 
373
- ### Phase 53 Confidence and Scoring Framework
374
- **Branch:** `feature/phase-53-confidence` | **Priority:** HIGH
375
- **Issue:** `issues/053-confidence.md`
 
 
 
 
 
 
 
 
 
 
376
 
377
- **Summary:** Unified confidence engine: every claim carries a 0–100 confidence score. Confidence decay: evidence older than 6 months loses 0.5% per week. Multi-source boost: the same finding confirmed by 3+ independent sources raises confidence by 15 points per additional source. Uncertainty propagation through graph paths: weak evidence reduces confidence of downstream claims. Evidence ranker: CONFIRMED ≥ 80, PROBABLE ≥ 50, WEAK ≥ 20, REJECTED < 20. All investigator weights become dynamic — adjusted by the confidence engine based on historical accuracy of each investigator type.
 
378
 
379
- **Files to create:** `ai/confidence_engine.py`, `ai/evidence_ranker.py`
 
 
 
380
 
381
  ---
382
 
383
- ### Phase 54 Investigation Workspace and Case Management
384
- **Branch:** `feature/phase-54-workspace` | **Priority:** MEDIUM
385
- **Issue:** `issues/054-workspace.md`
386
 
387
- **Summary:** Persistent investigation workspace: save and resume investigations. Export investigation as a shareable link with integrity hash. Bookmark entities for the watchlist. Step-by-step investigation wizard for first-time users. Investigation replay: see how conclusions were built step by step (powered by the provenance layer). Case templates: reusable investigation setups for common patterns (politician-contractor, circular ownership, electoral bond donor). Multi-user collaboration: multiple analysts can annotate the same investigation (government/organisation deployments). Undo enrichment with full revert history (Flowsint issue #109 pattern).
 
 
 
388
 
389
- **Routes:** `POST /workspace`, `GET /workspace/{id}`, `GET /workspace/{id}/share`, `POST /workspace/{id}/revert/{step}`
 
390
 
391
  ---
392
 
393
- ### Phase 55 Expanded Data Pipeline (367+ Sources)
394
- **Branch:** `feature/phase-55-data-expansion` | **Priority:** CRITICAL
395
- **Issue:** `issues/055-data-expansion.md`
 
 
 
 
396
 
397
- **Summary:** Expand from 21 to 367+ verified real Indian government data sources. Priority additions: all 28 High Courts, all 700+ district courts via NJDG, all state CAG reports (not just central), MCA company master bulk download (6M+ companies), AGMARKNET commodity prices, PARIVESH environment clearances, TRAI telecom orders, DGFT trade data, CCI antitrust orders, EPFO payroll data, all state e-Gazette publications, 29 Pollution Control Boards, 29 state forest department portals, all PSU annual reports. Each new scraper auto-registers with the plugin system — zero changes to core code. Dataset management module: SHA-256 verification, versioning, auto-download, and retry.
 
398
 
399
- **Files to create:** 30+ new scraper files, `data/dataset_manager.py`, updated `datasets/bharatgraph_sources.csv`
400
 
401
  ---
402
 
403
- ### Phase 56 — Production Launch
404
- **Branch:** `feature/phase-56-production` | **Priority:** PLANNED
405
- **Issue:** `issues/056-production.md`
 
 
 
 
 
 
 
 
 
 
 
406
 
407
- **Summary:** Full CI/CD pipeline with automated end-to-end tests on all 25+ API routes. Load testing at 100 concurrent users. Composite Neo4j indexes on all frequently-queried property combinations. Mobile-responsive layout across all views. Progressive Web App (PWA) manifest with offline capability via service worker. Full OpenAPI 3.0 documentation. Postman collection for all endpoints. Correction request workflow: any entity can submit a correction with documentary evidence — verified corrections processed within 14 days. Public launch announcement. Dedicated documentation site.
 
 
 
 
 
408
 
409
  ---
410
 
411
- ## Phase Execution Order Summary
 
 
 
 
 
 
 
 
 
 
 
 
412
 
413
- | Sequence | Phase | Reason for position |
414
- |----------|-------|---------------------|
415
- | 31 | Runtime Profile | Must precede all compute-intensive phases |
416
- | 32 | Entity Resolution v2 | Fixes data quality — all later analysis depends on it |
417
- | 33 | Custom Graph Engine | Infrastructure — decouples from Neo4j limits |
418
- | 34 | Vector Search | Requires graph engine + embeddings |
419
- | 35 | Plugin System | Required for data expansion phases |
420
- | 36 | Rule Engine | Requires stable graph + plugin system |
421
- | 37 | Job Queue | Required for async AI inference phases |
422
- | 38–40 | DeepSeek R1/VL2/V3 | Requires job queue for background processing |
423
- | 41–43 | Legal, Forensic, Pivot | Builds on AI reasoning from 38–40 |
424
- | 44 | Geospatial | Independent — can run in parallel |
425
- | 45–46 | Provenance, Historical | Requires stable entity resolution |
426
- | 47–48 | Predict, Watchlist | Requires provenance + temporal data |
427
- | 49 | Observability | Should precede data expansion |
428
- | 50–51 | Language, Security | Can run in parallel |
429
- | 52–53 | Frontend, Confidence | Requires all backend phases |
430
- | 54 | Workspace | Requires confidence + provenance |
431
- | 55 | Data Expansion | Requires plugin system |
432
- | 56 | Production Launch | All phases complete |
 
1
+ # BharatGraph -- Complete Phase Roadmap
2
 
3
+ All branches merge into `main`. Branch naming: `feature/phase-N-name` or `fix/description`.
4
  Each phase has a GitHub Issue (see `issues/` directory) and a PR description template.
5
 
6
  ---
7
 
8
+ ## COMPLETED PHASES (1-31)
9
 
10
+ ### Phase 1 -- Data Collection
11
+ **Tag:** pre-v1 | 6 scrapers, 3,199+ records, base scraper with rate limiting and retry
 
12
 
13
+ ### Phase 2 -- Data Processing
14
+ **Tag:** pre-v2 | Indian name normalisation, Jaccard entity resolution, parallel pipeline
 
15
 
16
+ ### Phase 3 -- Graph Database
17
+ **Tag:** pre-v3 | Neo4j schema, 7 node types, stable MD5 IDs, 8 Cypher templates
 
18
 
19
+ ### Phase 4 -- FastAPI Backend
20
+ **Tag:** v0.12.0 | FastAPI + Pydantic + Neo4j dependency injection, source citations
 
21
 
22
+ ### Phase 5 -- Risk Scoring Engine
23
+ 5-indicator composite score, validate_language() forbidden-word enforcement
 
24
 
25
+ ### Phase 6 -- Expanded Data Sources (13 scrapers)
26
+ ICIJ, Wikidata, OpenSanctions, Lok Sabha, SEBI, Electoral Bonds added
 
27
 
28
+ ### Phase 7 -- NLP Document Intelligence
29
+ spaCy NER, Benford Law chi-squared, multilingual BERT NER, shadow draft detector
 
30
 
31
+ ### Phase 8 -- Advanced Graph Analytics
32
+ NetworkX betweenness/PageRank/Louvain, circular ownership, ghost company scorer
 
33
 
34
+ ### Phase 9 -- Eight New Indian Sources (21 total)
35
+ NJDG, ED, CVC, NCRB, LGD, IBBI, NGO Darpan, CPPP added with fallback samples
 
36
 
37
+ ### Phase 10 -- Multi-Investigator AI Engine
38
+ **Tag:** v0.10.0 | 12 parallel investigators, SHA-256 report hash, synthesis engine
 
39
 
40
+ ### Phase 11 -- Multilingual Platform (22 Languages)
41
+ All 22 Indian scheduled languages, auto-detection, Helsinki-NLP translation
 
42
 
43
+ ### Phase 12 -- PDF Dossier Generator
44
+ Jinja2 + WeasyPrint, SHA-256 integrity hash, GET /export/pdf/{id}
 
45
 
46
+ ### Phase 13 -- Production Frontend
47
+ Vanilla JS/HTML/CSS, D3.js force graph, 5 views, works offline from file://
 
48
 
49
+ ### Phase 14 -- Zero Cold-Start Deployment
50
+ **Tag:** v0.14.0 | HuggingFace Spaces Docker, service worker cache, GitHub Pages CI/CD
 
51
 
52
+ ### Phase 15 -- Mathematical Intelligence Engine
53
+ **Tag:** v0.15.0 | Spectral Fiedler value, Fourier FFT, 13th investigator (math)
 
54
 
55
+ ### Phase 16 -- Evidence Connection Map and Deep Investigation
56
+ **Tag:** v0.16.0 | 6-layer recursive investigation, connection mapper, WHY explanations
 
57
 
58
+ ### Phase 17 -- Security Hardening and Provenance Layer
59
+ **Tag:** v0.17.0 | Rate limiter, CSP/HSTS headers, input validator, SHA-256 audit log
 
60
 
61
+ ### Phase 18 -- Self-Learning System and Case Memory
62
+ Schema learner, pattern learner, weight optimiser (+-0.01 per 3 confirmed cases)
 
63
 
64
+ ### Phase 19 -- Affidavit Wealth Trajectory Engine
65
+ **Tag:** v0.19.0 | Kalman filter, 5-election series, 14th investigator (affidavit)
 
66
 
67
+ ### Phase 20 -- Biography Engine
68
+ Chronological timeline, 5 temporal convergence window types, neutral narrative
 
69
 
70
+ ### Phase 21 -- Benami Entity Detection
71
+ 5-factor proxy score, thresholds HIGH>=65 MODERATE>=40, 15th investigator
 
72
 
73
+ ### Phase 22 -- Procurement DNA, Cartel Detection, Full Pipeline
74
+ TF-IDF cosine >=0.72, award rotation, co-bidding network, 21 scrapers
 
75
 
76
+ ### Phase 23 -- Revolving Door and TBML Detection
77
+ 365-day cooling-off, pre-employment benefit, 2.5-sigma TBML, subcontract loops
 
78
 
79
+ ### Phase 24 -- Linguistic Fingerprinting
80
+ Burrows Delta authorship, template reuse detection, ghost-writing detection
 
81
 
82
+ ### Phase 25 -- Policy-Benefit Causal Analysis
83
+ Granger causality (lags 1-6), transfer entropy, CACA cross-ministry chain
 
84
 
85
+ ### Phase 26 -- Adversarial Counterevidence
86
+ Forced disproof, competing hypotheses, uncertainty propagation
 
87
 
88
+ ### Phase 27 -- Multi-Agent Debate Engine
89
+ 7-agent 3-round debate, iMAD hesitation detection, minority dissent preserved
 
90
 
91
+ ### Phase 28 -- Dark Pattern Detection
92
+ PrefixSpan sequential mining, 6 pre-defined high-risk sequences
 
93
 
94
+ ### Phase 29 -- UX Overhaul and i18n
95
+ Evidence panel (4 tabs), D3 graph redesign, 22-language UI, timeline view
 
96
 
97
+ ### Phase 30 -- Bug Fix Sprint
98
+ **Tag:** v0.30.0 | 26 bugs resolved including BUG-1 (search crash), BUG-2 (7 missing loaders)
99
+
100
+ ### Phase 31 -- Runtime Profile and Auto-Scaling
101
+ **Tag:** v0.31.0 | Hardware detector, LOW/MEDIUM/HIGH profiles, GET /runtime endpoint
102
+ **Branch:** `feature/phase-31-runtime-profile`
103
+ **Files:** config/runtime_profile.py, config/model_selector.py, api/routes/runtime.py
104
+ **Tests:** 15 unit tests in tests/test_runtime_profile.py
105
+ **Profile assignment:** cpu*2 + ram*2 + gpu*2 + disk + docker + db_local (max 9)
106
+
107
+ ---
108
+
109
+ ## PLANNED PHASES
110
+
111
+ ---
112
+
113
+ ### Phase 32 -- Entity Resolution v2: Canonical Identity Engine
114
+ **Branch:** `feature/phase-32-entity-resolution`
115
+ **Priority:** CRITICAL -- fixes broken evidence chains across all phases
116
+
117
+ **Problem:** Jaccard token similarity misses transliteration variants, honorific
118
+ variations ("Sh. Ram Kumar" vs "Shri Ramkumar"), and cross-script name forms.
119
+ The same person stored under 3+ IDs = broken evidence chains.
120
+
121
+ **Algorithms:**
122
+ - Jaro-Winkler (weight 0.30) -- character-level typo and transliteration
123
+ - Jaccard token overlap (weight 0.20) -- word-order variations
124
+ - Sentence-transformers cosine (weight 0.35) -- multilingual name variants
125
+ - Exact PAN/CIN/GSTIN match (weight 1.0, overrides all) -- deterministic keys
126
+
127
+ **New files:**
128
+ - `processing/entity_resolver_v2.py` -- CanonicalIdentityEngine class
129
+ - `processing/canonical_id.py` -- stable SHA-256 ID generation functions
130
+ - `processing/alias_graph.py` -- AliasGraph: alias_name -> canonical_id lookup
131
+
132
+ **Indian name normalisation added:**
133
+ - Remove honorifics: Sh., Smt., Dr., Late, Sri, Shri, Er., Adv., Col.
134
+ - Normalise suffixes: Private Limited -> Pvt Ltd, LLP, Ltd
135
+ - Script-aware: Devanagari -> Latin transliteration for comparison
136
+
137
+ **Integration:** pipeline.py resolve_dataset() upgraded to use v2 engine
138
+
139
+ ---
140
+
141
+ ### Phase 33 -- Custom Graph Engine: Eliminate Neo4j 50K Limit
142
+ **Branch:** `feature/phase-33-custom-graph-engine`
143
+ **Priority:** HIGH -- AuraDB free tier caps at 50K nodes / 175K relationships
144
+
145
+ **Architecture:**
146
+ ```
147
+ graph_engine/
148
+ +-- store.py -- LevelDB key-value backing store
149
+ +-- hnsw.py -- HNSW vector index (M=16, ef=200)
150
+ +-- query_planner.py -- Cypher-to-native query translator
151
+ +-- temporal.py -- Time-weighted edge decay by relationship type
152
+ +-- version_control.py -- Git-style diff log for graph mutations
153
+ +-- compat_layer.py -- Translates all existing Cypher to native calls
154
+ ```
155
+
156
+ **Temporal edge decay lambdas:**
157
+ - court_order: 0.00005 (slowest -- court records are permanent)
158
+ - cag_audit: 0.0002
159
+ - government_portal: 0.0005
160
+ - director_of: 0.0003
161
+ - member_of: 0.0005
162
+ - news_article: 0.001
163
+ - social_media: 0.01 (fastest decay)
164
+
165
+ **Version control:** Every graph mutation is recorded as a diff with before/after
166
+ hashes. Detects when government portals silently modify records post-publication.
167
+ Anti-forensics pattern: commit A -> commit B (change) -> commit C (reverts to A) = flag
168
+
169
+ ---
170
+
171
+ ### Phase 34 -- Vector Search and Hybrid Retrieval
172
+ **Branch:** `feature/phase-34-vector-search`
173
+
174
+ **Problem:** Keyword search misses semantically similar documents. Searching
175
+ "Maharashtra road contract irregularity" does not find CAG reports about
176
+ "highway construction irregularity in Pune" even though they are the same topic.
177
+
178
+ **Algorithms:**
179
+ - FAISS (cpu) or Qdrant for vector index
180
+ - BM25 for keyword ranking
181
+ - Reciprocal Rank Fusion (k=60): RRF = sum(1 / (60 + rank))
182
+ - Query classifier routes to appropriate retrieval strategy
183
+
184
+ **Query routing:**
185
+ | Query type | Keywords | Retrieval mix |
186
+ |-----------|---------|--------------|
187
+ | factual | who is, what is, when did | BM25 70% + vector 30% |
188
+ | relational | connected to, path from | Graph 80% + vector 20% |
189
+ | temporal | before, after, election, contract date | Graph 60% + BM25 40% |
190
+ | exploratory | similar to, pattern, cluster | Vector 60% + community 40% |
191
+
192
+ **Embedding model:** paraphrase-multilingual-MiniLM-L12-v2 (covers all 22 languages)
193
+
194
+ ---
195
+
196
+ ### Phase 35 -- Plugin System and YAML Enrichers
197
+ **Branch:** `feature/phase-35-plugins`
198
+
199
+ **Lazy-loading plugin architecture** -- new data sources added by dropping
200
+ a YAML file in `enrichers/` with no code changes.
201
+
202
+ **Plugin registry also covers algorithms** -- new detection algorithms
203
+ registered as plugins, enabling Phase 57 A/B testing.
204
+
205
+ ---
206
+
207
+ ### Phase 36 -- Sigma-Style YAML Rule Engine
208
+ **Branch:** `feature/phase-36-rule-engine`
209
+
210
+ **Problem:** Adding a new detection rule requires writing Python + Cypher.
211
+ Non-developer investigators cannot contribute detection logic.
212
+
213
+ **YAML -> Cypher compiler** -- a rule file specifies conditions, thresholds,
214
+ and actions. The engine compiles it to Cypher at startup.
215
+
216
+ **10 built-in rules shipped:**
217
+ 1. `cartel_rotation.yaml` -- same vendor group rotates wins
218
+ 2. `electoral_bond_proximity.yaml` -- bond + contract within 12 months (CRITICAL)
219
+ 3. `family_directorship_web.yaml` -- politician's family = company director
220
+ 4. `audit_contract_overlap.yaml` -- continued contracts after CAG audit flag
221
+ 5. `shell_company_age_contract.yaml` -- company < 6 months old + large contract
222
+ 6. `single_bidder_high_value.yaml` -- single bid above district average
223
+ 7. `circular_ownership_3node.yaml` -- 3-node corporate ownership cycle
224
+ 8. `revolving_door_365day.yaml` -- government to private within 1 year
225
+ 9. `address_cluster_directors.yaml` -- 3+ companies same registered address
226
+ 10. `pre_election_contract_surge.yaml` -- contract spend spike 90 days before poll
227
+
228
+ ---
229
+
230
+ ### Phase 37 -- Job Queue and Worker Pool
231
+ **Branch:** `feature/phase-37-job-queue`
232
+
233
+ **Redis-backed job queue** with state machine: INIT -> QUEUED -> RUNNING -> DONE
234
+
235
+ **Algorithm job priorities:**
236
+ - Priority 1 (immediate): entity_resolution, neurosymbolic_risk, rule_engine
237
+ - Priority 2 (30s): gnn_tbml, election_burst, shap_explanation, graphrag_summary
238
+ - Priority 3 (5min): corruption_dna, metapath_walk, community_detection, topic_modeling
239
+ - Priority 4 (off-peak): fingerprint_index, gcpal_pretraining, wayback_drift
240
+
241
+ ---
242
+
243
+ ### Phase 38 -- DeepSeek-R1 Chain-of-Thought Reasoning
244
+ **Branch:** `feature/phase-38-deepseek-r1`
245
+
246
+ **Problem:** Current synthesis logic (3+ investigators agreeing = HIGH) is a
247
+ vote count, not reasoning. No audit trail of how a conclusion was reached.
248
+
249
+ **DeepSeek-R1 integration:**
250
+ - Receives: graph findings + SHAP explanations + TruthChain evidence IDs
251
+ - Generates: step-by-step reasoning chain citing specific evidence node IDs
252
+ - Produces: 2 competing hypotheses with scores, then a final verdict
253
+ - Verdict levels: CONFIRMED (>=80), PROBABLE (>=50), WEAK (>=20), INSUFFICIENT
254
+
255
+ **Anti-hallucination enforcement:**
256
+ - Every R1 claim must cite a TruthChain node_id (format: [EVIDENCE-XXXX])
257
+ - Post-generation validation: regex check for invented node IDs
258
+ - Invalid citations are stripped before the report is returned
259
+
260
+ **Fallback:** When DeepSeek API is unavailable, the existing multi-investigator
261
+ synthesis provides the output. R1 augments -- it does not replace.
262
+
263
+ ---
264
+
265
+ ### Phase 38B -- GraphRAG: Graph-Guided LLM Retrieval (NEW)
266
+ **Branch:** `feature/phase-38b-graphrag`
267
+
268
+ **Problem:** R1 cannot answer global questions like "What are the main corruption
269
+ themes across all 5,000 CAG audit reports?" Standard RAG retrieves isolated chunks.
270
+
271
+ **GraphRAG approach:**
272
+ 1. Run Leiden clustering over all scraped documents and graph nodes
273
+ 2. For each community > 3 nodes, R1 generates a community summary
274
+ 3. At query time: embed query -> retrieve top-k community summaries by cosine
275
+ 4. Feed summaries + relevant subgraph as structured context to R1
276
+
277
+ **New files:**
278
+ - `ai/graphrag/community_indexer.py` -- builds community summaries offline
279
+ - `ai/graphrag/graphrag_retriever.py` -- query-time retrieval
280
+
281
+ **Integration with Phase 38:** R1 receives GraphRAG community summaries instead
282
+ of raw graph fragments -- dramatically reduces hallucination.
283
+
284
+ ---
285
+
286
+ ### Phase 39 -- DeepSeek-VL2 Visual Evidence Analysis
287
+ **Branch:** `feature/phase-39-deepseek-vl2`
288
+
289
+ Analyse scanned affidavit PDFs, audit report images, and newspaper clippings.
290
+ Signature mismatch detection. Document image authenticity via Shannon entropy.
291
+ OCR pipeline for non-digital government documents.
292
+
293
+ ---
294
+
295
+ ### Phase 40 -- DeepSeek-V3 Multilingual Dossier Generation
296
+ **Branch:** `feature/phase-40-deepseek-v3`
297
+
298
+ Generate full investigation reports in all 22 Indian languages.
299
+ CONFIRMED/PROBABLE/WEAK/INSUFFICIENT grading on every finding.
300
+ Length: 800-1200 words per report. Export to PDF with trilingual header.
301
+
302
+ ---
303
+
304
+ ### Phase 41 -- Legal Intelligence Pipeline
305
+ **Branch:** `feature/phase-41-legal`
306
+
307
+ **IPC Section Classifier:**
308
+ - Algorithm: TF-IDF + OneVsRestClassifier(LogisticRegression) -- multi-label
309
+ - 8 corruption-relevant IPC sections: 420, 409, 13, 7, 120B, 467, 468, 471
310
+ - Keyword fallback when model not trained
311
+
312
+ **Crime triple extractor:**
313
+ - Pattern: Subject -> Action -> Object from legal text
314
+ - Store as directed evidence edges: (Company)-[:BRIBED]->(Official)
315
+
316
+ **Semantic Role Labelling (SRL):**
317
+ - ARG0 (agent) -> entity who acted
318
+ - ARG2 (recipient) -> entity who benefited
319
+ - V (predicate) -> action type: BRIBED, APPROVED, AWARDED
320
+
321
+ **BK-tree** for out-of-vocabulary legal term repair.
322
+
323
+ ---
324
+
325
+ ### Phase 42 -- Forensic Content Intelligence
326
+ **Branch:** `feature/phase-42-forensic-content`
327
+
328
+ **Shannon entropy classifier:**
329
+ | Document type | Expected range |
330
+ |--------------|----------------|
331
+ | government_order | 3.8 -- 5.2 bits |
332
+ | cag_report | 4.0 -- 5.4 bits |
333
+ | tender_document | 3.5 -- 5.0 bits |
334
+ | court_order | 3.9 -- 5.3 bits |
335
+
336
+ Documents outside expected range flagged as SUSPICIOUS or LIKELY_FABRICATED.
337
+
338
+ **Perceptual hash (pHash)** for image-based document copy detection.
339
+ **PAN/CIN/Aadhaar regex extraction** from document text.
340
+ **Lexical diversity score** -- repetitive templates have diversity < 0.3.
341
+
342
+ ---
343
+
344
+ ### Phase 43 -- Pivot Recommendation Engine
345
+ **Branch:** `feature/phase-43-pivot`
346
+
347
+ **Problem:** After finding a suspicious entity, the next best investigation
348
+ target is unclear. The pivot engine scores all connected entities.
349
+
350
+ **6-factor scoring:**
351
+ | Factor | Weight | Description |
352
+ |--------|--------|-------------|
353
+ | pagerank | 0.20 | How central is this entity? |
354
+ | evidence_gap | 0.25 | How much do we NOT know? |
355
+ | risk_signals | 0.20 | log(risk_signals + 1) |
356
+ | connection_strength | 0.15 | Edge weight to current entity |
357
+ | temporal_recency | 0.10 | Recently active? |
358
+ | unexplored_depth | 0.10 | Unexplored 2-hop nodes |
359
+
360
+ **Route:** `GET /pivot/{entity_id}?already_investigated=id1,id2`
361
+
362
+ ---
363
+
364
+ ### Phase 44 -- Geospatial Verification via Satellite
365
+ **Branch:** `feature/phase-44-satellite`
366
+
367
+ Sentinel-2 L2A time series for project verification.
368
+ NDVI change detection for forest diversion claims.
369
+ NDBI (built-up index) for construction completion verification.
370
+ SAR (Sentinel-1) for flood infrastructure claims.
371
+ Compare contract completion claims vs satellite-observable progress.
372
+
373
+ ---
374
+
375
+ ### Phase 45 -- W3C PROV-DM Provenance and TruthChain
376
+ **Branch:** `feature/phase-45-provenance`
377
+
378
+ **TruthChain algorithm:**
379
+ - Each evidence node has: SHA-256 ID, source_type, content_hash, timestamp, status
380
+ - Merkle tree over all evidence: root_hash changes if ANY evidence changes
381
+ - Temporal decay: weight(E,t) = base_weight * exp(-lambda_type * days)
382
+ - Status propagation: MODIFIED evidence propagates DEPENDS_ON_MODIFIED to descendants
383
+ - Aggregate confidence = active_weight / total_weight
384
+
385
+ **Decay rates by source:**
386
+ - court_order: 0.0001 (permanent)
387
+ - cag_audit: 0.0002
388
+ - government_portal: 0.0005
389
+ - news_article: 0.001
390
+ - social_media: 0.01
391
+
392
+ **Export:** JSON-LD using W3C PROV-DM ontology + Schema.org
393
+ **Blockchain anchor:** Merkle root stored in audit_chain.py (Bitcoin via OpenTimestamps)
394
+
395
+ ---
396
+
397
+ ### Phase 46 -- Source Drift and Historical Record Analysis
398
+ **Branch:** `feature/phase-46-source-drift`
399
+
400
+ **Wayback CDX API** to detect when government records are silently modified.
401
+ **7 fault types** (ISWC 2024 taxonomy):
402
+ - node_disappearance: entity removed from portal
403
+ - edge_rewiring: director change silently backdated
404
+ - attribute_drift: contract amount modified post-publication
405
+ - cluster_split: formerly linked entities disconnected
406
+ - cluster_merge: separate networks joined
407
+ - temporal_burst: sudden new relationship creation
408
+ - isolation: previously connected entity becomes isolated
409
+
410
+ **Anti-forensics detection:** commit A -> commit B (change) -> commit C (reverts) = SUPPRESS_ATTEMPT
411
+
412
+ ---
413
+
414
+ ### Phase 47 -- Predictive Risk Trajectory
415
+ **Branch:** `feature/phase-47-predictive`
416
+
417
+ **ARIMA(2,1,1) risk prediction:**
418
+ - Fits on monthly risk score history (min 12 data points)
419
+ - Forecasts 6 months ahead with 80% confidence intervals
420
+ - Alert when predicted score crosses HIGH threshold
421
+
422
+ **GCPAL contrastive pre-training for label scarcity:**
423
+ - India's 1:707 confirmed-corruption ratio makes traditional supervised ML difficult
424
+ - GCPAL mines supervised signals from the unlabelled relationship graph
425
+ - Three augmented views: node feature dropout + edge dropout + KNN view
426
+ - NT-Xent contrastive loss (temperature = 0.07)
427
+ - Fine-tunes on confirmed cases from case_memory (min 5 needed)
428
 
429
  ---
430
 
431
+ ### Phase 48 -- Watchlist, Alerts, and ARIMA Prediction
432
+ **Branch:** `feature/phase-48-watchlist`
433
 
434
+ WebSocket push alerts when risk score changes for watched entities.
435
+ YAML alert rules (same format as Phase 36).
436
+ Webhook support for journalist notification systems.
437
 
438
  ---
439
 
440
+ ### Phase 49 -- Observability and Reliability
441
+ **Branch:** `feature/phase-49-observability`
 
442
 
443
+ Prometheus /metrics endpoint.
444
+ Stale-data alerts when pipeline has not run in >7 days.
445
+ Ingestion validator checks all 20 node types have recent data.
446
+ /health upgraded to return per-source freshness status.
447
 
448
+ ---
449
+
450
+ ### Phase 50 -- Security v2: RBAC and JWT
451
+ **Branch:** `feature/phase-50-security-v2`
452
+
453
+ Role-based access control: Lead Investigator, Contributor, Reviewer, Observer.
454
+ JWT authentication with refresh tokens.
455
+ DPDP Act compliance (India Data Protection).
456
+ Entity-level access control for sensitive investigations.
457
 
458
  ---
459
 
460
+ ### Phase 51 -- Electoral Bond Causal Graph Engine
461
+ **Branch:** `feature/phase-51-electoral-bond-causal`
462
+
463
+ **Critical missing feature.** The data exists but the causal chain is not mapped.
464
+
465
+ **Full graph path:**
466
+ Corporate donor -> ElectoralBond -> Party -> Ministry -> Policy -> Contract -> Company
467
 
468
+ **Algorithm:** Granger causality (from Phase 25) + Difference-in-Differences
469
+ to establish whether policy changes statistically follow bond purchases.
470
 
471
+ **New node type:** PolicyChange (date, ministry, beneficiaries)
472
+ **New relationship:** FOLLOWED_BOND (lag_days, p_value, granger_f_stat)
473
+
474
+ **New route:** `GET /electoral-bond/causal/{company_id}`
475
 
476
  ---
477
 
478
+ ### Phase 52 -- Parliament Performance Analytics
479
+ **Branch:** `feature/phase-52-parliament`
480
+
481
+ **New data sources:** Lok Sabha division votes (loksabha.nic.in/Loksabha/Divisions),
482
+ Rajya Sabha Q&A archive, Praja.org legislator data.
483
 
484
+ **MP accountability score:**
485
+ - Attendance rate (0.30 weight)
486
+ - Questions asked per session (0.25 weight)
487
+ - Vote consistency with party line vs independent votes (0.20 weight)
488
+ - Bills sponsored (0.15 weight)
489
+ - Starred questions with substantive follow-up (0.10 weight)
490
 
491
+ **New route:** `GET /parliament/performance/{politician_id}`
492
+ **New node type:** DivisionVote, ParliamentSession
493
+ **New relationship:** VOTED_IN, ASKED_STARRED_QUESTION
494
 
495
  ---
496
 
497
+ ### Phase 53 -- Media Ownership Graph
498
+ **Branch:** `feature/phase-53-media-ownership`
499
+
500
+ **New data sources:** MIB media license registry, TRAI spectrum allocations.
501
+
502
+ **Graph paths:**
503
+ - Channel -> Corporate parent -> Promoter -> Political donor
504
+ - Channel -> Editorial stance correlation (NLP) -> Political entity
505
 
506
+ **Editorial bias detection:** NLP sentiment analysis comparing coverage of
507
+ political entities across channels with known ownership structures.
508
 
509
+ **New node types:** MediaChannel, SpectrumLicense, EditorialEntity
510
+ **New route:** `GET /media/ownership/{channel_id}`
511
 
512
  ---
513
 
514
+ ### Phase 54 -- Constituency Development Index
515
+ **Branch:** `feature/phase-54-constituency`
 
516
 
517
+ **Data sources:** NDAP district SDG scores, MGNREGS employment data,
518
+ PM Kisan disbursements, PM Awas completions, Swachh Bharat ODF data.
519
 
520
+ **Algorithm:** Regression analysis -- does the constituency improve during
521
+ the politician's tenure vs comparison period?
522
+
523
+ **Pre-election spending surge detection:** CUSUM on district spending in
524
+ 90 days before election vs annual baseline.
525
+
526
+ **New route:** `GET /constituency/{id}/development`
527
+ **Satellite verification:** Sentinel-2 images corroborate claimed completions.
528
 
529
  ---
530
 
531
+ ### Phase 55 -- Family Dynasty and Nepotism Graph
532
+ **Branch:** `feature/phase-55-dynasty`
533
+
534
+ **Data source:** FAMILY_OF edges extracted from MyNeta affidavit declarations
535
+ ("Spouse: X", "Dependent 1: Y"). Already partially available in existing data.
536
 
537
+ **Dynasty depth score:**
538
+ - Count of family members in government positions
539
+ - Count of family-controlled companies with government contracts
540
+ - Count of elections won by family members across generations
541
+ - Geographic concentration (same constituency or district)
542
 
543
+ **New relationship:** FAMILY_OF (role: spouse/child/sibling/parent)
544
+ **New route:** `GET /dynasty/{politician_id}`
545
 
546
  ---
547
 
548
+ ### Phase 56 -- RTI Intelligence Engine
549
+ **Branch:** `feature/phase-56-rti`
550
+
551
+ **RTI auto-filer:** System detects evidence gaps in any investigation and
552
+ drafts the exact RTI application to fill them.
553
+
554
+ **Gap detection algorithm:**
555
+ - For each HIGH-risk finding: check if primary source data is available
556
+ - If data missing: identify the correct Public Information Officer
557
+ - Generate RTI draft citing the specific provisions (RTI Act 2005, Sections 6-8)
558
 
559
+ **RTI outcome tracker:** Index filed RTI applications from RTI Online portal.
560
+ Map outcomes to graph: PIOs who deny information for high-risk entities = flag.
561
 
562
+ **New route:** `GET /rti/draft/{entity_id}` (generates RTI text)
563
+ **New node type:** RTIApplication, PublicInformationOfficer
564
 
565
  ---
566
 
567
+ ### Phase 57 -- A/B Algorithm Testing Framework (NEW)
568
+ **Branch:** `feature/phase-57-ab-testing`
 
569
 
570
+ **Multi-armed bandit (Thompson Sampling) for algorithm selection:**
571
+ - Each algorithm arm has Beta(alpha, beta) prior over performance
572
+ - alpha = times algorithm was "preferred" by human review
573
+ - beta = times algorithm was "not preferred"
574
+ - Select arm with highest sampled value at each request
575
 
576
+ **Use case:** When upgrading from static risk scorer -> ML ensemble ->
577
+ NeuroSymbolic, verify the new algorithm actually improves outcomes.
578
+
579
+ **New route:** `GET /admin/algorithm-performance`
580
 
581
  ---
582
 
583
+ ### Phase 58 -- Real-Time Stream Processing (NEW)
584
+ **Branch:** `feature/phase-58-streaming`
585
+
586
+ **Problem:** Pipeline runs in batches. Breaking leads appear hours late.
587
 
588
+ **Redis Streams** (Kafka fallback) for real-time event ingestion.
589
+ **CUSUM online anomaly detection** on the stream (no batch needed).
590
+ **Sliding window aggregation** for real-time indicator updates.
591
 
592
+ **Events processed in real-time:**
593
+ - new_contract: immediate CUSUM check on contract value
594
+ - new_audit_report: check if any tracked entities are mentioned
595
+ - new_enforcement_action: update risk scores for named entities
596
+ - source_modification: detect when a scraped page changes
597
 
598
  ---
599
 
600
+ ### Phase 59 -- CorruptionDNA Fingerprint (NEW)
601
+ **Branch:** `feature/phase-59-corruption-dna`
 
602
 
603
+ **Problem:** Two entities in the same corruption network may have no direct
604
+ graph edge -- different states, different directors, but identical patterns.
605
 
606
+ **512-dim fingerprint = concat(:**
607
+ - Node2Vec structural embedding (128d)
608
+ - TF-IDF document vector (128d)
609
+ - Benford's Law digit distribution (9d, padded to 16d)
610
+ - Temporal burst vector (64d)
611
+ - Linguistic fingerprint -- Burrows Delta (64d)
612
+ - Entity type one-hot (16d)
613
+ - Risk indicator vector (16d)
614
+ - CAG audit TF-IDF (64d)
615
+ - Institutional path vector (32d)
616
+
617
+ **MinHash LSH** for efficient similarity search (cosine > 0.82 = same network).
618
+ **New route:** `GET /dna/{entity_id}` and `GET /dna/similar/{entity_id}`
619
 
620
  ---
621
 
622
+ ### Phase 60 -- ElectionProximityBurst Detector (NEW)
623
+ **Branch:** `feature/phase-60-election-burst`
624
+
625
+ **The only corruption detection algorithm that encodes the Indian electoral
626
+ calendar as a statistical regression variable.**
627
 
628
+ **Algorithm:**
629
+ 1. Load full Indian electoral calendar (Lok Sabha + 28 state assemblies)
630
+ 2. ARIMA(2,1,1) on monthly metric aggregates
631
+ 3. PELT changepoint detection on ARIMA residuals
632
+ 4. Match changepoints to election proximity (within 180 days)
633
+ 5. CUSUM control chart with k=0.5, h=5.0
634
+ 6. Granger causality: does election_proximity_days Granger-cause the metric?
635
 
636
+ **Output:** burst_score (0-100), election_burst_flags, cusum_alerts,
637
+ Granger p-value, interpretation in plain language.
638
+
639
+ **Integrated as 16th investigator** (temporal, weight 0.10)
640
 
641
  ---
642
 
643
+ ### Phase 61 -- BennamiGNN: Heterogeneous Graph Neural Network (NEW)
644
+ **Branch:** `feature/phase-61-benami-gnn`
645
+
646
+ **Problem:** 5-factor heuristic misses multi-hop benami: politician's cousin
647
+ is director (not the politician), company has legitimate small contracts before
648
+ being used for a large fraudulent one.
649
+
650
+ **H-GNN architecture:**
651
+ - 8 relation types: DIRECTOR_OF, WON_CONTRACT, SHARES_ADDRESS, RELATED_TO,
652
+ AWARDED_BY, FAMILY_MEMBER_OF, APPEARS_IN_AUDIT, SANCTIONED_BY
653
+ - Layer 0: Per-type linear projection to d=64
654
+ - Layer 1: Relation-aware message passing
655
+ - Layer 2: Entity-type attention
656
+ - Layer 3: Classification head -> benami_score in [0,1]
657
 
658
+ **Fallback:** Always falls back to existing 5-factor heuristic when:
659
+ - PyTorch not installed
660
+ - Subgraph has < 5 nodes
661
+ - Model not trained yet
662
 
663
+ **Training:** Fine-tunes on confirmed benami cases from case_memory.
664
 
665
  ---
666
 
667
+ ### Phase 62 -- CartelDNA Sequential Mining (NEW)
668
+ **Branch:** `feature/phase-62-cartel-dna`
 
669
 
670
+ **Problem:** Current cartel detector checks single-tender award rotation.
671
+ Temporal cartels rotate wins across months and across ministries to avoid
672
+ statistical detection within any one ministry.
673
 
674
+ **CartelDNA = PrefixSpan + HITS + DBSCAN:**
675
+ 1. PrefixSpan on bid event sequences (company, category, month, rank)
676
+ 2. Detect alternating rank order patterns (length 2-6, min support 3)
677
+ 3. HITS on co-bidding network: authority = real winners, hub = fake competitors
678
+ 4. DBSCAN geographic clustering (epsilon = 50km, min_samples = 3)
679
+ 5. Cartel confidence = 0.35*pattern + 0.25*alternation + 0.20*geo + 0.20*HITS
680
+
681
+ **New route:** `GET /cartel/dna/{entity_id}`
682
 
683
  ---
684
 
685
+ ### Phase 63 -- SHAP and LIME Explainability Layer (NEW)
686
+ **Branch:** `feature/phase-63-explainability`
687
+
688
+ **Problem:** Every risk score has no explanation. Journalists cannot publish
689
+ "score: 67" without "why: politician_overlap drove +24 points."
690
 
691
+ **SHAP TreeExplainer** on the ML ensemble from Phase 19 upgrade:
692
+ - Feature contributions for each of the 5 indicators
693
+ - Counterfactual: "If contract_concentration were 0, score would be 43"
694
+ - Baseline score (expected value)
695
 
696
+ **LIME** locally linear approximation for non-tree models.
697
+
698
+ **New fields added to all risk responses:**
699
+ - shap_top_drivers: [{feature, shap_value, direction}]
700
+ - shap_counterfactual: plain-language minimum change to flip risk level
701
+ - shap_baseline: expected value before any features
702
+
703
+ **New route:** `GET /risk/explain/{entity_id}`
704
 
705
  ---
706
 
707
+ ### Phase 64 -- Cross-Language Entity Disambiguation (NEW)
708
+ **Branch:** `feature/phase-64-cross-lingual`
 
709
 
710
+ **Problem:** "Modi" / "modi" / "modii" appear in 22 scripts -- potentially
711
+ stored as separate graph nodes. Cross-lingual entity linker maps all variants
712
+ to a single canonical node using Wikidata Q-numbers.
713
 
714
+ **XLM-RoBERTa** zero-shot entity linking.
715
+ **Wikidata SPARQL** for canonical Q-number lookup (existing scraper extended).
716
+ **Transliteration confidence score** per script pair.
717
 
718
  ---
719
 
720
+ ### Phase 65 -- Knowledge Graph Completion (Missing Link Prediction) (NEW)
721
+ **Branch:** `feature/phase-65-kg-completion`
 
722
 
723
+ **TransE** link prediction: h + r = t in d-dimensional space.
724
+ Missing edge score: ||h + r - t|| (lower = more probable edge).
725
 
726
+ **Use cases:**
727
+ - (Politician, DIRECTOR_OF, ?) -- suggest companies likely controlled
728
+ - (?, RELATED_TO, KnownShellCompany) -- find hidden associates
729
+ - (Company, WON_CONTRACT, ?) -- predict future contract awards
730
+
731
+ **Output:** List of probable missing edges with confidence scores,
732
+ presented as "Suggested next investigation targets."
733
 
734
  ---
735
 
736
+ ### Phase 66 -- LAS-GNN Temporal TBML Detection (NEW)
737
+ **Branch:** `feature/phase-66-las-gnn`
738
+
739
+ **Problem:** Current TBML detector uses threshold rules. Temporal money
740
+ laundering (pre-election scatter-gather, below-threshold smurfing) is
741
+ invisible to structural analysis.
742
 
743
+ **LAS-GNN:** LSTM aggregator on directed transaction graphs.
744
+ Learns sequential order of edges imposed by timestamps.
745
+ Detects motifs: scatter-gather, fan-in/fan-out, layering, pre-election burst.
746
 
747
+ **Indian-specific motifs:**
748
+ - Pre-election scatter: funds split to many accounts < 6 months before election
749
+ - Post-contract layering: payment -> N shell companies -> reconsolidated
750
+ - Smurfing below threshold: many transactions < Rs 2 lakh (PMLA threshold)
751
+ - Circular director rotation: A appoints X -> X at B -> B pays A
752
 
753
  ---
754
 
755
+ ### Phase 67 -- NeuroSymbolic Risk Reasoning (NEW)
756
+ **Branch:** `feature/phase-67-neurosymbolic`
 
757
 
758
+ **Fuses three reasoning modes into one coherent system:**
759
 
760
+ Stage 1 -- DEDUCTIVE (Phase 36 YAML rules):
761
+ - Rules fire with certainty = 1.0 (logical certainty)
762
+ - CRITICAL rule match -> score forced >= 75
763
+
764
+ Stage 2 -- INDUCTIVE (Phase 19 ML ensemble + SHAP):
765
+ - GNN/ML soft score in [0,1]
766
+ - SHAP feature contributions
767
+
768
+ Stage 3 -- ABDUCTIVE (Phase 38 DeepSeek-R1):
769
+ - Chain-of-thought synthesis citing TruthChain evidence IDs
770
+ - 2 competing hypotheses with scores
771
+
772
+ Stage 4 -- Integration:
773
+ - final_score = 0.40*rule_certainty + 0.35*gnn_score + 0.25*r1_confidence
774
+ - Adversarial override: if adversarial engine finds contradicting evidence -> cap at PROBABLE
775
 
776
  ---
777
 
778
+ ### Phase 68 -- InstitutionMetapath2Vec Embeddings (NEW)
779
+ **Branch:** `feature/phase-68-metapath`
 
780
 
781
+ **5 Indian-specific metapaths** for structured random walks:
782
+ 1. politician_enrichment: Politician-DIRECTOR_OF-Company-WON_CONTRACT-Contract
783
+ 2. circular_enrichment: Politician-MEMBER_OF-Party-CONTROLS-Ministry-...-DIRECTOR_OF-Politician
784
+ 3. audit_flag_circular: Company-WON_CONTRACT-Contract-MENTIONED_IN-AuditReport-AUDITS-Ministry
785
+ 4. shell_address_cluster: Director-DIRECTOR_OF-Company-SHARES_ADDRESS-Company
786
+ 5. constituency_benefit: Politician-REPRESENTS-Constituency-LOCATED_IN-District-HAS_PROJECT-Contract
787
 
788
+ **128-dim entity embeddings** trained via Word2Vec skip-gram on guided walks.
789
+ **find_similar_by_metapath()** finds entities with the same institutional role
790
+ across different states -- invisible to structural graph analysis.
791
 
792
  ---
793
 
794
+ ### Phase 69 -- Geospatial Risk Clustering (NEW)
795
+ **Branch:** `feature/phase-69-geospatial`
 
796
 
797
+ **Moran's I** spatial autocorrelation on district-level risk scores.
798
+ I > 0 = spatial corruption hotspots cluster together.
799
 
800
+ **LISA** (Local Indicators of Spatial Association):
801
+ - High-High cluster: high-risk district surrounded by high-risk districts
802
+ - Low-High outlier: low-risk district in high-risk region (potential evasion)
803
+ - High-Low outlier: targeted corruption in otherwise clean district
804
+
805
+ **Output:** District-level choropleth with cluster classification.
806
+ **New route:** `GET /geospatial/risk-clusters`
807
 
808
  ---
809
 
810
+ ### Phase 70 -- Dynamic Knowledge Graph Anomaly Detection (NEW)
811
+ **Branch:** `feature/phase-70-dynamic-kg`
 
812
 
813
+ Continuously monitors graph for unexpected structural changes.
814
+ 7 fault types (ISWC 2024): node_disappearance, edge_rewiring,
815
+ attribute_drift, cluster_split, cluster_merge, temporal_burst, isolation.
816
 
817
+ **Contextual anomaly detection:** entity that was HIGH-risk 3 months ago
818
+ is now suddenly LOW-risk = possible evidence suppression.
819
 
820
  ---
821
 
822
+ ### Phase 71 -- GCPAL Contrastive Pre-Training (NEW)
823
+ **Branch:** `feature/phase-71-gcpal`
824
+
825
+ **Label scarcity problem:** India has very few confirmed corruption cases
826
+ relative to the total number of entities (estimated 1:707 ratio).
827
+ Standard supervised ML cannot train on this imbalance.
828
 
829
+ **GCPAL solution:** NT-Xent contrastive loss on 3 augmented views:
830
+ - View 1: node feature dropout (20%)
831
+ - View 2: edge dropout (20%)
832
+ - View 3: KNN implicit interactions (k=5)
833
+
834
+ Pre-trains on unlabelled graph. Fine-tunes on case_memory confirmed cases.
835
 
836
  ---
837
 
838
+ ### Phase 72 -- Automated Source Credibility Scoring (NEW)
839
+ **Branch:** `feature/phase-72-source-credibility`
840
+
841
+ Bayesian credibility model per source:
842
+ - institutional_authority: government > NGO > news > social
843
+ - historical_accuracy: confirmed vs denied past claims
844
+ - methodology_transparency: does source explain collection method?
845
+ - timeliness: freshness decay
846
+ - cross_source_corroboration: independent corroboration count
847
+
848
+ Bayesian update after each confirmed/denied case.
849
+
850
+ ---
851
 
852
+ ### Phase 73 -- Investigative RAG Over Case Memory (NEW)
853
+ **Branch:** `feature/phase-73-rag-cases`
854
 
855
+ **RAG over all past investigation reports** in case_memory.
856
+ Query: "Past investigations involving electoral bonds and road contracts"
857
+ -> Dense retrieval -> Top-k case summaries as context
858
+ -> DeepSeek-R1 synthesizes commonalities and suggests strategy.
859
 
860
  ---
861
 
862
+ ### Phase 74 -- Continuous Model Drift Detection (NEW)
863
+ **Branch:** `feature/phase-74-drift`
 
864
 
865
+ **Population Stability Index (PSI):**
866
+ - PSI < 0.10: stable
867
+ - PSI 0.10-0.25: monitor closely
868
+ - PSI > 0.25: retrain required
869
 
870
+ **ADWIN (Adaptive Windowing):** streaming concept drift detection.
871
+ Auto-triggers GCPAL retraining job when drift detected.
872
 
873
  ---
874
 
875
+ ### Phase 75 -- Ethics and Bias Audit System (NEW)
876
+ **Branch:** `feature/phase-75-ethics`
877
+
878
+ **Fairness metrics:**
879
+ - Demographic parity: P(HIGH_RISK | party=A) approx= P(HIGH_RISK | party=B)
880
+ - Equal opportunity: TPR equal across entity types
881
+ - Predictive parity: PPV equal across geographic regions
882
 
883
+ **Bias detection:** chi-squared test, disparate impact ratio, SHAP fairness.
884
+ **Mitigation:** Reweighing, adversarial debiasing, calibration.
885
 
886
+ **New route:** `GET /admin/bias-audit`
887
 
888
  ---
889
 
890
+ ## BRANCH WORKFLOW
891
+
892
+ ```bash
893
+ # Before each new phase:
894
+ git checkout main && git pull origin main
895
+ git checkout -b feature/phase-N-name
896
+
897
+ # After all commits:
898
+ git push origin feature/phase-N-name
899
+ # Open PR on GitHub -> merge -> pull main -> tag
900
+
901
+ # Tag every completed phase:
902
+ git tag -a vN.0.0 -m "Phase N: description"
903
+ git push origin vN.0.0
904
 
905
+ # Deploy to HuggingFace after every merge:
906
+ git push hf main --force
907
+
908
+ # Reseed after every deploy:
909
+ curl -X POST https://abinazebinoly-bharatgraph.hf.space/admin/seed
910
+ ```
911
 
912
  ---
913
 
914
+ ## VERSION HISTORY
915
+
916
+ | Version | Phase | Key addition |
917
+ |---------|-------|--------------|
918
+ | v0.30.0 | 30 | Bug fix sprint -- 26 bugs resolved |
919
+ | v0.31.0 | 31 | Runtime profile auto-scaling |
920
+ | v0.32.0 | 32 | Entity resolution v2 (planned) |
921
+ | v0.33.0 | 33 | Custom graph engine (planned) |
922
+ | v0.40.0 | 40 | DeepSeek-V3 multilingual reports (planned) |
923
+ | v0.50.0 | 50 | Security v2 RBAC (planned) |
924
+ | v1.0.0 | 75 | Full production launch (planned) |
925
+
926
+ ---
927
 
928
+ ## Developed by Abinaze Binoy