Implement rotation-clone presence engine (#1) + unit tests + CI tests
Build APK / build (push) Waiting to run

- detect/PresenceEngine.kt: identity-agnostic streaming detector for key-rotating clones (novel-churn gate, seamless-handover chain, co-movement gate, coherence). Full design in docs/detection-rotation-clone.md.
- Wired into ScanService as a parallel signal; CONFIRMED verdict raises a distinct rotating-tracker alert (softer tiers stay silent pending real-capture validation).
- PresenceEngineTest: synthetic clone (moving -> CONFIRMED), stationary clone (gated), single real tracker + far-ambient (CLEAR).
- CI now runs :app:testDebugUnitTest so the engine has behavioural verification, not just a compile check.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0187UiEtasyowhEBYs6s9iF5
This commit is contained in:
Kara Zajac
2026-07-15 00:35:37 -04:00
parent 0fa6a2dd2a
commit ad81964398
8 changed files with 292 additions and 10 deletions
@@ -0,0 +1,157 @@
package org.soulstone.vigil.detect
import org.soulstone.vigil.util.Geohash
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.roundToInt
import kotlin.math.sin
import kotlin.math.sqrt
/**
* The rotation-clone detector (problem #1) — the thing AirGuard and the platform
* detectors structurally cannot do. It ignores device identity and instead tracks
* whether ONE physical radio maintains an unbroken, close-range, co-moving RF
* *presence* even as its advertised identity churns thousands of times faster than
* any DULT-compliant tracker is allowed to (24h separated rotation).
*
* Streaming and pure-ish: feed separated-state sightings in time order via
* [onSighting]; it returns a [Verdict]. Session-scoped — call [reset] on start.
* Full design + rationale: docs/detection-rotation-clone.md.
*
* Key discriminator: the **seamless novel-handover chain** — a single radio whose
* id changes yields handovers into *novel* ids with no RSSI discontinuity and no
* time gap; a crowd of many radios yields gappy, RSSI-incoherent handovers. Novel
* churn is a *gate*, not just a score term: without it this is not a rotating
* clone and the (separate) identity detector owns the case.
*/
class PresenceEngine {
enum class Tier { CLEAR, WATCHING, PROBABLE, CONFIRMED }
data class Verdict(
val score: Int,
val tier: Tier,
val seamlessNovelHandovers: Int,
val distinctCells: Int,
val netMeters: Double,
val novelIds: Int
)
companion object {
const val R_CLOSE = -65 // dBm; the on-body/in-bag close band
const val G_BREAK_MS = 20_000L // gap that ends a presence run
const val G_SEAM_MS = 6_000L // handover must be near-immediate to be "seamless"
const val EPS_RSSI = 8.0 // dB; one radio's step-to-step RSSI
const val ALPHA = 0.3 // RSSI EWMA factor
const val NOVELTY_HORIZON_MS = 30 * 60_000L
const val D_NET_M = 500.0 // co-movement: net displacement
const val K_CELLS = 3 // co-movement: distinct geohash-7 cells
const val T_MIN_MIN = 10.0 // dwell for full duration credit
const val N_HANDOVER = 12 // seamless novel handovers for full credit / gate
const val RHO_NOVEL_PER_MIN = 0.7 // min sustained novel-seamless rate
}
private val seen = HashSet<String>()
private val seenOrder = ArrayDeque<Pair<String, Long>>()
private var novelCount = 0
private var active = false
private var startTs = 0L
private var lastTs = 0L
private var lastId: String? = null
private var ewmaRssi = 0.0
private var ewmaAbsResid = 0.0
private var seamlessNovel = 0
private val cells = HashSet<String>()
private var startLat = 0.0
private var startLon = 0.0
private var haveStart = false
private var netMeters = 0.0
@Synchronized
fun reset() {
seen.clear(); seenOrder.clear(); novelCount = 0; endRun()
}
@Synchronized
fun onSighting(id: String, rssi: Int, ts: Long, lat: Double?, lon: Double?): Verdict {
// Novelty bookkeeping over the horizon.
while (seenOrder.isNotEmpty() && ts - seenOrder.first().second > NOVELTY_HORIZON_MS) {
seen.remove(seenOrder.removeFirst().first)
}
val novel = id !in seen
if (novel) { seen.add(id); seenOrder.addLast(id to ts); novelCount++ }
// Only the close band builds a presence run.
if (rssi < R_CLOSE) return verdict()
if (!active || ts - lastTs > G_BREAK_MS) { startRun(id, rssi, ts, lat, lon); return verdict() }
val resid = rssi - ewmaRssi
if (id != lastId) {
if (abs(resid) <= EPS_RSSI && (ts - lastTs) <= G_SEAM_MS && novel) seamlessNovel++
}
ewmaRssi = ALPHA * rssi + (1 - ALPHA) * ewmaRssi
ewmaAbsResid = ALPHA * abs(resid) + (1 - ALPHA) * ewmaAbsResid
lastTs = ts; lastId = id
if (lat != null && lon != null) {
cells.add(Geohash.encode(lat, lon, 7))
if (haveStart) netMeters = haversineMeters(startLat, startLon, lat, lon)
}
return verdict()
}
private fun startRun(id: String, rssi: Int, ts: Long, lat: Double?, lon: Double?) {
active = true; startTs = ts; lastTs = ts; lastId = id
ewmaRssi = rssi.toDouble(); ewmaAbsResid = 0.0; seamlessNovel = 0
cells.clear(); netMeters = 0.0
if (lat != null && lon != null) {
startLat = lat; startLon = lon; haveStart = true; cells.add(Geohash.encode(lat, lon, 7))
} else haveStart = false
}
private fun endRun() {
active = false; lastId = null; seamlessNovel = 0; cells.clear(); netMeters = 0.0; haveStart = false
}
private fun verdict(): Verdict {
if (!active) return Verdict(0, Tier.CLEAR, 0, 0, 0.0, novelCount)
val durMin = (lastTs - startTs) / 60_000.0
// Novel-churn is a GATE: no impossible rotation rate => not a clone, the
// identity detector owns it.
val churnAnom = durMin > 0 && seamlessNovel >= N_HANDOVER &&
(seamlessNovel / durMin) >= RHO_NOVEL_PER_MIN
if (!churnAnom) return Verdict(0, Tier.CLEAR, seamlessNovel, cells.size, netMeters, novelCount)
val comoves = netMeters >= D_NET_M && cells.size >= K_CELLS
if (!comoves) {
// Impossible churn but co-movement not yet established (e.g. dense area) — soft only.
return Verdict(50, Tier.WATCHING, seamlessNovel, cells.size, netMeters, novelCount)
}
val coherent = ewmaAbsResid <= EPS_RSSI
var score = 0.0
score += (durMin / T_MIN_MIN).coerceIn(0.0, 1.0) * 30
score += (seamlessNovel.toDouble() / N_HANDOVER).coerceIn(0.0, 1.0) * 30
score += (cells.size.toDouble() / (2.0 * K_CELLS)).coerceIn(0.0, 1.0) * 20
score += (if (coherent) 1.0 else 0.4) * 20
val s = score.roundToInt()
val tier = when {
s >= 85 -> Tier.CONFIRMED
s >= 70 -> Tier.PROBABLE
s >= 40 -> Tier.WATCHING
else -> Tier.CLEAR
}
return Verdict(s, tier, seamlessNovel, cells.size, netMeters, novelCount)
}
}
private fun haversineMeters(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double {
val r = 6_371_000.0
val dLat = Math.toRadians(lat2 - lat1)
val dLon = Math.toRadians(lon2 - lon1)
val a = sin(dLat / 2) * sin(dLat / 2) +
cos(Math.toRadians(lat1)) * cos(Math.toRadians(lat2)) * sin(dLon / 2) * sin(dLon / 2)
return r * 2 * atan2(sqrt(a), sqrt(1 - a))
}
@@ -28,6 +28,8 @@ import org.soulstone.vigil.data.db.TrackerEntity
import org.soulstone.vigil.data.db.VigilDatabase
import org.soulstone.vigil.data.location.LocationProvider
import org.soulstone.vigil.data.settings.Settings
import org.soulstone.vigil.detect.PresenceEngine
import org.soulstone.vigil.model.SeparatedState
import org.soulstone.vigil.model.TrackerObservation
import org.soulstone.vigil.scan.BleTrackerScanner
@@ -46,6 +48,7 @@ class ScanService : LifecycleService() {
private const val CHANNEL_ID = "vigil_watch"
private const val NOTIFICATION_ID = 0x5161 // "VIGIL"
private const val PRUNE_INTERVAL_MS = 6 * 3_600_000L
private const val CLONE_COOLDOWN_MS = 2 * 3_600_000L
const val ACTION_START = "org.soulstone.vigil.action.START"
const val ACTION_STOP = "org.soulstone.vigil.action.STOP"
@@ -71,6 +74,8 @@ class ScanService : LifecycleService() {
private lateinit var repo: TrackerRepository
private lateinit var location: LocationProvider
private lateinit var scanner: BleTrackerScanner
private val presence = PresenceEngine()
private var lastCloneAlertMs = 0L
private var pruneJob: Job? = null
override fun onCreate() {
@@ -93,6 +98,7 @@ class ScanService : LifecycleService() {
private fun begin() {
if (_running.value) return
presence.reset()
startInForeground()
location.start() // best-effort; scanning still runs without a fix (just no co-movement)
if (!scanner.start()) {
@@ -110,8 +116,23 @@ class ScanService : LifecycleService() {
}
private fun onObservation(obs: TrackerObservation) {
val fix = location.location.value
// Rotation-clone presence engine (problem #1) — fed synchronously so its
// streaming state stays ordered. Only a CONFIRMED verdict raises a user
// alert; softer tiers stay silent until validated on real captures.
if (obs.separated == SeparatedState.SEPARATED) {
val v = presence.onSighting(obs.stableId, obs.rssi, obs.timestampMs, fix?.latitude, fix?.longitude)
if (v.tier == PresenceEngine.Tier.CONFIRMED &&
obs.timestampMs - lastCloneAlertMs > CLONE_COOLDOWN_MS
) {
lastCloneAlertMs = obs.timestampMs
raiseCloneAlert()
}
}
// Temporal co-movement (identity path) — persisted + evaluated off-thread.
lifecycleScope.launch {
val fix = location.location.value
val result = runCatching {
repo.record(obs, fix?.latitude, fix?.longitude, settings.sensitivity.value)
}.getOrNull() ?: return@launch
@@ -163,6 +184,17 @@ class ScanService : LifecycleService() {
Log.w(TAG, "ALERT: ${tracker.stableId} (${tracker.ecosystem})")
}
private fun raiseCloneAlert() {
val n = buildNotification(
title = "Possible hidden tracker",
text = "A rotating-ID tracker appears to be moving with you",
high = true
)
getSystemService(NotificationManager::class.java)?.notify(NOTIFICATION_ID + 1, n)
vibrate()
Log.w(TAG, "CLONE ALERT: rotating-id presence confirmed")
}
private fun vibrate() {
val v = currentVibrator() ?: return
val effect = VibrationEffect.createWaveform(longArrayOf(0, 250, 120, 250, 120, 400), -1)
@@ -0,0 +1,82 @@
package org.soulstone.vigil.detect
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Behavioural tests for the rotation-clone [PresenceEngine], driven by synthetic
* traces standing in for the record/replay harness (design doc §5). Trackers
* advertise every ~2 s; a rotating clone changes its advertised id every 30 s.
*/
class PresenceEngineTest {
private val stepMs = 2_000L
private val steps = 900 // 30 min at 2 s
private val cloneRotationMs = 30_000L // Find You default
private fun maxTier(
idAt: (Int) -> String,
rssiAt: (Int) -> Int,
latAt: (Int) -> Double?,
lonAt: (Int) -> Double?
): PresenceEngine.Tier {
val engine = PresenceEngine()
engine.reset()
var max = PresenceEngine.Tier.CLEAR
for (i in 0 until steps) {
val v = engine.onSighting(idAt(i), rssiAt(i), i * stepMs, latAt(i), lonAt(i))
if (v.tier.ordinal > max.ordinal) max = v.tier
}
return max
}
// A rotating clone that moves with the victim must be CONFIRMED.
@Test
fun cloneMovingIsConfirmed() {
val tier = maxTier(
idAt = { i -> "clone-${(i * stepMs) / cloneRotationMs}" }, // new id every 30 s
rssiAt = { i -> -55 + (i % 3 - 1) }, // close, coherent
latAt = { 40.0 },
lonAt = { i -> -74.0 + i * 0.00003 } // marches ~2.4 km
)
assertEquals(PresenceEngine.Tier.CONFIRMED, tier)
}
// Same rotating churn but stationary: co-movement gate must hold it below CONFIRMED.
@Test
fun cloneStationaryIsNotConfirmed() {
val tier = maxTier(
idAt = { i -> "clone-${(i * stepMs) / cloneRotationMs}" },
rssiAt = { i -> -55 + (i % 3 - 1) },
latAt = { 40.0 },
lonAt = { -74.0 } // fixed => no co-movement
)
assertTrue("stationary clone should not confirm, was $tier", tier.ordinal < PresenceEngine.Tier.CONFIRMED.ordinal)
}
// A single non-rotating tracker moving with you is NOT the presence engine's job
// (the identity detector owns it); the churn gate must keep this CLEAR.
@Test
fun singleRealTrackerIsClear() {
val tier = maxTier(
idAt = { "realtag" }, // one id, never rotates
rssiAt = { i -> -55 + (i % 3 - 1) },
latAt = { 40.0 },
lonAt = { i -> -74.0 + i * 0.00003 }
)
assertEquals(PresenceEngine.Tier.CLEAR, tier)
}
// Lots of novel ids but always far (out of the close band): no presence, CLEAR.
@Test
fun ambientFarIsClear() {
val tier = maxTier(
idAt = { i -> "ambient-$i" }, // novel every time
rssiAt = { -85 }, // below the close band
latAt = { i -> 40.0 + i * 0.00003 },
lonAt = { -74.0 }
)
assertEquals(PresenceEngine.Tier.CLEAR, tier)
}
}