← Back to Case Studies
Nov 2026Director — Cloud & Infrastructure Architecture & Principal Agentic AI Architect

Edge-to-Pocket Sovereign AI: On-Device Mobile NPU Agent Runtime & Fail-Closed Shield Gateway

Sub-15ms on-device tool dispatch, 100% offline NPU inference capability, fail-closed Cedar/Shield policy mutations, and seamless Wear OS / Android Auto companion telemetry.

#Agentic AI#Edge AI#On-Device NPU#Kotlin Multiplatform#Zero-Trust#Mobile Architecture#case-study
🗺️ Inspect System Topology

“Sovereign AI cannot stop at the datacenter rack. If your pocket runtime requires a round-trip to a public cloud API to search your personal memory journal or dispatch a device action—or worse, if a remote gateway timeout defaults to an open mutation—you have neither sovereignty nor resilience. We built an on-device mobile NPU agent runtime paired with a fail-closed Shield Gateway.”

1. The Problem

Extending a sovereign datacenter control plane to mobile, wearable, and automotive edge surfaces exposed three architectural gaps in conventional cloud-tethered mobile AI apps:

  1. Cloud-Tethered Latency & Offline Fragility: Most mobile AI assistants are thin HTTP wrappers around remote cloud LLMs. When traversing dead cellular zones, hospital basements, or high-latency transit corridors, tool dispatch and personal memory retrieval fail completely.
  2. Unstructured Mobile Tool Invocation & Hallucinated Intents: Prompting a mobile LLM to generate raw Android intents or deep links without a deterministic local schema registry leads to malformed parameters, silent permission failures, and unverified background mutations.
  3. Permissive Gateway Failure Modes Across the WAN Boundary: When a mobile client dispatches an infrastructure mutation or fleet command back to the home datacenter (ai.virtualsach.in), standard retry middleware often treats partial JSON responses or policy-engine timeouts ambiguously—risking unauthorized state changes or out-of-order replay.

We needed an Edge-to-Pocket Sovereign AI Runtime—a Kotlin Multiplatform (KMP) and Jetpack Compose Material 3 mobile architecture executing quantized models directly on the mobile Neural Processing Unit (NPU), indexing an encrypted on-device Memory Journal, binding deterministic AppFunctions and a local Skill Registry, and communicating with the datacenter fleet exclusively through a Fail-Closed Shield Gateway.


2. The Constraints

  • 100% Offline On-Device NPU Execution & Thermal Safety: The mobile runtime had to download, verify (SHA-256), and execute quantized on-device SLMs (Q4_K_M / hardware-accelerated NPU delegates) locally with a built-in NPU Benchmark Suite that throttles context length if silicon thermal or battery thresholds degrade.
  • Deterministic AppFunctions & Skill Registry Binding: Every on-device tool call—whether querying the local SQLite/vector Memory Journal, scheduling an offline task, or projecting status to Wear OS and Android Auto—had to validate against a compiled schema registry in <15ms before execution.
  • Fail-Closed Shield Gateway Mutations: Every outbound mutation traversing the WAN to ai.virtualsach.in had to pass mTLS/Tailscale identity verification and deterministic Shield Policy evaluation; any network drop, schema mismatch, or policy uncertainty had to fail closed immediately with a typed rejection receipt.
  • Full Trajectory Replay & Auditability: Every multi-step reasoning turn (prompt, local RAG retrieval, NPU token latency, tool call, and Shield verdict) had to be persisted locally for deterministic Trajectory Replay and causal debugging.

3. Architecture & Key Decisions

We architected a split-horizon Pocket-to-Datacenter Sovereign Stack coupling an on-device Kotlin Multiplatform / Compose Material 3 runtime with our edge Shield Gateway:

flowchart TB
    subgraph Pocket["Tier 1: On-Device Mobile Silicon & Companion Surfaces (Kotlin / Compose M3)"]
        UI["Compose Material 3 Cockpit & Trajectory Replay<br/>+ Wear OS Tile & Android Auto Telemetry"]
        NPU["On-Device NPU Model Manager & Benchmark Engine<br/>(Quantized Local SLM · Thermal & Latency Guard)"]
        Journal["Encrypted Local Memory Journal<br/>(SQLite + On-Device Vector Embeddings & Hybrid RAG)"]
        Registry["Deterministic AppFunctions & Skill Registry<br/>(Typed Schema Validation · Sub-15ms Dispatch)"]
        UI --> NPU
        NPU <--> Journal
        NPU --> Registry
    end

    subgraph Shield["Tier 2: Fail-Closed Shield Security Boundary (ai.virtualsach.in)"]
        Gateway["Shield Edge Gateway<br/>(mTLS · Cryptographic Nonce · Replay Protection)"]
        Policy["Deterministic Shield Policy Engine<br/>(Read-Only Pass · Mutation Fail-Closed Gate)"]
        Gateway --> Policy
    end

    subgraph Fleet["Tier 3: Sovereign Datacenter Fleet (Proxmox VE & Talos K8s)"]
        Control["16-Node Sovereign Fleet & Arize Phoenix OTLP<br/>(Fleet Ops · Slot Telemetry · Vault State)"]
    end

    Registry -->|"Outbound Fleet Action (HTTPS / mTLS)"| Gateway
    Policy -->|"ALLOW (Verified Read / Approved Intent)"| Control
    Policy -.->|"DENY / Timeout -> Fail-Closed Receipt"| UI

Decision 1: On-Device Model Manager with Hardware NPU Benchmarking

Rather than hardcoding a single model binary, we built a lifecycle-aware On-Device Model Manager with an integrated NPU Benchmark Engine. Before promoting a downloaded quantized model shard into the active inference slot, the runtime executes a deterministic warmup and token-throughput benchmark across the device’s NPU/GPU accelerators, recording prefill time-to-first-token (TTFT), decode tokens/sec, and memory pressure. If thermal throttling is detected, the router seamlessly steps down to a smaller quantized profile or defers non-urgent background indexing.

Decision 2: Deterministic AppFunctions DB Scanner & Skill Registry

To prevent the on-device SLM from hallucinating tool arguments, we implemented an AppFunctions DB Scanner and Skill Registry that exposes strictly typed capability descriptors to the model’s grammar-constrained tool caller and enforces fail-closed mutation semantics:

// Fail-Closed Skill Dispatch & Shield Gateway Mutation Guard (Kotlin Multiplatform)
package in.virtualsach.shield.runtime

import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.serialization.Serializable

@Serializable
enum class MutationClass { READ_ONLY, LOCAL_STATE, FLEET_MUTATION }

@Serializable
data class ShieldVerdict(
    val allowed: Boolean,
    val policyId: String,
    val reason: String,
    val trajectorySpanId: String,
)

class FailClosedSkillDispatcher(
    private val localRegistry: SkillRegistry,
    private val shieldClient: ShieldGatewayClient,
    private val trajectoryStore: TrajectoryReplayStore,
) {
    suspend fun dispatch(skillId: String, payload: Map<String, String>): ShieldVerdict {
        val descriptor = localRegistry.resolve(skillId)
            ?: return failClosed(skillId, "UNREGISTERED_SKILL: '$skillId' absent from local AppFunctions DB.")

        if (!descriptor.validateSchema(payload)) {
            return failClosed(skillId, "SCHEMA_VIOLATION: Payload failed strict local parameter contract.")
        }

        if (descriptor.mutationClass == MutationClass.FLEET_MUTATION) {
            val remoteVerdict = withTimeoutOrNull(2_500L) {
                shieldClient.evaluateAndExecute(skillId, payload)
            }
            // Any timeout, transport error, or ambiguous response MUST fail closed
            if (remoteVerdict == null || !remoteVerdict.allowed) {
                return failClosed(
                    skillId,
                    remoteVerdict?.reason ?: "SHIELD_TIMEOUT_FAIL_CLOSED: Gateway unreachable within 2500ms.",
                )
            }
            trajectoryStore.record(skillId, payload, remoteVerdict)
            return remoteVerdict
        }

        val localResult = localRegistry.executeLocal(descriptor, payload)
        trajectoryStore.record(skillId, payload, localResult)
        return localResult
    }

    private fun failClosed(skillId: String, reason: String): ShieldVerdict =
        ShieldVerdict(allowed = false, policyId = "shield.fail-closed.v1", reason = reason, trajectorySpanId = skillId)
}

Decision 3: Local Memory Journal & Causal Trajectory Replay

We engineered an on-device Memory Journal backed by local SQLite storage and quantized vector embeddings, enabling sub-15ms semantic recall across personal engineering notes, voice transcripts, and fleet status snapshots with zero cloud egress. Every reasoning turn is captured in a structured Trajectory Replay ledger—allowing the operator to scrub step-by-step through past agent decisions on the phone or inspect companion summaries via Wear OS and Android Auto surfaces.


4. Failure Modes & What Went Wrong

Incident 1: Optimistic UI State Desync During Transient Cellular Dropouts

  • What Happened: In an early prototype of the remote fleet action trigger, the mobile UI optimistically rendered a mutation as "Queued / Applied" when the HTTPS request to ai.virtualsach.in timed out over a high-loss cellular handoff, assuming a background WorkManager job would eventually replay it.
  • Root Cause: Treating infrastructure control-plane mutations like social-media “like” buttons violates zero-trust semantics; a delayed background replay executing 20 minutes later can hit a mutated fleet state.
  • Architectural Fix: We stripped all optimistic mutation queueing for FLEET_MUTATION skills and enforced a strict 2,500ms synchronous Fail-Closed Shield Gate with single-use cryptographic nonces. If the Shield Gateway does not return an explicit signed ALLOW receipt within the window, the mutation is aborted and logged as SHIELD_TIMEOUT_FAIL_CLOSED.

Incident 2: Cold-Start NPU Context Thrashing on Background Memory Indexing

  • What Happened: Triggering bulk vector embedding generation for the Memory Journal simultaneously with an interactive voice/chat turn caused NPU delegate memory contention, spiking first-token latency from 190ms to 1,850ms.
  • Root Cause: Background ingestion and foreground interactive reasoning competed for the same unified mobile memory and NPU execution queue.
  • Architectural Fix: We added priority preemption inside the On-Device Model Manager: foreground interactive turns immediately preempt background Memory Journal indexing jobs, which resume only when the device is idle and thermal headroom is verified by the NPU Benchmark Engine.

5. Measurable Outcomes

Metric Cloud-Tethered Mobile AI Wrapper (Before) On-Device NPU & Shield Runtime (After) Impact
Local Tool & Memory Dispatch 420ms–1,200ms (WAN round-trip required) <15ms on-device (AppFunctions + SQLite RAG) 30x–80x faster local action & memory recall
Offline Operational Capability 0% (hard failure without Internet) 100% offline NPU inference & journal search Zero dependency on external cloud APIs
Ambiguous Remote Mutation Escapes Possible under retry/timeout jitter 0 escapes (100% fail-closed Shield contract) Deterministic zero-trust WAN boundary
Interactive NPU First-Token (TTFT) Contended during background indexing <210ms P95 (preemptive NPU scheduler) Smooth 60 FPS Compose M3 UX under load
Companion Surface Reach Phone screen only Phone + Wear OS + Android Auto telemetry Unified sovereign observability on the move

6. First-Principles Takeaway

Edge sovereignty means your intelligence lives on your silicon, and your perimeter fails closed.

An on-device NPU is not a novelty benchmark; it is a sovereignty boundary. By running quantized models, vector memory journals, and schema-checked tool registries directly on mobile silicon—and treating every WAN call to the home datacenter as an untrusted crossing through a fail-closed Shield Gateway—you achieve both instantaneous local intelligence and uncompromising infrastructure security.


Architecture and decisions: mine. Debugging sessions at odd hours: mine. AI assistance: structure, syntax, first draft. — Sachin

INTERACTIVE ARCHITECTURAL INTERROGATION

⚡ Challenge This Architecture Blueprint with Virtual Sachin (AI Digital Twin)

Open Full Twin Showreel ↗

Stress-test the architectural decisions, failure modes, and operational trade-offs behind Edge-to-Pocket Sovereign AI: On-Device Mobile NPU Agent Runtime & Fail-Closed Shield Gateway directly against the edge-native RAG Digital Twin:

⚡ Theme Adaptive Shift
Switching layouts matching domain reading affinity...