packages) {
+ OPTED_OUT_REF.set(packages == null ? Collections.emptySet() : Set.copyOf(packages));
+ }
+
+ private final Binder binder = new Binder() {
+ @Override
+ protected boolean onTransact(int code, Parcel data, Parcel reply, int flags)
+ throws RemoteException {
+ if (code != TRANSACTION_SUMMARIZE) {
+ return super.onTransact(code, data, reply, flags);
+ }
+ data.enforceInterface(BRIDGE_DESCRIPTOR);
+ enforceVerifiedNasCaller();
+ final String requestJson = data.readString();
+ final NotificationSummaryClient client = CLIENT_REF.get();
+ final NotificationSummaryClient effective = client != null
+ ? client
+ : new NotificationSummaryClient(null);
+ try {
+ final String response = effective
+ .handleBridgeRequestJson(requestJson, OPTED_OUT_REF.get())
+ .toString();
+ reply.writeNoException();
+ reply.writeString(response);
+ return true;
+ } catch (JSONException failed) {
+ reply.writeNoException();
+ reply.writeString("{\"redacted\":true}");
+ return true;
+ }
+ }
+ };
+
+ @Override
+ public IBinder onBind(Intent intent) {
+ return binder;
+ }
+
+ private void enforceVerifiedNasCaller() {
+ final int callingUid = Binder.getCallingUid();
+ if (callingUid <= 0) {
+ throw new SecurityException("Invalid calling UID");
+ }
+ final PackageManager pm = getPackageManager();
+ if (pm == null) {
+ throw new SecurityException("PackageManager unavailable");
+ }
+ final String[] packages = pm.getPackagesForUid(callingUid);
+ if (packages == null || packages.length != 1 || !NAS_PACKAGE.equals(packages[0])) {
+ throw new SecurityException("Caller is not AlphaNotificationAssistant");
+ }
+ try {
+ final PackageInfo info = pm.getPackageInfo(NAS_PACKAGE, PackageManager.MATCH_SYSTEM_ONLY);
+ if (info == null || info.applicationInfo == null) {
+ throw new SecurityException("AlphaNotificationAssistant is not a system package");
+ }
+ final int flags = info.applicationInfo.flags;
+ final boolean isSystem = (flags
+ & (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
+ if (!isSystem || !info.applicationInfo.enabled) {
+ throw new SecurityException("AlphaNotificationAssistant is inactive");
+ }
+ if (pm.checkSignatures("android", NAS_PACKAGE) != PackageManager.SIGNATURE_MATCH) {
+ throw new SecurityException("AlphaNotificationAssistant is not platform-signed");
+ }
+ } catch (PackageManager.NameNotFoundException missing) {
+ throw new SecurityException("AlphaNotificationAssistant not installed", missing);
+ }
+ }
+}
diff --git a/apps/app/android/alpha-notifications/src/main/java/ai/alphacompute/notifications/NotificationPrivacyFilter.java b/apps/app/android/alpha-notifications/src/main/java/ai/alphacompute/notifications/NotificationPrivacyFilter.java
new file mode 100644
index 0000000000..4796964a71
--- /dev/null
+++ b/apps/app/android/alpha-notifications/src/main/java/ai/alphacompute/notifications/NotificationPrivacyFilter.java
@@ -0,0 +1,225 @@
+package ai.alphacompute.notifications;
+
+import java.util.Collections;
+import java.util.Locale;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+/**
+ * Fail-closed privacy classifier for incoming Android notifications.
+ *
+ * Guarantees that 2FA/OTP codes, password managers, authenticators, banking/payment alerts,
+ * lockscreen-private notifications, and owner-excluded packages are redacted before any local
+ * LLM inference, cloud fallback, or digest persistence.
+ */
+public final class NotificationPrivacyFilter {
+ /** Matches {@code android.app.Notification.VISIBILITY_SECRET}. */
+ public static final int VISIBILITY_SECRET = -1;
+
+ /** Matches {@code android.app.Notification.VISIBILITY_PRIVATE}. */
+ public static final int VISIBILITY_PRIVATE = 0;
+
+ /** Matches {@code android.app.Notification.VISIBILITY_PUBLIC}. */
+ public static final int VISIBILITY_PUBLIC = 1;
+
+ /** Privacy classification mirroring {@code spec/app/notifications/index.md}. */
+ public enum Sensitivity {
+ CLEAR,
+ OTP_CODE,
+ CREDENTIAL,
+ FINANCIAL,
+ LOCKSCREEN_PRIVATE,
+ OPTED_OUT
+ }
+
+ /** Normalized notification payload inspected by the privacy filter. */
+ public static final class NotificationInput {
+ public final String packageName;
+ public final String title;
+ public final String text;
+ public final String bigText;
+ public final String category;
+ public final int visibility;
+ public final boolean deviceLocked;
+ public final boolean userUnlocked;
+
+ public NotificationInput(
+ String packageName,
+ String title,
+ String text,
+ String bigText,
+ String category,
+ int visibility,
+ boolean deviceLocked,
+ boolean userUnlocked) {
+ this.packageName = packageName == null ? "" : packageName.trim();
+ this.title = title == null ? "" : title.trim();
+ this.text = text == null ? "" : text.trim();
+ this.bigText = bigText == null ? "" : bigText.trim();
+ this.category = category == null ? "" : category.trim();
+ this.visibility = visibility;
+ this.deviceLocked = deviceLocked;
+ this.userUnlocked = userUnlocked;
+ }
+ }
+
+ /** Immutable result of fail-closed privacy screening. */
+ public static final class FilterDecision {
+ public final boolean allowed;
+ public final Sensitivity sensitivity;
+ public final String reason;
+
+ public FilterDecision(boolean allowed, Sensitivity sensitivity, String reason) {
+ this.allowed = allowed;
+ this.sensitivity = sensitivity;
+ this.reason = reason;
+ }
+ }
+
+ private static final Set CREDENTIAL_PACKAGE_TOKENS = Set.of(
+ "1password", "onepassword", "bitwarden", "keepass", "proton.android.pass",
+ "dashlane", "lastpass", "enpass", "nordpass", "roboform", "keychain",
+ "authenticator", "authy", "duomobile", "yubico", "aegis", "2fas",
+ "freeotp", "ente.auth", "permissioncontroller", "packageinstaller",
+ "com.android.settings");
+
+ private static final Set FINANCIAL_PACKAGE_TOKENS = Set.of(
+ "wallet", "bank", "chase", "wellsfargo", "bofa", "bankofamerica",
+ "citibank", "citi.mobile", "amex", "americanexpress", "capitalone",
+ "paypal", "venmo", "cashapp", "squareup.cash", "coinbase", "robinhood",
+ "schwab", "fidelity", "vanguard", "stripe", "wise", "transferwise",
+ "revolut", "monzo", "chime", "zelle", "metamask", "phantom",
+ "ai.alphacompute.wallet");
+
+ private static final Pattern OTP_DIGITS_PATTERN = Pattern.compile(
+ "(?:^|[^0-9A-Za-z])(?:[A-Za-z]-)?\\d{4,8}(?:$|[^0-9A-Za-z])|"
+ + "(?:^|[^0-9])\\d{3}[-\\s]\\d{3}(?:$|[^0-9])");
+
+ private static final Pattern OTP_CONTEXT_PATTERN = Pattern.compile(
+ "(?i)\\b(otp|2fa|mfa|totp|one[-\\s]?time|passcode|verification\\s+code|"
+ + "security\\s+code|login\\s+code|sign[-\\s]?in\\s+code|auth(?:entication)?\\s+code|"
+ + "confirm(?:ation)?\\s+code|do\\s+not\\s+share\\s+this\\s+code|"
+ + "enter\\s+(?:this\\s+)?code|verify\\s+your\\s+(?:account|login|identity))\\b");
+
+ private static final Pattern CREDENTIAL_CONTENT_PATTERN = Pattern.compile(
+ "(?i)\\b(password\\s+reset|reset\\s+your\\s+password|temporary\\s+password|"
+ + "recovery\\s+(?:code|phrase|key)|seed\\s+phrase|private\\s+key|passkey|"
+ + "magic\\s+link|approve\\s+(?:this\\s+)?sign[-\\s]?in|login\\s+request|"
+ + "two[-\\s]?factor|credential\\s+manager)\\b");
+
+ private static final Pattern FINANCIAL_CONTENT_PATTERN = Pattern.compile(
+ "(?i)\\b(wire\\s+transfer|direct\\s+deposit|bank\\s+account|routing\\s+number|"
+ + "account\\s+balance|card\\s+ending\\s+in|credit\\s+card|debit\\s+card|"
+ + "cvv|pin\\s+number|ssn|social\\s+security|fraud\\s+alert|suspicious\\s+charge|"
+ + "payment\\s+(?:sent|received|declined|authorized)|withdrawal|ach\\s+transfer|"
+ + "transaction\\s+alert|charge\\s+of\\s+\\$?\\d)\\b");
+
+ private NotificationPrivacyFilter() {}
+
+ /** Evaluates whether {@code input} may be summarized, failing closed on any sensitive signal. */
+ public static FilterDecision evaluate(NotificationInput input) {
+ return evaluate(input, Collections.emptySet());
+ }
+
+ /** Evaluates whether {@code input} may be summarized given the owner's opted-out packages. */
+ public static FilterDecision evaluate(NotificationInput input, Set optedOutPackages) {
+ if (input == null || input.packageName.isEmpty()) {
+ return new FilterDecision(false, Sensitivity.LOCKSCREEN_PRIVATE, "missing_input");
+ }
+ if (!input.userUnlocked) {
+ return new FilterDecision(false, Sensitivity.LOCKSCREEN_PRIVATE, "user_locked");
+ }
+ if (input.visibility == VISIBILITY_SECRET) {
+ return new FilterDecision(false, Sensitivity.LOCKSCREEN_PRIVATE, "visibility_secret");
+ }
+ if (input.deviceLocked && input.visibility == VISIBILITY_PRIVATE) {
+ return new FilterDecision(false, Sensitivity.LOCKSCREEN_PRIVATE, "lockscreen_private");
+ }
+ if (optedOutPackages != null && optedOutPackages.contains(input.packageName)) {
+ return new FilterDecision(false, Sensitivity.OPTED_OUT, "package_opted_out");
+ }
+ final Sensitivity packageSensitivity = classifyPackage(input.packageName);
+ if (packageSensitivity != Sensitivity.CLEAR) {
+ return new FilterDecision(false, packageSensitivity, "sensitive_package");
+ }
+ final String combined = joinNonEmpty(input.title, input.text, input.bigText);
+ final Sensitivity textSensitivity = classifyText(combined);
+ if (textSensitivity != Sensitivity.CLEAR) {
+ return new FilterDecision(false, textSensitivity, "sensitive_content");
+ }
+ return new FilterDecision(true, Sensitivity.CLEAR, "clear");
+ }
+
+ /** Classifies sensitivity from package identity alone. */
+ public static Sensitivity classifyPackage(String packageName) {
+ if (packageName == null || packageName.trim().isEmpty()) {
+ return Sensitivity.LOCKSCREEN_PRIVATE;
+ }
+ final String lower = packageName.toLowerCase(Locale.ROOT);
+ if (containsAnyToken(lower, CREDENTIAL_PACKAGE_TOKENS)) {
+ return Sensitivity.CREDENTIAL;
+ }
+ if (containsAnyToken(lower, FINANCIAL_PACKAGE_TOKENS)) {
+ return Sensitivity.FINANCIAL;
+ }
+ return Sensitivity.CLEAR;
+ }
+
+ /** Classifies sensitivity from notification text or model output. */
+ public static Sensitivity classifyText(String text) {
+ if (text == null || text.trim().isEmpty()) {
+ return Sensitivity.CLEAR;
+ }
+ if (OTP_CONTEXT_PATTERN.matcher(text).find() && OTP_DIGITS_PATTERN.matcher(text).find()) {
+ return Sensitivity.OTP_CODE;
+ }
+ if (CREDENTIAL_CONTENT_PATTERN.matcher(text).find()) {
+ return Sensitivity.CREDENTIAL;
+ }
+ if (FINANCIAL_CONTENT_PATTERN.matcher(text).find()) {
+ return Sensitivity.FINANCIAL;
+ }
+ return Sensitivity.CLEAR;
+ }
+
+ /** Returns true when {@code text} contains OTP, credential, or financial indicators. */
+ public static boolean isSensitiveText(String text) {
+ return classifyText(text) != Sensitivity.CLEAR;
+ }
+
+ /** Returns true when {@code packageName} belongs to a protected credential or financial app. */
+ public static boolean isSensitivePackage(String packageName) {
+ return classifyPackage(packageName) != Sensitivity.CLEAR;
+ }
+
+ private static boolean containsAnyToken(String haystack, Set tokens) {
+ for (String token : tokens) {
+ if (haystack.contains(token)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static String joinNonEmpty(String a, String b, String c) {
+ final StringBuilder sb = new StringBuilder();
+ appendPiece(sb, a);
+ appendPiece(sb, b);
+ appendPiece(sb, c);
+ return sb.toString();
+ }
+
+ private static void appendPiece(StringBuilder sb, String piece) {
+ if (piece == null) {
+ return;
+ }
+ final String trimmed = piece.trim();
+ if (trimmed.isEmpty()) {
+ return;
+ }
+ if (sb.length() > 0) {
+ sb.append(' ');
+ }
+ sb.append(trimmed);
+ }
+}
diff --git a/apps/app/android/alpha-notifications/src/main/java/ai/alphacompute/notifications/NotificationSummaryClient.java b/apps/app/android/alpha-notifications/src/main/java/ai/alphacompute/notifications/NotificationSummaryClient.java
new file mode 100644
index 0000000000..a270d9671f
--- /dev/null
+++ b/apps/app/android/alpha-notifications/src/main/java/ai/alphacompute/notifications/NotificationSummaryClient.java
@@ -0,0 +1,365 @@
+package ai.alphacompute.notifications;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URL;
+import java.nio.charset.StandardCharsets;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * Local agent bridge client for {@code POST /api/alpha/notifications/summarize} with fail-closed
+ * privacy enforcement, loopback-only transport, strict latency timeout, and deterministic offline fallback.
+ */
+public final class NotificationSummaryClient {
+ /** Resident agent HTTP route for notification summarization and bundle classification. */
+ public static final String SUMMARIZE_PATH = "/api/alpha/notifications/summarize";
+
+ /** Resident agent HTTP route for reading and updating notification policy. */
+ public static final String POLICY_PATH = "/api/alpha/notifications/policy";
+
+ /** Resident agent HTTP route for checking router and digest status. */
+ public static final String STATUS_PATH = "/api/alpha/notifications/status";
+
+ /** Default per-request latency budget in milliseconds. */
+ public static final long DEFAULT_TIMEOUT_MS = 1_200L;
+
+ /** Maximum response payload accepted from the local agent. */
+ private static final int MAX_RESPONSE_BYTES = 32_768;
+
+ /** Pluggable HTTP/IPC transport to Alpha's resident agent. */
+ public interface AgentTransport {
+ /** Sends an HTTP/IPC request to the resident agent asynchronously. */
+ CompletableFuture send(String method, String path, byte[] body, long timeoutMs);
+ }
+
+ /** Raw status and UTF-8 body returned by {@link AgentTransport}. */
+ public static final class TransportResponse {
+ public final int statusCode;
+ public final byte[] body;
+
+ public TransportResponse(int statusCode, byte[] body) {
+ this.statusCode = statusCode;
+ this.body = body == null ? new byte[0] : body;
+ }
+ }
+
+ /** Outcome of a notification summarization request. */
+ public static final class SummaryResult {
+ public final boolean redacted;
+ public final NotificationPrivacyFilter.Sensitivity sensitivity;
+ public final NotificationThreadGrouper.BundleType bundleType;
+ public final String summary;
+ public final String source;
+ public final boolean fellBack;
+
+ public SummaryResult(
+ boolean redacted,
+ NotificationPrivacyFilter.Sensitivity sensitivity,
+ NotificationThreadGrouper.BundleType bundleType,
+ String summary,
+ String source,
+ boolean fellBack) {
+ this.redacted = redacted;
+ this.sensitivity = sensitivity;
+ this.bundleType = bundleType;
+ this.summary = summary;
+ this.source = source;
+ this.fellBack = fellBack;
+ }
+
+ /** Builds a fail-closed redacted decision. */
+ public static SummaryResult redacted(NotificationPrivacyFilter.Sensitivity sensitivity) {
+ return new SummaryResult(
+ true,
+ sensitivity,
+ NotificationThreadGrouper.BundleType.OTHER,
+ "",
+ "redacted",
+ false);
+ }
+
+ /** Serializes this result into the compact JSON payload returned over Binder IPC. */
+ public JSONObject toJson() throws JSONException {
+ return new JSONObject()
+ .put("redacted", redacted)
+ .put("sensitivity", sensitivity.name().toLowerCase(java.util.Locale.ROOT))
+ .put("bundleType", bundleType.adjustmentType())
+ .put("bundle", bundleType.wireName())
+ .put("summary", summary)
+ .put("source", source)
+ .put("fellBack", fellBack);
+ }
+ }
+
+ private final AgentTransport transport;
+ private final long timeoutMs;
+
+ public NotificationSummaryClient(AgentTransport transport) {
+ this(transport, DEFAULT_TIMEOUT_MS);
+ }
+
+ public NotificationSummaryClient(AgentTransport transport, long timeoutMs) {
+ this.transport = transport;
+ this.timeoutMs = Math.max(50L, timeoutMs);
+ }
+
+ /** Creates a loopback-only HTTP client targeting the local resident agent base URL. */
+ public static NotificationSummaryClient forLoopbackUrl(String baseUrl, long timeoutMs) {
+ if (!isLoopbackUrl(baseUrl)) {
+ throw new IllegalArgumentException("Notification summary client permits loopback URLs only");
+ }
+ final String normalized = baseUrl.replaceAll("/+$", "");
+ return new NotificationSummaryClient(new LoopbackHttpTransport(normalized), timeoutMs);
+ }
+
+ /** Verifies that {@code rawUrl} strictly resolves to a local loopback interface. */
+ public static boolean isLoopbackUrl(String rawUrl) {
+ if (rawUrl == null || rawUrl.trim().isEmpty()) {
+ return false;
+ }
+ try {
+ final URI uri = URI.create(rawUrl.trim());
+ final String scheme = uri.getScheme();
+ if (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme)) {
+ return false;
+ }
+ final String host = uri.getHost();
+ return "127.0.0.1".equals(host)
+ || "localhost".equalsIgnoreCase(host)
+ || "::1".equals(host)
+ || "[::1]".equals(host);
+ } catch (IllegalArgumentException invalid) {
+ return false;
+ }
+ }
+
+ /**
+ * Screens {@code input} fail-closed and summarizes {@code batch} via the resident agent,
+ * falling back deterministically on timeout, transport error, or rate limit.
+ */
+ public SummaryResult summarize(
+ NotificationPrivacyFilter.NotificationInput input,
+ NotificationThreadGrouper.ThreadBatch batch,
+ Set optedOutPackages) {
+ final NotificationPrivacyFilter.FilterDecision decision =
+ NotificationPrivacyFilter.evaluate(input, optedOutPackages);
+ if (!decision.allowed) {
+ return SummaryResult.redacted(decision.sensitivity);
+ }
+ if (batch == null) {
+ return new SummaryResult(
+ false,
+ NotificationPrivacyFilter.Sensitivity.CLEAR,
+ NotificationThreadGrouper.BundleType.OTHER,
+ "",
+ "deterministic",
+ true);
+ }
+ for (String line : batch.messages) {
+ final NotificationPrivacyFilter.Sensitivity msgSensitivity =
+ NotificationPrivacyFilter.classifyText(line);
+ if (msgSensitivity != NotificationPrivacyFilter.Sensitivity.CLEAR) {
+ return SummaryResult.redacted(msgSensitivity);
+ }
+ }
+
+ final String fallbackSummary = NotificationThreadGrouper.buildDeterministicSummary(batch);
+ if (transport == null || !batch.warrantsSummary || batch.rateLimited) {
+ return new SummaryResult(
+ false,
+ NotificationPrivacyFilter.Sensitivity.CLEAR,
+ batch.bundleType,
+ batch.warrantsSummary ? fallbackSummary : "",
+ "deterministic",
+ transport != null && batch.warrantsSummary);
+ }
+
+ try {
+ final JSONObject payload = new JSONObject();
+ payload.put("packageName", input.packageName);
+ payload.put("threadKey", batch.threadKey);
+ payload.put("title", batch.title);
+ payload.put("category", input.category);
+ payload.put("isConversation", batch.conversation);
+ payload.put("fallbackBundle", batch.bundleType.wireName());
+ payload.put("maxSummaryChars", NotificationThreadGrouper.MAX_SUMMARY_CHARS);
+ final JSONArray messagesJson = new JSONArray();
+ for (String msg : batch.messages) {
+ messagesJson.put(msg);
+ }
+ payload.put("messages", messagesJson);
+
+ final byte[] bodyBytes = payload.toString().getBytes(StandardCharsets.UTF_8);
+ final TransportResponse response = transport
+ .send("POST", SUMMARIZE_PATH, bodyBytes, timeoutMs)
+ .get(timeoutMs, TimeUnit.MILLISECONDS);
+ if (response == null || response.statusCode < 200 || response.statusCode >= 300) {
+ return deterministicFallback(batch, fallbackSummary);
+ }
+ final JSONObject decoded = new JSONObject(
+ new String(response.body, StandardCharsets.UTF_8));
+ if (decoded.optBoolean("redacted", false)) {
+ return SummaryResult.redacted(NotificationPrivacyFilter.Sensitivity.OPTED_OUT);
+ }
+ final String cleanSummary = NotificationThreadGrouper.sanitizeSummary(
+ decoded.optString("summary", ""));
+ if (cleanSummary.isEmpty() || NotificationPrivacyFilter.isSensitiveText(cleanSummary)) {
+ return deterministicFallback(batch, fallbackSummary);
+ }
+ final NotificationThreadGrouper.BundleType resolvedBundle = decoded.has("bundleType")
+ ? NotificationThreadGrouper.BundleType.fromAdjustmentType(
+ decoded.optInt("bundleType", batch.bundleType.adjustmentType()))
+ : decoded.has("bundle")
+ ? NotificationThreadGrouper.BundleType.fromWireName(
+ decoded.optString("bundle", batch.bundleType.wireName()))
+ : batch.bundleType;
+ final String source = decoded.optString("source", "local");
+ return new SummaryResult(
+ false,
+ NotificationPrivacyFilter.Sensitivity.CLEAR,
+ resolvedBundle,
+ cleanSummary,
+ source.isEmpty() ? "local" : source,
+ false);
+ } catch (TimeoutException | InterruptedException | ExecutionException | JSONException | RuntimeException failed) {
+ if (failed instanceof InterruptedException) {
+ Thread.currentThread().interrupt();
+ }
+ return deterministicFallback(batch, fallbackSummary);
+ }
+ }
+
+ /**
+ * Handles a raw Binder JSON request originating from {@code AlphaNotificationAssistantService}.
+ */
+ public JSONObject handleBridgeRequestJson(String requestJson, Set optedOutPackages) throws JSONException {
+ if (requestJson == null || requestJson.trim().isEmpty()) {
+ return SummaryResult.redacted(NotificationPrivacyFilter.Sensitivity.LOCKSCREEN_PRIVATE).toJson();
+ }
+ final JSONObject req = new JSONObject(requestJson);
+ final String packageName = req.optString("packageName", "");
+ final String title = req.optString("title", "");
+ final boolean isConversation = req.optBoolean("isConversation", false);
+ final int fallbackType = req.optInt("fallbackBundleType", 0);
+ final JSONArray rawMessages = req.optJSONArray("messages");
+ final List messages = new java.util.ArrayList<>();
+ final StringBuilder joined = new StringBuilder();
+ if (rawMessages != null) {
+ for (int i = 0; i < rawMessages.length(); i++) {
+ final String item = rawMessages.optString(i, "").trim();
+ if (!item.isEmpty()) {
+ messages.add(item);
+ if (joined.length() > 0) {
+ joined.append(' ');
+ }
+ joined.append(item);
+ }
+ }
+ }
+ final NotificationPrivacyFilter.NotificationInput input =
+ new NotificationPrivacyFilter.NotificationInput(
+ packageName,
+ title,
+ joined.toString(),
+ "",
+ isConversation ? "msg" : "",
+ NotificationPrivacyFilter.VISIBILITY_PUBLIC,
+ false,
+ true);
+ final NotificationThreadGrouper.ThreadBatch batch =
+ new NotificationThreadGrouper.ThreadBatch(
+ NotificationThreadGrouper.buildThreadKey(packageName, title, null),
+ packageName,
+ title,
+ NotificationThreadGrouper.BundleType.fromAdjustmentType(fallbackType),
+ isConversation,
+ messages,
+ false,
+ false,
+ !messages.isEmpty());
+ return summarize(input, batch, optedOutPackages == null ? Collections.emptySet() : optedOutPackages).toJson();
+ }
+
+ private static SummaryResult deterministicFallback(
+ NotificationThreadGrouper.ThreadBatch batch, String fallbackSummary) {
+ return new SummaryResult(
+ false,
+ NotificationPrivacyFilter.Sensitivity.CLEAR,
+ batch.bundleType,
+ fallbackSummary,
+ "deterministic",
+ true);
+ }
+
+ private static final class LoopbackHttpTransport implements AgentTransport {
+ private final String baseUrl;
+
+ LoopbackHttpTransport(String baseUrl) {
+ this.baseUrl = baseUrl;
+ }
+
+ @Override
+ public CompletableFuture send(
+ String method, String path, byte[] body, long timeoutMs) {
+ return CompletableFuture.supplyAsync(() -> {
+ HttpURLConnection conn = null;
+ try {
+ final URL url = URI.create(baseUrl + path).toURL();
+ conn = (HttpURLConnection) url.openConnection();
+ final int timeout = (int) Math.min(Integer.MAX_VALUE, Math.max(50L, timeoutMs));
+ conn.setConnectTimeout(timeout);
+ conn.setReadTimeout(timeout);
+ conn.setRequestMethod(method);
+ conn.setRequestProperty("Accept", "application/json");
+ if (body != null && body.length > 0) {
+ conn.setDoOutput(true);
+ conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
+ try (OutputStream out = conn.getOutputStream()) {
+ out.write(body);
+ }
+ }
+ final int code = conn.getResponseCode();
+ final InputStream stream = code >= 200 && code < 400
+ ? conn.getInputStream()
+ : conn.getErrorStream();
+ if (stream == null) {
+ return new TransportResponse(code, new byte[0]);
+ }
+ try (InputStream in = stream;
+ ByteArrayOutputStream buffer = new ByteArrayOutputStream()) {
+ final byte[] chunk = new byte[4096];
+ int read;
+ int total = 0;
+ while ((read = in.read(chunk)) >= 0) {
+ total += read;
+ if (total > MAX_RESPONSE_BYTES) {
+ return new TransportResponse(502, new byte[0]);
+ }
+ buffer.write(chunk, 0, read);
+ }
+ return new TransportResponse(code, buffer.toByteArray());
+ }
+ } catch (IOException failed) {
+ return new TransportResponse(503, new byte[0]);
+ } finally {
+ if (conn != null) {
+ conn.disconnect();
+ }
+ }
+ });
+ }
+ }
+}
diff --git a/apps/app/android/alpha-notifications/src/main/java/ai/alphacompute/notifications/NotificationThreadGrouper.java b/apps/app/android/alpha-notifications/src/main/java/ai/alphacompute/notifications/NotificationThreadGrouper.java
new file mode 100644
index 0000000000..a87500d048
--- /dev/null
+++ b/apps/app/android/alpha-notifications/src/main/java/ai/alphacompute/notifications/NotificationThreadGrouper.java
@@ -0,0 +1,396 @@
+package ai.alphacompute.notifications;
+
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+/**
+ * Pure-Java conversation batcher, deduplicator, rate limiter, Android 17 bundle classifier,
+ * and deterministic single-line summary builder.
+ */
+public final class NotificationThreadGrouper {
+ /** Maximum characters permitted in a single-line notification summary. */
+ public static final int MAX_SUMMARY_CHARS = 140;
+
+ /** Default cap on tracked conversation threads in bounded memory. */
+ public static final int DEFAULT_MAX_THREADS = 64;
+
+ /** Default cap on retained messages per thread. */
+ public static final int DEFAULT_MAX_MESSAGES_PER_THREAD = 6;
+
+ /** Default minimum interval in milliseconds between LLM inference dispatches per thread. */
+ public static final long DEFAULT_RATE_LIMIT_MS = 3_000L;
+
+ /** Minimum body length before a single notification warrants summarization. */
+ public static final int MIN_SUMMARIZE_CHARS = 48;
+
+ /**
+ * Bundle categories matching Android 17 {@code android.service.notification.Adjustment.TYPE_*}
+ * integer constants.
+ */
+ public enum BundleType {
+ OTHER(0, "other"),
+ PROMOTION(1, "promotions"),
+ NEWS(2, "news"),
+ SOCIAL_MEDIA(3, "social"),
+ CONTENT_RECOMMENDATION(4, "recs");
+
+ private final int adjustmentType;
+ private final String wireName;
+
+ BundleType(int adjustmentType, String wireName) {
+ this.adjustmentType = adjustmentType;
+ this.wireName = wireName;
+ }
+
+ /** Integer value written to {@code Adjustment.KEY_TYPE}. */
+ public int adjustmentType() {
+ return adjustmentType;
+ }
+
+ /** Wire identifier exchanged with the resident Alpha agent. */
+ public String wireName() {
+ return wireName;
+ }
+
+ /** Resolves an Android {@code Adjustment.TYPE_*} integer into a {@link BundleType}. */
+ public static BundleType fromAdjustmentType(int value) {
+ for (BundleType candidate : values()) {
+ if (candidate.adjustmentType == value) {
+ return candidate;
+ }
+ }
+ return OTHER;
+ }
+
+ /** Resolves a wire name (or conversation alias) into a {@link BundleType}. */
+ public static BundleType fromWireName(String raw) {
+ if (raw == null) {
+ return OTHER;
+ }
+ final String normalized = raw.trim().toLowerCase(Locale.ROOT);
+ switch (normalized) {
+ case "promo":
+ case "promotions":
+ case "promotion":
+ return PROMOTION;
+ case "news":
+ return NEWS;
+ case "social":
+ case "social_media":
+ return SOCIAL_MEDIA;
+ case "recs":
+ case "recommendations":
+ case "content_recommendation":
+ return CONTENT_RECOMMENDATION;
+ default:
+ return OTHER;
+ }
+ }
+ }
+
+ /** Snapshot of a grouped notification thread after ingestion. */
+ public static final class ThreadBatch {
+ public final String threadKey;
+ public final String packageName;
+ public final String title;
+ public final BundleType bundleType;
+ public final boolean conversation;
+ public final List messages;
+ public final boolean deduplicated;
+ public final boolean rateLimited;
+ public final boolean warrantsSummary;
+
+ public ThreadBatch(
+ String threadKey,
+ String packageName,
+ String title,
+ BundleType bundleType,
+ boolean conversation,
+ List messages,
+ boolean deduplicated,
+ boolean rateLimited,
+ boolean warrantsSummary) {
+ this.threadKey = threadKey;
+ this.packageName = packageName;
+ this.title = title;
+ this.bundleType = bundleType;
+ this.conversation = conversation;
+ this.messages = Collections.unmodifiableList(new ArrayList<>(messages));
+ this.deduplicated = deduplicated;
+ this.rateLimited = rateLimited;
+ this.warrantsSummary = warrantsSummary;
+ }
+ }
+
+ private static final class ThreadState {
+ final Deque messages = new ArrayDeque<>();
+ long lastInferenceAtMs = Long.MIN_VALUE;
+ }
+
+ private static final Set SOCIAL_PACKAGE_TOKENS = Set.of(
+ "instagram", "twitter", "x.android", "tiktok", "reddit", "facebook.katana",
+ "threads", "bsky", "bluesky", "mastodon", "linkedin", "snapchat", "pinterest");
+
+ private static final Set NEWS_PACKAGE_TOKENS = Set.of(
+ "nytimes", "wsj", "washingtonpost", "bbc.news", "reuters", "apnews",
+ "bloomberg", "theguardian", "economist", "substack", "feedly", "flipboard",
+ "apple.news", "news");
+
+ private static final Set RECOMMENDATION_PACKAGE_TOKENS = Set.of(
+ "youtube", "spotify", "netflix", "twitch", "hulu", "disneyplus",
+ "max.android", "audible", "pocketcasts", "overcast", "medium");
+
+ private static final Pattern PROMO_PATTERN = Pattern.compile(
+ "(?i)\\b(\\d{1,2}%\\s*off|promo\\s+code|coupon|flash\\s+sale|limited[-\\s]?time\\s+offer|"
+ + "free\\s+shipping|clearance|special\\s+offer|save\\s+\\$\\d|deal\\s+of\\s+the\\s+day|"
+ + "shop\\s+now|subscribe\\s+and\\s+save|exclusive\\s+discount)\\b");
+
+ private static final Pattern NEWS_PATTERN = Pattern.compile(
+ "(?i)\\b(breaking\\s+news|developing\\s+story|top\\s+stories|morning\\s+briefing|"
+ + "evening\\s+briefing|headline|live\\s+updates|editorial|newsletter)\\b");
+
+ private static final Pattern SOCIAL_PATTERN = Pattern.compile(
+ "(?i)\\b(liked\\s+your|commented\\s+on|replied\\s+to\\s+your\\s+post|"
+ + "started\\s+following|followed\\s+you|mentioned\\s+you|reposted|retweeted|"
+ + "tagged\\s+you|reacted\\s+to\\s+your)\\b");
+
+ private static final Pattern RECOMMENDATION_PATTERN = Pattern.compile(
+ "(?i)\\b(recommended\\s+for\\s+you|trending\\s+now|new\\s+episode|watch\\s+now|"
+ + "listen\\s+now|just\\s+uploaded|picked\\s+for\\s+you|because\\s+you\\s+watched|"
+ + "top\\s+picks)\\b");
+
+ private static final Pattern SLOP_PREFIX_PATTERN = Pattern.compile(
+ "(?i)^(?:(?:ai\\s+)?summary|tl;?dr|here(?:'s|\\s+is)\\s+(?:a\\s+)?summary|"
+ + "sure,?\\s+here(?:'s|\\s+is)[^:]*|certainly[,!]?)\\s*[:\\-\\u2013\\u2014]?\\s*");
+
+ private static final Pattern MULTI_SPACE_PATTERN = Pattern.compile("[\\r\\n\\t\\s]+");
+
+ private final int maxThreads;
+ private final int maxMessagesPerThread;
+ private final long rateLimitMs;
+ private final Map threads;
+
+ public NotificationThreadGrouper() {
+ this(DEFAULT_MAX_THREADS, DEFAULT_MAX_MESSAGES_PER_THREAD, DEFAULT_RATE_LIMIT_MS);
+ }
+
+ public NotificationThreadGrouper(int maxThreads, int maxMessagesPerThread, long rateLimitMs) {
+ this.maxThreads = Math.max(1, maxThreads);
+ this.maxMessagesPerThread = Math.max(1, maxMessagesPerThread);
+ this.rateLimitMs = Math.max(0L, rateLimitMs);
+ this.threads = new LinkedHashMap(this.maxThreads, 0.75f, true) {
+ @Override
+ protected boolean removeEldestEntry(Map.Entry eldest) {
+ return size() > NotificationThreadGrouper.this.maxThreads;
+ }
+ };
+ }
+
+ /** Ingests one clear notification into its thread batch, applying dedup and rate limiting. */
+ public synchronized ThreadBatch ingest(
+ String packageName,
+ String key,
+ String groupKey,
+ String category,
+ String title,
+ String body,
+ boolean isConversation,
+ long nowMs) {
+ final String safePkg = packageName == null ? "" : packageName.trim();
+ final String safeTitle = collapseWhitespace(title);
+ final String safeBody = collapseWhitespace(body);
+ final String threadKey = buildThreadKey(safePkg, key, groupKey);
+ final BundleType bundleType = classifyBundle(safePkg, category, safeTitle, safeBody, isConversation);
+
+ ThreadState state = threads.get(threadKey);
+ if (state == null) {
+ state = new ThreadState();
+ threads.put(threadKey, state);
+ }
+
+ final String compactLine = buildCompactLine(safeTitle, safeBody);
+ final boolean deduplicated = !compactLine.isEmpty() && compactLine.equals(state.messages.peekLast());
+ if (!compactLine.isEmpty() && !deduplicated) {
+ while (state.messages.size() >= maxMessagesPerThread) {
+ state.messages.removeFirst();
+ }
+ state.messages.addLast(compactLine);
+ }
+
+ final boolean warrantsSummary = state.messages.size() >= 2
+ || safeBody.length() >= MIN_SUMMARIZE_CHARS;
+
+ boolean rateLimited = false;
+ if (warrantsSummary && !deduplicated) {
+ if (state.lastInferenceAtMs != Long.MIN_VALUE
+ && rateLimitMs > 0L
+ && (nowMs - state.lastInferenceAtMs) < rateLimitMs) {
+ rateLimited = true;
+ } else {
+ state.lastInferenceAtMs = nowMs;
+ }
+ } else if (deduplicated) {
+ rateLimited = true;
+ }
+
+ return new ThreadBatch(
+ threadKey,
+ safePkg,
+ safeTitle,
+ bundleType,
+ isConversation || "msg".equals(category),
+ new ArrayList<>(state.messages),
+ deduplicated,
+ rateLimited,
+ warrantsSummary);
+ }
+
+ /** Removes a thread when dismissed or seen by the user. */
+ public synchronized void removeThread(String threadKey) {
+ if (threadKey != null) {
+ threads.remove(threadKey);
+ }
+ }
+
+ /** Clears all tracked threads. */
+ public synchronized void clear() {
+ threads.clear();
+ }
+
+ /** Returns the current number of tracked threads. */
+ public synchronized int trackedThreadCount() {
+ return threads.size();
+ }
+
+ /** Classifies a notification into its Android 17 {@link BundleType}. */
+ public static BundleType classifyBundle(
+ String packageName,
+ String category,
+ String title,
+ String body,
+ boolean isConversation) {
+ if (isConversation || "msg".equals(category)) {
+ return BundleType.OTHER;
+ }
+ final String lowerPkg = packageName == null ? "" : packageName.toLowerCase(Locale.ROOT);
+ final String combined = collapseWhitespace((title == null ? "" : title) + " " + (body == null ? "" : body));
+ if ("promo".equals(category) || PROMO_PATTERN.matcher(combined).find()) {
+ return BundleType.PROMOTION;
+ }
+ if ("recommendation".equals(category)
+ || containsAnyToken(lowerPkg, RECOMMENDATION_PACKAGE_TOKENS)
+ || RECOMMENDATION_PATTERN.matcher(combined).find()) {
+ return BundleType.CONTENT_RECOMMENDATION;
+ }
+ if (containsAnyToken(lowerPkg, NEWS_PACKAGE_TOKENS) || NEWS_PATTERN.matcher(combined).find()) {
+ return BundleType.NEWS;
+ }
+ if ("social".equals(category)
+ || containsAnyToken(lowerPkg, SOCIAL_PACKAGE_TOKENS)
+ || SOCIAL_PATTERN.matcher(combined).find()) {
+ return BundleType.SOCIAL_MEDIA;
+ }
+ return BundleType.OTHER;
+ }
+
+ /** Builds a clean deterministic offline summary for {@code batch}. */
+ public static String buildDeterministicSummary(ThreadBatch batch) {
+ if (batch == null) {
+ return "";
+ }
+ return buildDeterministicSummary(batch.title, batch.messages);
+ }
+
+ /** Builds a concise single-line deterministic summary from {@code title} and recent messages. */
+ public static String buildDeterministicSummary(String title, List messages) {
+ if (messages == null || messages.isEmpty()) {
+ return sanitizeSummary(title);
+ }
+ final int count = messages.size();
+ if (count == 1) {
+ return sanitizeSummary(messages.get(0));
+ }
+ final String cleanTitle = collapseWhitespace(title);
+ final String latest = collapseWhitespace(messages.get(count - 1));
+ final String strippedLatest = !cleanTitle.isEmpty() && latest.startsWith(cleanTitle + ": ")
+ ? latest.substring(cleanTitle.length() + 2)
+ : latest;
+ final String prefix = cleanTitle.isEmpty()
+ ? count + " updates: "
+ : cleanTitle + " (" + count + "): ";
+ return sanitizeSummary(prefix + strippedLatest);
+ }
+
+ /** Sanitizes model or deterministic text into a clean bounded single-line summary. */
+ public static String sanitizeSummary(String raw) {
+ if (raw == null) {
+ return "";
+ }
+ String clean = collapseWhitespace(raw);
+ clean = SLOP_PREFIX_PATTERN.matcher(clean).replaceFirst("").trim();
+ if (clean.length() > MAX_SUMMARY_CHARS) {
+ int cut = MAX_SUMMARY_CHARS - 1;
+ int lastSpace = clean.lastIndexOf(' ', cut);
+ if (lastSpace > MAX_SUMMARY_CHARS / 2) {
+ cut = lastSpace;
+ }
+ clean = clean.substring(0, cut).trim() + "\u2026";
+ }
+ return clean;
+ }
+
+ /** Computes a stable grouping key from package, notification key, and optional group key. */
+ public static String buildThreadKey(String packageName, String key, String groupKey) {
+ final String pkg = packageName == null ? "" : packageName.trim();
+ if (groupKey != null && !groupKey.trim().isEmpty()) {
+ return pkg + "|" + groupKey.trim();
+ }
+ return pkg + "|" + (key == null ? "" : key.trim());
+ }
+
+ private static String buildCompactLine(String title, String body) {
+ if (body.isEmpty()) {
+ return title;
+ }
+ if (title.isEmpty() || body.startsWith(title)) {
+ return body;
+ }
+ return title + ": " + body;
+ }
+
+ private static boolean containsAnyToken(String haystack, Set tokens) {
+ if (haystack.isEmpty()) {
+ return false;
+ }
+ for (String token : tokens) {
+ if (haystack.contains(token)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static String collapseWhitespace(String value) {
+ if (value == null || value.isEmpty()) {
+ return "";
+ }
+ final StringBuilder filtered = new StringBuilder(value.length());
+ for (int i = 0; i < value.length(); i++) {
+ final char ch = value.charAt(i);
+ if (ch == '\r' || ch == '\n' || ch == '\t') {
+ filtered.append(' ');
+ } else if (!Character.isISOControl(ch)) {
+ filtered.append(ch);
+ }
+ }
+ return MULTI_SPACE_PATTERN.matcher(filtered.toString()).replaceAll(" ").trim();
+ }
+}
diff --git a/apps/app/android/alpha-notifications/src/test/java/ai/alphacompute/notifications/NotificationIntelligenceTest.java b/apps/app/android/alpha-notifications/src/test/java/ai/alphacompute/notifications/NotificationIntelligenceTest.java
new file mode 100644
index 0000000000..eff7a91d7f
--- /dev/null
+++ b/apps/app/android/alpha-notifications/src/test/java/ai/alphacompute/notifications/NotificationIntelligenceTest.java
@@ -0,0 +1,361 @@
+package ai.alphacompute.notifications;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.junit.Test;
+
+/**
+ * Pure JVM unit tests for {@link NotificationPrivacyFilter}, {@link NotificationThreadGrouper},
+ * and {@link NotificationSummaryClient}.
+ */
+public final class NotificationIntelligenceTest {
+ private static void check(boolean condition, String message) {
+ if (!condition) {
+ throw new AssertionError(message);
+ }
+ }
+
+ /** Verifies fail-closed privacy redaction across OTP, credentials, financial, lockscreen, and opt-out rules. */
+ @Test
+ public void testFailClosedPrivacyRedaction() {
+ NotificationPrivacyFilter.FilterDecision otp = NotificationPrivacyFilter.evaluate(
+ new NotificationPrivacyFilter.NotificationInput(
+ "com.example.sms",
+ "Security Alert",
+ "Your verification code is 914820. Do not share this code.",
+ "",
+ "msg",
+ NotificationPrivacyFilter.VISIBILITY_PUBLIC,
+ false,
+ true));
+ check(!otp.allowed && otp.sensitivity == NotificationPrivacyFilter.Sensitivity.OTP_CODE,
+ "6-digit OTP code must be redacted");
+
+ NotificationPrivacyFilter.FilterDecision hyphenOtp = NotificationPrivacyFilter.evaluate(
+ new NotificationPrivacyFilter.NotificationInput(
+ "com.example.mail",
+ "Sign-in",
+ "Use one-time passcode 482-910 to sign in",
+ "",
+ "email",
+ NotificationPrivacyFilter.VISIBILITY_PUBLIC,
+ false,
+ true));
+ check(!hyphenOtp.allowed && hyphenOtp.sensitivity == NotificationPrivacyFilter.Sensitivity.OTP_CODE,
+ "hyphenated OTP code must be redacted");
+
+ NotificationPrivacyFilter.FilterDecision pwMgr = NotificationPrivacyFilter.evaluate(
+ new NotificationPrivacyFilter.NotificationInput(
+ "com.onepassword.android",
+ "1Password",
+ "Autofill ready",
+ "",
+ "",
+ NotificationPrivacyFilter.VISIBILITY_PUBLIC,
+ false,
+ true));
+ check(!pwMgr.allowed && pwMgr.sensitivity == NotificationPrivacyFilter.Sensitivity.CREDENTIAL,
+ "password manager package must be redacted");
+
+ NotificationPrivacyFilter.FilterDecision authApp = NotificationPrivacyFilter.evaluate(
+ new NotificationPrivacyFilter.NotificationInput(
+ "com.authy.authy",
+ "Authy",
+ "New token",
+ "",
+ "",
+ NotificationPrivacyFilter.VISIBILITY_PUBLIC,
+ false,
+ true));
+ check(!authApp.allowed && authApp.sensitivity == NotificationPrivacyFilter.Sensitivity.CREDENTIAL,
+ "authenticator package must be redacted");
+
+ NotificationPrivacyFilter.FilterDecision resetMail = NotificationPrivacyFilter.evaluate(
+ new NotificationPrivacyFilter.NotificationInput(
+ "com.example.mail",
+ "Account",
+ "Click this magic link to reset your password",
+ "",
+ "email",
+ NotificationPrivacyFilter.VISIBILITY_PUBLIC,
+ false,
+ true));
+ check(!resetMail.allowed && resetMail.sensitivity == NotificationPrivacyFilter.Sensitivity.CREDENTIAL,
+ "password reset magic link must be redacted");
+
+ NotificationPrivacyFilter.FilterDecision bankPkg = NotificationPrivacyFilter.evaluate(
+ new NotificationPrivacyFilter.NotificationInput(
+ "com.chase.sig.android",
+ "Chase",
+ "Statement ready",
+ "",
+ "",
+ NotificationPrivacyFilter.VISIBILITY_PUBLIC,
+ false,
+ true));
+ check(!bankPkg.allowed && bankPkg.sensitivity == NotificationPrivacyFilter.Sensitivity.FINANCIAL,
+ "banking package must be redacted");
+
+ NotificationPrivacyFilter.FilterDecision bankText = NotificationPrivacyFilter.evaluate(
+ new NotificationPrivacyFilter.NotificationInput(
+ "com.example.sms",
+ "Alert",
+ "Suspicious charge of $249.00 on credit card ending in 4242",
+ "",
+ "msg",
+ NotificationPrivacyFilter.VISIBILITY_PUBLIC,
+ false,
+ true));
+ check(!bankText.allowed && bankText.sensitivity == NotificationPrivacyFilter.Sensitivity.FINANCIAL,
+ "financial charge alert must be redacted");
+
+ NotificationPrivacyFilter.FilterDecision lockPrivate = NotificationPrivacyFilter.evaluate(
+ new NotificationPrivacyFilter.NotificationInput(
+ "org.thoughtcrime.securesms",
+ "Alex",
+ "Pick up groceries on the way home",
+ "",
+ "msg",
+ NotificationPrivacyFilter.VISIBILITY_PRIVATE,
+ true,
+ true));
+ check(!lockPrivate.allowed && lockPrivate.sensitivity == NotificationPrivacyFilter.Sensitivity.LOCKSCREEN_PRIVATE,
+ "VISIBILITY_PRIVATE while device locked must be redacted");
+
+ NotificationPrivacyFilter.FilterDecision unlockedPrivate = NotificationPrivacyFilter.evaluate(
+ new NotificationPrivacyFilter.NotificationInput(
+ "org.thoughtcrime.securesms",
+ "Alex",
+ "Pick up groceries on the way home",
+ "",
+ "msg",
+ NotificationPrivacyFilter.VISIBILITY_PRIVATE,
+ false,
+ true));
+ check(unlockedPrivate.allowed && unlockedPrivate.sensitivity == NotificationPrivacyFilter.Sensitivity.CLEAR,
+ "VISIBILITY_PRIVATE while unlocked is allowed for clear content");
+
+ NotificationPrivacyFilter.FilterDecision secret = NotificationPrivacyFilter.evaluate(
+ new NotificationPrivacyFilter.NotificationInput(
+ "org.thoughtcrime.securesms",
+ "Alex",
+ "Hello",
+ "",
+ "msg",
+ NotificationPrivacyFilter.VISIBILITY_SECRET,
+ false,
+ true));
+ check(!secret.allowed && secret.sensitivity == NotificationPrivacyFilter.Sensitivity.LOCKSCREEN_PRIVATE,
+ "VISIBILITY_SECRET must always be redacted");
+
+ NotificationPrivacyFilter.FilterDecision directBoot = NotificationPrivacyFilter.evaluate(
+ new NotificationPrivacyFilter.NotificationInput(
+ "org.thoughtcrime.securesms",
+ "Alex",
+ "Hello",
+ "",
+ "msg",
+ NotificationPrivacyFilter.VISIBILITY_PUBLIC,
+ false,
+ false));
+ check(!directBoot.allowed && directBoot.sensitivity == NotificationPrivacyFilter.Sensitivity.LOCKSCREEN_PRIVATE,
+ "locked user profile must fail closed");
+
+ NotificationPrivacyFilter.FilterDecision optedOut = NotificationPrivacyFilter.evaluate(
+ new NotificationPrivacyFilter.NotificationInput(
+ "com.example.chat",
+ "Sam",
+ "Dinner at 7?",
+ "",
+ "msg",
+ NotificationPrivacyFilter.VISIBILITY_PUBLIC,
+ false,
+ true),
+ Set.of("com.example.chat"));
+ check(!optedOut.allowed && optedOut.sensitivity == NotificationPrivacyFilter.Sensitivity.OPTED_OUT,
+ "owner-excluded package must be skipped");
+ }
+
+ /** Verifies thread batching, deduplication, rate limiting, LRU eviction, bundle classification, and summary sanitization. */
+ @Test
+ public void testThreadGrouperBundlingRateLimitAndSanitization() {
+ NotificationThreadGrouper grouper = new NotificationThreadGrouper(2, 3, 5_000L);
+
+ NotificationThreadGrouper.ThreadBatch first = grouper.ingest(
+ "org.thoughtcrime.securesms", "k1", "g1", "msg", "Sam", "On my way", true, 1_000L);
+ check(!first.warrantsSummary && !first.deduplicated && !first.rateLimited,
+ "single short message does not trigger summarization");
+ check(first.bundleType == NotificationThreadGrouper.BundleType.OTHER,
+ "conversation stays in OTHER bundle");
+
+ NotificationThreadGrouper.ThreadBatch dup = grouper.ingest(
+ "org.thoughtcrime.securesms", "k1", "g1", "msg", "Sam", "On my way", true, 1_500L);
+ check(dup.deduplicated && dup.messages.size() == 1,
+ "identical consecutive message must deduplicate");
+
+ NotificationThreadGrouper.ThreadBatch second = grouper.ingest(
+ "org.thoughtcrime.securesms", "k1", "g1", "msg", "Sam", "Bringing coffee too", true, 2_000L);
+ check(second.warrantsSummary && !second.rateLimited && second.messages.size() == 2,
+ "second unique message in thread triggers batch summarization");
+
+ NotificationThreadGrouper.ThreadBatch burst = grouper.ingest(
+ "org.thoughtcrime.securesms", "k1", "g1", "msg", "Sam", "Be there in 5 minutes", true, 3_000L);
+ check(burst.warrantsSummary && burst.rateLimited && burst.messages.size() == 3,
+ "rapid third message within 5s cooldown must be rate-limited");
+
+ NotificationThreadGrouper.ThreadBatch afterWindow = grouper.ingest(
+ "org.thoughtcrime.securesms", "k1", "g1", "msg", "Sam", "At the front door", true, 8_500L);
+ check(afterWindow.warrantsSummary && !afterWindow.rateLimited && afterWindow.messages.size() == 3,
+ "message after cooldown passes rate limit and caps thread window at 3");
+ check(afterWindow.messages.get(0).contains("Bringing coffee too"),
+ "oldest message evicted when maxMessagesPerThread reached");
+
+ grouper.ingest("com.shop.app", "k2", null, "promo", "Shop", "Flash sale 40% off shoes today only across the store", false, 9_000L);
+ grouper.ingest("com.nytimes.android", "k3", null, "", "NYT", "Morning briefing: top stories across markets and tech", false, 9_100L);
+ check(grouper.trackedThreadCount() == 2, "LRU eviction bounds tracked threads to maxThreads=2");
+
+ check(NotificationThreadGrouper.classifyBundle("com.shop.app", "promo", "Deal", "30% off", false)
+ == NotificationThreadGrouper.BundleType.PROMOTION, "promo bundle");
+ check(NotificationThreadGrouper.classifyBundle("com.reuters.app", "", "Breaking news", "Rates unchanged", false)
+ == NotificationThreadGrouper.BundleType.NEWS, "news bundle");
+ check(NotificationThreadGrouper.classifyBundle("com.instagram.android", "social", "Maya", "Maya liked your photo", false)
+ == NotificationThreadGrouper.BundleType.SOCIAL_MEDIA, "social bundle");
+ check(NotificationThreadGrouper.classifyBundle("com.google.android.youtube", "recommendation", "Video", "Recommended for you", false)
+ == NotificationThreadGrouper.BundleType.CONTENT_RECOMMENDATION, "recs bundle");
+
+ String cleaned = NotificationThreadGrouper.sanitizeSummary("AI Summary:\n Team moved standup to 10:30am\t");
+ check("Team moved standup to 10:30am".equals(cleaned), "strips slop prefix and whitespace: " + cleaned);
+
+ String bounded = NotificationThreadGrouper.sanitizeSummary("word ".repeat(60));
+ check(bounded.length() <= NotificationThreadGrouper.MAX_SUMMARY_CHARS,
+ "summary must never exceed 140 chars");
+
+ String det = NotificationThreadGrouper.buildDeterministicSummary(
+ "Design", Arrays.asList("Design: Draft uploaded", "Design: Ready for feedback"));
+ check("Design (2): Ready for feedback".equals(det), "deterministic batch summary: " + det);
+ }
+
+ /** Verifies loopback guard, pre-transport redaction, agent success, error fallback, timeout fallback, and leaky-output guard. */
+ @Test
+ public void testSummaryClientRoutingFallbackAndTimeout() throws Exception {
+ check(NotificationSummaryClient.isLoopbackUrl("http://127.0.0.1:4310"), "127.0.0.1 allowed");
+ check(NotificationSummaryClient.isLoopbackUrl("http://localhost:4310"), "localhost allowed");
+ check(!NotificationSummaryClient.isLoopbackUrl("https://evil.example.com"), "remote URL refused");
+ check(!NotificationSummaryClient.isLoopbackUrl("file:///etc/passwd"), "file scheme refused");
+
+ boolean rejectedRemote = false;
+ try {
+ NotificationSummaryClient.forLoopbackUrl("https://api.example.com", 500L);
+ } catch (IllegalArgumentException expected) {
+ rejectedRemote = true;
+ }
+ check(rejectedRemote, "forLoopbackUrl must reject non-loopback endpoints");
+
+ AtomicInteger transportCalls = new AtomicInteger(0);
+ NotificationSummaryClient.AgentTransport okTransport = (method, path, body, timeoutMs) -> {
+ transportCalls.incrementAndGet();
+ String json = "{\"summary\":\"Sam is on the way with coffee\",\"bundle\":\"other\",\"source\":\"local\"}";
+ return CompletableFuture.completedFuture(
+ new NotificationSummaryClient.TransportResponse(200, json.getBytes(StandardCharsets.UTF_8)));
+ };
+ NotificationSummaryClient client = new NotificationSummaryClient(okTransport, 500L);
+
+ NotificationPrivacyFilter.NotificationInput otpInput =
+ new NotificationPrivacyFilter.NotificationInput(
+ "com.example.sms", "Auth", "Your 2FA code is 551092", "", "msg",
+ NotificationPrivacyFilter.VISIBILITY_PUBLIC, false, true);
+ NotificationThreadGrouper.ThreadBatch otpBatch = new NotificationThreadGrouper.ThreadBatch(
+ "com.example.sms|1", "com.example.sms", "Auth",
+ NotificationThreadGrouper.BundleType.OTHER, true,
+ Collections.singletonList("Auth: Your 2FA code is 551092"), false, false, true);
+ NotificationSummaryClient.SummaryResult otpResult = client.summarize(otpInput, otpBatch, Collections.emptySet());
+ check(otpResult.redacted && transportCalls.get() == 0,
+ "sensitive OTP notification must NEVER invoke transport");
+
+ NotificationPrivacyFilter.NotificationInput clearInput =
+ new NotificationPrivacyFilter.NotificationInput(
+ "org.thoughtcrime.securesms", "Sam",
+ "Heading over now, picked up two oat lattes from the corner cafe", "", "msg",
+ NotificationPrivacyFilter.VISIBILITY_PUBLIC, false, true);
+ NotificationThreadGrouper.ThreadBatch clearBatch = new NotificationThreadGrouper.ThreadBatch(
+ "org.thoughtcrime.securesms|g1", "org.thoughtcrime.securesms", "Sam",
+ NotificationThreadGrouper.BundleType.OTHER, true,
+ Arrays.asList("Sam: On my way", "Sam: Picked up two oat lattes"), false, false, true);
+ NotificationSummaryClient.SummaryResult llmResult = client.summarize(clearInput, clearBatch, Collections.emptySet());
+ check(!llmResult.redacted && !llmResult.fellBack && "local".equals(llmResult.source)
+ && "Sam is on the way with coffee".equals(llmResult.summary)
+ && transportCalls.get() == 1,
+ "clear batch routes to resident agent and returns clean summary");
+
+ NotificationSummaryClient failingClient = new NotificationSummaryClient(
+ (method, path, body, timeoutMs) -> CompletableFuture.completedFuture(
+ new NotificationSummaryClient.TransportResponse(503, "{}".getBytes(StandardCharsets.UTF_8))),
+ 300L);
+ NotificationSummaryClient.SummaryResult errorFallback =
+ failingClient.summarize(clearInput, clearBatch, Collections.emptySet());
+ check(!errorFallback.redacted && errorFallback.fellBack
+ && "deterministic".equals(errorFallback.source)
+ && errorFallback.summary.contains("Sam (2):"),
+ "HTTP 503 falls back cleanly to deterministic summary");
+
+ NotificationSummaryClient slowClient = new NotificationSummaryClient(
+ (method, path, body, timeoutMs) -> new CompletableFuture<>(),
+ 80L);
+ long start = System.nanoTime();
+ NotificationSummaryClient.SummaryResult timeoutFallback =
+ slowClient.summarize(clearInput, clearBatch, Collections.emptySet());
+ long elapsedMs = (System.nanoTime() - start) / 1_000_000L;
+ check(!timeoutFallback.redacted && timeoutFallback.fellBack
+ && "deterministic".equals(timeoutFallback.source)
+ && elapsedMs < 500L,
+ "slow transport honors timeout budget and falls back deterministically (elapsed=" + elapsedMs + "ms)");
+
+ NotificationSummaryClient leakyModelClient = new NotificationSummaryClient(
+ (method, path, body, timeoutMs) -> CompletableFuture.completedFuture(
+ new NotificationSummaryClient.TransportResponse(
+ 200,
+ "{\"summary\":\"Your verification code is 123456\",\"source\":\"cloud\"}"
+ .getBytes(StandardCharsets.UTF_8))),
+ 300L);
+ NotificationSummaryClient.SummaryResult postGuard =
+ leakyModelClient.summarize(clearInput, clearBatch, Collections.emptySet());
+ check(postGuard.fellBack && "deterministic".equals(postGuard.source),
+ "post-response privacy guard rejects sensitive model output");
+
+ JSONObject bridgeReq = new JSONObject()
+ .put("packageName", "org.thoughtcrime.securesms")
+ .put("title", "Sam")
+ .put("isConversation", true)
+ .put("fallbackBundleType", 0)
+ .put("messages", new JSONArray().put("Sam: On my way").put("Sam: Bringing coffee"));
+ JSONObject bridgeRes = client.handleBridgeRequestJson(bridgeReq.toString(), Collections.emptySet());
+ check(!bridgeRes.getBoolean("redacted")
+ && "Sam is on the way with coffee".equals(bridgeRes.getString("summary")),
+ "Binder JSON bridge contract returns summarized payload");
+
+ JSONObject sensitiveBridgeReq = new JSONObject()
+ .put("packageName", "com.x8bit.bitwarden")
+ .put("title", "Bitwarden")
+ .put("messages", new JSONArray().put("Vault unlocked"));
+ JSONObject sensitiveBridgeRes = client.handleBridgeRequestJson(
+ sensitiveBridgeReq.toString(), Collections.emptySet());
+ check(sensitiveBridgeRes.getBoolean("redacted")
+ && sensitiveBridgeRes.getString("summary").isEmpty(),
+ "Binder JSON bridge contract redacts sensitive packages fail-closed");
+ }
+
+ /** Standalone JVM runner matching AlphaControlPolicyTest for fast CI/local verification. */
+ public static void main(String[] args) throws Exception {
+ NotificationIntelligenceTest suite = new NotificationIntelligenceTest();
+ suite.testFailClosedPrivacyRedaction();
+ suite.testThreadGrouperBundlingRateLimitAndSanitization();
+ suite.testSummaryClientRoutingFallbackAndTimeout();
+ System.out.println("PASS alpha-notifications JUnit suite (3 test methods)");
+ }
+}
diff --git a/apps/app/android/alpha-play-bridge/build.gradle b/apps/app/android/alpha-play-bridge/build.gradle
new file mode 100644
index 0000000000..d957aa2506
--- /dev/null
+++ b/apps/app/android/alpha-play-bridge/build.gradle
@@ -0,0 +1,27 @@
+apply plugin: 'com.android.library'
+
+android {
+ namespace 'ai.alphacompute.playbridge'
+ compileSdk rootProject.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 36
+
+ defaultConfig {
+ minSdk rootProject.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 29
+ targetSdk rootProject.hasProperty('targetSdkVersion') ? rootProject.ext.targetSdkVersion : 36
+ consumerProguardFiles 'consumer-rules.pro'
+ }
+
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_17
+ targetCompatibility JavaVersion.VERSION_17
+ }
+
+ testOptions {
+ unitTests.returnDefaultValues = true
+ }
+}
+
+dependencies {
+ implementation project(':capacitor-android')
+ testImplementation "junit:junit:${rootProject.hasProperty('junitVersion') ? rootProject.ext.junitVersion : '4.13.2'}"
+ testImplementation 'org.json:json:20250517'
+}
diff --git a/apps/app/android/alpha-play-bridge/consumer-rules.pro b/apps/app/android/alpha-play-bridge/consumer-rules.pro
new file mode 100644
index 0000000000..d7bedb6c74
--- /dev/null
+++ b/apps/app/android/alpha-play-bridge/consumer-rules.pro
@@ -0,0 +1,3 @@
+-keep class ai.alphacompute.playbridge.AlphaPlayBridgePlugin { *; }
+-keep class ai.alphacompute.playbridge.AlphaPlayBridge { *; }
+-keep class ai.alphacompute.playbridge.SandboxedPlayPolicy { *; }
diff --git a/apps/app/android/alpha-play-bridge/src/main/AndroidManifest.xml b/apps/app/android/alpha-play-bridge/src/main/AndroidManifest.xml
new file mode 100644
index 0000000000..86dfe87794
--- /dev/null
+++ b/apps/app/android/alpha-play-bridge/src/main/AndroidManifest.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/apps/app/android/alpha-play-bridge/src/main/java/ai/alphacompute/playbridge/AlphaPlayBridge.java b/apps/app/android/alpha-play-bridge/src/main/java/ai/alphacompute/playbridge/AlphaPlayBridge.java
new file mode 100644
index 0000000000..a3302f1ac5
--- /dev/null
+++ b/apps/app/android/alpha-play-bridge/src/main/java/ai/alphacompute/playbridge/AlphaPlayBridge.java
@@ -0,0 +1,677 @@
+package ai.alphacompute.playbridge;
+
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ServiceConnection;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.content.pm.ResolveInfo;
+import android.content.pm.Signature;
+import android.content.pm.SigningInfo;
+import android.net.Uri;
+import android.os.IBinder;
+import android.os.Parcel;
+import android.os.ParcelFileDescriptor;
+import android.os.RemoteException;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * Android bridge orchestrating Sandboxed Google Play status audits, fail-closed
+ * GSF -> GMS -> Play Store verified installation, and user-app removal.
+ */
+public final class AlphaPlayBridge {
+ /** Cross-process Binder interface descriptor matching {@code AlphaPlayInstallerService.BINDER_DESCRIPTOR}. */
+ public static final String INSTALLER_BINDER_DESCRIPTOR =
+ "ai.alphacompute.playinstaller.IAlphaPlayInstaller";
+
+ /** Binder transaction code matching {@code AlphaPlayInstallerService.TRANSACTION_INSTALL_PACKAGE}. */
+ public static final int TRANSACTION_INSTALL_PACKAGE = IBinder.FIRST_CALL_TRANSACTION;
+
+ private static final long BIND_TIMEOUT_MS = 10_000L;
+
+ /** Port querying installed package metadata and AOSP GmsCompat readiness. */
+ public interface PackageInspector {
+ /** Returns true when {@code app.grapheneos.gmscompat} is installed as a system package. */
+ boolean isGmsCompatPresent();
+
+ /** Returns true when {@code ai.alphacompute.playinstaller} exposes the installer service action. */
+ boolean isInstallerServicePresent();
+
+ /** Inspects one package name, returning an absent record if not installed. */
+ SandboxedPlayPolicy.PackageInspection inspect(String packageName);
+ }
+
+ /** Port delegating verified package commits and user-app uninstallation to Android / AlphaPlayInstaller. */
+ public interface InstallerGateway {
+ /** Loads the staged Sandboxed Google Play release manifest from local app storage, or returns {@code null} if absent. */
+ default SandboxedPlayPolicy.InstallManifestSpec loadStagedManifest() {
+ return null;
+ }
+
+ /** Verifies staged artifacts for the release manifest before any install session starts. */
+ SandboxedPlayPolicy.ValidationOutcome verifyRelease(SandboxedPlayPolicy.InstallManifestSpec manifest);
+
+ /** Installs one verified package strictly as an unprivileged {@code /data/app} user app. */
+ SandboxedPlayPolicy.ValidationOutcome installPackage(SandboxedPlayPolicy.ManifestPackageSpec entry);
+
+ /** Uninstalls one unprivileged {@code /data/app} Google package. */
+ SandboxedPlayPolicy.ValidationOutcome uninstallPackage(String packageName);
+ }
+
+ /** Callback receiving deterministic install phase transitions. */
+ public interface ProgressListener {
+ /** Invoked whenever the active install phase advances or settles. */
+ void onPhase(String phase, String packageName, String failureCode);
+ }
+
+ private final PackageInspector inspector;
+ private final InstallerGateway gateway;
+
+ /** Constructs a bridge backed by live Android {@link PackageManager} and {@code AlphaPlayInstaller}. */
+ public AlphaPlayBridge(Context context) {
+ this(new AndroidPackageInspector(context.getApplicationContext()), new AndroidInstallerGateway(context.getApplicationContext()));
+ }
+
+ /** Constructs a bridge with explicit ports for deterministic JVM unit verification. */
+ public AlphaPlayBridge(PackageInspector inspector, InstallerGateway gateway) {
+ this.inspector = inspector;
+ this.gateway = gateway;
+ }
+
+ /** Audits current GmsCompat readiness, package installation status, and zero-priv-app isolation. */
+ public SandboxedPlayPolicy.SandboxAudit audit() {
+ return SandboxedPlayPolicy.auditSandbox(
+ inspector.isGmsCompatPresent(),
+ inspector.isInstallerServicePresent(),
+ inspector.inspect(SandboxedPlayPolicy.PACKAGE_GSF),
+ inspector.inspect(SandboxedPlayPolicy.PACKAGE_GMS),
+ inspector.inspect(SandboxedPlayPolicy.PACKAGE_VENDING)
+ );
+ }
+
+ /** Serializes the live sandbox audit into the JSON contract consumed by the Alpha app. */
+ public JSONObject statusJson() throws JSONException {
+ return serializeAudit(audit());
+ }
+
+ /**
+ * Fails closed unless GmsCompat is ready, zero privileged Google grants exist, and the
+ * supplied manifest passes cryptographic and ordering verification.
+ */
+ public JSONObject verifyRelease(JSONObject manifestJson) throws JSONException {
+ SandboxedPlayPolicy.SandboxAudit current = audit();
+ if (!current.gmsCompatReady()) {
+ return serializeOutcome(
+ SandboxedPlayPolicy.ValidationOutcome.fail(
+ current.failureCode().isEmpty() ? "GMS_COMPAT_MISSING" : current.failureCode(),
+ current.failureMessage().isEmpty() ? "GmsCompat runtime unavailable" : current.failureMessage()
+ ),
+ current
+ );
+ }
+ if (current.googlePrivAppGrants() > 0 || !current.sandboxedInDataApp()) {
+ return serializeOutcome(
+ SandboxedPlayPolicy.ValidationOutcome.fail("PRIVILEGED_GRANT_DETECTED", "Privileged Google grant detected"),
+ current
+ );
+ }
+ SandboxedPlayPolicy.InstallManifestSpec manifest = resolveManifest(manifestJson);
+ SandboxedPlayPolicy.ValidationOutcome manifestCheck = SandboxedPlayPolicy.validateManifest(manifest);
+ if (!manifestCheck.ok()) {
+ return serializeOutcome(manifestCheck, current);
+ }
+ SandboxedPlayPolicy.ValidationOutcome gatewayCheck = gateway.verifyRelease(manifest);
+ return serializeOutcome(gatewayCheck, audit());
+ }
+
+ /**
+ * Installs one package from a validated release manifest only if it is the exact next
+ * package required in GSF -> GMS -> Play Store order and zero privileged grants exist.
+ */
+ public JSONObject installPackage(String packageName, JSONObject manifestJson) throws JSONException {
+ SandboxedPlayPolicy.SandboxAudit before = audit();
+ if (!before.gmsCompatReady() || before.googlePrivAppGrants() > 0 || !before.sandboxedInDataApp()) {
+ return serializeOutcome(
+ SandboxedPlayPolicy.ValidationOutcome.fail(
+ before.failureCode().isEmpty() ? "SANDBOX_PRECONDITION_FAILED" : before.failureCode(),
+ before.failureMessage().isEmpty() ? "Sandbox preconditions not met" : before.failureMessage()
+ ),
+ before
+ );
+ }
+ SandboxedPlayPolicy.InstallManifestSpec manifest = resolveManifest(manifestJson);
+ SandboxedPlayPolicy.ValidationOutcome manifestCheck = SandboxedPlayPolicy.validateManifest(manifest);
+ if (!manifestCheck.ok()) {
+ return serializeOutcome(manifestCheck, before);
+ }
+ Set alreadyInstalled = installedPackageSet(before);
+ SandboxedPlayPolicy.ValidationOutcome orderCheck =
+ SandboxedPlayPolicy.validateStepOrder(packageName, alreadyInstalled);
+ if (!orderCheck.ok()) {
+ return serializeOutcome(orderCheck, before);
+ }
+ SandboxedPlayPolicy.ManifestPackageSpec targetEntry = findEntry(manifest, packageName);
+ if (targetEntry == null) {
+ return serializeOutcome(
+ SandboxedPlayPolicy.ValidationOutcome.fail("UNKNOWN_PACKAGE", "Package missing from manifest"),
+ before
+ );
+ }
+ SandboxedPlayPolicy.ValidationOutcome commitOutcome = gateway.installPackage(targetEntry);
+ SandboxedPlayPolicy.SandboxAudit after = audit();
+ if (!commitOutcome.ok()) {
+ return serializeOutcome(commitOutcome, after);
+ }
+ if (after.googlePrivAppGrants() > 0 || !after.sandboxedInDataApp() || !after.signersVerified()) {
+ return serializeOutcome(
+ SandboxedPlayPolicy.ValidationOutcome.fail(
+ after.failureCode().isEmpty() ? "PRIVILEGED_GRANT_DETECTED" : after.failureCode(),
+ after.failureMessage().isEmpty() ? "Post-install sandbox audit failed" : after.failureMessage()
+ ),
+ after
+ );
+ }
+ return serializeOutcome(SandboxedPlayPolicy.ValidationOutcome.pass(), after);
+ }
+
+ /**
+ * Executes the complete fail-closed 1-tap Sandboxed Google Play installation workflow:
+ * {@code verifying -> installing_gsf -> installing_gms -> installing_store -> installed | failed}.
+ */
+ public JSONObject installSuite(JSONObject manifestJson, ProgressListener listener) throws JSONException {
+ notifyProgress(listener, "verifying", "", "");
+ SandboxedPlayPolicy.SandboxAudit before = audit();
+ if (!before.gmsCompatReady()) {
+ String code = before.failureCode().isEmpty() ? "GMS_COMPAT_MISSING" : before.failureCode();
+ notifyProgress(listener, "failed", "", code);
+ return serializeOutcome(
+ SandboxedPlayPolicy.ValidationOutcome.fail(code, before.failureMessage()),
+ before
+ );
+ }
+ if (before.googlePrivAppGrants() > 0 || !before.sandboxedInDataApp()) {
+ notifyProgress(listener, "failed", "", "PRIVILEGED_GRANT_DETECTED");
+ return serializeOutcome(
+ SandboxedPlayPolicy.ValidationOutcome.fail("PRIVILEGED_GRANT_DETECTED", "Privileged Google grant detected"),
+ before
+ );
+ }
+ SandboxedPlayPolicy.InstallManifestSpec manifest = resolveManifest(manifestJson);
+ SandboxedPlayPolicy.ValidationOutcome manifestCheck = SandboxedPlayPolicy.validateManifest(manifest);
+ if (!manifestCheck.ok()) {
+ notifyProgress(listener, "failed", "", manifestCheck.failureCode());
+ return serializeOutcome(manifestCheck, before);
+ }
+ SandboxedPlayPolicy.ValidationOutcome verified = gateway.verifyRelease(manifest);
+ if (!verified.ok()) {
+ notifyProgress(listener, "failed", "", verified.failureCode());
+ return serializeOutcome(verified, before);
+ }
+ Set completed = new HashSet<>();
+ for (SandboxedPlayPolicy.ManifestPackageSpec entry : manifest.entries()) {
+ SandboxedPlayPolicy.ValidationOutcome orderCheck =
+ SandboxedPlayPolicy.validateStepOrder(entry.packageName(), completed);
+ if (!orderCheck.ok()) {
+ notifyProgress(listener, "failed", entry.packageName(), orderCheck.failureCode());
+ return serializeOutcome(orderCheck, audit());
+ }
+ notifyProgress(listener, phaseForPackage(entry.packageName()), entry.packageName(), "");
+ SandboxedPlayPolicy.ValidationOutcome stepResult = gateway.installPackage(entry);
+ SandboxedPlayPolicy.SandboxAudit stepAudit = audit();
+ if (!stepResult.ok()) {
+ notifyProgress(listener, "failed", entry.packageName(), stepResult.failureCode());
+ return serializeOutcome(stepResult, stepAudit);
+ }
+ if (stepAudit.googlePrivAppGrants() > 0 || !stepAudit.sandboxedInDataApp() || !stepAudit.signersVerified()) {
+ String code = stepAudit.failureCode().isEmpty() ? "PRIVILEGED_GRANT_DETECTED" : stepAudit.failureCode();
+ notifyProgress(listener, "failed", entry.packageName(), code);
+ return serializeOutcome(
+ SandboxedPlayPolicy.ValidationOutcome.fail(code, stepAudit.failureMessage()),
+ stepAudit
+ );
+ }
+ completed.add(entry.packageName());
+ }
+ SandboxedPlayPolicy.SandboxAudit finalAudit = audit();
+ if (!"installed".equals(finalAudit.phase())) {
+ String code = finalAudit.failureCode().isEmpty() ? "POST_INSTALL_INCOMPLETE" : finalAudit.failureCode();
+ notifyProgress(listener, "failed", "", code);
+ return serializeOutcome(
+ SandboxedPlayPolicy.ValidationOutcome.fail(code, "Final sandbox audit did not confirm installed state"),
+ finalAudit
+ );
+ }
+ notifyProgress(listener, "installed", "", "");
+ return serializeOutcome(SandboxedPlayPolicy.ValidationOutcome.pass(), finalAudit);
+ }
+
+ /** Uninstalls sandboxed Google Play packages in reverse dependency order, refusing any privileged package. */
+ public JSONObject uninstallSuite() throws JSONException {
+ SandboxedPlayPolicy.SandboxAudit before = audit();
+ if (before.googlePrivAppGrants() > 0) {
+ return serializeOutcome(
+ SandboxedPlayPolicy.ValidationOutcome.fail(
+ "PRIVILEGED_GRANT_DETECTED",
+ "Refusing to remove privileged system Google packages"
+ ),
+ before
+ );
+ }
+ for (String pkg : SandboxedPlayPolicy.REQUIRED_UNINSTALL_ORDER) {
+ SandboxedPlayPolicy.PackageInspection inspection = inspector.inspect(pkg);
+ if (!inspection.installed()) {
+ continue;
+ }
+ if (!inspection.isSandboxedUserApp()) {
+ return serializeOutcome(
+ SandboxedPlayPolicy.ValidationOutcome.fail(
+ "PRIVILEGED_GRANT_DETECTED",
+ "Refusing to remove non-sandboxed package: " + pkg
+ ),
+ audit()
+ );
+ }
+ SandboxedPlayPolicy.ValidationOutcome removed = gateway.uninstallPackage(pkg);
+ if (!removed.ok()) {
+ return serializeOutcome(removed, audit());
+ }
+ }
+ return serializeOutcome(SandboxedPlayPolicy.ValidationOutcome.pass(), audit());
+ }
+
+ /**
+ * Resolves a staged APK filename inside {@code stagingDir}, failing closed on path traversal,
+ * symlinks, or missing regular files.
+ */
+ public static Path resolveStagedApkPath(Path stagingDir, String apkFileName) {
+ if (stagingDir == null || apkFileName == null || apkFileName.isBlank()) {
+ return null;
+ }
+ if (apkFileName.contains("/") || apkFileName.contains("\\") || apkFileName.contains("..")) {
+ return null;
+ }
+ Path normalizedRoot = stagingDir.toAbsolutePath().normalize();
+ if (!Files.isDirectory(normalizedRoot) || Files.isSymbolicLink(normalizedRoot)) {
+ return null;
+ }
+ Path candidate = normalizedRoot.resolve(apkFileName).normalize();
+ if (!candidate.startsWith(normalizedRoot) || candidate.equals(normalizedRoot)) {
+ return null;
+ }
+ if (!Files.isRegularFile(candidate) || Files.isSymbolicLink(candidate)) {
+ return null;
+ }
+ return candidate;
+ }
+
+ /** Executes one cross-process Binder transaction carrying entry metadata and a read-only APK descriptor. */
+ static SandboxedPlayPolicy.ValidationOutcome transactInstall(
+ IBinder binder,
+ SandboxedPlayPolicy.ManifestPackageSpec entry,
+ ParcelFileDescriptor apkFd
+ ) {
+ Parcel data = Parcel.obtain();
+ Parcel reply = Parcel.obtain();
+ try {
+ data.writeInterfaceToken(INSTALLER_BINDER_DESCRIPTOR);
+ data.writeString(entry.packageName());
+ data.writeLong(entry.versionCode());
+ data.writeString(entry.apkFileName());
+ data.writeString(entry.apkSha256());
+ data.writeString(entry.signerSha256());
+ data.writeLong(entry.sizeBytes());
+ data.writeInt(1);
+ apkFd.writeToParcel(data, 0);
+ if (!binder.transact(TRANSACTION_INSTALL_PACKAGE, data, reply, 0)) {
+ return SandboxedPlayPolicy.ValidationOutcome.fail(
+ "INSTALLER_TRANSACT_FAILED",
+ "AlphaPlayInstaller rejected install transaction for " + entry.packageName()
+ );
+ }
+ reply.readException();
+ boolean ok = reply.readInt() != 0;
+ String failureCode = reply.readString();
+ String message = reply.readString();
+ if (ok) {
+ return SandboxedPlayPolicy.ValidationOutcome.pass();
+ }
+ return SandboxedPlayPolicy.ValidationOutcome.fail(
+ failureCode == null || failureCode.isBlank() ? "INSTALLER_FAILED" : failureCode,
+ message == null || message.isBlank() ? "AlphaPlayInstaller refused package" : message
+ );
+ } catch (RemoteException | RuntimeException error) {
+ return SandboxedPlayPolicy.ValidationOutcome.fail(
+ "INSTALLER_IPC_ERROR",
+ error.getMessage() == null ? "Binder IPC failed" : error.getMessage()
+ );
+ } finally {
+ reply.recycle();
+ data.recycle();
+ }
+ }
+
+ private SandboxedPlayPolicy.InstallManifestSpec resolveManifest(JSONObject raw) {
+ if (raw != null && raw.length() > 0) {
+ return parseManifest(raw);
+ }
+ return gateway.loadStagedManifest();
+ }
+
+ /** Parses a JSON release manifest into an immutable {@link SandboxedPlayPolicy.InstallManifestSpec}. */
+ public static SandboxedPlayPolicy.InstallManifestSpec parseManifest(JSONObject raw) {
+ if (raw == null) {
+ return null;
+ }
+ int schemaVersion = raw.optInt("schemaVersion", 0);
+ String channel = raw.optString("channel", "");
+ long timestamp = raw.optLong("releaseTimestampEpochSec", 0L);
+ JSONArray array = raw.optJSONArray("entries");
+ List entries = new ArrayList<>();
+ if (array != null) {
+ for (int i = 0; i < array.length(); i++) {
+ JSONObject item = array.optJSONObject(i);
+ if (item == null) {
+ entries.add(null);
+ continue;
+ }
+ entries.add(new SandboxedPlayPolicy.ManifestPackageSpec(
+ item.optString("packageName", null),
+ item.optLong("versionCode", 0L),
+ item.optString("apkFileName", null),
+ item.optString("apkSha256", null),
+ item.optString("signerSha256", null),
+ item.optLong("sizeBytes", 0L)
+ ));
+ }
+ }
+ return new SandboxedPlayPolicy.InstallManifestSpec(schemaVersion, channel, timestamp, entries);
+ }
+
+ private static Set installedPackageSet(SandboxedPlayPolicy.SandboxAudit audit) {
+ Set set = new HashSet<>();
+ if (audit.gsf().installed()) set.add(SandboxedPlayPolicy.PACKAGE_GSF);
+ if (audit.gms().installed()) set.add(SandboxedPlayPolicy.PACKAGE_GMS);
+ if (audit.store().installed()) set.add(SandboxedPlayPolicy.PACKAGE_VENDING);
+ return set;
+ }
+
+ private static SandboxedPlayPolicy.ManifestPackageSpec findEntry(
+ SandboxedPlayPolicy.InstallManifestSpec manifest,
+ String packageName
+ ) {
+ for (SandboxedPlayPolicy.ManifestPackageSpec entry : manifest.entries()) {
+ if (packageName.equals(entry.packageName())) {
+ return entry;
+ }
+ }
+ return null;
+ }
+
+ private static String phaseForPackage(String packageName) {
+ if (SandboxedPlayPolicy.PACKAGE_GSF.equals(packageName)) return "installing_gsf";
+ if (SandboxedPlayPolicy.PACKAGE_GMS.equals(packageName)) return "installing_gms";
+ return "installing_store";
+ }
+
+ private static void notifyProgress(ProgressListener listener, String phase, String pkg, String failureCode) {
+ if (listener != null) {
+ listener.onPhase(phase, pkg, failureCode);
+ }
+ }
+
+ private static JSONObject serializeOutcome(
+ SandboxedPlayPolicy.ValidationOutcome outcome,
+ SandboxedPlayPolicy.SandboxAudit audit
+ ) throws JSONException {
+ JSONObject payload = serializeAudit(audit);
+ payload.put("ok", outcome.ok());
+ if (!outcome.ok()) {
+ payload.put("failureCode", outcome.failureCode());
+ payload.put("failureMessage", outcome.message());
+ }
+ return payload;
+ }
+
+ private static JSONObject serializeAudit(SandboxedPlayPolicy.SandboxAudit audit) throws JSONException {
+ JSONObject packages = new JSONObject()
+ .put("gsf", serializePackage(audit.gsf()))
+ .put("gms", serializePackage(audit.gms()))
+ .put("store", serializePackage(audit.store()));
+ return new JSONObject()
+ .put("phase", audit.phase())
+ .put("gmsCompatReady", audit.gmsCompatReady())
+ .put("gmsCompatPresent", audit.gmsCompatPresent())
+ .put("installerPresent", audit.installerPresent())
+ .put("googlePrivAppGrants", audit.googlePrivAppGrants())
+ .put("sandboxedInDataApp", audit.sandboxedInDataApp())
+ .put("signersVerified", audit.signersVerified())
+ .put("failureCode", audit.failureCode())
+ .put("failureMessage", audit.failureMessage())
+ .put("packages", packages);
+ }
+
+ private static JSONObject serializePackage(SandboxedPlayPolicy.PackageInspection pkg) throws JSONException {
+ return new JSONObject()
+ .put("packageName", pkg.packageName())
+ .put("installed", pkg.installed())
+ .put("versionCode", pkg.versionCode())
+ .put("sandboxedInDataApp", pkg.isSandboxedUserApp())
+ .put("zeroPrivAppGrants", pkg.privilegedGrantCount() == 0)
+ .put("officialGoogleSigner", pkg.hasOfficialGoogleSigner());
+ }
+
+ private static final class AndroidPackageInspector implements PackageInspector {
+ private final Context context;
+
+ AndroidPackageInspector(Context context) {
+ this.context = context;
+ }
+
+ @Override public boolean isGmsCompatPresent() {
+ PackageManager pm = context.getPackageManager();
+ try {
+ PackageInfo info = pm.getPackageInfo(
+ SandboxedPlayPolicy.GMS_COMPAT_PACKAGE,
+ PackageManager.MATCH_SYSTEM_ONLY
+ );
+ return info != null && info.applicationInfo != null && info.applicationInfo.enabled;
+ } catch (PackageManager.NameNotFoundException missing) {
+ return false;
+ }
+ }
+
+ @Override public boolean isInstallerServicePresent() {
+ PackageManager pm = context.getPackageManager();
+ Intent intent = new Intent(SandboxedPlayPolicy.INSTALLER_ACTION)
+ .setPackage(SandboxedPlayPolicy.INSTALLER_PACKAGE);
+ ResolveInfo resolved = pm.resolveService(intent, PackageManager.MATCH_SYSTEM_ONLY);
+ return resolved != null && resolved.serviceInfo != null;
+ }
+
+ @Override public SandboxedPlayPolicy.PackageInspection inspect(String packageName) {
+ PackageManager pm = context.getPackageManager();
+ try {
+ PackageInfo info = pm.getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES);
+ if (info == null || info.applicationInfo == null) {
+ return SandboxedPlayPolicy.PackageInspection.absent(packageName);
+ }
+ ApplicationInfo appInfo = info.applicationInfo;
+ int flags = appInfo.flags;
+ boolean isSystem = (flags & ApplicationInfo.FLAG_SYSTEM) != 0;
+ boolean isUpdatedSystem = (flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
+ boolean isPrivileged = isSystem && appInfo.sourceDir != null
+ && (appInfo.sourceDir.contains("/priv-app/") || appInfo.sourceDir.startsWith("/system"));
+ SigningInfo signingInfo = info.signingInfo;
+ List digests = new ArrayList<>();
+ boolean multipleSigners = false;
+ if (signingInfo != null) {
+ multipleSigners = signingInfo.hasMultipleSigners();
+ Signature[] signers = signingInfo.getApkContentsSigners();
+ if (signers != null) {
+ for (Signature sig : signers) {
+ digests.add(SandboxedPlayPolicy.sha256Hex(sig.toByteArray()));
+ }
+ }
+ }
+ return new SandboxedPlayPolicy.PackageInspection(
+ packageName,
+ true,
+ info.getLongVersionCode(),
+ appInfo.sourceDir == null ? "" : appInfo.sourceDir,
+ isSystem,
+ isUpdatedSystem,
+ isPrivileged,
+ multipleSigners,
+ Collections.unmodifiableList(digests)
+ );
+ } catch (PackageManager.NameNotFoundException missing) {
+ return SandboxedPlayPolicy.PackageInspection.absent(packageName);
+ }
+ }
+ }
+
+ private static final class AndroidInstallerGateway implements InstallerGateway {
+ private static final String STAGED_DIR = "sandboxed-play";
+ private static final String STAGED_MANIFEST_FILE = "release-manifest.json";
+ private final Context context;
+
+ AndroidInstallerGateway(Context context) {
+ this.context = context;
+ }
+
+ @Override public SandboxedPlayPolicy.InstallManifestSpec loadStagedManifest() {
+ Path manifestPath = context.getNoBackupFilesDir().toPath()
+ .resolve(STAGED_DIR)
+ .resolve(STAGED_MANIFEST_FILE);
+ if (!Files.isRegularFile(manifestPath) || Files.isSymbolicLink(manifestPath)) {
+ return null;
+ }
+ try {
+ String raw = new String(Files.readAllBytes(manifestPath), StandardCharsets.UTF_8);
+ return parseManifest(new JSONObject(raw));
+ } catch (IOException | JSONException unreadable) {
+ return null;
+ }
+ }
+
+ @Override public SandboxedPlayPolicy.ValidationOutcome verifyRelease(
+ SandboxedPlayPolicy.InstallManifestSpec manifest
+ ) {
+ PackageManager pm = context.getPackageManager();
+ Intent intent = new Intent(SandboxedPlayPolicy.INSTALLER_ACTION)
+ .setPackage(SandboxedPlayPolicy.INSTALLER_PACKAGE);
+ ResolveInfo resolved = pm.resolveService(intent, PackageManager.MATCH_SYSTEM_ONLY);
+ if (resolved == null || resolved.serviceInfo == null) {
+ return SandboxedPlayPolicy.ValidationOutcome.fail(
+ "INSTALLER_MISSING",
+ "AlphaPlayInstaller service is not installed on this system image"
+ );
+ }
+ return SandboxedPlayPolicy.validateManifest(manifest);
+ }
+
+ @Override public SandboxedPlayPolicy.ValidationOutcome installPackage(
+ SandboxedPlayPolicy.ManifestPackageSpec entry
+ ) {
+ Path stagingDir = context.getNoBackupFilesDir().toPath().resolve(STAGED_DIR);
+ Path stagedApk = resolveStagedApkPath(stagingDir, entry.apkFileName());
+ if (stagedApk == null) {
+ return SandboxedPlayPolicy.ValidationOutcome.fail(
+ "STAGED_APK_MISSING",
+ "Verified staged APK missing or unsafe: " + entry.apkFileName()
+ );
+ }
+ Intent bindIntent = new Intent(SandboxedPlayPolicy.INSTALLER_ACTION)
+ .setPackage(SandboxedPlayPolicy.INSTALLER_PACKAGE);
+ CountDownLatch connected = new CountDownLatch(1);
+ AtomicReference binderRef = new AtomicReference<>();
+ ServiceConnection connection = new ServiceConnection() {
+ @Override public void onServiceConnected(ComponentName name, IBinder service) {
+ binderRef.set(service);
+ connected.countDown();
+ }
+
+ @Override public void onServiceDisconnected(ComponentName name) {
+ binderRef.set(null);
+ }
+ };
+ boolean bound = false;
+ try {
+ bound = context.bindService(bindIntent, connection, Context.BIND_AUTO_CREATE);
+ if (!bound) {
+ return SandboxedPlayPolicy.ValidationOutcome.fail(
+ "INSTALLER_BIND_REFUSED",
+ "Unable to bind AlphaPlayInstaller service"
+ );
+ }
+ if (!connected.await(BIND_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
+ return SandboxedPlayPolicy.ValidationOutcome.fail(
+ "INSTALLER_BIND_TIMEOUT",
+ "Timed out binding AlphaPlayInstaller service"
+ );
+ }
+ IBinder binder = binderRef.get();
+ if (binder == null) {
+ return SandboxedPlayPolicy.ValidationOutcome.fail(
+ "INSTALLER_DISCONNECTED",
+ "AlphaPlayInstaller disconnected before transaction"
+ );
+ }
+ try (ParcelFileDescriptor apkFd = ParcelFileDescriptor.open(
+ stagedApk.toFile(),
+ ParcelFileDescriptor.MODE_READ_ONLY
+ )) {
+ return transactInstall(binder, entry, apkFd);
+ }
+ } catch (InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ return SandboxedPlayPolicy.ValidationOutcome.fail(
+ "INSTALLER_BIND_INTERRUPTED",
+ "Interrupted while binding AlphaPlayInstaller service"
+ );
+ } catch (IOException | RuntimeException error) {
+ return SandboxedPlayPolicy.ValidationOutcome.fail(
+ "INSTALL_DISPATCH_FAILED",
+ error.getMessage() == null ? "Install IPC failed" : error.getMessage()
+ );
+ } finally {
+ if (bound) {
+ try {
+ context.unbindService(connection);
+ } catch (RuntimeException ignored) {
+ }
+ }
+ }
+ }
+
+ @Override public SandboxedPlayPolicy.ValidationOutcome uninstallPackage(String packageName) {
+ try {
+ Intent uninstall = new Intent(Intent.ACTION_DELETE, Uri.parse("package:" + packageName))
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ context.startActivity(uninstall);
+ return SandboxedPlayPolicy.ValidationOutcome.pass();
+ } catch (RuntimeException error) {
+ return SandboxedPlayPolicy.ValidationOutcome.fail(
+ "UNINSTALL_FAILED",
+ error.getMessage() == null ? "Uninstall failed" : error.getMessage()
+ );
+ }
+ }
+ }
+}
diff --git a/apps/app/android/alpha-play-bridge/src/main/java/ai/alphacompute/playbridge/AlphaPlayBridgePlugin.java b/apps/app/android/alpha-play-bridge/src/main/java/ai/alphacompute/playbridge/AlphaPlayBridgePlugin.java
new file mode 100644
index 0000000000..9a9109c5d8
--- /dev/null
+++ b/apps/app/android/alpha-play-bridge/src/main/java/ai/alphacompute/playbridge/AlphaPlayBridgePlugin.java
@@ -0,0 +1,117 @@
+package ai.alphacompute.playbridge;
+
+import android.content.Context;
+import com.getcapacitor.JSObject;
+import com.getcapacitor.Plugin;
+import com.getcapacitor.PluginCall;
+import com.getcapacitor.PluginMethod;
+import com.getcapacitor.annotation.CapacitorPlugin;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * Capacitor plugin exposing Sandboxed Google Play status, fail-closed GSF -> GMS -> Play Store
+ * installation, and user-app removal to the Alpha app.
+ */
+@CapacitorPlugin(name = "AlphaPlayBridge")
+public final class AlphaPlayBridgePlugin extends Plugin {
+ private final ExecutorService executor = Executors.newSingleThreadExecutor(task -> {
+ Thread thread = new Thread(task, "AlphaPlayBridgePlugin");
+ thread.setDaemon(true);
+ return thread;
+ });
+
+ @Override protected void handleOnDestroy() {
+ executor.shutdownNow();
+ super.handleOnDestroy();
+ }
+
+ /** Returns live GmsCompat readiness, package install status, and zero-priv-app audit. */
+ @PluginMethod public void status(PluginCall call) {
+ dispatch(call, "status", call.getData());
+ }
+
+ /** Verifies a Sandboxed Google Play release manifest and sandbox preconditions. */
+ @PluginMethod public void verifyRelease(PluginCall call) {
+ dispatch(call, "verifyRelease", call.getData());
+ }
+
+ /** Installs one verified Google package in strict GSF -> GMS -> Play Store order. */
+ @PluginMethod public void installPackage(PluginCall call) {
+ dispatch(call, "installPackage", call.getData());
+ }
+
+ /** Triggers 1-tap verified GSF -> GMS -> Play Store installation with progress notifications. */
+ @PluginMethod public void installSuite(PluginCall call) {
+ executor.execute(() -> {
+ try {
+ Context context = getContext();
+ if (context == null) {
+ call.reject("Android context unavailable", "CONTEXT_UNAVAILABLE");
+ return;
+ }
+ JSONObject params = call.getData() == null ? new JSONObject() : call.getData();
+ JSONObject manifest = params.has("manifest") ? params.optJSONObject("manifest") : params;
+ AlphaPlayBridge bridge = new AlphaPlayBridge(context);
+ JSONObject result = bridge.installSuite(manifest, this::emitProgress);
+ call.resolve(JSObject.fromJSONObject(result));
+ } catch (JSONException error) {
+ call.reject(error.getMessage() == null ? "Play install failed" : error.getMessage(), "PLAY_BRIDGE_ERROR");
+ }
+ });
+ }
+
+ /** Removes sandboxed Google Play user apps in reverse dependency order. */
+ @PluginMethod public void uninstallSuite(PluginCall call) {
+ dispatch(call, "uninstallSuite", call.getData());
+ }
+
+ /** Headless dispatch entry point for Alpha broker callers without an active WebView. */
+ public static JSONObject invoke(Context context, String method, JSONObject params) throws JSONException {
+ JSONObject input = params == null ? new JSONObject() : params;
+ AlphaPlayBridge bridge = new AlphaPlayBridge(context);
+ return switch (method) {
+ case "status" -> bridge.statusJson();
+ case "verifyRelease" -> bridge.verifyRelease(input.has("manifest") ? input.optJSONObject("manifest") : input);
+ case "installPackage" -> bridge.installPackage(
+ input.optString("packageName", ""),
+ input.optJSONObject("manifest")
+ );
+ case "installSuite" -> bridge.installSuite(
+ input.has("manifest") ? input.optJSONObject("manifest") : input,
+ null
+ );
+ case "uninstallSuite" -> bridge.uninstallSuite();
+ default -> new JSONObject()
+ .put("ok", false)
+ .put("failureCode", "UNKNOWN_METHOD")
+ .put("failureMessage", "Unsupported AlphaPlayBridge method: " + method);
+ };
+ }
+
+ private void dispatch(PluginCall call, String method, JSONObject params) {
+ executor.execute(() -> {
+ try {
+ Context context = getContext();
+ if (context == null) {
+ call.reject("Android context unavailable", "CONTEXT_UNAVAILABLE");
+ return;
+ }
+ JSONObject result = invoke(context, method, params);
+ call.resolve(JSObject.fromJSONObject(result));
+ } catch (JSONException error) {
+ call.reject(error.getMessage() == null ? "Play bridge failed" : error.getMessage(), "PLAY_BRIDGE_ERROR");
+ }
+ });
+ }
+
+ private void emitProgress(String phase, String packageName, String failureCode) {
+ JSObject payload = new JSObject();
+ payload.put("phase", phase);
+ payload.put("packageName", packageName);
+ payload.put("failureCode", failureCode);
+ notifyListeners("installProgress", payload);
+ }
+}
diff --git a/apps/app/android/alpha-play-bridge/src/main/java/ai/alphacompute/playbridge/SandboxedPlayPolicy.java b/apps/app/android/alpha-play-bridge/src/main/java/ai/alphacompute/playbridge/SandboxedPlayPolicy.java
new file mode 100644
index 0000000000..f1ced39e9b
--- /dev/null
+++ b/apps/app/android/alpha-play-bridge/src/main/java/ai/alphacompute/playbridge/SandboxedPlayPolicy.java
@@ -0,0 +1,425 @@
+package ai.alphacompute.playbridge;
+
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+import java.util.regex.Pattern;
+
+/**
+ * Pure JVM fail-closed policy verifier for Sandboxed Google Play matching
+ * {@code apps/app/aosp/sandboxed-play/gmscompat-pin.json} and {@code PlayPackageVerifier}.
+ */
+public final class SandboxedPlayPolicy {
+ /** Official Google LLC APK signing certificate SHA-256 for GSF, GMS, and Play Store. */
+ public static final String OFFICIAL_GOOGLE_SIGNER_SHA256 =
+ "f0fd6c5b410f25cb25c3b53346c8972fae30f8ee7411df910480ad6b2d60db83";
+
+ /** Package ID for GrapheneOS GmsCompat runtime. */
+ public static final String GMS_COMPAT_PACKAGE = "app.grapheneos.gmscompat";
+
+ /** Package ID for Alpha's privileged unprivileged-session Play installer service. */
+ public static final String INSTALLER_PACKAGE = "ai.alphacompute.playinstaller";
+
+ /** Bound service action exposed by {@code AlphaPlayInstallerService}. */
+ public static final String INSTALLER_ACTION =
+ "ai.alphacompute.playinstaller.ACTION_INSTALL_SANDBOXED_PLAY";
+
+ /** Package ID for Google Services Framework. */
+ public static final String PACKAGE_GSF = "com.google.android.gsf";
+
+ /** Package ID for Google Play Services. */
+ public static final String PACKAGE_GMS = "com.google.android.gms";
+
+ /** Package ID for Google Play Store. */
+ public static final String PACKAGE_VENDING = "com.android.vending";
+
+ /** Strict dependency-ordered install sequence. */
+ public static final List REQUIRED_INSTALL_ORDER = List.of(
+ PACKAGE_GSF,
+ PACKAGE_GMS,
+ PACKAGE_VENDING
+ );
+
+ /** Strict reverse dependency order for removing sandboxed Google packages. */
+ public static final List REQUIRED_UNINSTALL_ORDER = List.of(
+ PACKAGE_VENDING,
+ PACKAGE_GMS,
+ PACKAGE_GSF
+ );
+
+ /** Supported release manifest schema version. */
+ public static final int SUPPORTED_SCHEMA_VERSION = 1;
+
+ private static final Pattern HEX_SHA256 = Pattern.compile("^[0-9a-f]{64}$");
+ private static final Pattern SAFE_APK_FILENAME = Pattern.compile("^[A-Za-z0-9._-]+\\.apk$");
+ private static final long MAX_SINGLE_APK_BYTES = 512L * 1024L * 1024L;
+
+ private SandboxedPlayPolicy() {}
+
+ /** Observed package facts for one Google Play component on the device. */
+ public record PackageInspection(
+ String packageName,
+ boolean installed,
+ long versionCode,
+ String sourceDir,
+ boolean systemApp,
+ boolean updatedSystemApp,
+ boolean privilegedApp,
+ boolean hasMultipleSigners,
+ List signerSha256s
+ ) {
+ /** Returns a clean absent package snapshot. */
+ public static PackageInspection absent(String packageName) {
+ return new PackageInspection(
+ packageName,
+ false,
+ 0L,
+ "",
+ false,
+ false,
+ false,
+ false,
+ Collections.emptyList()
+ );
+ }
+
+ /** Returns true when this package lives strictly inside {@code /data/app/} with zero system or privileged flags. */
+ public boolean isSandboxedUserApp() {
+ if (!installed) return true;
+ return isSandboxedLocation(sourceDir) && !systemApp && !updatedSystemApp && !privilegedApp;
+ }
+
+ /** Returns true when this package carries a single signer matching Google's pinned release certificate. */
+ public boolean hasOfficialGoogleSigner() {
+ if (!installed) return true;
+ if (hasMultipleSigners || signerSha256s == null || signerSha256s.size() != 1) {
+ return false;
+ }
+ return constantTimeHexEquals(OFFICIAL_GOOGLE_SIGNER_SHA256, signerSha256s.get(0));
+ }
+
+ /** Returns 1 when installed with privileged or system grants, else 0. */
+ public int privilegedGrantCount() {
+ if (!installed) return 0;
+ return (systemApp || updatedSystemApp || privilegedApp) ? 1 : 0;
+ }
+ }
+
+ /** Aggregated sandbox audit across GmsCompat, AlphaPlayInstaller, and all three Google packages. */
+ public record SandboxAudit(
+ String phase,
+ boolean gmsCompatReady,
+ boolean gmsCompatPresent,
+ boolean installerPresent,
+ PackageInspection gsf,
+ PackageInspection gms,
+ PackageInspection store,
+ int googlePrivAppGrants,
+ boolean sandboxedInDataApp,
+ boolean signersVerified,
+ String failureCode,
+ String failureMessage
+ ) {}
+
+ /** Single package descriptor inside a Sandboxed Google Play release manifest. */
+ public record ManifestPackageSpec(
+ String packageName,
+ long versionCode,
+ String apkFileName,
+ String apkSha256,
+ String signerSha256,
+ long sizeBytes
+ ) {}
+
+ /** Release manifest describing the verified GSF, GMS, and Play Store APKs. */
+ public record InstallManifestSpec(
+ int schemaVersion,
+ String channel,
+ long releaseTimestampEpochSec,
+ List entries
+ ) {}
+
+ /** Machine-readable verification outcome. */
+ public record ValidationOutcome(boolean ok, String failureCode, String message) {
+ /** Returns a passing outcome. */
+ public static ValidationOutcome pass() {
+ return new ValidationOutcome(true, "", "ok");
+ }
+
+ /** Returns a failing outcome with a stable code. */
+ public static ValidationOutcome fail(String failureCode, String message) {
+ return new ValidationOutcome(false, failureCode, message);
+ }
+ }
+
+ /** Returns true only when {@code sourceDir} points into the unprivileged {@code /data/app/} partition. */
+ public static boolean isSandboxedLocation(String sourceDir) {
+ return sourceDir != null
+ && sourceDir.startsWith("/data/app/")
+ && !sourceDir.contains("..");
+ }
+
+ /** Computes a fail-closed sandbox audit across GmsCompat, installer, and all three Google packages. */
+ public static SandboxAudit auditSandbox(
+ boolean gmsCompatPresent,
+ boolean installerPresent,
+ PackageInspection gsf,
+ PackageInspection gms,
+ PackageInspection store
+ ) {
+ PackageInspection safeGsf = gsf == null ? PackageInspection.absent(PACKAGE_GSF) : gsf;
+ PackageInspection safeGms = gms == null ? PackageInspection.absent(PACKAGE_GMS) : gms;
+ PackageInspection safeStore = store == null ? PackageInspection.absent(PACKAGE_VENDING) : store;
+ boolean gmsCompatReady = gmsCompatPresent && installerPresent;
+
+ int privGrants = safeGsf.privilegedGrantCount()
+ + safeGms.privilegedGrantCount()
+ + safeStore.privilegedGrantCount();
+ boolean allInDataApp = safeGsf.isSandboxedUserApp()
+ && safeGms.isSandboxedUserApp()
+ && safeStore.isSandboxedUserApp();
+ boolean signersOk = safeGsf.hasOfficialGoogleSigner()
+ && safeGms.hasOfficialGoogleSigner()
+ && safeStore.hasOfficialGoogleSigner();
+
+ if (privGrants > 0) {
+ return new SandboxAudit(
+ "failed",
+ gmsCompatReady,
+ gmsCompatPresent,
+ installerPresent,
+ safeGsf,
+ safeGms,
+ safeStore,
+ privGrants,
+ false,
+ signersOk,
+ "PRIVILEGED_GRANT_DETECTED",
+ "Google packages must hold zero privileged or system grants"
+ );
+ }
+ if (!allInDataApp) {
+ return new SandboxAudit(
+ "failed",
+ gmsCompatReady,
+ gmsCompatPresent,
+ installerPresent,
+ safeGsf,
+ safeGms,
+ safeStore,
+ 0,
+ false,
+ signersOk,
+ "UNSANDBOXED_PARTITION",
+ "Google packages must reside strictly inside /data/app"
+ );
+ }
+ if (!signersOk) {
+ return new SandboxAudit(
+ "failed",
+ gmsCompatReady,
+ gmsCompatPresent,
+ installerPresent,
+ safeGsf,
+ safeGms,
+ safeStore,
+ 0,
+ true,
+ false,
+ "SIGNING_CERT_MISMATCH",
+ "Installed Google package does not match pinned official Google certificate"
+ );
+ }
+ if ((safeGms.installed() && !safeGsf.installed()) || (safeStore.installed() && !safeGms.installed())) {
+ return new SandboxAudit(
+ "failed",
+ gmsCompatReady,
+ gmsCompatPresent,
+ installerPresent,
+ safeGsf,
+ safeGms,
+ safeStore,
+ 0,
+ true,
+ true,
+ "INVALID_INSTALL_ORDER",
+ "Installed Google Play components violate GSF -> GMS -> Play Store dependency order"
+ );
+ }
+ if (gmsCompatReady && safeGsf.installed() && safeGms.installed() && safeStore.installed()) {
+ return new SandboxAudit(
+ "installed",
+ true,
+ gmsCompatPresent,
+ installerPresent,
+ safeGsf,
+ safeGms,
+ safeStore,
+ 0,
+ true,
+ true,
+ "",
+ ""
+ );
+ }
+ String code = gmsCompatReady ? "" : (!gmsCompatPresent ? "GMS_COMPAT_MISSING" : "INSTALLER_MISSING");
+ String msg = gmsCompatReady
+ ? ""
+ : (!gmsCompatPresent ? "GrapheneOS GmsCompat runtime is not present on this OS build" : "AlphaPlayInstaller system service is unavailable");
+ return new SandboxAudit(
+ "idle",
+ gmsCompatReady,
+ gmsCompatPresent,
+ installerPresent,
+ safeGsf,
+ safeGms,
+ safeStore,
+ 0,
+ true,
+ true,
+ code,
+ msg
+ );
+ }
+
+ /** Validates a release manifest for schema, strict GSF -> GMS -> Play Store ordering, safe filenames, and Google signer pin. */
+ public static ValidationOutcome validateManifest(InstallManifestSpec manifest) {
+ if (manifest == null) {
+ return ValidationOutcome.fail("NULL_MANIFEST", "Manifest is required");
+ }
+ if (manifest.schemaVersion() != SUPPORTED_SCHEMA_VERSION) {
+ return ValidationOutcome.fail("UNSUPPORTED_SCHEMA", "Expected schemaVersion " + SUPPORTED_SCHEMA_VERSION);
+ }
+ if (manifest.channel() == null || manifest.channel().isBlank()) {
+ return ValidationOutcome.fail("INVALID_CHANNEL", "Release channel must be non-empty");
+ }
+ if (manifest.releaseTimestampEpochSec() <= 0L) {
+ return ValidationOutcome.fail("INVALID_TIMESTAMP", "Release timestamp must be positive");
+ }
+ List entries = manifest.entries();
+ if (entries == null || entries.size() != REQUIRED_INSTALL_ORDER.size()) {
+ return ValidationOutcome.fail("INVALID_ENTRY_COUNT", "Manifest must declare GSF, GMS, and Play Store");
+ }
+ List declaredOrder = new ArrayList<>(entries.size());
+ Set seen = new HashSet<>();
+ for (ManifestPackageSpec entry : entries) {
+ if (entry == null || entry.packageName() == null) {
+ return ValidationOutcome.fail("NULL_ENTRY", "Manifest contains a null entry");
+ }
+ if (!seen.add(entry.packageName())) {
+ return ValidationOutcome.fail("DUPLICATE_PACKAGE", "Duplicate package entry: " + entry.packageName());
+ }
+ ValidationOutcome entryOutcome = validateEntry(entry);
+ if (!entryOutcome.ok()) {
+ return entryOutcome;
+ }
+ declaredOrder.add(entry.packageName());
+ }
+ if (!REQUIRED_INSTALL_ORDER.equals(declaredOrder)) {
+ return ValidationOutcome.fail("INVALID_INSTALL_ORDER", "Install order must be GSF -> GMS -> Play Store");
+ }
+ return ValidationOutcome.pass();
+ }
+
+ /** Validates prerequisite ordering before staging one Google package. */
+ public static ValidationOutcome validateStepOrder(String targetPackage, Set alreadyInstalled) {
+ if (targetPackage == null || !REQUIRED_INSTALL_ORDER.contains(targetPackage)) {
+ return ValidationOutcome.fail("UNKNOWN_PACKAGE", "Unsupported package: " + targetPackage);
+ }
+ String expected = nextRequiredPackage(alreadyInstalled);
+ if (!targetPackage.equals(expected)) {
+ return ValidationOutcome.fail(
+ "ORDER_INVARIANT_BROKEN",
+ "Expected next package " + expected + ", got " + targetPackage
+ );
+ }
+ return ValidationOutcome.pass();
+ }
+
+ /** Returns the next required package in GSF -> GMS -> Play Store order, or {@code null} when all three are present. */
+ public static String nextRequiredPackage(Set alreadyInstalled) {
+ Set installed = alreadyInstalled == null ? Collections.emptySet() : alreadyInstalled;
+ for (String required : REQUIRED_INSTALL_ORDER) {
+ if (!installed.contains(required)) {
+ return required;
+ }
+ }
+ return null;
+ }
+
+ /** Computes lowercase hexadecimal SHA-256 digest of raw bytes. */
+ public static String sha256Hex(byte[] bytes) {
+ try {
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ byte[] hashed = digest.digest(bytes);
+ StringBuilder out = new StringBuilder(hashed.length * 2);
+ for (byte value : hashed) {
+ out.append(Character.forDigit((value >> 4) & 0xf, 16));
+ out.append(Character.forDigit(value & 0xf, 16));
+ }
+ return out.toString();
+ } catch (NoSuchAlgorithmException impossible) {
+ throw new IllegalStateException("SHA-256 unavailable", impossible);
+ }
+ }
+
+ /** Constant-time equality comparison for lowercase/uppercase hex SHA-256 strings. */
+ public static boolean constantTimeHexEquals(String expectedHex, String actualHex) {
+ byte[] expected = hexToBytes(normalizeHex(expectedHex));
+ byte[] actual = hexToBytes(normalizeHex(actualHex));
+ if (expected == null || actual == null) {
+ return false;
+ }
+ return MessageDigest.isEqual(expected, actual);
+ }
+
+ private static ValidationOutcome validateEntry(ManifestPackageSpec entry) {
+ if (!REQUIRED_INSTALL_ORDER.contains(entry.packageName())) {
+ return ValidationOutcome.fail("UNKNOWN_PACKAGE", "Unknown package: " + entry.packageName());
+ }
+ if (entry.versionCode() <= 0L) {
+ return ValidationOutcome.fail("INVALID_VERSION", "versionCode must be positive");
+ }
+ if (entry.apkFileName() == null
+ || entry.apkFileName().contains("..")
+ || !SAFE_APK_FILENAME.matcher(entry.apkFileName()).matches()) {
+ return ValidationOutcome.fail("UNSAFE_FILENAME", "Unsafe APK filename: " + entry.apkFileName());
+ }
+ if (entry.sizeBytes() <= 0L || entry.sizeBytes() > MAX_SINGLE_APK_BYTES) {
+ return ValidationOutcome.fail("INVALID_SIZE", "APK size outside bounds");
+ }
+ if (!HEX_SHA256.matcher(normalizeHex(entry.apkSha256())).matches()) {
+ return ValidationOutcome.fail("INVALID_APK_SHA256", "Malformed APK SHA-256");
+ }
+ String signer = normalizeHex(entry.signerSha256());
+ if (!HEX_SHA256.matcher(signer).matches() || !constantTimeHexEquals(OFFICIAL_GOOGLE_SIGNER_SHA256, signer)) {
+ return ValidationOutcome.fail("UNTRUSTED_MANIFEST_SIGNER", "Manifest signer must match pinned Google certificate");
+ }
+ return ValidationOutcome.pass();
+ }
+
+ private static String normalizeHex(String raw) {
+ return raw == null ? "" : raw.trim().toLowerCase(Locale.ROOT);
+ }
+
+ private static byte[] hexToBytes(String hex) {
+ if (hex == null || hex.length() != 64) {
+ return null;
+ }
+ byte[] out = new byte[32];
+ for (int i = 0; i < 32; i++) {
+ int hi = Character.digit(hex.charAt(i * 2), 16);
+ int lo = Character.digit(hex.charAt(i * 2 + 1), 16);
+ if (hi < 0 || lo < 0) {
+ return null;
+ }
+ out[i] = (byte) ((hi << 4) | lo);
+ }
+ return out;
+ }
+}
diff --git a/apps/app/android/alpha-play-bridge/src/test/java/ai/alphacompute/playbridge/AlphaPlayBridgeTest.java b/apps/app/android/alpha-play-bridge/src/test/java/ai/alphacompute/playbridge/AlphaPlayBridgeTest.java
new file mode 100644
index 0000000000..ab23cb5c32
--- /dev/null
+++ b/apps/app/android/alpha-play-bridge/src/test/java/ai/alphacompute/playbridge/AlphaPlayBridgeTest.java
@@ -0,0 +1,295 @@
+// spec/app/playStore/index.md, "Story: Enforce zero privileged Google grants and strict dependency order"
+package ai.alphacompute.playbridge;
+
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.json.JSONArray;
+import org.json.JSONObject;
+import org.junit.Test;
+
+/** Pure JVM JUnit tests verifying Sandboxed Google Play bridge ordering, signer pinning, and zero-priv-app isolation. */
+public final class AlphaPlayBridgeTest {
+ private static final String GOOGLE_CERT = SandboxedPlayPolicy.OFFICIAL_GOOGLE_SIGNER_SHA256;
+ private static final String FAKE_CERT = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
+ private static final String SHA_GSF = "1111111111111111111111111111111111111111111111111111111111111111";
+ private static final String SHA_GMS = "2222222222222222222222222222222222222222222222222222222222222222";
+ private static final String SHA_STORE = "3333333333333333333333333333333333333333333333333333333333333333";
+
+ private static void check(boolean condition, String message) {
+ if (!condition) {
+ throw new AssertionError(message);
+ }
+ }
+
+ private static JSONObject validManifestJson() throws Exception {
+ return new JSONObject()
+ .put("schemaVersion", 1)
+ .put("channel", "stable")
+ .put("releaseTimestampEpochSec", 1790000000L)
+ .put("entries", new JSONArray()
+ .put(new JSONObject()
+ .put("packageName", SandboxedPlayPolicy.PACKAGE_GSF)
+ .put("versionCode", 37L)
+ .put("apkFileName", "gsf-37.apk")
+ .put("apkSha256", SHA_GSF)
+ .put("signerSha256", GOOGLE_CERT)
+ .put("sizeBytes", 4_194_304L))
+ .put(new JSONObject()
+ .put("packageName", SandboxedPlayPolicy.PACKAGE_GMS)
+ .put("versionCode", 2520L)
+ .put("apkFileName", "gms-2520.apk")
+ .put("apkSha256", SHA_GMS)
+ .put("signerSha256", GOOGLE_CERT)
+ .put("sizeBytes", 64_000_000L))
+ .put(new JSONObject()
+ .put("packageName", SandboxedPlayPolicy.PACKAGE_VENDING)
+ .put("versionCode", 4600L)
+ .put("apkFileName", "vending-4600.apk")
+ .put("apkSha256", SHA_STORE)
+ .put("signerSha256", GOOGLE_CERT)
+ .put("sizeBytes", 32_000_000L)));
+ }
+
+ private static final class FakeDevice {
+ boolean gmsCompatPresent = true;
+ boolean installerPresent = true;
+ boolean failVerify = false;
+ String failPackage = "";
+ boolean injectPrivGrantOnGms = false;
+ SandboxedPlayPolicy.InstallManifestSpec stagedManifest = null;
+ final Map installed = new HashMap<>();
+ final List installCalls = new ArrayList<>();
+ final List uninstallCalls = new ArrayList<>();
+
+ AlphaPlayBridge createBridge() {
+ AlphaPlayBridge.PackageInspector inspector = new AlphaPlayBridge.PackageInspector() {
+ @Override public boolean isGmsCompatPresent() {
+ return gmsCompatPresent;
+ }
+
+ @Override public boolean isInstallerServicePresent() {
+ return installerPresent;
+ }
+
+ @Override public SandboxedPlayPolicy.PackageInspection inspect(String packageName) {
+ return installed.getOrDefault(packageName, SandboxedPlayPolicy.PackageInspection.absent(packageName));
+ }
+ };
+ AlphaPlayBridge.InstallerGateway gateway = new AlphaPlayBridge.InstallerGateway() {
+ @Override public SandboxedPlayPolicy.InstallManifestSpec loadStagedManifest() {
+ return stagedManifest;
+ }
+
+ @Override public SandboxedPlayPolicy.ValidationOutcome verifyRelease(
+ SandboxedPlayPolicy.InstallManifestSpec manifest
+ ) {
+ if (failVerify) {
+ return SandboxedPlayPolicy.ValidationOutcome.fail("MANIFEST_SIGNATURE_INVALID", "Signature rejected");
+ }
+ return SandboxedPlayPolicy.ValidationOutcome.pass();
+ }
+
+ @Override public SandboxedPlayPolicy.ValidationOutcome installPackage(
+ SandboxedPlayPolicy.ManifestPackageSpec entry
+ ) {
+ installCalls.add(entry.packageName());
+ if (entry.packageName().equals(failPackage)) {
+ return SandboxedPlayPolicy.ValidationOutcome.fail("INSTALL_SESSION_FAILED", "Simulated session failure");
+ }
+ boolean privileged = injectPrivGrantOnGms && SandboxedPlayPolicy.PACKAGE_GMS.equals(entry.packageName());
+ installed.put(entry.packageName(), new SandboxedPlayPolicy.PackageInspection(
+ entry.packageName(),
+ true,
+ entry.versionCode(),
+ privileged ? "/system/priv-app/" + entry.apkFileName() : "/data/app/~~sandbox/" + entry.apkFileName(),
+ privileged,
+ false,
+ privileged,
+ false,
+ List.of(GOOGLE_CERT)
+ ));
+ return SandboxedPlayPolicy.ValidationOutcome.pass();
+ }
+
+ @Override public SandboxedPlayPolicy.ValidationOutcome uninstallPackage(String packageName) {
+ uninstallCalls.add(packageName);
+ installed.remove(packageName);
+ return SandboxedPlayPolicy.ValidationOutcome.pass();
+ }
+ };
+ return new AlphaPlayBridge(inspector, gateway);
+ }
+ }
+
+ /** Verifies 1-tap happy path installs strictly in GSF -> GMS -> Play Store order and uninstalls in reverse. */
+ @Test
+ public void testVerifiedInstallOrderAndReverseUninstall() throws Exception {
+ FakeDevice device = new FakeDevice();
+ AlphaPlayBridge bridge = device.createBridge();
+
+ JSONObject initial = bridge.statusJson();
+ check("idle".equals(initial.getString("phase")), "initial status is idle");
+ check(initial.getBoolean("gmsCompatReady"), "GmsCompat + installer ready");
+ check(initial.getInt("googlePrivAppGrants") == 0, "zero priv-app grants initially");
+
+ List phases = new ArrayList<>();
+ JSONObject result = bridge.installSuite(validManifestJson(), (phase, pkg, code) -> phases.add(phase));
+ check(result.getBoolean("ok"), "valid install succeeds");
+ check("installed".equals(result.getString("phase")), "final phase is installed");
+ check(result.getInt("googlePrivAppGrants") == 0, "zero priv-app grants after install");
+ check(result.getBoolean("sandboxedInDataApp"), "all packages reside in /data/app");
+ check(
+ List.of("verifying", "installing_gsf", "installing_gms", "installing_store", "installed").equals(phases),
+ "exact state transitions emitted: " + phases
+ );
+ check(
+ SandboxedPlayPolicy.REQUIRED_INSTALL_ORDER.equals(device.installCalls),
+ "packages installed strictly in GSF -> GMS -> Play Store order"
+ );
+
+ JSONObject removed = bridge.uninstallSuite();
+ check(removed.getBoolean("ok"), "uninstall succeeds");
+ check("idle".equals(removed.getString("phase")), "phase returns to idle after uninstall");
+ check(
+ SandboxedPlayPolicy.REQUIRED_UNINSTALL_ORDER.equals(device.uninstallCalls),
+ "uninstall runs strictly in Play Store -> GMS -> GSF order"
+ );
+ }
+
+ /** Verifies fail-closed rejection on wrong manifest order, untrusted signer, path traversal, and missing GmsCompat. */
+ @Test
+ public void testFailClosedManifestAndEnvironmentChecks() throws Exception {
+ FakeDevice device = new FakeDevice();
+ AlphaPlayBridge bridge = device.createBridge();
+
+ JSONObject swapped = validManifestJson();
+ JSONArray entries = swapped.getJSONArray("entries");
+ JSONObject first = entries.getJSONObject(0);
+ JSONObject second = entries.getJSONObject(1);
+ entries.put(0, second);
+ entries.put(1, first);
+ JSONObject wrongOrder = bridge.installSuite(swapped, null);
+ check(!wrongOrder.getBoolean("ok"), "GMS before GSF rejected");
+ check("INVALID_INSTALL_ORDER".equals(wrongOrder.getString("failureCode")), "wrong order code");
+ check(device.installCalls.isEmpty(), "zero packages installed when manifest order invalid");
+
+ JSONObject badSigner = validManifestJson();
+ badSigner.getJSONArray("entries").getJSONObject(0).put("signerSha256", FAKE_CERT);
+ JSONObject signerRejected = bridge.installSuite(badSigner, null);
+ check(!signerRejected.getBoolean("ok"), "untrusted signer rejected");
+ check("UNTRUSTED_MANIFEST_SIGNER".equals(signerRejected.getString("failureCode")), "signer failure code");
+
+ JSONObject traversal = validManifestJson();
+ traversal.getJSONArray("entries").getJSONObject(0).put("apkFileName", "../evil.apk");
+ JSONObject traversalRejected = bridge.installSuite(traversal, null);
+ check(!traversalRejected.getBoolean("ok"), "path traversal rejected");
+ check("UNSAFE_FILENAME".equals(traversalRejected.getString("failureCode")), "unsafe filename code");
+
+ JSONObject outOfOrderSingle = bridge.installPackage(SandboxedPlayPolicy.PACKAGE_VENDING, validManifestJson());
+ check(!outOfOrderSingle.getBoolean("ok"), "direct Play Store install before GSF rejected");
+ check("ORDER_INVARIANT_BROKEN".equals(outOfOrderSingle.getString("failureCode")), "step order invariant code");
+
+ device.gmsCompatPresent = false;
+ JSONObject noCompat = bridge.installSuite(validManifestJson(), null);
+ check(!noCompat.getBoolean("ok"), "missing GmsCompat fails closed");
+ check("GMS_COMPAT_MISSING".equals(noCompat.getString("failureCode")), "GMS_COMPAT_MISSING code");
+ }
+
+ /** Verifies mid-install failure and privileged-grant detection halt immediately without advancing to Play Store. */
+ @Test
+ public void testMidInstallFailureAndPrivilegedGrantRefusal() throws Exception {
+ FakeDevice failMid = new FakeDevice();
+ failMid.failPackage = SandboxedPlayPolicy.PACKAGE_GMS;
+ AlphaPlayBridge failBridge = failMid.createBridge();
+ JSONObject midResult = failBridge.installSuite(validManifestJson(), null);
+ check(!midResult.getBoolean("ok"), "GMS failure halts suite");
+ check(
+ List.of(SandboxedPlayPolicy.PACKAGE_GSF, SandboxedPlayPolicy.PACKAGE_GMS).equals(failMid.installCalls),
+ "Play Store never attempted after GMS failure"
+ );
+
+ FakeDevice privDevice = new FakeDevice();
+ privDevice.injectPrivGrantOnGms = true;
+ AlphaPlayBridge privBridge = privDevice.createBridge();
+ JSONObject privResult = privBridge.installSuite(validManifestJson(), null);
+ check(!privResult.getBoolean("ok"), "privileged Google grant fails closed");
+ check("PRIVILEGED_GRANT_DETECTED".equals(privResult.getString("failureCode")), "priv-app failure code");
+ check(privResult.getInt("googlePrivAppGrants") == 1, "priv grant count reported");
+ check(
+ List.of(SandboxedPlayPolicy.PACKAGE_GSF, SandboxedPlayPolicy.PACKAGE_GMS).equals(privDevice.installCalls),
+ "Play Store blocked once privileged grant detected"
+ );
+
+ JSONObject refusedUninstall = privBridge.uninstallSuite();
+ check(!refusedUninstall.getBoolean("ok"), "refuses uninstalling privileged system Google packages");
+ check("PRIVILEGED_GRANT_DETECTED".equals(refusedUninstall.getString("failureCode")), "uninstall refusal code");
+ }
+
+ /** Verifies empty-parameter plugin calls resolve staged manifests and fail closed when none is staged. */
+ @Test
+ public void testStagedManifestFallbackFailsClosedWhenAbsent() throws Exception {
+ FakeDevice device = new FakeDevice();
+ AlphaPlayBridge bridge = device.createBridge();
+
+ JSONObject missing = bridge.verifyRelease(new JSONObject());
+ check(!missing.getBoolean("ok"), "absent staged manifest fails closed");
+ check("NULL_MANIFEST".equals(missing.getString("failureCode")), "NULL_MANIFEST when absent");
+
+ device.stagedManifest = AlphaPlayBridge.parseManifest(validManifestJson());
+ JSONObject verified = bridge.verifyRelease(new JSONObject());
+ check(verified.getBoolean("ok"), "staged manifest resolves and verifies cleanly");
+
+ JSONObject gsfStep = bridge.installPackage(SandboxedPlayPolicy.PACKAGE_GSF, null);
+ check(gsfStep.getBoolean("ok"), "stepwise GSF install resolves staged manifest");
+ check(List.of(SandboxedPlayPolicy.PACKAGE_GSF).equals(device.installCalls), "GSF installed via staged manifest");
+ }
+
+ /** Verifies staged APK path containment refuses missing files, path escapes, and symlinks, and IPC metadata matches service. */
+ @Test
+ public void testStagedApkPathContainmentAndIpcContract() throws Exception {
+ check(
+ "ai.alphacompute.playinstaller.IAlphaPlayInstaller".equals(AlphaPlayBridge.INSTALLER_BINDER_DESCRIPTOR),
+ "IPC descriptor must match AlphaPlayInstallerService.BINDER_DESCRIPTOR"
+ );
+ check(
+ AlphaPlayBridge.TRANSACTION_INSTALL_PACKAGE == android.os.IBinder.FIRST_CALL_TRANSACTION,
+ "IPC transaction code must match AlphaPlayInstallerService.TRANSACTION_INSTALL_PACKAGE"
+ );
+
+ Path staging = Files.createTempDirectory("alpha-play-bridge-stage-");
+ Path outside = Files.createTempFile("alpha-play-outside-", ".apk");
+ try {
+ Path validApk = staging.resolve("gsf-37.apk");
+ Files.write(validApk, "staged-gsf".getBytes(StandardCharsets.UTF_8));
+ Path resolved = AlphaPlayBridge.resolveStagedApkPath(staging, "gsf-37.apk");
+ check(validApk.toAbsolutePath().normalize().equals(resolved), "regular staged APK resolves cleanly");
+ check(AlphaPlayBridge.resolveStagedApkPath(staging, "missing.apk") == null, "missing APK fails closed");
+ check(AlphaPlayBridge.resolveStagedApkPath(staging, "../evil.apk") == null, "path traversal fails closed");
+ check(AlphaPlayBridge.resolveStagedApkPath(staging, "/etc/passwd") == null, "absolute path fails closed");
+
+ Path symlinkApk = staging.resolve("link.apk");
+ Files.createSymbolicLink(symlinkApk, outside);
+ check(AlphaPlayBridge.resolveStagedApkPath(staging, "link.apk") == null, "symlink APK fails closed");
+ } finally {
+ Files.deleteIfExists(staging.resolve("link.apk"));
+ Files.deleteIfExists(staging.resolve("gsf-37.apk"));
+ Files.deleteIfExists(staging);
+ Files.deleteIfExists(outside);
+ }
+ }
+
+ /** Standalone JVM entry point for fast verification without Gradle overhead. */
+ public static void main(String[] args) throws Exception {
+ AlphaPlayBridgeTest suite = new AlphaPlayBridgeTest();
+ suite.testVerifiedInstallOrderAndReverseUninstall();
+ suite.testFailClosedManifestAndEnvironmentChecks();
+ suite.testMidInstallFailureAndPrivilegedGrantRefusal();
+ suite.testStagedManifestFallbackFailsClosedWhenAbsent();
+ suite.testStagedApkPathContainmentAndIpcContract();
+ }
+}
diff --git a/apps/app/android/alpha-theme-bridge/build.gradle b/apps/app/android/alpha-theme-bridge/build.gradle
new file mode 100644
index 0000000000..7936aba59e
--- /dev/null
+++ b/apps/app/android/alpha-theme-bridge/build.gradle
@@ -0,0 +1,27 @@
+apply plugin: 'com.android.library'
+
+android {
+ namespace 'ai.alphacompute.themebridge'
+ compileSdk rootProject.hasProperty('compileSdkVersion') ? rootProject.ext.compileSdkVersion : 36
+
+ defaultConfig {
+ minSdk rootProject.hasProperty('minSdkVersion') ? rootProject.ext.minSdkVersion : 29
+ targetSdk rootProject.hasProperty('targetSdkVersion') ? rootProject.ext.targetSdkVersion : 36
+ consumerProguardFiles 'consumer-rules.pro'
+ }
+
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_17
+ targetCompatibility JavaVersion.VERSION_17
+ }
+
+ testOptions {
+ unitTests.returnDefaultValues = true
+ }
+}
+
+dependencies {
+ implementation project(':capacitor-android')
+ testImplementation "junit:junit:${rootProject.hasProperty('junitVersion') ? rootProject.ext.junitVersion : '4.13.2'}"
+ testImplementation 'org.json:json:20250517'
+}
diff --git a/apps/app/android/alpha-theme-bridge/consumer-rules.pro b/apps/app/android/alpha-theme-bridge/consumer-rules.pro
new file mode 100644
index 0000000000..4395de9dd9
--- /dev/null
+++ b/apps/app/android/alpha-theme-bridge/consumer-rules.pro
@@ -0,0 +1,3 @@
+-keep class ai.alphacompute.themebridge.AlphaThemeBridgePlugin { *; }
+-keep class ai.alphacompute.themebridge.AlphaThemeBridge { *; }
+-keep class ai.alphacompute.themebridge.AlphaThemeCatalog { *; }
diff --git a/apps/app/android/alpha-theme-bridge/src/main/AndroidManifest.xml b/apps/app/android/alpha-theme-bridge/src/main/AndroidManifest.xml
new file mode 100644
index 0000000000..4fded9fc9e
--- /dev/null
+++ b/apps/app/android/alpha-theme-bridge/src/main/AndroidManifest.xml
@@ -0,0 +1,32 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/apps/app/android/alpha-theme-bridge/src/main/java/ai/alphacompute/themebridge/AlphaThemeBridge.java b/apps/app/android/alpha-theme-bridge/src/main/java/ai/alphacompute/themebridge/AlphaThemeBridge.java
new file mode 100644
index 0000000000..724ae26d00
--- /dev/null
+++ b/apps/app/android/alpha-theme-bridge/src/main/java/ai/alphacompute/themebridge/AlphaThemeBridge.java
@@ -0,0 +1,303 @@
+package ai.alphacompute.themebridge;
+
+import android.app.UiModeManager;
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.os.Process;
+import android.os.UserHandle;
+import android.provider.Settings;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * Atomic full-OS theme pack and navigation policy switcher backed by Android {@code OverlayManager}.
+ * Rolls back previously enabled overlays if any RRO activation fails so SystemUI, Launcher3,
+ * Settings, and framework-res never end up in a mixed state.
+ */
+public final class AlphaThemeBridge {
+ private static final String PREFS_NAME = "alpha_os_theme_bridge";
+ private static final String KEY_THEME_PACK = "active_theme_pack";
+ private static final String KEY_NAV_MODE = "active_nav_mode";
+
+ /** Port wrapping Android {@code OverlayManager} operations for full-OS RRO switching. */
+ public interface OverlayBackend {
+ /** Returns true when the OS supports runtime RRO overlay activation for Alpha themes. */
+ boolean isSupported();
+
+ /** Enables {@code overlayPackage} exclusively in its declared overlay category. */
+ boolean setEnabledExclusiveInCategory(String overlayPackage);
+
+ /** Applies OS dark/light polarity and optional Monet seed palette when permitted. */
+ void applySystemPolarity(boolean dark, String seedHex);
+ }
+
+ /** Persistence port storing active theme pack and navigation mode IDs. */
+ public interface StateStore {
+ /** Reads a persisted string value or returns {@code fallback}. */
+ String getString(String key, String fallback);
+
+ /** Persists a string value atomically. */
+ void putString(String key, String value);
+ }
+
+ private final OverlayBackend overlays;
+ private final StateStore store;
+
+ /** Constructs a live Android theme bridge over {@code OverlayManager} and {@code SharedPreferences}. */
+ public AlphaThemeBridge(Context context) {
+ Context appContext = context.getApplicationContext();
+ this.overlays = new AndroidOverlayBackend(appContext);
+ this.store = new SharedPrefsStateStore(appContext);
+ }
+
+ /** Constructs a theme bridge with explicit ports for deterministic JVM unit tests. */
+ public AlphaThemeBridge(OverlayBackend overlays, StateStore store) {
+ this.overlays = overlays;
+ this.store = store;
+ }
+
+ /** Returns all six curated theme packs and both navigation modes as JSON. */
+ public JSONObject listThemesJson() throws JSONException {
+ JSONArray packs = new JSONArray();
+ for (AlphaThemeCatalog.ThemePackSpec spec : AlphaThemeCatalog.packs()) {
+ packs.put(new JSONObject()
+ .put("id", spec.id())
+ .put("name", spec.name())
+ .put("scheme", spec.scheme())
+ .put("isDefault", spec.isDefault())
+ .put("seedHex", "#" + spec.seedHex())
+ .put("overlays", new JSONObject()
+ .put("framework", spec.frameworkOverlay())
+ .put("systemui", spec.systemUiOverlay())
+ .put("launcher3", spec.launcher3Overlay())
+ .put("settings", spec.settingsOverlay())));
+ }
+ JSONArray modes = new JSONArray();
+ for (AlphaThemeCatalog.NavModeSpec mode : AlphaThemeCatalog.navModes()) {
+ modes.put(new JSONObject()
+ .put("id", mode.id())
+ .put("name", mode.name())
+ .put("overlayPackage", mode.overlayPackage())
+ .put("homeBackOnly", mode.homeBackOnly())
+ .put("isDefault", mode.isDefault()));
+ }
+ return new JSONObject()
+ .put("defaultThemeId", AlphaThemeCatalog.DEFAULT_THEME_ID)
+ .put("defaultNavModeId", AlphaThemeCatalog.DEFAULT_NAV_MODE_ID)
+ .put("packs", packs)
+ .put("navModes", modes);
+ }
+
+ /** Returns the currently active theme pack, navigation mode, and OS overlay availability. */
+ public JSONObject statusJson() throws JSONException {
+ AlphaThemeCatalog.ThemePackSpec activePack = activeThemePack();
+ AlphaThemeCatalog.NavModeSpec activeNav = activeNavMode();
+ return new JSONObject()
+ .put("ok", true)
+ .put("activeThemeId", activePack.id())
+ .put("activeScheme", activePack.scheme())
+ .put("activeNavModeId", activeNav.id())
+ .put("osOverlaysAvailable", overlays.isSupported());
+ }
+
+ /**
+ * Atomically applies one curated full-OS theme pack across framework, SystemUI, Launcher3,
+ * and Settings RROs. Rolls back all applied overlays if any target fails.
+ */
+ public JSONObject applyTheme(String packId) throws JSONException {
+ AlphaThemeCatalog.ThemePackSpec target = AlphaThemeCatalog.findPack(packId);
+ if (target == null) {
+ return failureJson("UNKNOWN_THEME_PACK", "Unsupported theme pack: " + packId);
+ }
+ AlphaThemeCatalog.ThemePackSpec previous = activeThemePack();
+ if (overlays.isSupported()) {
+ List targetOverlays = target.allOverlayPackages();
+ List previousOverlays = previous.allOverlayPackages();
+ List appliedIndices = new ArrayList<>();
+ for (int idx = 0; idx < targetOverlays.size(); idx++) {
+ String overlayPkg = targetOverlays.get(idx);
+ boolean ok;
+ try {
+ ok = overlays.setEnabledExclusiveInCategory(overlayPkg);
+ } catch (RuntimeException error) {
+ ok = false;
+ }
+ if (!ok) {
+ rollbackOverlays(appliedIndices, previousOverlays);
+ return failureJson(
+ "OVERLAY_APPLY_FAILED",
+ "Failed activating overlay " + overlayPkg + "; rolled back to " + previous.id()
+ );
+ }
+ appliedIndices.add(idx);
+ }
+ try {
+ overlays.applySystemPolarity(target.isDark(), target.seedHex());
+ } catch (RuntimeException ignored) {
+ }
+ }
+ store.putString(KEY_THEME_PACK, target.id());
+ return statusJson();
+ }
+
+ /** Toggles between stock Android Recents gestures and focused Home + Back via mutable Launcher3 RRO. */
+ public JSONObject setNavigationMode(String modeId) throws JSONException {
+ AlphaThemeCatalog.NavModeSpec target = AlphaThemeCatalog.findNavMode(modeId);
+ if (target == null) {
+ return failureJson("UNKNOWN_NAV_MODE", "Unsupported navigation mode: " + modeId);
+ }
+ if (overlays.isSupported()) {
+ boolean ok;
+ try {
+ ok = overlays.setEnabledExclusiveInCategory(target.overlayPackage());
+ } catch (RuntimeException error) {
+ ok = false;
+ }
+ if (!ok) {
+ return failureJson(
+ "NAV_OVERLAY_APPLY_FAILED",
+ "Failed activating navigation overlay " + target.overlayPackage()
+ );
+ }
+ }
+ store.putString(KEY_NAV_MODE, target.id());
+ return statusJson();
+ }
+
+ /** Resets both theme pack and navigation policy back to Ink Dark and Stock Android gestures. */
+ public JSONObject resetDefaults() throws JSONException {
+ JSONObject themeResult = applyTheme(AlphaThemeCatalog.DEFAULT_THEME_ID);
+ if (!themeResult.optBoolean("ok", false)) {
+ return themeResult;
+ }
+ return setNavigationMode(AlphaThemeCatalog.DEFAULT_NAV_MODE_ID);
+ }
+
+ private AlphaThemeCatalog.ThemePackSpec activeThemePack() {
+ String saved = store.getString(KEY_THEME_PACK, AlphaThemeCatalog.DEFAULT_THEME_ID);
+ AlphaThemeCatalog.ThemePackSpec found = AlphaThemeCatalog.findPack(saved);
+ return found != null ? found : AlphaThemeCatalog.findPack(AlphaThemeCatalog.DEFAULT_THEME_ID);
+ }
+
+ private AlphaThemeCatalog.NavModeSpec activeNavMode() {
+ String saved = store.getString(KEY_NAV_MODE, AlphaThemeCatalog.DEFAULT_NAV_MODE_ID);
+ AlphaThemeCatalog.NavModeSpec found = AlphaThemeCatalog.findNavMode(saved);
+ return found != null ? found : AlphaThemeCatalog.findNavMode(AlphaThemeCatalog.DEFAULT_NAV_MODE_ID);
+ }
+
+ private void rollbackOverlays(List appliedIndices, List previousOverlays) {
+ for (int i = appliedIndices.size() - 1; i >= 0; i--) {
+ int idx = appliedIndices.get(i);
+ try {
+ overlays.setEnabledExclusiveInCategory(previousOverlays.get(idx));
+ } catch (RuntimeException ignored) {
+ }
+ }
+ }
+
+ private JSONObject failureJson(String code, String message) throws JSONException {
+ JSONObject status = statusJson();
+ status.put("ok", false);
+ status.put("failureCode", code);
+ status.put("failureMessage", message);
+ return status;
+ }
+
+ private static final class SharedPrefsStateStore implements StateStore {
+ private final SharedPreferences prefs;
+
+ SharedPrefsStateStore(Context context) {
+ this.prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
+ }
+
+ @Override public String getString(String key, String fallback) {
+ String value = prefs.getString(key, fallback);
+ return value == null ? fallback : value;
+ }
+
+ @Override public void putString(String key, String value) {
+ prefs.edit().putString(key, value).apply();
+ }
+ }
+
+ private static final class AndroidOverlayBackend implements OverlayBackend {
+ private final Context context;
+
+ AndroidOverlayBackend(Context context) {
+ this.context = context;
+ }
+
+ @Override public boolean isSupported() {
+ Object manager = resolveOverlayManager();
+ if (manager == null) {
+ return false;
+ }
+ try {
+ Method method = manager.getClass().getMethod("getOverlayInfo", String.class, UserHandle.class);
+ Object info = method.invoke(
+ manager,
+ AlphaThemeCatalog.findPack(AlphaThemeCatalog.DEFAULT_THEME_ID).frameworkOverlay(),
+ Process.myUserHandle()
+ );
+ return info != null;
+ } catch (ReflectiveOperationException | RuntimeException unavailable) {
+ return false;
+ }
+ }
+
+ @Override public boolean setEnabledExclusiveInCategory(String overlayPackage) {
+ Object manager = resolveOverlayManager();
+ if (manager == null) {
+ return false;
+ }
+ try {
+ Method method = manager.getClass().getMethod(
+ "setEnabledExclusiveInCategory",
+ String.class,
+ UserHandle.class
+ );
+ method.invoke(manager, overlayPackage, Process.myUserHandle());
+ return true;
+ } catch (ReflectiveOperationException | RuntimeException error) {
+ return false;
+ }
+ }
+
+ @Override public void applySystemPolarity(boolean dark, String seedHex) {
+ UiModeManager uiMode = context.getSystemService(UiModeManager.class);
+ if (uiMode != null) {
+ try {
+ uiMode.setApplicationNightMode(
+ dark ? UiModeManager.MODE_NIGHT_YES : UiModeManager.MODE_NIGHT_NO
+ );
+ } catch (RuntimeException ignored) {
+ }
+ }
+ try {
+ String payload = "{\"android.theme.customization.system_palette\":\"" + seedHex + "\","
+ + "\"android.theme.customization.accent_color\":\"" + seedHex + "\","
+ + "\"android.theme.customization.theme_style\":\"TONAL_SPOT\","
+ + "\"android.theme.customization.color_source\":\"preset\"}";
+ Settings.Secure.putString(
+ context.getContentResolver(),
+ "theme_customization_overlay_packages",
+ payload
+ );
+ } catch (RuntimeException ignored) {
+ }
+ }
+
+ private Object resolveOverlayManager() {
+ try {
+ Class> omClass = Class.forName("android.content.om.OverlayManager");
+ return context.getSystemService(omClass);
+ } catch (ClassNotFoundException | RuntimeException unavailable) {
+ return null;
+ }
+ }
+ }
+}
diff --git a/apps/app/android/alpha-theme-bridge/src/main/java/ai/alphacompute/themebridge/AlphaThemeBridgePlugin.java b/apps/app/android/alpha-theme-bridge/src/main/java/ai/alphacompute/themebridge/AlphaThemeBridgePlugin.java
new file mode 100644
index 0000000000..63cfd292a5
--- /dev/null
+++ b/apps/app/android/alpha-theme-bridge/src/main/java/ai/alphacompute/themebridge/AlphaThemeBridgePlugin.java
@@ -0,0 +1,88 @@
+package ai.alphacompute.themebridge;
+
+import android.content.Context;
+import com.getcapacitor.JSObject;
+import com.getcapacitor.Plugin;
+import com.getcapacitor.PluginCall;
+import com.getcapacitor.PluginMethod;
+import com.getcapacitor.annotation.CapacitorPlugin;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * Capacitor plugin exposing curated full-OS theme pack switching and toggleable navigation
+ * policy overlays to the Alpha Settings UI.
+ */
+@CapacitorPlugin(name = "AlphaThemeBridge")
+public final class AlphaThemeBridgePlugin extends Plugin {
+ private final ExecutorService executor = Executors.newSingleThreadExecutor(task -> {
+ Thread thread = new Thread(task, "AlphaThemeBridgePlugin");
+ thread.setDaemon(true);
+ return thread;
+ });
+
+ @Override protected void handleOnDestroy() {
+ executor.shutdownNow();
+ super.handleOnDestroy();
+ }
+
+ /** Returns the curated six-pack theme catalog and navigation mode registry. */
+ @PluginMethod public void listThemes(PluginCall call) {
+ dispatch(call, "listThemes", call.getData());
+ }
+
+ /** Returns active theme pack, navigation mode, and OS overlay availability. */
+ @PluginMethod public void getStatus(PluginCall call) {
+ dispatch(call, "getStatus", call.getData());
+ }
+
+ /** Applies one curated full-OS theme pack atomically across all four RRO targets. */
+ @PluginMethod public void applyTheme(PluginCall call) {
+ dispatch(call, "applyTheme", call.getData());
+ }
+
+ /** Switches between stock Android Recents gestures and focused Home + Back. */
+ @PluginMethod public void setNavigationMode(PluginCall call) {
+ dispatch(call, "setNavigationMode", call.getData());
+ }
+
+ /** Resets theme pack and navigation mode to defaults (Ink Dark + Stock Android gestures). */
+ @PluginMethod public void resetTheme(PluginCall call) {
+ dispatch(call, "resetTheme", call.getData());
+ }
+
+ /** Headless dispatch entry point for broker callers without an active WebView. */
+ public static JSONObject invoke(Context context, String method, JSONObject params) throws JSONException {
+ JSONObject input = params == null ? new JSONObject() : params;
+ AlphaThemeBridge bridge = new AlphaThemeBridge(context);
+ return switch (method) {
+ case "listThemes" -> bridge.listThemesJson();
+ case "getStatus" -> bridge.statusJson();
+ case "applyTheme" -> bridge.applyTheme(input.optString("packId", ""));
+ case "setNavigationMode" -> bridge.setNavigationMode(input.optString("modeId", ""));
+ case "resetTheme" -> bridge.resetDefaults();
+ default -> new JSONObject()
+ .put("ok", false)
+ .put("failureCode", "UNKNOWN_METHOD")
+ .put("failureMessage", "Unsupported AlphaThemeBridge method: " + method);
+ };
+ }
+
+ private void dispatch(PluginCall call, String method, JSONObject params) {
+ executor.execute(() -> {
+ try {
+ Context context = getContext();
+ if (context == null) {
+ call.reject("Android context unavailable", "CONTEXT_UNAVAILABLE");
+ return;
+ }
+ JSONObject result = invoke(context, method, params);
+ call.resolve(JSObject.fromJSONObject(result));
+ } catch (JSONException error) {
+ call.reject(error.getMessage() == null ? "Theme bridge failed" : error.getMessage(), "THEME_BRIDGE_ERROR");
+ }
+ });
+ }
+}
diff --git a/apps/app/android/alpha-theme-bridge/src/main/java/ai/alphacompute/themebridge/AlphaThemeCatalog.java b/apps/app/android/alpha-theme-bridge/src/main/java/ai/alphacompute/themebridge/AlphaThemeCatalog.java
new file mode 100644
index 0000000000..f66c12d4d4
--- /dev/null
+++ b/apps/app/android/alpha-theme-bridge/src/main/java/ai/alphacompute/themebridge/AlphaThemeCatalog.java
@@ -0,0 +1,141 @@
+package ai.alphacompute.themebridge;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Canonical registry of the six curated Alpha OKLCH full-OS theme packs and two toggleable
+ * navigation policy RROs, aligned with {@code packages/design-system/themes} and
+ * {@code apps/app/aosp/themes/theme-packs.manifest.json}.
+ */
+public final class AlphaThemeCatalog {
+ /** Default boot and reset theme pack ID. */
+ public static final String DEFAULT_THEME_ID = "ink-dark";
+
+ /** Default navigation policy preserving stock Android Recents gestures. */
+ public static final String DEFAULT_NAV_MODE_ID = "stock-recents";
+
+ /** Exclusive OverlayManager category for navigation policy RROs. */
+ public static final String NAV_MODE_CATEGORY = "ai.alphacompute.alpha.navmode";
+
+ /** Immutable descriptor for one curated full-OS theme pack and its four RRO packages. */
+ public record ThemePackSpec(
+ String id,
+ String name,
+ String scheme,
+ boolean isDefault,
+ String seedHex,
+ String frameworkOverlay,
+ String systemUiOverlay,
+ String launcher3Overlay,
+ String settingsOverlay
+ ) {
+ /** Returns all four RRO package names in deterministic activation order. */
+ public List allOverlayPackages() {
+ return List.of(frameworkOverlay, systemUiOverlay, launcher3Overlay, settingsOverlay);
+ }
+
+ /** Returns true when this theme pack uses dark UI polarity. */
+ public boolean isDark() {
+ return "dark".equals(scheme);
+ }
+ }
+
+ /** Immutable descriptor for one toggleable navigation policy overlay. */
+ public record NavModeSpec(
+ String id,
+ String name,
+ String overlayPackage,
+ boolean homeBackOnly,
+ boolean isDefault
+ ) {}
+
+ private static final List PACKS = List.of(
+ pack("ink-dark", "Ink Dark", "dark", true, "8A93FF", "inkdark"),
+ pack("crisp-light", "Crisp Light", "light", false, "0000FF", "crisplight"),
+ pack("tokyo-night", "Tokyo Night", "dark", false, "7AA8FE", "tokyonight"),
+ pack("gruvbox", "Gruvbox", "dark", false, "F1BA44", "gruvbox"),
+ pack("catppuccin", "Catppuccin", "dark", false, "CCA6FC", "catppuccin"),
+ pack("everforest", "Everforest", "dark", false, "A7C788", "everforest")
+ );
+
+ private static final List NAV_MODES = List.of(
+ new NavModeSpec(
+ "stock-recents",
+ "Stock Android gestures",
+ "ai.alphacompute.alpha.navmode.stockrecents",
+ false,
+ true
+ ),
+ new NavModeSpec(
+ "focused-home-back",
+ "Focused Home & Back",
+ "ai.alphacompute.alpha.navmode.focusedhomeback",
+ true,
+ false
+ )
+ );
+
+ private static final Map PACK_BY_ID = buildPackIndex();
+ private static final Map NAV_BY_ID = buildNavIndex();
+
+ private AlphaThemeCatalog() {}
+
+ /** Returns all six curated full-OS theme packs in presentation order. */
+ public static List packs() {
+ return PACKS;
+ }
+
+ /** Returns all supported navigation policy modes. */
+ public static List navModes() {
+ return NAV_MODES;
+ }
+
+ /** Looks up a theme pack by ID, or returns {@code null} if unknown. */
+ public static ThemePackSpec findPack(String id) {
+ return id == null ? null : PACK_BY_ID.get(id);
+ }
+
+ /** Looks up a navigation policy mode by ID, or returns {@code null} if unknown. */
+ public static NavModeSpec findNavMode(String id) {
+ return id == null ? null : NAV_BY_ID.get(id);
+ }
+
+ private static ThemePackSpec pack(
+ String id,
+ String name,
+ String scheme,
+ boolean isDefault,
+ String seedHex,
+ String slug
+ ) {
+ return new ThemePackSpec(
+ id,
+ name,
+ scheme,
+ isDefault,
+ seedHex,
+ "ai.alphacompute.alpha.theme." + slug + ".framework",
+ "ai.alphacompute.alpha.theme." + slug + ".systemui",
+ "ai.alphacompute.alpha.theme." + slug + ".launcher3",
+ "ai.alphacompute.alpha.theme." + slug + ".settings"
+ );
+ }
+
+ private static Map buildPackIndex() {
+ Map map = new LinkedHashMap<>();
+ for (ThemePackSpec spec : PACKS) {
+ map.put(spec.id(), spec);
+ }
+ return Map.copyOf(map);
+ }
+
+ private static Map buildNavIndex() {
+ Map map = new LinkedHashMap<>();
+ for (NavModeSpec spec : NAV_MODES) {
+ map.put(spec.id(), spec);
+ }
+ return Map.copyOf(map);
+ }
+}
diff --git a/apps/app/android/alpha-theme-bridge/src/test/java/ai/alphacompute/themebridge/AlphaThemeBridgeTest.java b/apps/app/android/alpha-theme-bridge/src/test/java/ai/alphacompute/themebridge/AlphaThemeBridgeTest.java
new file mode 100644
index 0000000000..ac8440017f
--- /dev/null
+++ b/apps/app/android/alpha-theme-bridge/src/test/java/ai/alphacompute/themebridge/AlphaThemeBridgeTest.java
@@ -0,0 +1,165 @@
+// spec/app/themes/index.md, "Story: Enforce atomic rollback and single-flight theme and navigation switching"
+package ai.alphacompute.themebridge;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.json.JSONObject;
+import org.junit.Test;
+
+/** Pure JVM JUnit tests verifying full-OS RRO switching, atomic rollback, and navigation mode toggling. */
+public final class AlphaThemeBridgeTest {
+ private static void check(boolean condition, String message) {
+ if (!condition) {
+ throw new AssertionError(message);
+ }
+ }
+
+ private static final class FakeOverlayBackend implements AlphaThemeBridge.OverlayBackend {
+ boolean supported = true;
+ String failOnPackage = "";
+ final List enabledCalls = new ArrayList<>();
+ final Map activeBySuffix = new HashMap<>();
+ boolean lastDark = true;
+ String lastSeedHex = "8A93FF";
+
+ @Override public boolean isSupported() {
+ return supported;
+ }
+
+ @Override public boolean setEnabledExclusiveInCategory(String overlayPackage) {
+ enabledCalls.add(overlayPackage);
+ if (overlayPackage.equals(failOnPackage)) {
+ return false;
+ }
+ String category = overlayPackage.startsWith(AlphaThemeCatalog.NAV_MODE_CATEGORY)
+ ? AlphaThemeCatalog.NAV_MODE_CATEGORY
+ : overlayPackage.substring(overlayPackage.lastIndexOf('.') + 1);
+ activeBySuffix.put(category, overlayPackage);
+ return true;
+ }
+
+ @Override public void applySystemPolarity(boolean dark, String seedHex) {
+ lastDark = dark;
+ lastSeedHex = seedHex;
+ }
+ }
+
+ private static final class MemoryStore implements AlphaThemeBridge.StateStore {
+ final Map data = new HashMap<>();
+
+ @Override public String getString(String key, String fallback) {
+ return data.getOrDefault(key, fallback);
+ }
+
+ @Override public void putString(String key, String value) {
+ data.put(key, value);
+ }
+ }
+
+ /** Verifies all six curated packs expose 24 unique RRO packages and switch cleanly with polarity updates. */
+ @Test
+ public void testCatalogIntegrityAndFullOsThemeSwitch() throws Exception {
+ check(AlphaThemeCatalog.packs().size() == 6, "exactly six curated theme packs");
+ Set uniqueOverlays = new HashSet<>();
+ for (AlphaThemeCatalog.ThemePackSpec spec : AlphaThemeCatalog.packs()) {
+ check(spec.allOverlayPackages().size() == 4, "four target RROs per pack");
+ uniqueOverlays.addAll(spec.allOverlayPackages());
+ }
+ check(uniqueOverlays.size() == 24, "24 distinct RRO overlay package names");
+
+ FakeOverlayBackend backend = new FakeOverlayBackend();
+ MemoryStore store = new MemoryStore();
+ AlphaThemeBridge bridge = new AlphaThemeBridge(backend, store);
+
+ JSONObject initial = bridge.statusJson();
+ check("ink-dark".equals(initial.getString("activeThemeId")), "default theme is ink-dark");
+ check("stock-recents".equals(initial.getString("activeNavModeId")), "default nav is stock-recents");
+
+ JSONObject switched = bridge.applyTheme("tokyo-night");
+ check(switched.getBoolean("ok"), "tokyo-night apply succeeds");
+ check("tokyo-night".equals(switched.getString("activeThemeId")), "active theme updated to tokyo-night");
+ check(backend.lastDark, "tokyo-night keeps dark polarity");
+ check("7AA8FE".equals(backend.lastSeedHex), "tokyo-night seed hex applied");
+ check(
+ "ai.alphacompute.alpha.theme.tokyonight.systemui".equals(backend.activeBySuffix.get("systemui")),
+ "SystemUI overlay enabled"
+ );
+
+ JSONObject crispLight = bridge.applyTheme("crisp-light");
+ check(crispLight.getBoolean("ok"), "crisp-light apply succeeds");
+ check("light".equals(crispLight.getString("activeScheme")), "crisp-light scheme is light");
+ check(!backend.lastDark, "crisp-light switches OS polarity to light");
+ }
+
+ /** Verifies atomic rollback restores all previously enabled overlays when a mid-switch target fails. */
+ @Test
+ public void testAtomicRollbackOnPartialOverlayFailure() throws Exception {
+ FakeOverlayBackend backend = new FakeOverlayBackend();
+ MemoryStore store = new MemoryStore();
+ AlphaThemeBridge bridge = new AlphaThemeBridge(backend, store);
+
+ check(bridge.applyTheme("everforest").getBoolean("ok"), "initial everforest apply succeeds");
+ backend.failOnPackage = "ai.alphacompute.alpha.theme.gruvbox.launcher3";
+
+ JSONObject failed = bridge.applyTheme("gruvbox");
+ check(!failed.getBoolean("ok"), "partial failure returns ok=false");
+ check("OVERLAY_APPLY_FAILED".equals(failed.getString("failureCode")), "failure code reported");
+ check("everforest".equals(failed.getString("activeThemeId")), "active theme preserved as everforest");
+ check(
+ "ai.alphacompute.alpha.theme.everforest.framework".equals(backend.activeBySuffix.get("framework")),
+ "framework overlay rolled back to everforest"
+ );
+ check(
+ "ai.alphacompute.alpha.theme.everforest.systemui".equals(backend.activeBySuffix.get("systemui")),
+ "SystemUI overlay rolled back to everforest"
+ );
+ check(
+ "ai.alphacompute.alpha.theme.everforest.launcher3".equals(backend.activeBySuffix.get("launcher3")),
+ "Launcher3 remained on everforest"
+ );
+
+ JSONObject unknown = bridge.applyTheme("nonexistent-theme");
+ check(!unknown.getBoolean("ok"), "unknown theme rejected");
+ check("UNKNOWN_THEME_PACK".equals(unknown.getString("failureCode")), "unknown theme code");
+ }
+
+ /** Verifies toggleable navigation mode switches between stock-recents and focused-home-back and resets cleanly. */
+ @Test
+ public void testNavigationModeToggleAndReset() throws Exception {
+ FakeOverlayBackend backend = new FakeOverlayBackend();
+ MemoryStore store = new MemoryStore();
+ AlphaThemeBridge bridge = new AlphaThemeBridge(backend, store);
+
+ JSONObject focused = bridge.setNavigationMode("focused-home-back");
+ check(focused.getBoolean("ok"), "focused-home-back toggle succeeds");
+ check("focused-home-back".equals(focused.getString("activeNavModeId")), "nav mode persisted");
+ check(
+ "ai.alphacompute.alpha.navmode.focusedhomeback".equals(
+ backend.activeBySuffix.get(AlphaThemeCatalog.NAV_MODE_CATEGORY)
+ ),
+ "focused-home-back overlay enabled exclusively"
+ );
+
+ JSONObject invalidNav = bridge.setNavigationMode("three-buttons");
+ check(!invalidNav.getBoolean("ok"), "unsupported nav mode refused");
+ check("UNKNOWN_NAV_MODE".equals(invalidNav.getString("failureCode")), "unknown nav mode code");
+
+ check(bridge.applyTheme("catppuccin").getBoolean("ok"), "catppuccin apply succeeds");
+ JSONObject reset = bridge.resetDefaults();
+ check(reset.getBoolean("ok"), "reset succeeds");
+ check("ink-dark".equals(reset.getString("activeThemeId")), "reset restores ink-dark");
+ check("stock-recents".equals(reset.getString("activeNavModeId")), "reset restores stock-recents");
+ }
+
+ /** Standalone JVM entry point for fast verification without Gradle overhead. */
+ public static void main(String[] args) throws Exception {
+ AlphaThemeBridgeTest suite = new AlphaThemeBridgeTest();
+ suite.testCatalogIntegrityAndFullOsThemeSwitch();
+ suite.testAtomicRollbackOnPartialOverlayFailure();
+ suite.testNavigationModeToggleAndReset();
+ }
+}
diff --git a/apps/app/aosp/notification-assistant/Android.bp b/apps/app/aosp/notification-assistant/Android.bp
new file mode 100644
index 0000000000..5ae4f7c1a6
--- /dev/null
+++ b/apps/app/aosp/notification-assistant/Android.bp
@@ -0,0 +1,36 @@
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+android_app {
+ name: "AlphaNotificationAssistant",
+ manifest: "AndroidManifest.xml",
+ srcs: [
+ "src/**/*.java",
+ ],
+ privileged: true,
+ system_ext_specific: true,
+ certificate: "platform",
+ platform_apis: true,
+ required: [
+ "AlphaNotificationAssistantPrivappPermissions",
+ "AlphaNotificationAssistantOverlay",
+ ],
+}
+
+prebuilt_etc {
+ name: "AlphaNotificationAssistantPrivappPermissions",
+ src: "privapp-permissions-alpha-notification-assistant.xml",
+ sub_dir: "permissions",
+ filename_from_src: true,
+ system_ext_specific: true,
+}
+
+runtime_resource_overlay {
+ name: "AlphaNotificationAssistantOverlay",
+ manifest: "overlay/AndroidManifest.xml",
+ resource_dirs: ["overlay/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
diff --git a/apps/app/aosp/notification-assistant/AndroidManifest.xml b/apps/app/aosp/notification-assistant/AndroidManifest.xml
new file mode 100644
index 0000000000..80e21ee737
--- /dev/null
+++ b/apps/app/aosp/notification-assistant/AndroidManifest.xml
@@ -0,0 +1,23 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/apps/app/aosp/notification-assistant/README.md b/apps/app/aosp/notification-assistant/README.md
new file mode 100644
index 0000000000..7d0969fee1
--- /dev/null
+++ b/apps/app/aosp/notification-assistant/README.md
@@ -0,0 +1,52 @@
+# Alpha Notification Assistant (Zero GMS, Android 17 AOSP)
+
+Platform-signed privileged `NotificationAssistantService` replacing stock AOSP
+`ExtServices` / proprietary Google `Android System Intelligence` (`com.google.android.as`)
+so Android 17's native SystemUI notification summaries (`Adjustment.KEY_SUMMARIZATION`)
+and notification bundles (`Adjustment.KEY_TYPE`) run natively on Alpha OS with zero GMS
+and zero AICore.
+
+## Architecture
+
+1. **SystemUI / Framework Hook (RRO Overlay)**
+ - `AlphaNotificationAssistantOverlay` sets:
+ - `config_defaultAssistantAccessComponent` = `ai.alphacompute.notificationassistant/ai.alphacompute.notifications.aosp.AlphaNotificationAssistantService`
+ - `config_systemNotificationIntelligence` = `ai.alphacompute.notificationassistant`
+ - Android 17 (`alpha_stallion_phone`) already ships `systemui/android.app.nm_summarization=true`,
+ `notification_classification=true`, and the Settings UI (`NotificationSummarizationActivity`,
+ `NotificationBundlesActivity`); this module supplies the missing LLM-backed assistant.
+2. **Fail-Closed Privacy Boundary (In-Process)**
+ - Before any summarization or Binder IPC, `AlphaNotificationAssistantService.classifySensitivity(...)`
+ redacts and skips:
+ - 2FA / OTP verification codes
+ - Password managers, authenticators, and credential/reset alerts
+ - Banking, card, wallet, and financial transaction alerts
+ - `VISIBILITY_SECRET` and lockscreen-`VISIBILITY_PRIVATE` notifications while locked or before user unlock
+ - Owner-excluded packages
+3. **Least-Privilege Permissions & Network Isolation**
+ - `AndroidManifest.xml` does **not** request `android.permission.INTERNET`, `INJECT_EVENTS`,
+ `READ_SMS`, or `WRITE_SECURE_SETTINGS`.
+ - `privapp-permissions-alpha-notification-assistant.xml` whitelists only
+ `BIND_NOTIFICATION_ASSISTANT_SERVICE` and `STATUS_BAR_SERVICE`.
+ - `sepolicy/alpha_notification_assistant.te` places the service in isolated domain
+ `alpha_notification_assistant` with a `neverallow` denying all TCP/UDP/raw/ICMP/packet sockets.
+4. **Resident Hybrid Inference Router + Deterministic Fallback**
+ - Non-sensitive notifications that warrant summarization (multi-message threads or messages
+ >= 48 chars) send a compact Binder IPC call solely to the system-installed, canonical
+ release-signed `ai.alphacompute.alphaphone` bridge within a 1.2s latency budget and bounded
+ 16-task queue.
+ - `apps/agent` routes through Alpha's hybrid smart router (`local-llm.ts` / `alpha.llmMode`):
+ on-device Gemma 4 E2B when installed and free RAM >= 1024 MB (8 GB Pixel guardrail),
+ Eliza Cloud fallback when enabled and reachable, and deterministic grouping fallback otherwise.
+ - If the bridge is unbound, low-memory is asserted, or IPC times out, `AlphaNotificationAssistantService`
+ attaches a clean bounded single-line deterministic summary (<= 140 chars) with zero blocking.
+
+## Verification
+
+Run the standalone AOSP plan and API-36 compile/policy test:
+
+```bash
+python3 apps/app/aosp/notification-assistant/test_nas_plan.py
+```
+
+Formal privacy and routing invariants live in `spec/app/notifications/index.md`.
diff --git a/apps/app/aosp/notification-assistant/notification-assistant.mk b/apps/app/aosp/notification-assistant/notification-assistant.mk
new file mode 100644
index 0000000000..58ec1b6fda
--- /dev/null
+++ b/apps/app/aosp/notification-assistant/notification-assistant.mk
@@ -0,0 +1,6 @@
+alpha_notification_assistant_dir := $(patsubst %/,%,$(dir $(lastword $(MAKEFILE_LIST))))
+PRODUCT_PACKAGES += \
+ AlphaNotificationAssistant \
+ AlphaNotificationAssistantPrivappPermissions \
+ AlphaNotificationAssistantOverlay
+SYSTEM_EXT_PRIVATE_SEPOLICY_DIRS += $(alpha_notification_assistant_dir)/sepolicy
diff --git a/apps/app/aosp/notification-assistant/overlay/AndroidManifest.xml b/apps/app/aosp/notification-assistant/overlay/AndroidManifest.xml
new file mode 100644
index 0000000000..82325a7415
--- /dev/null
+++ b/apps/app/aosp/notification-assistant/overlay/AndroidManifest.xml
@@ -0,0 +1,9 @@
+
+
+
+
+
diff --git a/apps/app/aosp/notification-assistant/overlay/res/values/config.xml b/apps/app/aosp/notification-assistant/overlay/res/values/config.xml
new file mode 100644
index 0000000000..9e2bbab54d
--- /dev/null
+++ b/apps/app/aosp/notification-assistant/overlay/res/values/config.xml
@@ -0,0 +1,8 @@
+
+
+
+ ai.alphacompute.notificationassistant/ai.alphacompute.notifications.aosp.AlphaNotificationAssistantService
+ ai.alphacompute.notificationassistant
+
diff --git a/apps/app/aosp/notification-assistant/privapp-permissions-alpha-notification-assistant.xml b/apps/app/aosp/notification-assistant/privapp-permissions-alpha-notification-assistant.xml
new file mode 100644
index 0000000000..fcb151dbf9
--- /dev/null
+++ b/apps/app/aosp/notification-assistant/privapp-permissions-alpha-notification-assistant.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
diff --git a/apps/app/aosp/notification-assistant/sepolicy/alpha_notification_assistant.te b/apps/app/aosp/notification-assistant/sepolicy/alpha_notification_assistant.te
new file mode 100644
index 0000000000..41920accec
--- /dev/null
+++ b/apps/app/aosp/notification-assistant/sepolicy/alpha_notification_assistant.te
@@ -0,0 +1,21 @@
+type alpha_notification_assistant, domain, coredomain;
+app_domain(alpha_notification_assistant)
+
+type alpha_notification_assistant_data_file, file_type, data_file_type, core_data_file_type, app_data_file_type;
+allow alpha_notification_assistant alpha_notification_assistant_data_file:dir create_dir_perms;
+allow alpha_notification_assistant alpha_notification_assistant_data_file:file create_file_perms;
+
+binder_use(alpha_notification_assistant)
+
+allow alpha_notification_assistant {
+ activity_service
+ notification_service
+ package_service
+ power_service
+ trust_service
+ user_service
+}:service_manager find;
+
+neverallow alpha_notification_assistant self:{ tcp_socket udp_socket rawip_socket icmp_socket packet_socket } {
+ create connect bind listen accept
+};
diff --git a/apps/app/aosp/notification-assistant/sepolicy/seapp_contexts b/apps/app/aosp/notification-assistant/sepolicy/seapp_contexts
new file mode 100644
index 0000000000..6c156f6924
--- /dev/null
+++ b/apps/app/aosp/notification-assistant/sepolicy/seapp_contexts
@@ -0,0 +1 @@
+user=_app seinfo=platform name=ai.alphacompute.notificationassistant isPrivApp=true domain=alpha_notification_assistant type=alpha_notification_assistant_data_file levelFrom=user
diff --git a/apps/app/aosp/notification-assistant/src/ai/alphacompute/notifications/aosp/AlphaNotificationAssistantService.java b/apps/app/aosp/notification-assistant/src/ai/alphacompute/notifications/aosp/AlphaNotificationAssistantService.java
new file mode 100644
index 0000000000..814fd3f31b
--- /dev/null
+++ b/apps/app/aosp/notification-assistant/src/ai/alphacompute/notifications/aosp/AlphaNotificationAssistantService.java
@@ -0,0 +1,893 @@
+package ai.alphacompute.notifications.aosp;
+
+import android.app.ActivityManager;
+import android.app.KeyguardManager;
+import android.app.Notification;
+import android.app.NotificationChannel;
+import android.content.ComponentName;
+import android.content.Context;
+import android.content.Intent;
+import android.content.ServiceConnection;
+import android.content.pm.ApplicationInfo;
+import android.content.pm.PackageInfo;
+import android.content.pm.PackageManager;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.IBinder;
+import android.os.Parcel;
+import android.os.RemoteException;
+import android.os.UserManager;
+import android.service.notification.Adjustment;
+import android.service.notification.NotificationAssistantService;
+import android.service.notification.NotificationStats;
+import android.service.notification.StatusBarNotification;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Deque;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.regex.Pattern;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * Zero-GMS Android 17 NotificationAssistantService for Alpha OS.
+ *
+ * Applies fail-closed in-process privacy redaction before any IPC or summarization,
+ * classifies bundle types onto {@link Adjustment#KEY_TYPE}, and attaches bounded concise
+ * single-line summaries onto {@link Adjustment#KEY_SUMMARIZATION} via signature-verified
+ * Binder IPC to Alpha's resident hybrid inference router with deterministic offline fallback.
+ */
+public final class AlphaNotificationAssistantService extends NotificationAssistantService {
+ /** Sole authorized resident Alpha host package for summary IPC. */
+ public static final String ALPHA_PACKAGE = "ai.alphacompute.alphaphone";
+
+ /** Binder action exposed by Alpha's resident notification summary bridge. */
+ public static final String ACTION_NOTIFICATION_SUMMARY_BRIDGE =
+ "ai.alphacompute.notifications.ACTION_NOTIFICATION_SUMMARY_BRIDGE";
+
+ /** Binder transaction descriptor shared with Alpha's summary bridge. */
+ public static final String SUMMARY_BRIDGE_DESCRIPTOR =
+ "ai.alphacompute.notifications.IAlphaNotificationSummaryBridge";
+
+ /** Binder transaction code for synchronous single-batch summary requests. */
+ public static final int TRANSACTION_SUMMARIZE = IBinder.FIRST_CALL_TRANSACTION;
+
+ /** Maximum length of an attached notification summary line. */
+ public static final int MAX_SUMMARY_CHARS = 140;
+
+ /** Maximum tracked notification threads retained in bounded memory. */
+ public static final int MAX_TRACKED_THREADS = 64;
+
+ /** Maximum recent messages retained per thread for conversation summarization. */
+ public static final int MAX_MESSAGES_PER_THREAD = 6;
+
+ /** Minimum text length before a single notification warrants summarization. */
+ public static final int MIN_SUMMARIZE_CHARS = 48;
+
+ /** Strict latency budget in milliseconds for async IPC summary requests. */
+ public static final long IPC_TIMEOUT_MS = 1_200L;
+
+ /** Strict upper bound on concurrent in-flight IPC summarization jobs. */
+ public static final int MAX_PENDING_IPC_TASKS = 16;
+
+ /** SHA-256 certificate digest of Alpha's canonical release signer. */
+ static final byte[] ALPHA_SIGNER_SHA256 = new byte[] {
+ (byte) 0xed, (byte) 0xbf, (byte) 0xca, (byte) 0xcb,
+ (byte) 0x1d, (byte) 0xa6, (byte) 0x89, (byte) 0x00,
+ (byte) 0x8b, (byte) 0xf4, (byte) 0xe7, (byte) 0xd6,
+ (byte) 0x75, (byte) 0x17, (byte) 0x6c, (byte) 0x30,
+ (byte) 0x2d, (byte) 0xec, (byte) 0xf8, (byte) 0x31,
+ (byte) 0x61, (byte) 0xa8, (byte) 0x77, (byte) 0xeb,
+ (byte) 0x8b, (byte) 0x1d, (byte) 0xe4, (byte) 0xff,
+ (byte) 0xae, (byte) 0x04, (byte) 0x45, (byte) 0xed,
+ };
+
+ /**
+ * SHA-256 certificate digest of the development signer permitted exclusively on
+ * {@code userdebug}/{@code eng} builds ({@code Build.IS_DEBUGGABLE}).
+ */
+ static final String ALPHA_DEBUG_SIGNER_HEX =
+ "227ddd0bf51116a69fb6f8f8ceb32ee2df9ed086471bceec4f9a26f48f31d5d5";
+
+ private static final byte[] ALPHA_DEBUG_SIGNER_SHA256 =
+ decodeHexDigest(ALPHA_DEBUG_SIGNER_HEX);
+
+ /** Fail-closed privacy classification for incoming notifications. */
+ public enum Sensitivity {
+ CLEAR,
+ OTP_CODE,
+ CREDENTIAL,
+ FINANCIAL,
+ LOCKSCREEN_PRIVATE
+ }
+
+ /** Immutable summary payload attached to a notification adjustment. */
+ public static final class SummaryAdjustmentPlan {
+ public final int bundleType;
+ public final String summary;
+ public final String source;
+
+ public SummaryAdjustmentPlan(int bundleType, String summary, String source) {
+ this.bundleType = bundleType;
+ this.summary = summary;
+ this.source = source;
+ }
+ }
+
+ private static final Set CREDENTIAL_PACKAGE_TOKENS = Set.of(
+ "1password", "onepassword", "bitwarden", "keepass", "proton.android.pass",
+ "dashlane", "lastpass", "enpass", "nordpass", "roboform", "keychain",
+ "authenticator", "authy", "duomobile", "yubico", "aegis", "2fas",
+ "freeotp", "ente.auth", "permissioncontroller", "packageinstaller",
+ "com.android.settings");
+
+ private static final Set FINANCIAL_PACKAGE_TOKENS = Set.of(
+ "wallet", "bank", "chase", "wellsfargo", "bofa", "bankofamerica",
+ "citibank", "citi.mobile", "amex", "americanexpress", "capitalone",
+ "paypal", "venmo", "cashapp", "squareup.cash", "coinbase", "robinhood",
+ "schwab", "fidelity", "vanguard", "stripe", "wise", "transferwise",
+ "revolut", "monzo", "chime", "zelle", "metamask", "phantom",
+ "ai.alphacompute.wallet");
+
+ private static final Set SOCIAL_PACKAGE_TOKENS = Set.of(
+ "instagram", "twitter", "x.android", "tiktok", "reddit", "facebook.katana",
+ "threads", "bsky", "bluesky", "mastodon", "linkedin", "snapchat", "pinterest");
+
+ private static final Set NEWS_PACKAGE_TOKENS = Set.of(
+ "nytimes", "wsj", "washingtonpost", "bbc.news", "reuters", "apnews",
+ "bloomberg", "theguardian", "economist", "substack", "feedly", "flipboard",
+ "apple.news", "news");
+
+ private static final Set RECOMMENDATION_PACKAGE_TOKENS = Set.of(
+ "youtube", "spotify", "netflix", "twitch", "hulu", "disneyplus",
+ "max.android", "audible", "pocketcasts", "overcast", "medium");
+
+ private static final Set SKIPPED_CATEGORIES = Set.of(
+ Notification.CATEGORY_CALL,
+ Notification.CATEGORY_ALARM,
+ Notification.CATEGORY_NAVIGATION,
+ Notification.CATEGORY_STOPWATCH,
+ Notification.CATEGORY_PROGRESS,
+ Notification.CATEGORY_TRANSPORT,
+ Notification.CATEGORY_SERVICE,
+ Notification.CATEGORY_SYSTEM);
+
+ private static final Pattern OTP_DIGITS_PATTERN = Pattern.compile(
+ "(?:^|[^0-9A-Za-z])(?:[A-Za-z]-)?\\d{4,8}(?:$|[^0-9A-Za-z])|"
+ + "(?:^|[^0-9])\\d{3}[-\\s]\\d{3}(?:$|[^0-9])");
+
+ private static final Pattern OTP_CONTEXT_PATTERN = Pattern.compile(
+ "(?i)\\b(otp|2fa|mfa|totp|one[-\\s]?time|passcode|verification\\s+code|"
+ + "security\\s+code|login\\s+code|sign[-\\s]?in\\s+code|auth(?:entication)?\\s+code|"
+ + "confirm(?:ation)?\\s+code|do\\s+not\\s+share\\s+this\\s+code|"
+ + "enter\\s+(?:this\\s+)?code|verify\\s+your\\s+(?:account|login|identity))\\b");
+
+ private static final Pattern CREDENTIAL_CONTENT_PATTERN = Pattern.compile(
+ "(?i)\\b(password\\s+reset|reset\\s+your\\s+password|temporary\\s+password|"
+ + "recovery\\s+(?:code|phrase|key)|seed\\s+phrase|private\\s+key|passkey|"
+ + "magic\\s+link|approve\\s+(?:this\\s+)?sign[-\\s]?in|login\\s+request|"
+ + "two[-\\s]?factor|credential\\s+manager)\\b");
+
+ private static final Pattern FINANCIAL_CONTENT_PATTERN = Pattern.compile(
+ "(?i)\\b(wire\\s+transfer|direct\\s+deposit|bank\\s+account|routing\\s+number|"
+ + "account\\s+balance|card\\s+ending\\s+in|credit\\s+card|debit\\s+card|"
+ + "cvv|pin\\s+number|ssn|social\\s+security|fraud\\s+alert|suspicious\\s+charge|"
+ + "payment\\s+(?:sent|received|declined|authorized)|withdrawal|ach\\s+transfer|"
+ + "transaction\\s+alert|charge\\s+of\\s+\\$?\\d)\\b");
+
+ private static final Pattern PROMO_CONTENT_PATTERN = Pattern.compile(
+ "(?i)\\b(\\d{1,2}%\\s*off|promo\\s+code|coupon|flash\\s+sale|limited[-\\s]?time\\s+offer|"
+ + "free\\s+shipping|clearance|special\\s+offer|save\\s+\\$\\d|deal\\s+of\\s+the\\s+day|"
+ + "shop\\s+now|subscribe\\s+and\\s+save|exclusive\\s+discount)\\b");
+
+ private static final Pattern NEWS_CONTENT_PATTERN = Pattern.compile(
+ "(?i)\\b(breaking\\s+news|developing\\s+story|top\\s+stories|morning\\s+briefing|"
+ + "evening\\s+briefing|headline|live\\s+updates|editorial|newsletter)\\b");
+
+ private static final Pattern SOCIAL_CONTENT_PATTERN = Pattern.compile(
+ "(?i)\\b(liked\\s+your|commented\\s+on|replied\\s+to\\s+your\\s+post|"
+ + "started\\s+following|followed\\s+you|mentioned\\s+you|reposted|retweeted|"
+ + "tagged\\s+you|reacted\\s+to\\s+your)\\b");
+
+ private static final Pattern RECOMMENDATION_CONTENT_PATTERN = Pattern.compile(
+ "(?i)\\b(recommended\\s+for\\s+you|trending\\s+now|new\\s+episode|watch\\s+now|"
+ + "listen\\s+now|just\\s+uploaded|picked\\s+for\\s+you|because\\s+you\\s+watched|"
+ + "top\\s+picks)\\b");
+
+ private static final Pattern SLOP_PREFIX_PATTERN = Pattern.compile(
+ "(?i)^(?:(?:ai\\s+)?summary|tl;?dr|here(?:'s|\\s+is)\\s+(?:a\\s+)?summary|"
+ + "sure,?\\s+here(?:'s|\\s+is)[^:]*|certainly[,!]?)\\s*[:\\-\\u2013\\u2014]?\\s*");
+
+ private static final Pattern MULTI_SPACE_PATTERN = Pattern.compile("[\\r\\n\\t\\s]+");
+
+ private final ExecutorService workerPool = Executors.newFixedThreadPool(2, runnable -> {
+ Thread thread = new Thread(runnable, "alpha-nas-worker");
+ thread.setDaemon(true);
+ return thread;
+ });
+
+ private final AtomicInteger pendingTasks = new AtomicInteger(0);
+ private final Set activeKeys = ConcurrentHashMap.newKeySet();
+ private final Set optedOutPackages = ConcurrentHashMap.newKeySet();
+
+ private final Map> threadHistory =
+ Collections.synchronizedMap(new LinkedHashMap>(MAX_TRACKED_THREADS, 0.75f, true) {
+ @Override
+ protected boolean removeEldestEntry(Map.Entry> eldest) {
+ return size() > MAX_TRACKED_THREADS;
+ }
+ });
+
+ private final AtomicReference bridgeBinderRef = new AtomicReference<>();
+ private volatile boolean bridgeBound;
+ private volatile CountDownLatch bridgeLatch = new CountDownLatch(1);
+
+ private final ServiceConnection bridgeConnection = new ServiceConnection() {
+ @Override
+ public void onServiceConnected(ComponentName name, IBinder service) {
+ bridgeBinderRef.set(service);
+ bridgeLatch.countDown();
+ }
+
+ @Override
+ public void onServiceDisconnected(ComponentName name) {
+ bridgeBinderRef.set(null);
+ }
+
+ @Override
+ public void onBindingDied(ComponentName name) {
+ bridgeBinderRef.set(null);
+ bridgeBound = false;
+ bridgeLatch.countDown();
+ }
+
+ @Override
+ public void onNullBinding(ComponentName name) {
+ bridgeBinderRef.set(null);
+ bridgeBound = false;
+ bridgeLatch.countDown();
+ }
+ };
+
+ @Override
+ public Adjustment onNotificationEnqueued(StatusBarNotification sbn) {
+ return handleEnqueued(sbn, null);
+ }
+
+ @Override
+ public Adjustment onNotificationEnqueued(
+ StatusBarNotification sbn, NotificationChannel channel) {
+ return handleEnqueued(sbn, channel);
+ }
+
+ @Override
+ public Adjustment onNotificationEnqueued(
+ StatusBarNotification sbn, NotificationChannel channel, RankingMap rankingMap) {
+ return handleEnqueued(sbn, channel);
+ }
+
+ @Override
+ public void onNotificationSnoozedUntilContext(
+ StatusBarNotification sbn, String snoozeCriterionId) {
+ if (sbn != null && sbn.getKey() != null) {
+ activeKeys.remove(sbn.getKey());
+ }
+ }
+
+ @Override
+ public void onNotificationsSeen(List keys) {
+ if (keys == null || keys.isEmpty()) {
+ return;
+ }
+ synchronized (threadHistory) {
+ for (String key : keys) {
+ if (key != null) {
+ threadHistory.remove(key);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void onNotificationRemoved(
+ StatusBarNotification sbn,
+ RankingMap rankingMap,
+ NotificationStats stats,
+ int reason) {
+ if (sbn != null && sbn.getKey() != null) {
+ activeKeys.remove(sbn.getKey());
+ threadHistory.remove(sbn.getKey());
+ }
+ }
+
+ @Override
+ public void onDestroy() {
+ unbindSummaryBridge();
+ workerPool.shutdownNow();
+ activeKeys.clear();
+ threadHistory.clear();
+ super.onDestroy();
+ }
+
+ private Adjustment handleEnqueued(StatusBarNotification sbn, NotificationChannel channel) {
+ if (sbn == null || sbn.getNotification() == null) {
+ return null;
+ }
+ final String pkg = sbn.getPackageName();
+ final String key = sbn.getKey();
+ if (pkg == null || pkg.isEmpty() || key == null || key.isEmpty()) {
+ return null;
+ }
+ if (optedOutPackages.contains(pkg)) {
+ return null;
+ }
+ final Notification notification = sbn.getNotification();
+ if (shouldSkipNotification(notification)) {
+ return null;
+ }
+ final String title = extractExtraText(notification.extras, Notification.EXTRA_TITLE);
+ final String text = extractExtraText(notification.extras, Notification.EXTRA_TEXT);
+ final String bigText = extractExtraText(notification.extras, Notification.EXTRA_BIG_TEXT);
+ final String convTitle = extractExtraText(notification.extras, Notification.EXTRA_CONVERSATION_TITLE);
+ final boolean deviceLocked = isDeviceLocked();
+ final boolean userUnlocked = isUserUnlockedSafe();
+
+ final Sensitivity sensitivity = classifySensitivity(
+ pkg,
+ title,
+ text,
+ bigText,
+ notification.category,
+ notification.visibility,
+ deviceLocked,
+ userUnlocked);
+ if (sensitivity != Sensitivity.CLEAR) {
+ return null;
+ }
+
+ final String primaryBody = !bigText.isEmpty() ? bigText : text;
+ final String effectiveTitle = !convTitle.isEmpty() ? convTitle : title;
+ final boolean isConversation = isConversationNotification(notification, channel, convTitle);
+ final int bundleType = classifyBundleType(
+ pkg, notification.category, effectiveTitle, primaryBody, isConversation);
+
+ final String threadKey = buildThreadKey(pkg, key, sbn.getGroupKey());
+ final List threadMessages = recordThreadMessage(threadKey, effectiveTitle, primaryBody);
+ activeKeys.add(key);
+
+ final boolean needsSummary = threadMessages.size() >= 2
+ || primaryBody.length() >= MIN_SUMMARIZE_CHARS;
+ final String deterministicSummary = needsSummary
+ ? buildDeterministicSummary(effectiveTitle, threadMessages, bundleType)
+ : "";
+
+ if (needsSummary && !isLowMemoryDevice()) {
+ scheduleAsyncInference(
+ sbn,
+ pkg,
+ key,
+ effectiveTitle,
+ threadMessages,
+ bundleType,
+ isConversation);
+ }
+
+ return buildAdjustment(sbn, bundleType, deterministicSummary);
+ }
+
+ private void scheduleAsyncInference(
+ final StatusBarNotification sbn,
+ final String pkg,
+ final String key,
+ final String title,
+ final List messages,
+ final int fallbackBundleType,
+ final boolean isConversation) {
+ if (pendingTasks.incrementAndGet() > MAX_PENDING_IPC_TASKS) {
+ pendingTasks.decrementAndGet();
+ return;
+ }
+ workerPool.execute(() -> {
+ try {
+ if (!activeKeys.contains(key)) {
+ return;
+ }
+ final SummaryAdjustmentPlan plan = requestSummaryViaAlphaIpc(
+ pkg, title, messages, fallbackBundleType, isConversation);
+ if (plan == null || !activeKeys.contains(key)) {
+ return;
+ }
+ if (classifySensitivity(
+ pkg, title, plan.summary, "", null, Notification.VISIBILITY_PUBLIC, false, true)
+ != Sensitivity.CLEAR) {
+ return;
+ }
+ final Adjustment refined = buildAdjustment(sbn, plan.bundleType, plan.summary);
+ if (refined != null) {
+ adjustNotification(refined);
+ }
+ } catch (RuntimeException ignored) {
+ return;
+ } finally {
+ pendingTasks.decrementAndGet();
+ }
+ });
+ }
+
+ private SummaryAdjustmentPlan requestSummaryViaAlphaIpc(
+ String pkg,
+ String title,
+ List messages,
+ int fallbackBundleType,
+ boolean isConversation) {
+ if (!isVerifiedAlphaHostInstalled()) {
+ return null;
+ }
+ final IBinder binder = ensureBridgeBinder(Math.min(400L, IPC_TIMEOUT_MS));
+ if (binder == null || !binder.isBinderAlive()) {
+ return null;
+ }
+ final Parcel data = Parcel.obtain();
+ final Parcel reply = Parcel.obtain();
+ try {
+ final JSONObject request = new JSONObject();
+ request.put("packageName", pkg);
+ request.put("title", title);
+ request.put("isConversation", isConversation);
+ request.put("fallbackBundleType", fallbackBundleType);
+ request.put("maxSummaryChars", MAX_SUMMARY_CHARS);
+ request.put("timeoutMs", IPC_TIMEOUT_MS);
+ final JSONArray arr = new JSONArray();
+ for (String msg : messages) {
+ arr.put(msg);
+ }
+ request.put("messages", arr);
+
+ data.writeInterfaceToken(SUMMARY_BRIDGE_DESCRIPTOR);
+ data.writeString(request.toString());
+ if (!binder.transact(TRANSACTION_SUMMARIZE, data, reply, 0)) {
+ return null;
+ }
+ reply.readException();
+ final String responseJson = reply.readString();
+ if (responseJson == null || responseJson.isEmpty()) {
+ return null;
+ }
+ final JSONObject response = new JSONObject(responseJson);
+ if (response.optBoolean("redacted", false)) {
+ return null;
+ }
+ final String rawSummary = response.optString("summary", "");
+ final String cleanSummary = sanitizeSummary(rawSummary);
+ if (cleanSummary.isEmpty()) {
+ return null;
+ }
+ final int resolvedBundle = normalizeBundleType(
+ response.optInt("bundleType", fallbackBundleType));
+ final String source = response.optString("source", "deterministic");
+ return new SummaryAdjustmentPlan(resolvedBundle, cleanSummary, source);
+ } catch (RemoteException | JSONException | SecurityException failed) {
+ return null;
+ } finally {
+ data.recycle();
+ reply.recycle();
+ }
+ }
+
+ private synchronized IBinder ensureBridgeBinder(long timeoutMs) {
+ final IBinder existing = bridgeBinderRef.get();
+ if (existing != null && existing.isBinderAlive()) {
+ return existing;
+ }
+ if (!bridgeBound) {
+ bridgeLatch = new CountDownLatch(1);
+ final Intent intent = new Intent(ACTION_NOTIFICATION_SUMMARY_BRIDGE);
+ intent.setPackage(ALPHA_PACKAGE);
+ try {
+ bridgeBound = bindService(intent, bridgeConnection, Context.BIND_AUTO_CREATE);
+ } catch (SecurityException refused) {
+ bridgeBound = false;
+ return null;
+ }
+ if (!bridgeBound) {
+ return null;
+ }
+ }
+ try {
+ bridgeLatch.await(Math.max(50L, timeoutMs), TimeUnit.MILLISECONDS);
+ } catch (InterruptedException interrupted) {
+ Thread.currentThread().interrupt();
+ return null;
+ }
+ final IBinder connected = bridgeBinderRef.get();
+ return connected != null && connected.isBinderAlive() ? connected : null;
+ }
+
+ private synchronized void unbindSummaryBridge() {
+ if (bridgeBound) {
+ try {
+ unbindService(bridgeConnection);
+ } catch (IllegalArgumentException ignored) {
+ bridgeBound = false;
+ }
+ bridgeBound = false;
+ }
+ bridgeBinderRef.set(null);
+ }
+
+ private boolean isVerifiedAlphaHostInstalled() {
+ final PackageManager pm = getPackageManager();
+ if (pm == null) {
+ return false;
+ }
+ try {
+ final PackageInfo info = pm.getPackageInfo(
+ ALPHA_PACKAGE,
+ PackageManager.MATCH_SYSTEM_ONLY | PackageManager.GET_SIGNING_CERTIFICATES);
+ if (info == null || info.applicationInfo == null) {
+ return false;
+ }
+ final int flags = info.applicationInfo.flags;
+ final boolean isSystem = (flags
+ & (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0;
+ final boolean isSuspended = (flags & ApplicationInfo.FLAG_SUSPENDED) != 0;
+ if (!isSystem || isSuspended || !info.applicationInfo.enabled) {
+ return false;
+ }
+ if (info.signingInfo == null || info.signingInfo.hasMultipleSigners()) {
+ return false;
+ }
+ final boolean matchesRelease = pm.hasSigningCertificate(
+ ALPHA_PACKAGE, ALPHA_SIGNER_SHA256, PackageManager.CERT_INPUT_SHA256);
+ final boolean debuggable = isDebuggableBuild();
+ final boolean matchesDebug = debuggable
+ && pm.hasSigningCertificate(
+ ALPHA_PACKAGE,
+ ALPHA_DEBUG_SIGNER_SHA256,
+ PackageManager.CERT_INPUT_SHA256);
+ return isAuthorizedSigner(debuggable, matchesRelease, matchesDebug);
+ } catch (PackageManager.NameNotFoundException | SecurityException unavailable) {
+ return false;
+ }
+ }
+
+ static boolean isDebuggableBuild() {
+ if (!"userdebug".equals(Build.TYPE) && !"eng".equals(Build.TYPE)) {
+ return false;
+ }
+ try {
+ return Build.class.getField("IS_DEBUGGABLE").getBoolean(null);
+ } catch (ReflectiveOperationException ignored) {
+ return false;
+ }
+ }
+
+ private boolean isDeviceLocked() {
+ final KeyguardManager km = getSystemService(KeyguardManager.class);
+ return km != null && (km.isKeyguardLocked() || km.isDeviceLocked());
+ }
+
+ private boolean isUserUnlockedSafe() {
+ final UserManager um = getSystemService(UserManager.class);
+ return um == null || um.isUserUnlocked();
+ }
+
+ private boolean isLowMemoryDevice() {
+ final ActivityManager am = getSystemService(ActivityManager.class);
+ if (am == null) {
+ return false;
+ }
+ final ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo();
+ am.getMemoryInfo(info);
+ return info.lowMemory;
+ }
+
+ private List recordThreadMessage(String threadKey, String title, String body) {
+ final String line = buildCompactLine(title, body);
+ synchronized (threadHistory) {
+ Deque deque = threadHistory.get(threadKey);
+ if (deque == null) {
+ deque = new ArrayDeque<>(MAX_MESSAGES_PER_THREAD);
+ threadHistory.put(threadKey, deque);
+ }
+ if (!line.isEmpty() && !line.equals(deque.peekLast())) {
+ while (deque.size() >= MAX_MESSAGES_PER_THREAD) {
+ deque.removeFirst();
+ }
+ deque.addLast(line);
+ }
+ return new ArrayList<>(deque);
+ }
+ }
+
+ private static Adjustment buildAdjustment(
+ StatusBarNotification sbn, int bundleType, String summary) {
+ final Bundle signals = new Bundle();
+ final int normalizedType = normalizeBundleType(bundleType);
+ final String cleanSummary = sanitizeSummary(summary);
+ if (normalizedType != Adjustment.TYPE_OTHER) {
+ signals.putInt(Adjustment.KEY_TYPE, normalizedType);
+ }
+ if (!cleanSummary.isEmpty()) {
+ signals.putCharSequence(Adjustment.KEY_SUMMARIZATION, cleanSummary);
+ }
+ if (signals.isEmpty()) {
+ return null;
+ }
+ return new Adjustment(
+ sbn.getPackageName(),
+ sbn.getKey(),
+ signals,
+ "alpha-notification-assistant",
+ sbn.getUser());
+ }
+
+ private static boolean shouldSkipNotification(Notification notification) {
+ if ((notification.flags & Notification.FLAG_GROUP_SUMMARY) != 0) {
+ return true;
+ }
+ if ((notification.flags & Notification.FLAG_ONGOING_EVENT) != 0) {
+ return true;
+ }
+ if (notification.category != null && SKIPPED_CATEGORIES.contains(notification.category)) {
+ return true;
+ }
+ return false;
+ }
+
+ private static boolean isConversationNotification(
+ Notification notification, NotificationChannel channel, String convTitle) {
+ if (Notification.CATEGORY_MESSAGE.equals(notification.category)) {
+ return true;
+ }
+ if (convTitle != null && !convTitle.isEmpty()) {
+ return true;
+ }
+ if (notification.extras != null
+ && notification.extras.getBoolean(Notification.EXTRA_IS_GROUP_CONVERSATION, false)) {
+ return true;
+ }
+ return channel != null && channel.getConversationId() != null
+ && !channel.getConversationId().isEmpty();
+ }
+
+ private static String extractExtraText(Bundle extras, String key) {
+ if (extras == null) {
+ return "";
+ }
+ final CharSequence value = extras.getCharSequence(key);
+ return value == null ? "" : value.toString().trim();
+ }
+
+ private static String buildThreadKey(String pkg, String key, String groupKey) {
+ if (groupKey != null && !groupKey.isEmpty()) {
+ return pkg + "|" + groupKey;
+ }
+ return pkg + "|" + key;
+ }
+
+ private static String buildCompactLine(String title, String body) {
+ final String cleanBody = collapseWhitespace(body);
+ final String cleanTitle = collapseWhitespace(title);
+ if (cleanBody.isEmpty()) {
+ return cleanTitle;
+ }
+ if (cleanTitle.isEmpty() || cleanBody.startsWith(cleanTitle)) {
+ return cleanBody;
+ }
+ return cleanTitle + ": " + cleanBody;
+ }
+
+ /**
+ * Classifies a notification's privacy sensitivity fail-closed.
+ * Any non-{@link Sensitivity#CLEAR} result MUST suppress summarization, IPC, and storage.
+ */
+ public static Sensitivity classifySensitivity(
+ String packageName,
+ String title,
+ String text,
+ String bigText,
+ String category,
+ int visibility,
+ boolean deviceLocked,
+ boolean userUnlocked) {
+ if (!userUnlocked) {
+ return Sensitivity.LOCKSCREEN_PRIVATE;
+ }
+ if (visibility == Notification.VISIBILITY_SECRET) {
+ return Sensitivity.LOCKSCREEN_PRIVATE;
+ }
+ if (deviceLocked && visibility == Notification.VISIBILITY_PRIVATE) {
+ return Sensitivity.LOCKSCREEN_PRIVATE;
+ }
+ final String lowerPkg = packageName == null ? "" : packageName.toLowerCase(Locale.ROOT);
+ if (containsAnyToken(lowerPkg, CREDENTIAL_PACKAGE_TOKENS)) {
+ return Sensitivity.CREDENTIAL;
+ }
+ if (containsAnyToken(lowerPkg, FINANCIAL_PACKAGE_TOKENS)) {
+ return Sensitivity.FINANCIAL;
+ }
+ final String combined = joinNonEmpty(title, text, bigText);
+ if (combined.isEmpty()) {
+ return Sensitivity.CLEAR;
+ }
+ if (OTP_CONTEXT_PATTERN.matcher(combined).find()
+ && OTP_DIGITS_PATTERN.matcher(combined).find()) {
+ return Sensitivity.OTP_CODE;
+ }
+ if (CREDENTIAL_CONTENT_PATTERN.matcher(combined).find()) {
+ return Sensitivity.CREDENTIAL;
+ }
+ if (FINANCIAL_CONTENT_PATTERN.matcher(combined).find()) {
+ return Sensitivity.FINANCIAL;
+ }
+ return Sensitivity.CLEAR;
+ }
+
+ /** Classifies a clear notification onto an Android 17 {@link Adjustment#KEY_TYPE} bundle id. */
+ public static int classifyBundleType(
+ String packageName,
+ String category,
+ String title,
+ String body,
+ boolean isConversation) {
+ if (isConversation || Notification.CATEGORY_MESSAGE.equals(category)) {
+ return Adjustment.TYPE_OTHER;
+ }
+ final String lowerPkg = packageName == null ? "" : packageName.toLowerCase(Locale.ROOT);
+ final String combined = joinNonEmpty(title, body, "");
+ if (Notification.CATEGORY_PROMO.equals(category)
+ || PROMO_CONTENT_PATTERN.matcher(combined).find()) {
+ return Adjustment.TYPE_PROMOTION;
+ }
+ if (Notification.CATEGORY_RECOMMENDATION.equals(category)
+ || containsAnyToken(lowerPkg, RECOMMENDATION_PACKAGE_TOKENS)
+ || RECOMMENDATION_CONTENT_PATTERN.matcher(combined).find()) {
+ return Adjustment.TYPE_CONTENT_RECOMMENDATION;
+ }
+ if (containsAnyToken(lowerPkg, NEWS_PACKAGE_TOKENS)
+ || NEWS_CONTENT_PATTERN.matcher(combined).find()) {
+ return Adjustment.TYPE_NEWS;
+ }
+ if (Notification.CATEGORY_SOCIAL.equals(category)
+ || containsAnyToken(lowerPkg, SOCIAL_PACKAGE_TOKENS)
+ || SOCIAL_CONTENT_PATTERN.matcher(combined).find()) {
+ return Adjustment.TYPE_SOCIAL_MEDIA;
+ }
+ return Adjustment.TYPE_OTHER;
+ }
+
+ /** Produces a clean, concise single-line deterministic fallback summary with zero slop. */
+ public static String buildDeterministicSummary(
+ String title, List messages, int bundleType) {
+ if (messages == null || messages.isEmpty()) {
+ return sanitizeSummary(title);
+ }
+ final int count = messages.size();
+ if (count == 1) {
+ return sanitizeSummary(messages.get(0));
+ }
+ final String latest = collapseWhitespace(messages.get(count - 1));
+ final String cleanTitle = collapseWhitespace(title);
+ final String prefix = cleanTitle.isEmpty()
+ ? count + " updates: "
+ : cleanTitle + " (" + count + "): ";
+ final String strippedLatest = !cleanTitle.isEmpty() && latest.startsWith(cleanTitle + ": ")
+ ? latest.substring(cleanTitle.length() + 2)
+ : latest;
+ return sanitizeSummary(prefix + strippedLatest);
+ }
+
+ /** Strips control characters, AI-slop prefixes, and enforces {@link #MAX_SUMMARY_CHARS}. */
+ public static String sanitizeSummary(String raw) {
+ if (raw == null) {
+ return "";
+ }
+ String clean = collapseWhitespace(raw);
+ clean = SLOP_PREFIX_PATTERN.matcher(clean).replaceFirst("").trim();
+ if (clean.length() > MAX_SUMMARY_CHARS) {
+ int cut = MAX_SUMMARY_CHARS - 1;
+ int lastSpace = clean.lastIndexOf(' ', cut);
+ if (lastSpace > MAX_SUMMARY_CHARS / 2) {
+ cut = lastSpace;
+ }
+ clean = clean.substring(0, cut).trim() + "\u2026";
+ }
+ return clean;
+ }
+
+ /** Clamps any incoming bundle type integer to a known Android 17 {@code Adjustment.TYPE_*}. */
+ public static int normalizeBundleType(int type) {
+ switch (type) {
+ case Adjustment.TYPE_PROMOTION:
+ case Adjustment.TYPE_NEWS:
+ case Adjustment.TYPE_SOCIAL_MEDIA:
+ case Adjustment.TYPE_CONTENT_RECOMMENDATION:
+ return type;
+ default:
+ return Adjustment.TYPE_OTHER;
+ }
+ }
+
+ /** Enforces release-only signing on user builds while allowing debug signing on debuggable builds. */
+ static boolean isAuthorizedSigner(
+ boolean isDebuggableBuild, boolean matchesRelease, boolean matchesDebug) {
+ if (matchesRelease) {
+ return true;
+ }
+ return isDebuggableBuild && matchesDebug;
+ }
+
+ /** Decodes a lowercase hexadecimal SHA-256 certificate digest into bytes. */
+ static byte[] decodeHexDigest(String hex) {
+ final int len = hex.length();
+ final byte[] out = new byte[len / 2];
+ for (int i = 0; i < len; i += 2) {
+ out[i / 2] = (byte) Integer.parseInt(hex.substring(i, i + 2), 16);
+ }
+ return out;
+ }
+
+ private static boolean containsAnyToken(String haystack, Set tokens) {
+ if (haystack.isEmpty()) {
+ return false;
+ }
+ for (String token : tokens) {
+ if (haystack.contains(token)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static String joinNonEmpty(String a, String b, String c) {
+ final StringBuilder sb = new StringBuilder();
+ appendPiece(sb, a);
+ appendPiece(sb, b);
+ appendPiece(sb, c);
+ return sb.toString();
+ }
+
+ private static void appendPiece(StringBuilder sb, String piece) {
+ if (piece == null) {
+ return;
+ }
+ final String trimmed = piece.trim();
+ if (trimmed.isEmpty()) {
+ return;
+ }
+ if (sb.length() > 0) {
+ sb.append(' ');
+ }
+ sb.append(trimmed);
+ }
+
+ private static String collapseWhitespace(String value) {
+ if (value == null || value.isEmpty()) {
+ return "";
+ }
+ final StringBuilder filtered = new StringBuilder(value.length());
+ for (int i = 0; i < value.length(); i++) {
+ final char ch = value.charAt(i);
+ if (ch == '\r' || ch == '\n' || ch == '\t') {
+ filtered.append(' ');
+ } else if (!Character.isISOControl(ch)) {
+ filtered.append(ch);
+ }
+ }
+ return MULTI_SPACE_PATTERN.matcher(filtered.toString()).replaceAll(" ").trim();
+ }
+}
diff --git a/apps/app/aosp/notification-assistant/test_nas_plan.py b/apps/app/aosp/notification-assistant/test_nas_plan.py
new file mode 100644
index 0000000000..9fd812943c
--- /dev/null
+++ b/apps/app/aosp/notification-assistant/test_nas_plan.py
@@ -0,0 +1,326 @@
+from pathlib import Path
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+import xml.etree.ElementTree as ET
+
+ROOT = Path(__file__).resolve().parent
+BRANDING_SYSTEM_ENTRY = ROOT.parent / 'branding' / 'system-entry'
+sys.path.insert(0, str(BRANDING_SYSTEM_ENTRY))
+
+from portable_tools import android_api_jar, java_binary
+
+API = android_api_jar(36)
+ANDROID_NS = '{http://schemas.android.com/apk/res/android}'
+RELEASE_SIGNER = ROOT.parent / 'signing' / 'release-signer.json'
+
+SYSTEM_API_STUBS = {
+ 'android/service/notification/Adjustment.java': (
+ 'package android.service.notification;'
+ 'import android.os.Bundle;'
+ 'import android.os.UserHandle;'
+ 'public final class Adjustment {'
+ ' public static final String KEY_TYPE = "key_type";'
+ ' public static final String KEY_SUMMARIZATION = "key_summarization";'
+ ' public static final int TYPE_OTHER = 0;'
+ ' public static final int TYPE_PROMOTION = 1;'
+ ' public static final int TYPE_NEWS = 2;'
+ ' public static final int TYPE_SOCIAL_MEDIA = 3;'
+ ' public static final int TYPE_CONTENT_RECOMMENDATION = 4;'
+ ' private final String mPackage;'
+ ' private final String mKey;'
+ ' private final Bundle mSignals;'
+ ' private final CharSequence mExplanation;'
+ ' private final UserHandle mUserHandle;'
+ ' public Adjustment(String pkg, String key, Bundle signals,'
+ ' CharSequence explanation, UserHandle userHandle) {'
+ ' this.mPackage = pkg;'
+ ' this.mKey = key;'
+ ' this.mSignals = signals;'
+ ' this.mExplanation = explanation;'
+ ' this.mUserHandle = userHandle;'
+ ' }'
+ ' public String getPackage() { return mPackage; }'
+ ' public String getKey() { return mKey; }'
+ ' public Bundle getSignals() { return mSignals; }'
+ ' public CharSequence getExplanation() { return mExplanation; }'
+ ' public UserHandle getUserHandle() { return mUserHandle; }'
+ '}'
+ ),
+ 'android/service/notification/NotificationStats.java': (
+ 'package android.service.notification;'
+ 'public final class NotificationStats {}'
+ ),
+ 'android/service/notification/NotificationAssistantService.java': (
+ 'package android.service.notification;'
+ 'import android.app.NotificationChannel;'
+ 'import java.util.List;'
+ 'public abstract class NotificationAssistantService extends NotificationListenerService {'
+ ' public abstract Adjustment onNotificationEnqueued(StatusBarNotification sbn);'
+ ' public Adjustment onNotificationEnqueued(StatusBarNotification sbn,'
+ ' NotificationChannel channel) {'
+ ' return onNotificationEnqueued(sbn);'
+ ' }'
+ ' public Adjustment onNotificationEnqueued(StatusBarNotification sbn,'
+ ' NotificationChannel channel, RankingMap rankingMap) {'
+ ' return onNotificationEnqueued(sbn, channel);'
+ ' }'
+ ' public abstract void onNotificationSnoozedUntilContext('
+ ' StatusBarNotification sbn, String snoozeCriterionId);'
+ ' public void onNotificationsSeen(List keys) {}'
+ ' public void onNotificationRemoved(StatusBarNotification sbn,'
+ ' RankingMap rankingMap, NotificationStats stats, int reason) {}'
+ ' public final void adjustNotification(Adjustment adjustment) {}'
+ '}'
+ ),
+}
+
+
+class NotificationAssistantPlanTest(unittest.TestCase):
+ def test_aosp_build_manifest_permissions_overlay_and_sepolicy_invariants(self):
+ bp = (ROOT / 'Android.bp').read_text()
+ self.assertIn('name: "AlphaNotificationAssistant"', bp)
+ self.assertIn('privileged: true', bp)
+ self.assertIn('system_ext_specific: true', bp)
+ self.assertIn('certificate: "platform"', bp)
+ self.assertIn('platform_apis: true', bp)
+ self.assertIn('name: "AlphaNotificationAssistantPrivappPermissions"', bp)
+ self.assertIn('name: "AlphaNotificationAssistantOverlay"', bp)
+
+ mk = (ROOT / 'notification-assistant.mk').read_text()
+ self.assertIn('AlphaNotificationAssistant', mk)
+ self.assertIn('AlphaNotificationAssistantPrivappPermissions', mk)
+ self.assertIn('AlphaNotificationAssistantOverlay', mk)
+ self.assertIn('SYSTEM_EXT_PRIVATE_SEPOLICY_DIRS += $(alpha_notification_assistant_dir)/sepolicy', mk)
+
+ manifest = ET.fromstring((ROOT / 'AndroidManifest.xml').read_text())
+ self.assertEqual(manifest.attrib['package'], 'ai.alphacompute.notificationassistant')
+ perms = {node.attrib[ANDROID_NS + 'name'] for node in manifest.findall('uses-permission')}
+ self.assertEqual(perms, {
+ 'android.permission.STATUS_BAR_SERVICE',
+ })
+ self.assertNotIn('ai.alphacompute.permission.AGENT_IPC', perms)
+ self.assertNotIn('android.permission.INTERNET', perms)
+ self.assertNotIn('android.permission.INJECT_EVENTS', perms)
+ self.assertNotIn('android.permission.WRITE_SECURE_SETTINGS', perms)
+
+ service = manifest.find('application/service')
+ self.assertIsNotNone(service)
+ self.assertEqual(
+ service.attrib[ANDROID_NS + 'permission'],
+ 'android.permission.BIND_NOTIFICATION_ASSISTANT_SERVICE',
+ )
+
+ privapp = ET.fromstring((ROOT / 'privapp-permissions-alpha-notification-assistant.xml').read_text())
+ blocks = privapp.findall('privapp-permissions')
+ self.assertEqual(len(blocks), 1)
+ self.assertEqual(blocks[0].attrib['package'], 'ai.alphacompute.notificationassistant')
+ granted = {p.attrib['name'] for p in blocks[0].findall('permission')}
+ self.assertEqual(granted, {
+ 'android.permission.BIND_NOTIFICATION_ASSISTANT_SERVICE',
+ 'android.permission.STATUS_BAR_SERVICE',
+ })
+
+ overlay_manifest = ET.fromstring((ROOT / 'overlay/AndroidManifest.xml').read_text())
+ self.assertEqual(overlay_manifest.attrib['package'], 'ai.alphacompute.alpha.overlay.notificationassistant')
+ overlay_tag = overlay_manifest.find('overlay')
+ self.assertIsNotNone(overlay_tag)
+ self.assertEqual(overlay_tag.attrib[ANDROID_NS + 'targetPackage'], 'android')
+ self.assertEqual(overlay_tag.attrib[ANDROID_NS + 'isStatic'], 'true')
+
+ overlay_cfg = ET.fromstring((ROOT / 'overlay/res/values/config.xml').read_text())
+ strings = {node.attrib['name']: (node.text or '').strip() for node in overlay_cfg.findall('string')}
+ self.assertEqual(
+ strings.get('config_defaultAssistantAccessComponent'),
+ 'ai.alphacompute.notificationassistant/ai.alphacompute.notifications.aosp.AlphaNotificationAssistantService',
+ )
+ self.assertEqual(
+ strings.get('config_systemNotificationIntelligence'),
+ 'ai.alphacompute.notificationassistant',
+ )
+
+ te = (ROOT / 'sepolicy/alpha_notification_assistant.te').read_text()
+ self.assertIn('type alpha_notification_assistant, domain, coredomain;', te)
+ self.assertIn('app_domain(alpha_notification_assistant)', te)
+ self.assertNotIn('net_domain(', te)
+ self.assertIn(
+ 'neverallow alpha_notification_assistant self:{ tcp_socket udp_socket rawip_socket icmp_socket packet_socket }',
+ te,
+ )
+ self.assertIn('notification_service', te)
+
+ seapp = (ROOT / 'sepolicy/seapp_contexts').read_text().strip()
+ self.assertIn('seinfo=platform', seapp)
+ self.assertIn('name=ai.alphacompute.notificationassistant', seapp)
+ self.assertIn('isPrivApp=true', seapp)
+ self.assertIn('domain=alpha_notification_assistant', seapp)
+
+ service_src = (ROOT / 'src/ai/alphacompute/notifications/aosp/AlphaNotificationAssistantService.java').read_text()
+ self.assertIn('Adjustment.KEY_SUMMARIZATION', service_src)
+ self.assertIn('Adjustment.KEY_TYPE', service_src)
+ self.assertIn('PackageManager.MATCH_SYSTEM_ONLY', service_src)
+ self.assertIn('hasSigningCertificate(', service_src)
+ self.assertNotIn('//', service_src)
+
+ def test_service_compiles_with_android_api36_and_policy_runs_on_jvm(self):
+ self.assertTrue(API.exists(), 'Android API 36 android.jar required')
+ expected_signer = json.loads(RELEASE_SIGNER.read_text())['signerSha256'].lower()
+ self.assertRegex(expected_signer, r'^[0-9a-f]{64}$')
+
+ with tempfile.TemporaryDirectory(prefix='alpha-nas-') as directory:
+ tmp = Path(directory)
+ stub_dir = tmp / 'stubs'
+ classes_dir = tmp / 'classes'
+ stub_dir.mkdir()
+ classes_dir.mkdir()
+
+ compile_files = [
+ str(ROOT / 'src/ai/alphacompute/notifications/aosp/AlphaNotificationAssistantService.java'),
+ ]
+ for rel, content in SYSTEM_API_STUBS.items():
+ path = stub_dir / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(content)
+ compile_files.append(str(path))
+
+ harness = tmp / 'NasPolicyTest.java'
+ harness.write_text(f'''
+package ai.alphacompute.notifications.aosp;
+
+import android.app.Notification;
+import android.service.notification.Adjustment;
+import java.util.Arrays;
+import java.util.Collections;
+
+public final class NasPolicyTest {{
+ private static void check(boolean condition, String label) {{
+ if (!condition) {{
+ throw new AssertionError("Failed: " + label);
+ }}
+ }}
+
+ private static String toHex(byte[] bytes) {{
+ StringBuilder sb = new StringBuilder(bytes.length * 2);
+ for (byte b : bytes) {{
+ sb.append(String.format("%02x", b & 0xff));
+ }}
+ return sb.toString();
+ }}
+
+ public static void main(String[] args) {{
+ check("{expected_signer}".equals(toHex(AlphaNotificationAssistantService.ALPHA_SIGNER_SHA256)),
+ "signer digest matches release-signer.json");
+ check(AlphaNotificationAssistantService.isAuthorizedSigner(false, true, false),
+ "user build accepts release signer");
+ check(!AlphaNotificationAssistantService.isAuthorizedSigner(false, false, true),
+ "user build rejects debug signer");
+ check(AlphaNotificationAssistantService.isAuthorizedSigner(true, false, true),
+ "userdebug build accepts debug signer");
+
+ check(AlphaNotificationAssistantService.classifySensitivity(
+ "com.example.chat", "Security", "Your verification code is 482910. Do not share this code.", "",
+ Notification.CATEGORY_MESSAGE, Notification.VISIBILITY_PUBLIC, false, true)
+ == AlphaNotificationAssistantService.Sensitivity.OTP_CODE,
+ "OTP code redacted");
+ check(AlphaNotificationAssistantService.classifySensitivity(
+ "com.x8bit.bitwarden", "Vault", "Unlocked", "",
+ null, Notification.VISIBILITY_PUBLIC, false, true)
+ == AlphaNotificationAssistantService.Sensitivity.CREDENTIAL,
+ "password manager redacted");
+ check(AlphaNotificationAssistantService.classifySensitivity(
+ "com.chase.sig.android", "Alert", "Deposit posted", "",
+ null, Notification.VISIBILITY_PUBLIC, false, true)
+ == AlphaNotificationAssistantService.Sensitivity.FINANCIAL,
+ "banking package redacted");
+ check(AlphaNotificationAssistantService.classifySensitivity(
+ "com.example.mail", "Notice", "Wire transfer of $500 authorized from card ending in 4242", "",
+ null, Notification.VISIBILITY_PUBLIC, false, true)
+ == AlphaNotificationAssistantService.Sensitivity.FINANCIAL,
+ "financial content redacted");
+ check(AlphaNotificationAssistantService.classifySensitivity(
+ "com.example.chat", "Alex", "See you at 6", "",
+ Notification.CATEGORY_MESSAGE, Notification.VISIBILITY_PRIVATE, true, true)
+ == AlphaNotificationAssistantService.Sensitivity.LOCKSCREEN_PRIVATE,
+ "lockscreen-private redacted while locked");
+ check(AlphaNotificationAssistantService.classifySensitivity(
+ "com.example.chat", "Alex", "See you at 6", "",
+ Notification.CATEGORY_MESSAGE, Notification.VISIBILITY_SECRET, false, true)
+ == AlphaNotificationAssistantService.Sensitivity.LOCKSCREEN_PRIVATE,
+ "VISIBILITY_SECRET always redacted");
+ check(AlphaNotificationAssistantService.classifySensitivity(
+ "com.example.chat", "Alex", "Are we still on for lunch at noon?", "",
+ Notification.CATEGORY_MESSAGE, Notification.VISIBILITY_PUBLIC, false, true)
+ == AlphaNotificationAssistantService.Sensitivity.CLEAR,
+ "normal chat message is clear");
+
+ check(AlphaNotificationAssistantService.classifyBundleType(
+ "com.shop.app", Notification.CATEGORY_PROMO, "Flash Sale", "Save 30% off today only", false)
+ == Adjustment.TYPE_PROMOTION,
+ "promo classified");
+ check(AlphaNotificationAssistantService.classifyBundleType(
+ "com.nytimes.android", null, "Morning Briefing", "Top stories today", false)
+ == Adjustment.TYPE_NEWS,
+ "news classified");
+ check(AlphaNotificationAssistantService.classifyBundleType(
+ "com.instagram.android", Notification.CATEGORY_SOCIAL, "Maya", "Maya liked your photo", false)
+ == Adjustment.TYPE_SOCIAL_MEDIA,
+ "social classified");
+ check(AlphaNotificationAssistantService.classifyBundleType(
+ "com.google.android.youtube", Notification.CATEGORY_RECOMMENDATION, "New video", "Recommended for you", false)
+ == Adjustment.TYPE_CONTENT_RECOMMENDATION,
+ "recommendation classified");
+ check(AlphaNotificationAssistantService.classifyBundleType(
+ "org.thoughtcrime.securesms", Notification.CATEGORY_MESSAGE, "Sam", "On my way", true)
+ == Adjustment.TYPE_OTHER,
+ "conversation stays out of promo/news/social bundles");
+
+ String cleaned = AlphaNotificationAssistantService.sanitizeSummary("Summary: Hello\\nworld\\tfrom Alpha ");
+ check("Hello world from Alpha".equals(cleaned), "strips slop prefix and newlines: " + cleaned);
+
+ String longInput = "A".repeat(220);
+ String bounded = AlphaNotificationAssistantService.sanitizeSummary(longInput);
+ check(bounded.length() <= AlphaNotificationAssistantService.MAX_SUMMARY_CHARS,
+ "summary length bounded <= 140");
+
+ String det = AlphaNotificationAssistantService.buildDeterministicSummary(
+ "Design Chat",
+ Arrays.asList("Design Chat: Mockups ready", "Design Chat: Let's review at 3pm"),
+ Adjustment.TYPE_OTHER);
+ check("Design Chat (2): Let's review at 3pm".equals(det), "deterministic batch summary: " + det);
+
+ check("Single update".equals(AlphaNotificationAssistantService.buildDeterministicSummary(
+ "App", Collections.singletonList("Single update"), Adjustment.TYPE_NEWS)),
+ "deterministic single summary");
+ System.out.println("PASS notification-assistant compile and policy tests");
+ }}
+}}
+''')
+ compile_files.append(str(harness))
+
+ subprocess.run(
+ [
+ java_binary('javac'),
+ '--release', '17',
+ '-Xlint:all',
+ '-classpath', str(API),
+ '-d', str(classes_dir),
+ *compile_files,
+ ],
+ check=True,
+ capture_output=True,
+ )
+ output = subprocess.check_output(
+ [
+ java_binary('java'),
+ '-cp', f'{classes_dir}:{API}',
+ 'ai.alphacompute.notifications.aosp.NasPolicyTest',
+ ],
+ text=True,
+ )
+ self.assertIn('PASS notification-assistant compile and policy tests', output)
+
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/apps/app/aosp/sandboxed-play/installer/src/ai/alphacompute/playinstaller/AlphaPlayInstallerService.java b/apps/app/aosp/sandboxed-play/installer/src/ai/alphacompute/playinstaller/AlphaPlayInstallerService.java
index d701ad04e1..ae0aff4b49 100644
--- a/apps/app/aosp/sandboxed-play/installer/src/ai/alphacompute/playinstaller/AlphaPlayInstallerService.java
+++ b/apps/app/aosp/sandboxed-play/installer/src/ai/alphacompute/playinstaller/AlphaPlayInstallerService.java
@@ -12,6 +12,11 @@
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
+import android.os.Parcel;
+import android.os.ParcelFileDescriptor;
+import android.os.RemoteException;
+import java.io.File;
+import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@@ -57,17 +62,70 @@ public final class AlphaPlayInstallerService extends Service {
static final String ALPHA_DEBUG_SIGNER_HEX =
"227ddd0bf51116a69fb6f8f8ceb32ee2df9ed086471bceec4f9a26f48f31d5d5";
+ /** Cross-process Binder interface descriptor for verified Alpha install transactions. */
+ public static final String BINDER_DESCRIPTOR =
+ "ai.alphacompute.playinstaller.IAlphaPlayInstaller";
+
+ /** Binder transaction code for single-package verified APK installation via ParcelFileDescriptor. */
+ public static final int TRANSACTION_INSTALL_PACKAGE = IBinder.FIRST_CALL_TRANSACTION;
+
private static final int COPY_BUFFER_BYTES = 64 * 1024;
+ private static final long MAX_IPC_APK_BYTES = 512L * 1024L * 1024L;
private final LocalBinder localBinder = new LocalBinder();
- /** Local service handle for verified callers. */
+ /** Service binder handling both local callers and cross-process AlphaPlayBridge IPC. */
public final class LocalBinder extends Binder {
/** Returns the hosting installer service after verifying caller identity. */
public AlphaPlayInstallerService getVerifiedService() {
enforceAlphaCaller();
return AlphaPlayInstallerService.this;
}
+
+ @Override
+ protected boolean onTransact(int code, Parcel data, Parcel reply, int flags)
+ throws RemoteException {
+ if (code == TRANSACTION_INSTALL_PACKAGE) {
+ data.enforceInterface(BINDER_DESCRIPTOR);
+ final String packageName = data.readString();
+ final long versionCode = data.readLong();
+ final String apkFileName = data.readString();
+ final String apkSha256 = data.readString();
+ final String signerSha256 = data.readString();
+ final long sizeBytes = data.readLong();
+ final ParcelFileDescriptor apkFd = data.readInt() != 0
+ ? ParcelFileDescriptor.CREATOR.createFromParcel(data)
+ : null;
+ final PlayPackageVerifier.PlayPackageEntry entry =
+ new PlayPackageVerifier.PlayPackageEntry(
+ packageName,
+ versionCode,
+ apkFileName,
+ apkSha256,
+ signerSha256,
+ sizeBytes);
+ final PlayPackageVerifier.VerificationResult result;
+ try (ParcelFileDescriptor ownedFd = apkFd) {
+ result = installVerifiedStagedApk(entry, ownedFd);
+ } catch (IOException closeError) {
+ if (reply != null) {
+ reply.writeNoException();
+ reply.writeInt(0);
+ reply.writeString("APK_FD_CLOSE_ERROR");
+ reply.writeString(closeError.getMessage());
+ }
+ return true;
+ }
+ if (reply != null) {
+ reply.writeNoException();
+ reply.writeInt(result.ok() ? 1 : 0);
+ reply.writeString(result.failureCode());
+ reply.writeString(result.message());
+ }
+ return true;
+ }
+ return super.onTransact(code, data, reply, flags);
+ }
}
@Override
@@ -75,6 +133,112 @@ public IBinder onBind(Intent intent) {
return localBinder;
}
+ /**
+ * Verifies a single staged APK delivered across process boundaries via a read-only
+ * {@link ParcelFileDescriptor}, enforces strict GSF -> GMS -> Play Store ordering against
+ * already-installed packages, verifies SHA-256 and pinned official Google signing cert,
+ * and commits the package into {@code /data/app} via {@link PackageInstaller.Session}.
+ */
+ public PlayPackageVerifier.VerificationResult installVerifiedStagedApk(
+ PlayPackageVerifier.PlayPackageEntry entry, ParcelFileDescriptor apkFd) {
+ enforceAlphaCaller();
+ if (entry == null) {
+ return PlayPackageVerifier.VerificationResult.fail("NULL_ENTRY", "Package entry is null");
+ }
+ if (apkFd == null) {
+ return PlayPackageVerifier.VerificationResult.fail("MISSING_APK_FD", "Staged APK descriptor is missing");
+ }
+ if (entry.sizeBytes() <= 0L || entry.sizeBytes() > MAX_IPC_APK_BYTES) {
+ return PlayPackageVerifier.VerificationResult.fail("INVALID_SIZE", "APK size outside permitted bounds");
+ }
+ final String expectedNext = PlayPackageVerifier.nextRequiredPackage(installedPlayPackages());
+ if (expectedNext == null || !expectedNext.equals(entry.packageName())) {
+ return PlayPackageVerifier.VerificationResult.fail(
+ "ORDER_INVARIANT_BROKEN",
+ "Expected next install " + expectedNext + ", got " + entry.packageName());
+ }
+ final String safeName = entry.apkFileName();
+ if (safeName == null || safeName.contains("/") || safeName.contains("\\") || safeName.contains("..")) {
+ return PlayPackageVerifier.VerificationResult.fail("UNSAFE_FILENAME", "Unsafe APK filename: " + safeName);
+ }
+ Path tempDir = null;
+ Path stagedFile = null;
+ try {
+ final File cacheRoot = getCacheDir();
+ if (cacheRoot == null) {
+ return PlayPackageVerifier.VerificationResult.fail("CACHE_UNAVAILABLE", "Installer cache dir unavailable");
+ }
+ tempDir = Files.createTempDirectory(cacheRoot.toPath(), "alpha-play-ipc-");
+ stagedFile = tempDir.resolve(safeName).normalize();
+ if (!stagedFile.startsWith(tempDir.normalize())) {
+ return PlayPackageVerifier.VerificationResult.fail("PATH_ESCAPE", "APK escapes staging dir");
+ }
+ final long copied = copyBounded(apkFd, stagedFile, entry.sizeBytes());
+ if (copied != entry.sizeBytes()) {
+ return PlayPackageVerifier.VerificationResult.fail(
+ "APK_SIZE_MISMATCH",
+ "Expected " + entry.sizeBytes() + " bytes, received " + copied);
+ }
+ final PlayPackageVerifier.ApkArchiveFacts facts = readArchiveFacts(stagedFile);
+ final PlayPackageVerifier.VerificationResult verified =
+ PlayPackageVerifier.verifyApk(entry, stagedFile, facts);
+ if (!verified.ok()) {
+ return verified;
+ }
+ return commitUnprivilegedSession(entry, stagedFile);
+ } catch (IOException ioError) {
+ return PlayPackageVerifier.VerificationResult.fail(
+ "IPC_STAGE_FAILED",
+ "Failed staging IPC APK: " + ioError.getMessage());
+ } finally {
+ if (stagedFile != null) {
+ try {
+ Files.deleteIfExists(stagedFile);
+ } catch (IOException ignored) {
+ }
+ }
+ if (tempDir != null) {
+ try {
+ Files.deleteIfExists(tempDir);
+ } catch (IOException ignored) {
+ }
+ }
+ }
+ }
+
+ private Set installedPlayPackages() {
+ final Set present = new HashSet<>();
+ final PackageManager pm = getPackageManager();
+ for (String pkg : PlayPackageVerifier.REQUIRED_INSTALL_ORDER) {
+ try {
+ if (pm.getPackageInfo(pkg, 0) != null) {
+ present.add(pkg);
+ }
+ } catch (PackageManager.NameNotFoundException ignored) {
+ }
+ }
+ return present;
+ }
+
+ private static long copyBounded(ParcelFileDescriptor apkFd, Path destination, long expectedBytes)
+ throws IOException {
+ long total = 0L;
+ final long maxRead = expectedBytes + 1L;
+ final byte[] buffer = new byte[COPY_BUFFER_BYTES];
+ try (InputStream input = new FileInputStream(apkFd.getFileDescriptor());
+ OutputStream output = Files.newOutputStream(destination)) {
+ int read;
+ while ((read = input.read(buffer)) != -1) {
+ total += read;
+ if (total > maxRead) {
+ return total;
+ }
+ output.write(buffer, 0, read);
+ }
+ }
+ return total;
+ }
+
/**
* Verifies every staged APK against {@code manifest} and commits each package in
* strict GSF -> GMS -> Play Store order into {@code /data/app} as an unprivileged user app.
diff --git a/apps/app/aosp/sandboxed-play/installer/test_play_verifier.py b/apps/app/aosp/sandboxed-play/installer/test_play_verifier.py
index 56f84772f2..72882a06d1 100644
--- a/apps/app/aosp/sandboxed-play/installer/test_play_verifier.py
+++ b/apps/app/aosp/sandboxed-play/installer/test_play_verifier.py
@@ -263,6 +263,11 @@ def test_java_compile_and_play_verifier_unit_suite(self):
"userdebug build accepts debug signer");
check(!AlphaPlayInstallerService.isAuthorizedSigner(true, false, false),
"userdebug build rejects unknown signer");
+ check("ai.alphacompute.playinstaller.IAlphaPlayInstaller".equals(
+ AlphaPlayInstallerService.BINDER_DESCRIPTOR),
+ "binder IPC descriptor matches AlphaPlayBridge");
+ check(AlphaPlayInstallerService.TRANSACTION_INSTALL_PACKAGE == android.os.IBinder.FIRST_CALL_TRANSACTION,
+ "binder IPC install transaction code matches FIRST_CALL_TRANSACTION");
System.out.println("PASS sandboxed-play compile and verifier unit suite");
}
diff --git a/apps/app/aosp/themes/Android.bp b/apps/app/aosp/themes/Android.bp
new file mode 100644
index 0000000000..7bb56876c8
--- /dev/null
+++ b/apps/app/aosp/themes/Android.bp
@@ -0,0 +1,219 @@
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeInkDarkFramework",
+ manifest: "packs/ink-dark/framework/AndroidManifest.xml",
+ resource_dirs: ["packs/ink-dark/framework/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeInkDarkSystemUI",
+ manifest: "packs/ink-dark/systemui/AndroidManifest.xml",
+ resource_dirs: ["packs/ink-dark/systemui/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeInkDarkLauncher3",
+ manifest: "packs/ink-dark/launcher3/AndroidManifest.xml",
+ resource_dirs: ["packs/ink-dark/launcher3/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeInkDarkSettings",
+ manifest: "packs/ink-dark/settings/AndroidManifest.xml",
+ resource_dirs: ["packs/ink-dark/settings/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeCrispLightFramework",
+ manifest: "packs/crisp-light/framework/AndroidManifest.xml",
+ resource_dirs: ["packs/crisp-light/framework/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeCrispLightSystemUI",
+ manifest: "packs/crisp-light/systemui/AndroidManifest.xml",
+ resource_dirs: ["packs/crisp-light/systemui/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeCrispLightLauncher3",
+ manifest: "packs/crisp-light/launcher3/AndroidManifest.xml",
+ resource_dirs: ["packs/crisp-light/launcher3/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeCrispLightSettings",
+ manifest: "packs/crisp-light/settings/AndroidManifest.xml",
+ resource_dirs: ["packs/crisp-light/settings/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeTokyoNightFramework",
+ manifest: "packs/tokyo-night/framework/AndroidManifest.xml",
+ resource_dirs: ["packs/tokyo-night/framework/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeTokyoNightSystemUI",
+ manifest: "packs/tokyo-night/systemui/AndroidManifest.xml",
+ resource_dirs: ["packs/tokyo-night/systemui/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeTokyoNightLauncher3",
+ manifest: "packs/tokyo-night/launcher3/AndroidManifest.xml",
+ resource_dirs: ["packs/tokyo-night/launcher3/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeTokyoNightSettings",
+ manifest: "packs/tokyo-night/settings/AndroidManifest.xml",
+ resource_dirs: ["packs/tokyo-night/settings/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeGruvboxFramework",
+ manifest: "packs/gruvbox/framework/AndroidManifest.xml",
+ resource_dirs: ["packs/gruvbox/framework/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeGruvboxSystemUI",
+ manifest: "packs/gruvbox/systemui/AndroidManifest.xml",
+ resource_dirs: ["packs/gruvbox/systemui/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeGruvboxLauncher3",
+ manifest: "packs/gruvbox/launcher3/AndroidManifest.xml",
+ resource_dirs: ["packs/gruvbox/launcher3/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeGruvboxSettings",
+ manifest: "packs/gruvbox/settings/AndroidManifest.xml",
+ resource_dirs: ["packs/gruvbox/settings/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeCatppuccinFramework",
+ manifest: "packs/catppuccin/framework/AndroidManifest.xml",
+ resource_dirs: ["packs/catppuccin/framework/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeCatppuccinSystemUI",
+ manifest: "packs/catppuccin/systemui/AndroidManifest.xml",
+ resource_dirs: ["packs/catppuccin/systemui/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeCatppuccinLauncher3",
+ manifest: "packs/catppuccin/launcher3/AndroidManifest.xml",
+ resource_dirs: ["packs/catppuccin/launcher3/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeCatppuccinSettings",
+ manifest: "packs/catppuccin/settings/AndroidManifest.xml",
+ resource_dirs: ["packs/catppuccin/settings/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeEverforestFramework",
+ manifest: "packs/everforest/framework/AndroidManifest.xml",
+ resource_dirs: ["packs/everforest/framework/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeEverforestSystemUI",
+ manifest: "packs/everforest/systemui/AndroidManifest.xml",
+ resource_dirs: ["packs/everforest/systemui/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeEverforestLauncher3",
+ manifest: "packs/everforest/launcher3/AndroidManifest.xml",
+ resource_dirs: ["packs/everforest/launcher3/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
+
+runtime_resource_overlay {
+ name: "AlphaThemeEverforestSettings",
+ manifest: "packs/everforest/settings/AndroidManifest.xml",
+ resource_dirs: ["packs/everforest/settings/res"],
+ product_specific: true,
+ certificate: "platform",
+ sdk_version: "current",
+}
diff --git a/apps/app/aosp/themes/generate-rro-themes.ts b/apps/app/aosp/themes/generate-rro-themes.ts
new file mode 100644
index 0000000000..307265ac80
--- /dev/null
+++ b/apps/app/aosp/themes/generate-rro-themes.ts
@@ -0,0 +1,76 @@
+#!/usr/bin/env node
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import {
+ THEME_PACKS,
+ evaluateThemeContrast,
+ generateAospThemeRroFiles,
+ renderThemePacksCss,
+} from "../../../../packages/design-system/themes/index.ts";
+
+const scriptDir = path.dirname(fileURLToPath(import.meta.url));
+const repoRoot = path.resolve(scriptDir, "../../../..");
+const packsCssPath = path.join(repoRoot, "packages/design-system/themes/packs.css");
+
+function verifyAllContrast(): void {
+ const failures: string[] = [];
+ for (const pack of THEME_PACKS) {
+ for (const check of evaluateThemeContrast(pack)) {
+ if (!check.pass) {
+ failures.push(`${pack.id} ${check.pair}: ${String(check.ratio)} < ${String(check.minimum)}`);
+ }
+ }
+ }
+ if (failures.length > 0) {
+ throw new Error(`WCAG contrast check failed:\n${failures.join("\n")}`);
+ }
+}
+
+function main(): void {
+ const args = new Set(process.argv.slice(2));
+ const checkOnly = args.has("--check");
+ verifyAllContrast();
+
+ const generatedFiles = [
+ ...generateAospThemeRroFiles(THEME_PACKS).map((file) => ({
+ absPath: path.join(scriptDir, file.relativePath),
+ displayPath: path.posix.join("apps/app/aosp/themes", file.relativePath),
+ content: file.content,
+ })),
+ {
+ absPath: packsCssPath,
+ displayPath: "packages/design-system/themes/packs.css",
+ content: renderThemePacksCss(THEME_PACKS),
+ },
+ ];
+
+ const drift: string[] = [];
+ let written = 0;
+
+ for (const entry of generatedFiles) {
+ const existing = existsSync(entry.absPath) ? readFileSync(entry.absPath, "utf8") : undefined;
+ if (existing === entry.content) continue;
+ if (checkOnly) {
+ drift.push(entry.displayPath);
+ continue;
+ }
+ mkdirSync(path.dirname(entry.absPath), { recursive: true });
+ writeFileSync(entry.absPath, entry.content, "utf8");
+ written += 1;
+ }
+
+ if (checkOnly) {
+ if (drift.length > 0) {
+ process.stderr.write(`Out-of-date generated theme files (${String(drift.length)}):\n${drift.join("\n")}\n`);
+ process.exitCode = 1;
+ return;
+ }
+ process.stdout.write(`OK: ${String(generatedFiles.length)} generated AOSP RRO & CSS theme files are up to date.\n`);
+ return;
+ }
+
+ process.stdout.write(`Generated ${String(generatedFiles.length)} theme files (${String(written)} updated).\n`);
+}
+
+main();
diff --git a/apps/app/aosp/themes/packs/catppuccin/framework/AndroidManifest.xml b/apps/app/aosp/themes/packs/catppuccin/framework/AndroidManifest.xml
new file mode 100644
index 0000000000..d872d86f7f
--- /dev/null
+++ b/apps/app/aosp/themes/packs/catppuccin/framework/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/catppuccin/framework/res/values/colors.xml b/apps/app/aosp/themes/packs/catppuccin/framework/res/values/colors.xml
new file mode 100644
index 0000000000..4b6c371fb9
--- /dev/null
+++ b/apps/app/aosp/themes/packs/catppuccin/framework/res/values/colors.xml
@@ -0,0 +1,36 @@
+
+
+
+ #CCA6FC
+ #CCA6FC
+ #1C1D29
+ #1C1D29
+ #FFCCA6FC
+ #1C1D29
+ #1C1D29
+ #1C1D29
+ #1C1D29
+ #262735
+ #313343
+ #3E4153
+ #12131D
+ #12131D
+ #CED7F0
+ #AAAFC2
+ #737689
+ #46495B
+ #CCA6FC
+ #CCA6FC
+ #CCA6FC
+ #3E4153
+ #262735
+ #313343
+ #3E4153
+ #262735
+ #1C1D29
+ #1C1D29
+ #1C1D29
+ #CCA6FC
+ #3E4153
+ #1C1D29
+
diff --git a/apps/app/aosp/themes/packs/catppuccin/launcher3/AndroidManifest.xml b/apps/app/aosp/themes/packs/catppuccin/launcher3/AndroidManifest.xml
new file mode 100644
index 0000000000..d4ceca73c6
--- /dev/null
+++ b/apps/app/aosp/themes/packs/catppuccin/launcher3/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/catppuccin/launcher3/res/values-night/colors.xml b/apps/app/aosp/themes/packs/catppuccin/launcher3/res/values-night/colors.xml
new file mode 100644
index 0000000000..b0e7c1e0f4
--- /dev/null
+++ b/apps/app/aosp/themes/packs/catppuccin/launcher3/res/values-night/colors.xml
@@ -0,0 +1,48 @@
+
+
+
+ #1C1D29
+ #CED7F0
+ #313343
+ #3E4153
+ #DAE1F6
+ #1C1D29
+ #46495B
+ #262735
+ #CED7F0
+ #F68199
+ #12131D
+ #CED7F0
+ #89C5F7
+ #737689
+ #313343
+ #AAAFC2
+ #9EDE9D
+ #262735
+ #CED7F0
+ #CCA6FC
+ #12131D
+ #CCA6FC
+ #313343
+ #CED7F0
+ #F68199
+ #9EDE9D
+ #FFB97A
+ #FFB97A
+ #262735
+ #262735
+ #CCA6FC
+ #CCA6FC
+ #CCA6FC
+ #CCA6FC
+ #262735
+ #262735
+ #262735
+ #313343
+ #313343
+ #3E4153
+ #313343
+ #1C1D29
+ #313343
+ #CED7F0
+
diff --git a/apps/app/aosp/themes/packs/catppuccin/launcher3/res/values/colors.xml b/apps/app/aosp/themes/packs/catppuccin/launcher3/res/values/colors.xml
new file mode 100644
index 0000000000..b0e7c1e0f4
--- /dev/null
+++ b/apps/app/aosp/themes/packs/catppuccin/launcher3/res/values/colors.xml
@@ -0,0 +1,48 @@
+
+
+
+ #1C1D29
+ #CED7F0
+ #313343
+ #3E4153
+ #DAE1F6
+ #1C1D29
+ #46495B
+ #262735
+ #CED7F0
+ #F68199
+ #12131D
+ #CED7F0
+ #89C5F7
+ #737689
+ #313343
+ #AAAFC2
+ #9EDE9D
+ #262735
+ #CED7F0
+ #CCA6FC
+ #12131D
+ #CCA6FC
+ #313343
+ #CED7F0
+ #F68199
+ #9EDE9D
+ #FFB97A
+ #FFB97A
+ #262735
+ #262735
+ #CCA6FC
+ #CCA6FC
+ #CCA6FC
+ #CCA6FC
+ #262735
+ #262735
+ #262735
+ #313343
+ #313343
+ #3E4153
+ #313343
+ #1C1D29
+ #313343
+ #CED7F0
+
diff --git a/apps/app/aosp/themes/packs/catppuccin/settings/AndroidManifest.xml b/apps/app/aosp/themes/packs/catppuccin/settings/AndroidManifest.xml
new file mode 100644
index 0000000000..bee8a23359
--- /dev/null
+++ b/apps/app/aosp/themes/packs/catppuccin/settings/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/catppuccin/settings/res/values/colors.xml b/apps/app/aosp/themes/packs/catppuccin/settings/res/values/colors.xml
new file mode 100644
index 0000000000..97521313a9
--- /dev/null
+++ b/apps/app/aosp/themes/packs/catppuccin/settings/res/values/colors.xml
@@ -0,0 +1,19 @@
+
+
+
+ #3E4153
+ #1C1D29
+ #46495B
+ #262735
+ #CED7F0
+ #AAAFC2
+ #CCA6FC
+ #12131D
+ #CCA6FC
+ #1C1D29
+ #262735
+ #262735
+ #CED7F0
+ #AAAFC2
+ #313343
+
diff --git a/apps/app/aosp/themes/packs/catppuccin/systemui/AndroidManifest.xml b/apps/app/aosp/themes/packs/catppuccin/systemui/AndroidManifest.xml
new file mode 100644
index 0000000000..d7622ba0ed
--- /dev/null
+++ b/apps/app/aosp/themes/packs/catppuccin/systemui/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/catppuccin/systemui/res/values/colors.xml b/apps/app/aosp/themes/packs/catppuccin/systemui/res/values/colors.xml
new file mode 100644
index 0000000000..c54b7fe89f
--- /dev/null
+++ b/apps/app/aosp/themes/packs/catppuccin/systemui/res/values/colors.xml
@@ -0,0 +1,21 @@
+
+
+
+ #3E4153
+ #1C1D29
+ #46495B
+ #262735
+ #F68199
+ #CED7F0
+ #313343
+ #AAAFC2
+ #9EDE9D
+ #CCA6FC
+ #12131D
+ #FFB97A
+ #CCA6FC
+ #CCA6FC
+ #1C1D29
+ #12131D
+ #1C1D29
+
diff --git a/apps/app/aosp/themes/packs/crisp-light/framework/AndroidManifest.xml b/apps/app/aosp/themes/packs/crisp-light/framework/AndroidManifest.xml
new file mode 100644
index 0000000000..b7ab6bf6d2
--- /dev/null
+++ b/apps/app/aosp/themes/packs/crisp-light/framework/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/crisp-light/framework/res/values/colors.xml b/apps/app/aosp/themes/packs/crisp-light/framework/res/values/colors.xml
new file mode 100644
index 0000000000..f21cc3fcc1
--- /dev/null
+++ b/apps/app/aosp/themes/packs/crisp-light/framework/res/values/colors.xml
@@ -0,0 +1,32 @@
+
+
+
+ #0000FF
+ #0000FF
+ #FFFFFF
+ #FFFFFF
+ #FF0000FF
+ #FFFFFF
+ #FFFFFF
+ #FFFFFF
+ #FFFFFF
+ #FAFAFA
+ #F3F3F3
+ #E6E6E6
+ #000000
+ #FFFFFF
+ #000000
+ #666666
+ #8C8C8C
+ #E3E3E3
+ #E6E6E6
+ #0000FF
+ #F3F3F3
+ #E6E6E6
+ #FAFAFA
+ #FAFAFA
+ #FFFFFF
+ #FFFFFF
+ #0000FF
+ #F3F3F3
+
diff --git a/apps/app/aosp/themes/packs/crisp-light/launcher3/AndroidManifest.xml b/apps/app/aosp/themes/packs/crisp-light/launcher3/AndroidManifest.xml
new file mode 100644
index 0000000000..4c9c00d993
--- /dev/null
+++ b/apps/app/aosp/themes/packs/crisp-light/launcher3/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/crisp-light/launcher3/res/values-night/colors.xml b/apps/app/aosp/themes/packs/crisp-light/launcher3/res/values-night/colors.xml
new file mode 100644
index 0000000000..c8f82600aa
--- /dev/null
+++ b/apps/app/aosp/themes/packs/crisp-light/launcher3/res/values-night/colors.xml
@@ -0,0 +1,48 @@
+
+
+
+ #FFFFFF
+ #000000
+ #F3F3F3
+ #E6E6E6
+ #000000
+ #FFFFFF
+ #E3E3E3
+ #FAFAFA
+ #000000
+ #C5221F
+ #FFFFFF
+ #000000
+ #0000B8
+ #8C8C8C
+ #F3F3F3
+ #666666
+ #147A38
+ #FFFFFF
+ #000000
+ #0000FF
+ #FFFFFF
+ #0000FF
+ #F3F3F3
+ #000000
+ #D93025
+ #1E8E3E
+ #E8A200
+ #8F5A00
+ #FAFAFA
+ #FAFAFA
+ #0000FF
+ #0000FF
+ #0000FF
+ #0000FF
+ #FFFFFF
+ #FAFAFA
+ #FAFAFA
+ #F3F3F3
+ #F3F3F3
+ #E6E6E6
+ #F3F3F3
+ #FFFFFF
+ #F3F3F3
+ #000000
+
diff --git a/apps/app/aosp/themes/packs/crisp-light/launcher3/res/values/colors.xml b/apps/app/aosp/themes/packs/crisp-light/launcher3/res/values/colors.xml
new file mode 100644
index 0000000000..c8f82600aa
--- /dev/null
+++ b/apps/app/aosp/themes/packs/crisp-light/launcher3/res/values/colors.xml
@@ -0,0 +1,48 @@
+
+
+
+ #FFFFFF
+ #000000
+ #F3F3F3
+ #E6E6E6
+ #000000
+ #FFFFFF
+ #E3E3E3
+ #FAFAFA
+ #000000
+ #C5221F
+ #FFFFFF
+ #000000
+ #0000B8
+ #8C8C8C
+ #F3F3F3
+ #666666
+ #147A38
+ #FFFFFF
+ #000000
+ #0000FF
+ #FFFFFF
+ #0000FF
+ #F3F3F3
+ #000000
+ #D93025
+ #1E8E3E
+ #E8A200
+ #8F5A00
+ #FAFAFA
+ #FAFAFA
+ #0000FF
+ #0000FF
+ #0000FF
+ #0000FF
+ #FFFFFF
+ #FAFAFA
+ #FAFAFA
+ #F3F3F3
+ #F3F3F3
+ #E6E6E6
+ #F3F3F3
+ #FFFFFF
+ #F3F3F3
+ #000000
+
diff --git a/apps/app/aosp/themes/packs/crisp-light/settings/AndroidManifest.xml b/apps/app/aosp/themes/packs/crisp-light/settings/AndroidManifest.xml
new file mode 100644
index 0000000000..339e49794c
--- /dev/null
+++ b/apps/app/aosp/themes/packs/crisp-light/settings/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/crisp-light/settings/res/values/colors.xml b/apps/app/aosp/themes/packs/crisp-light/settings/res/values/colors.xml
new file mode 100644
index 0000000000..ab86f4ea1e
--- /dev/null
+++ b/apps/app/aosp/themes/packs/crisp-light/settings/res/values/colors.xml
@@ -0,0 +1,19 @@
+
+
+
+ #E6E6E6
+ #FFFFFF
+ #E3E3E3
+ #FAFAFA
+ #000000
+ #666666
+ #0000FF
+ #FFFFFF
+ #0000FF
+ #FFFFFF
+ #FAFAFA
+ #FAFAFA
+ #000000
+ #666666
+ #F3F3F3
+
diff --git a/apps/app/aosp/themes/packs/crisp-light/systemui/AndroidManifest.xml b/apps/app/aosp/themes/packs/crisp-light/systemui/AndroidManifest.xml
new file mode 100644
index 0000000000..833bdd7173
--- /dev/null
+++ b/apps/app/aosp/themes/packs/crisp-light/systemui/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/crisp-light/systemui/res/values/colors.xml b/apps/app/aosp/themes/packs/crisp-light/systemui/res/values/colors.xml
new file mode 100644
index 0000000000..c0a2324d5c
--- /dev/null
+++ b/apps/app/aosp/themes/packs/crisp-light/systemui/res/values/colors.xml
@@ -0,0 +1,21 @@
+
+
+
+ #E6E6E6
+ #FFFFFF
+ #E3E3E3
+ #FAFAFA
+ #C5221F
+ #000000
+ #F3F3F3
+ #666666
+ #147A38
+ #0000FF
+ #FFFFFF
+ #8F5A00
+ #0000FF
+ #0000FF
+ #FFFFFF
+ #FFFFFF
+ #FFFFFF
+
diff --git a/apps/app/aosp/themes/packs/everforest/framework/AndroidManifest.xml b/apps/app/aosp/themes/packs/everforest/framework/AndroidManifest.xml
new file mode 100644
index 0000000000..419346a7fb
--- /dev/null
+++ b/apps/app/aosp/themes/packs/everforest/framework/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/everforest/framework/res/values/colors.xml b/apps/app/aosp/themes/packs/everforest/framework/res/values/colors.xml
new file mode 100644
index 0000000000..b82b4123bf
--- /dev/null
+++ b/apps/app/aosp/themes/packs/everforest/framework/res/values/colors.xml
@@ -0,0 +1,36 @@
+
+
+
+ #A7C788
+ #A7C788
+ #1B2527
+ #1B2527
+ #FFA7C788
+ #1B2527
+ #1B2527
+ #1B2527
+ #1B2527
+ #232F31
+ #2E3C3E
+ #3A4A4B
+ #101A1D
+ #101A1D
+ #D9D1BA
+ #ADB2A2
+ #737E73
+ #425252
+ #A7C788
+ #A7C788
+ #A7C788
+ #3A4A4B
+ #232F31
+ #2E3C3E
+ #3A4A4B
+ #232F31
+ #1B2527
+ #1B2527
+ #1B2527
+ #A7C788
+ #3A4A4B
+ #1B2527
+
diff --git a/apps/app/aosp/themes/packs/everforest/launcher3/AndroidManifest.xml b/apps/app/aosp/themes/packs/everforest/launcher3/AndroidManifest.xml
new file mode 100644
index 0000000000..886fdf615a
--- /dev/null
+++ b/apps/app/aosp/themes/packs/everforest/launcher3/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/everforest/launcher3/res/values-night/colors.xml b/apps/app/aosp/themes/packs/everforest/launcher3/res/values-night/colors.xml
new file mode 100644
index 0000000000..e62a77e159
--- /dev/null
+++ b/apps/app/aosp/themes/packs/everforest/launcher3/res/values-night/colors.xml
@@ -0,0 +1,48 @@
+
+
+
+ #1B2527
+ #D9D1BA
+ #2E3C3E
+ #3A4A4B
+ #E6DEC8
+ #1B2527
+ #425252
+ #232F31
+ #D9D1BA
+ #ED878B
+ #101A1D
+ #D9D1BA
+ #8AC1B6
+ #737E73
+ #2E3C3E
+ #ADB2A2
+ #A7C788
+ #232F31
+ #D9D1BA
+ #A7C788
+ #101A1D
+ #A7C788
+ #2E3C3E
+ #D9D1BA
+ #ED878B
+ #A7C788
+ #D9BE7C
+ #D9BE7C
+ #232F31
+ #232F31
+ #A7C788
+ #A7C788
+ #A7C788
+ #A7C788
+ #232F31
+ #232F31
+ #232F31
+ #2E3C3E
+ #2E3C3E
+ #3A4A4B
+ #2E3C3E
+ #1B2527
+ #2E3C3E
+ #D9D1BA
+
diff --git a/apps/app/aosp/themes/packs/everforest/launcher3/res/values/colors.xml b/apps/app/aosp/themes/packs/everforest/launcher3/res/values/colors.xml
new file mode 100644
index 0000000000..e62a77e159
--- /dev/null
+++ b/apps/app/aosp/themes/packs/everforest/launcher3/res/values/colors.xml
@@ -0,0 +1,48 @@
+
+
+
+ #1B2527
+ #D9D1BA
+ #2E3C3E
+ #3A4A4B
+ #E6DEC8
+ #1B2527
+ #425252
+ #232F31
+ #D9D1BA
+ #ED878B
+ #101A1D
+ #D9D1BA
+ #8AC1B6
+ #737E73
+ #2E3C3E
+ #ADB2A2
+ #A7C788
+ #232F31
+ #D9D1BA
+ #A7C788
+ #101A1D
+ #A7C788
+ #2E3C3E
+ #D9D1BA
+ #ED878B
+ #A7C788
+ #D9BE7C
+ #D9BE7C
+ #232F31
+ #232F31
+ #A7C788
+ #A7C788
+ #A7C788
+ #A7C788
+ #232F31
+ #232F31
+ #232F31
+ #2E3C3E
+ #2E3C3E
+ #3A4A4B
+ #2E3C3E
+ #1B2527
+ #2E3C3E
+ #D9D1BA
+
diff --git a/apps/app/aosp/themes/packs/everforest/settings/AndroidManifest.xml b/apps/app/aosp/themes/packs/everforest/settings/AndroidManifest.xml
new file mode 100644
index 0000000000..9f13f9fea2
--- /dev/null
+++ b/apps/app/aosp/themes/packs/everforest/settings/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/everforest/settings/res/values/colors.xml b/apps/app/aosp/themes/packs/everforest/settings/res/values/colors.xml
new file mode 100644
index 0000000000..a81933e3db
--- /dev/null
+++ b/apps/app/aosp/themes/packs/everforest/settings/res/values/colors.xml
@@ -0,0 +1,19 @@
+
+
+
+ #3A4A4B
+ #1B2527
+ #425252
+ #232F31
+ #D9D1BA
+ #ADB2A2
+ #A7C788
+ #101A1D
+ #A7C788
+ #1B2527
+ #232F31
+ #232F31
+ #D9D1BA
+ #ADB2A2
+ #2E3C3E
+
diff --git a/apps/app/aosp/themes/packs/everforest/systemui/AndroidManifest.xml b/apps/app/aosp/themes/packs/everforest/systemui/AndroidManifest.xml
new file mode 100644
index 0000000000..e78912e0ca
--- /dev/null
+++ b/apps/app/aosp/themes/packs/everforest/systemui/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/everforest/systemui/res/values/colors.xml b/apps/app/aosp/themes/packs/everforest/systemui/res/values/colors.xml
new file mode 100644
index 0000000000..e56e44492e
--- /dev/null
+++ b/apps/app/aosp/themes/packs/everforest/systemui/res/values/colors.xml
@@ -0,0 +1,21 @@
+
+
+
+ #3A4A4B
+ #1B2527
+ #425252
+ #232F31
+ #ED878B
+ #D9D1BA
+ #2E3C3E
+ #ADB2A2
+ #A7C788
+ #A7C788
+ #101A1D
+ #D9BE7C
+ #A7C788
+ #A7C788
+ #1B2527
+ #101A1D
+ #1B2527
+
diff --git a/apps/app/aosp/themes/packs/gruvbox/framework/AndroidManifest.xml b/apps/app/aosp/themes/packs/gruvbox/framework/AndroidManifest.xml
new file mode 100644
index 0000000000..8a4df6f275
--- /dev/null
+++ b/apps/app/aosp/themes/packs/gruvbox/framework/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/gruvbox/framework/res/values/colors.xml b/apps/app/aosp/themes/packs/gruvbox/framework/res/values/colors.xml
new file mode 100644
index 0000000000..5c675f4096
--- /dev/null
+++ b/apps/app/aosp/themes/packs/gruvbox/framework/res/values/colors.xml
@@ -0,0 +1,36 @@
+
+
+
+ #F1BA44
+ #F1BA44
+ #23201C
+ #23201C
+ #FFF1BA44
+ #23201C
+ #23201C
+ #23201C
+ #23201C
+ #2D2925
+ #3B3631
+ #4A443D
+ #1B1814
+ #1B1814
+ #EADBBE
+ #BAAE9C
+ #7C7368
+ #504942
+ #F1BA44
+ #F1BA44
+ #F1BA44
+ #4A443D
+ #2D2925
+ #3B3631
+ #4A443D
+ #2D2925
+ #23201C
+ #23201C
+ #23201C
+ #F1BA44
+ #4A443D
+ #23201C
+
diff --git a/apps/app/aosp/themes/packs/gruvbox/launcher3/AndroidManifest.xml b/apps/app/aosp/themes/packs/gruvbox/launcher3/AndroidManifest.xml
new file mode 100644
index 0000000000..36cf77cc8c
--- /dev/null
+++ b/apps/app/aosp/themes/packs/gruvbox/launcher3/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/gruvbox/launcher3/res/values-night/colors.xml b/apps/app/aosp/themes/packs/gruvbox/launcher3/res/values-night/colors.xml
new file mode 100644
index 0000000000..e165b7d5bc
--- /dev/null
+++ b/apps/app/aosp/themes/packs/gruvbox/launcher3/res/values-night/colors.xml
@@ -0,0 +1,48 @@
+
+
+
+ #23201C
+ #EADBBE
+ #3B3631
+ #4A443D
+ #F0E3CA
+ #23201C
+ #504942
+ #2D2925
+ #EADBBE
+ #FF7262
+ #1B1814
+ #EADBBE
+ #74B6B1
+ #7C7368
+ #3B3631
+ #BAAE9C
+ #B3BE49
+ #2D2925
+ #EADBBE
+ #F1BA44
+ #1B1814
+ #F1BA44
+ #3B3631
+ #EADBBE
+ #FF7262
+ #B3BE49
+ #F7913E
+ #F7913E
+ #2D2925
+ #2D2925
+ #F1BA44
+ #F1BA44
+ #F1BA44
+ #F1BA44
+ #2D2925
+ #2D2925
+ #2D2925
+ #3B3631
+ #3B3631
+ #4A443D
+ #3B3631
+ #23201C
+ #3B3631
+ #EADBBE
+
diff --git a/apps/app/aosp/themes/packs/gruvbox/launcher3/res/values/colors.xml b/apps/app/aosp/themes/packs/gruvbox/launcher3/res/values/colors.xml
new file mode 100644
index 0000000000..e165b7d5bc
--- /dev/null
+++ b/apps/app/aosp/themes/packs/gruvbox/launcher3/res/values/colors.xml
@@ -0,0 +1,48 @@
+
+
+
+ #23201C
+ #EADBBE
+ #3B3631
+ #4A443D
+ #F0E3CA
+ #23201C
+ #504942
+ #2D2925
+ #EADBBE
+ #FF7262
+ #1B1814
+ #EADBBE
+ #74B6B1
+ #7C7368
+ #3B3631
+ #BAAE9C
+ #B3BE49
+ #2D2925
+ #EADBBE
+ #F1BA44
+ #1B1814
+ #F1BA44
+ #3B3631
+ #EADBBE
+ #FF7262
+ #B3BE49
+ #F7913E
+ #F7913E
+ #2D2925
+ #2D2925
+ #F1BA44
+ #F1BA44
+ #F1BA44
+ #F1BA44
+ #2D2925
+ #2D2925
+ #2D2925
+ #3B3631
+ #3B3631
+ #4A443D
+ #3B3631
+ #23201C
+ #3B3631
+ #EADBBE
+
diff --git a/apps/app/aosp/themes/packs/gruvbox/settings/AndroidManifest.xml b/apps/app/aosp/themes/packs/gruvbox/settings/AndroidManifest.xml
new file mode 100644
index 0000000000..5e73696bab
--- /dev/null
+++ b/apps/app/aosp/themes/packs/gruvbox/settings/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/gruvbox/settings/res/values/colors.xml b/apps/app/aosp/themes/packs/gruvbox/settings/res/values/colors.xml
new file mode 100644
index 0000000000..acdc6a8187
--- /dev/null
+++ b/apps/app/aosp/themes/packs/gruvbox/settings/res/values/colors.xml
@@ -0,0 +1,19 @@
+
+
+
+ #4A443D
+ #23201C
+ #504942
+ #2D2925
+ #EADBBE
+ #BAAE9C
+ #F1BA44
+ #1B1814
+ #F1BA44
+ #23201C
+ #2D2925
+ #2D2925
+ #EADBBE
+ #BAAE9C
+ #3B3631
+
diff --git a/apps/app/aosp/themes/packs/gruvbox/systemui/AndroidManifest.xml b/apps/app/aosp/themes/packs/gruvbox/systemui/AndroidManifest.xml
new file mode 100644
index 0000000000..bfb7376804
--- /dev/null
+++ b/apps/app/aosp/themes/packs/gruvbox/systemui/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/gruvbox/systemui/res/values/colors.xml b/apps/app/aosp/themes/packs/gruvbox/systemui/res/values/colors.xml
new file mode 100644
index 0000000000..2ae4d4ec2c
--- /dev/null
+++ b/apps/app/aosp/themes/packs/gruvbox/systemui/res/values/colors.xml
@@ -0,0 +1,21 @@
+
+
+
+ #4A443D
+ #23201C
+ #504942
+ #2D2925
+ #FF7262
+ #EADBBE
+ #3B3631
+ #BAAE9C
+ #B3BE49
+ #F1BA44
+ #1B1814
+ #F7913E
+ #F1BA44
+ #F1BA44
+ #23201C
+ #1B1814
+ #23201C
+
diff --git a/apps/app/aosp/themes/packs/ink-dark/framework/AndroidManifest.xml b/apps/app/aosp/themes/packs/ink-dark/framework/AndroidManifest.xml
new file mode 100644
index 0000000000..96717f5e93
--- /dev/null
+++ b/apps/app/aosp/themes/packs/ink-dark/framework/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/ink-dark/framework/res/values/colors.xml b/apps/app/aosp/themes/packs/ink-dark/framework/res/values/colors.xml
new file mode 100644
index 0000000000..fda398b90b
--- /dev/null
+++ b/apps/app/aosp/themes/packs/ink-dark/framework/res/values/colors.xml
@@ -0,0 +1,36 @@
+
+
+
+ #8A93FF
+ #8A93FF
+ #000000
+ #000000
+ #FF8A93FF
+ #000000
+ #000000
+ #000000
+ #000000
+ #0B0B0B
+ #151515
+ #262626
+ #000000
+ #000000
+ #FFFFFF
+ #8F8F8F
+ #6B6B6B
+ #262626
+ #8A93FF
+ #8A93FF
+ #8A93FF
+ #262626
+ #0B0B0B
+ #151515
+ #262626
+ #0B0B0B
+ #000000
+ #000000
+ #000000
+ #8A93FF
+ #262626
+ #000000
+
diff --git a/apps/app/aosp/themes/packs/ink-dark/launcher3/AndroidManifest.xml b/apps/app/aosp/themes/packs/ink-dark/launcher3/AndroidManifest.xml
new file mode 100644
index 0000000000..27ba7a046d
--- /dev/null
+++ b/apps/app/aosp/themes/packs/ink-dark/launcher3/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/ink-dark/launcher3/res/values-night/colors.xml b/apps/app/aosp/themes/packs/ink-dark/launcher3/res/values-night/colors.xml
new file mode 100644
index 0000000000..d961ce2f9a
--- /dev/null
+++ b/apps/app/aosp/themes/packs/ink-dark/launcher3/res/values-night/colors.xml
@@ -0,0 +1,48 @@
+
+
+
+ #000000
+ #FFFFFF
+ #151515
+ #262626
+ #FFFFFF
+ #000000
+ #262626
+ #0B0B0B
+ #FFFFFF
+ #FF6B60
+ #000000
+ #FFFFFF
+ #8A93FF
+ #6B6B6B
+ #151515
+ #8F8F8F
+ #05C853
+ #0B0B0B
+ #FFFFFF
+ #8A93FF
+ #000000
+ #8A93FF
+ #151515
+ #FFFFFF
+ #D93025
+ #1E8E3E
+ #E8A200
+ #E8A200
+ #0B0B0B
+ #0B0B0B
+ #8A93FF
+ #8A93FF
+ #8A93FF
+ #8A93FF
+ #0B0B0B
+ #0B0B0B
+ #0B0B0B
+ #151515
+ #151515
+ #262626
+ #151515
+ #000000
+ #151515
+ #FFFFFF
+
diff --git a/apps/app/aosp/themes/packs/ink-dark/launcher3/res/values/colors.xml b/apps/app/aosp/themes/packs/ink-dark/launcher3/res/values/colors.xml
new file mode 100644
index 0000000000..d961ce2f9a
--- /dev/null
+++ b/apps/app/aosp/themes/packs/ink-dark/launcher3/res/values/colors.xml
@@ -0,0 +1,48 @@
+
+
+
+ #000000
+ #FFFFFF
+ #151515
+ #262626
+ #FFFFFF
+ #000000
+ #262626
+ #0B0B0B
+ #FFFFFF
+ #FF6B60
+ #000000
+ #FFFFFF
+ #8A93FF
+ #6B6B6B
+ #151515
+ #8F8F8F
+ #05C853
+ #0B0B0B
+ #FFFFFF
+ #8A93FF
+ #000000
+ #8A93FF
+ #151515
+ #FFFFFF
+ #D93025
+ #1E8E3E
+ #E8A200
+ #E8A200
+ #0B0B0B
+ #0B0B0B
+ #8A93FF
+ #8A93FF
+ #8A93FF
+ #8A93FF
+ #0B0B0B
+ #0B0B0B
+ #0B0B0B
+ #151515
+ #151515
+ #262626
+ #151515
+ #000000
+ #151515
+ #FFFFFF
+
diff --git a/apps/app/aosp/themes/packs/ink-dark/settings/AndroidManifest.xml b/apps/app/aosp/themes/packs/ink-dark/settings/AndroidManifest.xml
new file mode 100644
index 0000000000..88074bceda
--- /dev/null
+++ b/apps/app/aosp/themes/packs/ink-dark/settings/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/ink-dark/settings/res/values/colors.xml b/apps/app/aosp/themes/packs/ink-dark/settings/res/values/colors.xml
new file mode 100644
index 0000000000..c07410208d
--- /dev/null
+++ b/apps/app/aosp/themes/packs/ink-dark/settings/res/values/colors.xml
@@ -0,0 +1,19 @@
+
+
+
+ #262626
+ #000000
+ #262626
+ #0B0B0B
+ #FFFFFF
+ #8F8F8F
+ #8A93FF
+ #000000
+ #8A93FF
+ #000000
+ #0B0B0B
+ #0B0B0B
+ #FFFFFF
+ #8F8F8F
+ #151515
+
diff --git a/apps/app/aosp/themes/packs/ink-dark/systemui/AndroidManifest.xml b/apps/app/aosp/themes/packs/ink-dark/systemui/AndroidManifest.xml
new file mode 100644
index 0000000000..db22115aeb
--- /dev/null
+++ b/apps/app/aosp/themes/packs/ink-dark/systemui/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/ink-dark/systemui/res/values/colors.xml b/apps/app/aosp/themes/packs/ink-dark/systemui/res/values/colors.xml
new file mode 100644
index 0000000000..c98213cdd0
--- /dev/null
+++ b/apps/app/aosp/themes/packs/ink-dark/systemui/res/values/colors.xml
@@ -0,0 +1,21 @@
+
+
+
+ #262626
+ #000000
+ #262626
+ #0B0B0B
+ #FF6B60
+ #FFFFFF
+ #151515
+ #8F8F8F
+ #05C853
+ #8A93FF
+ #000000
+ #E8A200
+ #8A93FF
+ #8A93FF
+ #000000
+ #000000
+ #000000
+
diff --git a/apps/app/aosp/themes/packs/tokyo-night/framework/AndroidManifest.xml b/apps/app/aosp/themes/packs/tokyo-night/framework/AndroidManifest.xml
new file mode 100644
index 0000000000..291999fa67
--- /dev/null
+++ b/apps/app/aosp/themes/packs/tokyo-night/framework/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/tokyo-night/framework/res/values/colors.xml b/apps/app/aosp/themes/packs/tokyo-night/framework/res/values/colors.xml
new file mode 100644
index 0000000000..6213edce6f
--- /dev/null
+++ b/apps/app/aosp/themes/packs/tokyo-night/framework/res/values/colors.xml
@@ -0,0 +1,36 @@
+
+
+
+ #7AA8FE
+ #7AA8FE
+ #161925
+ #161925
+ #FF7AA8FE
+ #161925
+ #161925
+ #161925
+ #161925
+ #1E2333
+ #292E41
+ #31384F
+ #0E111C
+ #0E111C
+ #C7D2F3
+ #9CA4BB
+ #666E87
+ #363D55
+ #7AA8FE
+ #7AA8FE
+ #7AA8FE
+ #31384F
+ #1E2333
+ #292E41
+ #31384F
+ #1E2333
+ #161925
+ #161925
+ #161925
+ #7AA8FE
+ #31384F
+ #161925
+
diff --git a/apps/app/aosp/themes/packs/tokyo-night/launcher3/AndroidManifest.xml b/apps/app/aosp/themes/packs/tokyo-night/launcher3/AndroidManifest.xml
new file mode 100644
index 0000000000..c080d0e77b
--- /dev/null
+++ b/apps/app/aosp/themes/packs/tokyo-night/launcher3/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/tokyo-night/launcher3/res/values-night/colors.xml b/apps/app/aosp/themes/packs/tokyo-night/launcher3/res/values-night/colors.xml
new file mode 100644
index 0000000000..0c8ff7a2a2
--- /dev/null
+++ b/apps/app/aosp/themes/packs/tokyo-night/launcher3/res/values-night/colors.xml
@@ -0,0 +1,48 @@
+
+
+
+ #161925
+ #C7D2F3
+ #292E41
+ #31384F
+ #D9E1F7
+ #161925
+ #363D55
+ #1E2333
+ #C7D2F3
+ #FA7383
+ #0E111C
+ #C7D2F3
+ #6DD0F3
+ #666E87
+ #292E41
+ #9CA4BB
+ #97CD79
+ #1E2333
+ #C7D2F3
+ #7AA8FE
+ #0E111C
+ #7AA8FE
+ #292E41
+ #C7D2F3
+ #FA7383
+ #97CD79
+ #E8B364
+ #E8B364
+ #1E2333
+ #1E2333
+ #7AA8FE
+ #7AA8FE
+ #7AA8FE
+ #7AA8FE
+ #1E2333
+ #1E2333
+ #1E2333
+ #292E41
+ #292E41
+ #31384F
+ #292E41
+ #161925
+ #292E41
+ #C7D2F3
+
diff --git a/apps/app/aosp/themes/packs/tokyo-night/launcher3/res/values/colors.xml b/apps/app/aosp/themes/packs/tokyo-night/launcher3/res/values/colors.xml
new file mode 100644
index 0000000000..0c8ff7a2a2
--- /dev/null
+++ b/apps/app/aosp/themes/packs/tokyo-night/launcher3/res/values/colors.xml
@@ -0,0 +1,48 @@
+
+
+
+ #161925
+ #C7D2F3
+ #292E41
+ #31384F
+ #D9E1F7
+ #161925
+ #363D55
+ #1E2333
+ #C7D2F3
+ #FA7383
+ #0E111C
+ #C7D2F3
+ #6DD0F3
+ #666E87
+ #292E41
+ #9CA4BB
+ #97CD79
+ #1E2333
+ #C7D2F3
+ #7AA8FE
+ #0E111C
+ #7AA8FE
+ #292E41
+ #C7D2F3
+ #FA7383
+ #97CD79
+ #E8B364
+ #E8B364
+ #1E2333
+ #1E2333
+ #7AA8FE
+ #7AA8FE
+ #7AA8FE
+ #7AA8FE
+ #1E2333
+ #1E2333
+ #1E2333
+ #292E41
+ #292E41
+ #31384F
+ #292E41
+ #161925
+ #292E41
+ #C7D2F3
+
diff --git a/apps/app/aosp/themes/packs/tokyo-night/settings/AndroidManifest.xml b/apps/app/aosp/themes/packs/tokyo-night/settings/AndroidManifest.xml
new file mode 100644
index 0000000000..235d9dcc86
--- /dev/null
+++ b/apps/app/aosp/themes/packs/tokyo-night/settings/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/tokyo-night/settings/res/values/colors.xml b/apps/app/aosp/themes/packs/tokyo-night/settings/res/values/colors.xml
new file mode 100644
index 0000000000..a809c8f796
--- /dev/null
+++ b/apps/app/aosp/themes/packs/tokyo-night/settings/res/values/colors.xml
@@ -0,0 +1,19 @@
+
+
+
+ #31384F
+ #161925
+ #363D55
+ #1E2333
+ #C7D2F3
+ #9CA4BB
+ #7AA8FE
+ #0E111C
+ #7AA8FE
+ #161925
+ #1E2333
+ #1E2333
+ #C7D2F3
+ #9CA4BB
+ #292E41
+
diff --git a/apps/app/aosp/themes/packs/tokyo-night/systemui/AndroidManifest.xml b/apps/app/aosp/themes/packs/tokyo-night/systemui/AndroidManifest.xml
new file mode 100644
index 0000000000..88c7ab95b6
--- /dev/null
+++ b/apps/app/aosp/themes/packs/tokyo-night/systemui/AndroidManifest.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
diff --git a/apps/app/aosp/themes/packs/tokyo-night/systemui/res/values/colors.xml b/apps/app/aosp/themes/packs/tokyo-night/systemui/res/values/colors.xml
new file mode 100644
index 0000000000..6a9a223f64
--- /dev/null
+++ b/apps/app/aosp/themes/packs/tokyo-night/systemui/res/values/colors.xml
@@ -0,0 +1,21 @@
+
+
+
+ #31384F
+ #161925
+ #363D55
+ #1E2333
+ #FA7383
+ #C7D2F3
+ #292E41
+ #9CA4BB
+ #97CD79
+ #7AA8FE
+ #0E111C
+ #E8B364
+ #7AA8FE
+ #7AA8FE
+ #161925
+ #0E111C
+ #161925
+
diff --git a/apps/app/aosp/themes/theme-packs.manifest.json b/apps/app/aosp/themes/theme-packs.manifest.json
new file mode 100644
index 0000000000..814b639e86
--- /dev/null
+++ b/apps/app/aosp/themes/theme-packs.manifest.json
@@ -0,0 +1,276 @@
+{
+ "schemaVersion": 1,
+ "priority": 1010,
+ "categories": {
+ "framework": "ai.alphacompute.alpha.theme.framework",
+ "systemui": "ai.alphacompute.alpha.theme.systemui",
+ "launcher3": "ai.alphacompute.alpha.theme.launcher3",
+ "settings": "ai.alphacompute.alpha.theme.settings"
+ },
+ "targets": {
+ "framework": "android",
+ "systemui": "com.android.systemui",
+ "launcher3": "com.android.launcher3",
+ "settings": "com.android.settings"
+ },
+ "packs": [
+ {
+ "id": "ink-dark",
+ "name": "Ink Dark",
+ "scheme": "dark",
+ "isDefault": true,
+ "overlays": {
+ "framework": "ai.alphacompute.alpha.theme.inkdark.framework",
+ "systemui": "ai.alphacompute.alpha.theme.inkdark.systemui",
+ "launcher3": "ai.alphacompute.alpha.theme.inkdark.launcher3",
+ "settings": "ai.alphacompute.alpha.theme.inkdark.settings"
+ },
+ "seedHex": "#8A93FF",
+ "hexPalette": {
+ "background": "#000000",
+ "foreground": "#FFFFFF",
+ "card": "#0B0B0B",
+ "cardForeground": "#FFFFFF",
+ "popover": "#0B0B0B",
+ "popoverForeground": "#FFFFFF",
+ "primary": "#8A93FF",
+ "primaryForeground": "#000000",
+ "secondary": "#151515",
+ "secondaryForeground": "#FFFFFF",
+ "muted": "#151515",
+ "mutedForeground": "#8F8F8F",
+ "accent": "#262626",
+ "accentForeground": "#FFFFFF",
+ "destructive": "#FF6B60",
+ "destructiveForeground": "#000000",
+ "border": "#262626",
+ "input": "#6B6B6B",
+ "ring": "#8A93FF",
+ "ok": "#05C853",
+ "warn": "#E8A200",
+ "statusOk": "#1E8E3E",
+ "statusWarn": "#E8A200",
+ "statusError": "#D93025",
+ "info": "#8A93FF",
+ "alpha": "#8A93FF",
+ "alphaForeground": "#000000"
+ },
+ "minContrastPass": true
+ },
+ {
+ "id": "crisp-light",
+ "name": "Crisp Light",
+ "scheme": "light",
+ "isDefault": false,
+ "overlays": {
+ "framework": "ai.alphacompute.alpha.theme.crisplight.framework",
+ "systemui": "ai.alphacompute.alpha.theme.crisplight.systemui",
+ "launcher3": "ai.alphacompute.alpha.theme.crisplight.launcher3",
+ "settings": "ai.alphacompute.alpha.theme.crisplight.settings"
+ },
+ "seedHex": "#0000FF",
+ "hexPalette": {
+ "background": "#FFFFFF",
+ "foreground": "#000000",
+ "card": "#FAFAFA",
+ "cardForeground": "#000000",
+ "popover": "#FFFFFF",
+ "popoverForeground": "#000000",
+ "primary": "#0000FF",
+ "primaryForeground": "#FFFFFF",
+ "secondary": "#F3F3F3",
+ "secondaryForeground": "#000000",
+ "muted": "#F3F3F3",
+ "mutedForeground": "#666666",
+ "accent": "#E6E6E6",
+ "accentForeground": "#000000",
+ "destructive": "#C5221F",
+ "destructiveForeground": "#FFFFFF",
+ "border": "#E3E3E3",
+ "input": "#8C8C8C",
+ "ring": "#0000FF",
+ "ok": "#147A38",
+ "warn": "#8F5A00",
+ "statusOk": "#1E8E3E",
+ "statusWarn": "#E8A200",
+ "statusError": "#D93025",
+ "info": "#0000B8",
+ "alpha": "#0000FF",
+ "alphaForeground": "#FFFFFF"
+ },
+ "minContrastPass": true
+ },
+ {
+ "id": "tokyo-night",
+ "name": "Tokyo Night",
+ "scheme": "dark",
+ "isDefault": false,
+ "overlays": {
+ "framework": "ai.alphacompute.alpha.theme.tokyonight.framework",
+ "systemui": "ai.alphacompute.alpha.theme.tokyonight.systemui",
+ "launcher3": "ai.alphacompute.alpha.theme.tokyonight.launcher3",
+ "settings": "ai.alphacompute.alpha.theme.tokyonight.settings"
+ },
+ "seedHex": "#7AA8FE",
+ "hexPalette": {
+ "background": "#161925",
+ "foreground": "#C7D2F3",
+ "card": "#1E2333",
+ "cardForeground": "#C7D2F3",
+ "popover": "#1E2333",
+ "popoverForeground": "#C7D2F3",
+ "primary": "#7AA8FE",
+ "primaryForeground": "#0E111C",
+ "secondary": "#292E41",
+ "secondaryForeground": "#C7D2F3",
+ "muted": "#292E41",
+ "mutedForeground": "#9CA4BB",
+ "accent": "#31384F",
+ "accentForeground": "#D9E1F7",
+ "destructive": "#FA7383",
+ "destructiveForeground": "#0E111C",
+ "border": "#363D55",
+ "input": "#666E87",
+ "ring": "#7AA8FE",
+ "ok": "#97CD79",
+ "warn": "#E8B364",
+ "statusOk": "#97CD79",
+ "statusWarn": "#E8B364",
+ "statusError": "#FA7383",
+ "info": "#6DD0F3",
+ "alpha": "#7AA8FE",
+ "alphaForeground": "#0E111C"
+ },
+ "minContrastPass": true
+ },
+ {
+ "id": "gruvbox",
+ "name": "Gruvbox",
+ "scheme": "dark",
+ "isDefault": false,
+ "overlays": {
+ "framework": "ai.alphacompute.alpha.theme.gruvbox.framework",
+ "systemui": "ai.alphacompute.alpha.theme.gruvbox.systemui",
+ "launcher3": "ai.alphacompute.alpha.theme.gruvbox.launcher3",
+ "settings": "ai.alphacompute.alpha.theme.gruvbox.settings"
+ },
+ "seedHex": "#F1BA44",
+ "hexPalette": {
+ "background": "#23201C",
+ "foreground": "#EADBBE",
+ "card": "#2D2925",
+ "cardForeground": "#EADBBE",
+ "popover": "#2D2925",
+ "popoverForeground": "#EADBBE",
+ "primary": "#F1BA44",
+ "primaryForeground": "#1B1814",
+ "secondary": "#3B3631",
+ "secondaryForeground": "#EADBBE",
+ "muted": "#3B3631",
+ "mutedForeground": "#BAAE9C",
+ "accent": "#4A443D",
+ "accentForeground": "#F0E3CA",
+ "destructive": "#FF7262",
+ "destructiveForeground": "#1B1814",
+ "border": "#504942",
+ "input": "#7C7368",
+ "ring": "#F1BA44",
+ "ok": "#B3BE49",
+ "warn": "#F7913E",
+ "statusOk": "#B3BE49",
+ "statusWarn": "#F7913E",
+ "statusError": "#FF7262",
+ "info": "#74B6B1",
+ "alpha": "#F1BA44",
+ "alphaForeground": "#1B1814"
+ },
+ "minContrastPass": true
+ },
+ {
+ "id": "catppuccin",
+ "name": "Catppuccin",
+ "scheme": "dark",
+ "isDefault": false,
+ "overlays": {
+ "framework": "ai.alphacompute.alpha.theme.catppuccin.framework",
+ "systemui": "ai.alphacompute.alpha.theme.catppuccin.systemui",
+ "launcher3": "ai.alphacompute.alpha.theme.catppuccin.launcher3",
+ "settings": "ai.alphacompute.alpha.theme.catppuccin.settings"
+ },
+ "seedHex": "#CCA6FC",
+ "hexPalette": {
+ "background": "#1C1D29",
+ "foreground": "#CED7F0",
+ "card": "#262735",
+ "cardForeground": "#CED7F0",
+ "popover": "#262735",
+ "popoverForeground": "#CED7F0",
+ "primary": "#CCA6FC",
+ "primaryForeground": "#12131D",
+ "secondary": "#313343",
+ "secondaryForeground": "#CED7F0",
+ "muted": "#313343",
+ "mutedForeground": "#AAAFC2",
+ "accent": "#3E4153",
+ "accentForeground": "#DAE1F6",
+ "destructive": "#F68199",
+ "destructiveForeground": "#12131D",
+ "border": "#46495B",
+ "input": "#737689",
+ "ring": "#CCA6FC",
+ "ok": "#9EDE9D",
+ "warn": "#FFB97A",
+ "statusOk": "#9EDE9D",
+ "statusWarn": "#FFB97A",
+ "statusError": "#F68199",
+ "info": "#89C5F7",
+ "alpha": "#CCA6FC",
+ "alphaForeground": "#12131D"
+ },
+ "minContrastPass": true
+ },
+ {
+ "id": "everforest",
+ "name": "Everforest",
+ "scheme": "dark",
+ "isDefault": false,
+ "overlays": {
+ "framework": "ai.alphacompute.alpha.theme.everforest.framework",
+ "systemui": "ai.alphacompute.alpha.theme.everforest.systemui",
+ "launcher3": "ai.alphacompute.alpha.theme.everforest.launcher3",
+ "settings": "ai.alphacompute.alpha.theme.everforest.settings"
+ },
+ "seedHex": "#A7C788",
+ "hexPalette": {
+ "background": "#1B2527",
+ "foreground": "#D9D1BA",
+ "card": "#232F31",
+ "cardForeground": "#D9D1BA",
+ "popover": "#232F31",
+ "popoverForeground": "#D9D1BA",
+ "primary": "#A7C788",
+ "primaryForeground": "#101A1D",
+ "secondary": "#2E3C3E",
+ "secondaryForeground": "#D9D1BA",
+ "muted": "#2E3C3E",
+ "mutedForeground": "#ADB2A2",
+ "accent": "#3A4A4B",
+ "accentForeground": "#E6DEC8",
+ "destructive": "#ED878B",
+ "destructiveForeground": "#101A1D",
+ "border": "#425252",
+ "input": "#737E73",
+ "ring": "#A7C788",
+ "ok": "#A7C788",
+ "warn": "#D9BE7C",
+ "statusOk": "#A7C788",
+ "statusWarn": "#D9BE7C",
+ "statusError": "#ED878B",
+ "info": "#8AC1B6",
+ "alpha": "#A7C788",
+ "alphaForeground": "#101A1D"
+ },
+ "minContrastPass": true
+ }
+ ]
+}
diff --git a/apps/app/aosp/themes/themes.mk b/apps/app/aosp/themes/themes.mk
new file mode 100644
index 0000000000..157bfecdb3
--- /dev/null
+++ b/apps/app/aosp/themes/themes.mk
@@ -0,0 +1,26 @@
+# Generated from packages/design-system/themes - curated Alpha full-OS RRO theme packs.
+PRODUCT_PACKAGES += \
+ AlphaThemeInkDarkFramework \
+ AlphaThemeInkDarkSystemUI \
+ AlphaThemeInkDarkLauncher3 \
+ AlphaThemeInkDarkSettings \
+ AlphaThemeCrispLightFramework \
+ AlphaThemeCrispLightSystemUI \
+ AlphaThemeCrispLightLauncher3 \
+ AlphaThemeCrispLightSettings \
+ AlphaThemeTokyoNightFramework \
+ AlphaThemeTokyoNightSystemUI \
+ AlphaThemeTokyoNightLauncher3 \
+ AlphaThemeTokyoNightSettings \
+ AlphaThemeGruvboxFramework \
+ AlphaThemeGruvboxSystemUI \
+ AlphaThemeGruvboxLauncher3 \
+ AlphaThemeGruvboxSettings \
+ AlphaThemeCatppuccinFramework \
+ AlphaThemeCatppuccinSystemUI \
+ AlphaThemeCatppuccinLauncher3 \
+ AlphaThemeCatppuccinSettings \
+ AlphaThemeEverforestFramework \
+ AlphaThemeEverforestSystemUI \
+ AlphaThemeEverforestLauncher3 \
+ AlphaThemeEverforestSettings
diff --git a/spec/app/notifications/index.md b/spec/app/notifications/index.md
new file mode 100644
index 0000000000..c17104d4f7
--- /dev/null
+++ b/spec/app/notifications/index.md
@@ -0,0 +1,522 @@
+# Notification intelligence
+
+How Alpha's native Android 17 `NotificationAssistantService` and resident agent
+summarize and bundle incoming notifications without Google Play Services or
+AICore. Sensitive notifications (one-time passcodes, credentials, financial
+alerts, and lockscreen-private alerts) and owner-excluded packages are redacted
+fail-closed before any local or cloud inference runs and are never stored in the
+notification digest. Non-sensitive notifications route through Alpha's hybrid
+router: on-device Gemma 4 E2B when installed within the 8 GB RAM guardrail,
+Eliza Cloud fallback when permitted and reachable, and deterministic offline
+grouping otherwise, always emitting a bounded single-line summary.
+
+## Story: Summarize and bundle notifications with fail-closed privacy
+
+> As the owner, I want Android 17 notification summaries and bundles powered by
+> Alpha's local-first router without Google services, while guaranteeing that
+> 2FA codes, password managers, banking alerts, lockscreen-private alerts, and
+> opted-out apps are never summarized, sent to the cloud, or stored.
+
+### The notification state tracks owner policy, hybrid router mode, device RAM/model health, bounded digest count, and the last decision
+
+```quint
+type Actor = Owner | System | Router
+type Sensitivity = Clear | OtpCode | Credential | Financial | LockscreenPrivate
+type BundleType = BundleOther | BundleConversation | BundleSocial | BundleNews | BundlePromo | BundleRecs
+type RouterMode = ModeHybrid | ModeLocalOnly | ModeCloud | ModeOffline
+type SummarySource = SourceRedacted | SourceLocalLlm | SourceCloudLlm | SourceDeterministic
+
+type RouterHealth = {
+ localInstalled: bool,
+ freeRamMb: int,
+ cloudAvailable: bool,
+}
+
+type NotificationPolicy = {
+ summarizationEnabled: bool,
+ cloudFallbackEnabled: bool,
+ optedOutApps: Set[int],
+}
+
+type SummaryDecision = {
+ notifId: int,
+ appId: int,
+ sensitivity: Sensitivity,
+ bundle: BundleType,
+ source: SummarySource,
+ summaryLen: int,
+ sentToCloud: bool,
+ storedInDigest: bool,
+}
+
+type NotifEffect =
+ | CallLocalLlm({ notifId: int, appId: int })
+ | CallCloudLlm({ notifId: int, appId: int })
+ | AttachAdjustment({ notifId: int, bundle: BundleType, source: SummarySource, summaryLen: int })
+ | RecordDigest({ notifId: int, appId: int, bundle: BundleType, summaryLen: int })
+
+type NotificationState = {
+ policy: NotificationPolicy,
+ mode: RouterMode,
+ health: RouterHealth,
+ lastNotifId: int,
+ storedCount: int,
+ lastDecision: SummaryDecision,
+}
+
+type NotificationMoved = { state: NotificationState, out: List[NotifEffect] }
+
+pure val maxSummaryChars = 140
+pure val minLocalRamMb = 1024
+pure val maxStoredDigest = 50
+
+pure val initial: NotificationState = {
+ policy: {
+ summarizationEnabled: true,
+ cloudFallbackEnabled: true,
+ optedOutApps: Set(),
+ },
+ mode: ModeHybrid,
+ health: {
+ localInstalled: false,
+ freeRamMb: 0,
+ cloudAvailable: false,
+ },
+ lastNotifId: 0,
+ storedCount: 0,
+ lastDecision: {
+ notifId: 0,
+ appId: 0,
+ sensitivity: Clear,
+ bundle: BundleOther,
+ source: SourceRedacted,
+ summaryLen: 0,
+ sentToCloud: false,
+ storedInDigest: false,
+ },
+}
+
+pure def isSensitive(s: Sensitivity): bool = s != Clear
+
+pure def localLlmReady(health: RouterHealth): bool =
+ health.localInstalled and health.freeRamMb >= minLocalRamMb
+
+pure def clampSummaryLen(rawLen: int): int =
+ if (rawLen <= 0) 0 else if (rawLen > maxSummaryChars) maxSummaryChars else rawLen
+
+pure def selectSummarySource(
+ policy: NotificationPolicy,
+ mode: RouterMode,
+ health: RouterHealth,
+ appId: int,
+ sensitivity: Sensitivity,
+): SummarySource =
+ if (isSensitive(sensitivity) or not(policy.summarizationEnabled) or policy.optedOutApps.contains(appId)) {
+ SourceRedacted
+ } else if (mode == ModeOffline) {
+ SourceDeterministic
+ } else if (mode == ModeLocalOnly) {
+ if (localLlmReady(health)) SourceLocalLlm else SourceDeterministic
+ } else if (mode == ModeCloud) {
+ if (policy.cloudFallbackEnabled and health.cloudAvailable) SourceCloudLlm
+ else if (localLlmReady(health)) SourceLocalLlm
+ else SourceDeterministic
+ } else {
+ if (localLlmReady(health)) SourceLocalLlm
+ else if (policy.cloudFallbackEnabled and health.cloudAvailable) SourceCloudLlm
+ else SourceDeterministic
+ }
+
+pure val activeValues = Set(true, false)
+pure val allowedValues = Set(true, false)
+pure val modeValues = Set(ModeHybrid, ModeLocalOnly, ModeCloud, ModeOffline)
+pure val appIdValues = Set(1, 2)
+pure val localInstalledValues = Set(true, false)
+pure val freeRamMbValues = Set(512, 1400)
+pure val cloudAvailableValues = Set(true, false)
+pure val notifIdValues = Set(1, 2, 3)
+pure val sensitivityValues = Set(Clear, OtpCode, Credential, Financial, LockscreenPrivate)
+pure val bundleValues = Set(BundleOther, BundleConversation, BundleSocial, BundleNews, BundlePromo, BundleRecs)
+pure val rawSummaryLenValues = Set(0, 64, 220)
+pure val rawLenValues = Set(-5, 0, 64, 140, 220)
+pure val policyValues = Set(
+ { summarizationEnabled: true, cloudFallbackEnabled: true, optedOutApps: Set() },
+ { summarizationEnabled: true, cloudFallbackEnabled: false, optedOutApps: Set(1) },
+ { summarizationEnabled: false, cloudFallbackEnabled: true, optedOutApps: Set() },
+)
+pure val healthValues = Set(
+ { localInstalled: false, freeRamMb: 512, cloudAvailable: false },
+ { localInstalled: true, freeRamMb: 512, cloudAvailable: true },
+ { localInstalled: true, freeRamMb: 1400, cloudAvailable: false },
+ { localInstalled: true, freeRamMb: 1400, cloudAvailable: true },
+)
+pure val weight_setSummarizationEnabled = 8
+pure val weight_setCloudFallback = 8
+pure val weight_setRouterMode = 10
+pure val weight_optOutApp = 10
+pure val weight_optInApp = 8
+pure val weight_updateHealth = 15
+pure val weight_processNotification = 30
+```
+
+### The owner configures summarization, cloud fallback, router mode, and per-package opt-outs
+
+```quint
+pure def canSetSummarizationEnabled(n: NotificationState, active: bool, by: Actor): bool =
+ by == Owner and active != n.policy.summarizationEnabled
+
+pure def setSummarizationEnabled(n: NotificationState, active: bool, by: Actor): NotificationMoved =
+ {
+ state: { ...n, policy: { ...n.policy, summarizationEnabled: active } },
+ out: List(),
+ }
+
+pure def canSetCloudFallback(n: NotificationState, allowed: bool, by: Actor): bool =
+ by == Owner and allowed != n.policy.cloudFallbackEnabled
+
+pure def setCloudFallback(n: NotificationState, allowed: bool, by: Actor): NotificationMoved =
+ {
+ state: { ...n, policy: { ...n.policy, cloudFallbackEnabled: allowed } },
+ out: List(),
+ }
+
+pure def canSetRouterMode(n: NotificationState, mode: RouterMode, by: Actor): bool =
+ by == Owner and mode != n.mode
+
+pure def setRouterMode(n: NotificationState, mode: RouterMode, by: Actor): NotificationMoved =
+ {
+ state: { ...n, mode: mode },
+ out: List(),
+ }
+
+pure def canOptOutApp(n: NotificationState, appId: int, by: Actor): bool =
+ by == Owner and appId > 0 and not(n.policy.optedOutApps.contains(appId))
+
+pure def optOutApp(n: NotificationState, appId: int, by: Actor): NotificationMoved =
+ {
+ state: { ...n, policy: { ...n.policy, optedOutApps: n.policy.optedOutApps.union(Set(appId)) } },
+ out: List(),
+ }
+
+pure def canOptInApp(n: NotificationState, appId: int, by: Actor): bool =
+ by == Owner and n.policy.optedOutApps.contains(appId)
+
+pure def optInApp(n: NotificationState, appId: int, by: Actor): NotificationMoved =
+ {
+ state: { ...n, policy: { ...n.policy, optedOutApps: n.policy.optedOutApps.exclude(Set(appId)) } },
+ out: List(),
+ }
+```
+
+### The resident router reports local model availability, available device RAM, and cloud reachability
+
+```quint
+pure def canUpdateHealth(
+ n: NotificationState,
+ localInstalled: bool,
+ freeRamMb: int,
+ cloudAvailable: bool,
+ by: Actor,
+): bool =
+ by == Router and freeRamMb >= 0 and (
+ localInstalled != n.health.localInstalled
+ or freeRamMb != n.health.freeRamMb
+ or cloudAvailable != n.health.cloudAvailable
+ )
+
+pure def updateHealth(
+ n: NotificationState,
+ localInstalled: bool,
+ freeRamMb: int,
+ cloudAvailable: bool,
+ by: Actor,
+): NotificationMoved =
+ {
+ state: {
+ ...n,
+ health: {
+ localInstalled: localInstalled,
+ freeRamMb: freeRamMb,
+ cloudAvailable: cloudAvailable,
+ },
+ },
+ out: List(),
+ }
+```
+
+### Each enqueued notification passes fail-closed privacy and opt-out checks before routing to local Gemma, cloud fallback, or deterministic offline grouping
+
+```quint
+pure def canProcessNotification(
+ n: NotificationState,
+ notifId: int,
+ appId: int,
+ sensitivity: Sensitivity,
+ bundle: BundleType,
+ rawSummaryLen: int,
+ by: Actor,
+): bool =
+ by == System and notifId > n.lastNotifId and appId > 0 and rawSummaryLen >= 0
+
+pure def processNotification(
+ n: NotificationState,
+ notifId: int,
+ appId: int,
+ sensitivity: Sensitivity,
+ bundle: BundleType,
+ rawSummaryLen: int,
+ by: Actor,
+): NotificationMoved =
+ val chosen = selectSummarySource(n.policy, n.mode, n.health, appId, sensitivity)
+ val bounded = clampSummaryLen(rawSummaryLen)
+ val usesCloud = chosen == SourceCloudLlm
+ val usesLocal = chosen == SourceLocalLlm
+ val nextStored = if (n.storedCount < maxStoredDigest) n.storedCount + 1 else maxStoredDigest
+ val effects =
+ if (usesLocal) List(
+ CallLocalLlm({ notifId: notifId, appId: appId }),
+ AttachAdjustment({ notifId: notifId, bundle: bundle, source: chosen, summaryLen: bounded }),
+ RecordDigest({ notifId: notifId, appId: appId, bundle: bundle, summaryLen: bounded }),
+ )
+ else if (usesCloud) List(
+ CallCloudLlm({ notifId: notifId, appId: appId }),
+ AttachAdjustment({ notifId: notifId, bundle: bundle, source: chosen, summaryLen: bounded }),
+ RecordDigest({ notifId: notifId, appId: appId, bundle: bundle, summaryLen: bounded }),
+ )
+ else List(
+ AttachAdjustment({ notifId: notifId, bundle: bundle, source: chosen, summaryLen: bounded }),
+ RecordDigest({ notifId: notifId, appId: appId, bundle: bundle, summaryLen: bounded }),
+ )
+ if (chosen == SourceRedacted) {
+ state: {
+ ...n,
+ lastNotifId: notifId,
+ lastDecision: {
+ notifId: notifId,
+ appId: appId,
+ sensitivity: sensitivity,
+ bundle: BundleOther,
+ source: SourceRedacted,
+ summaryLen: 0,
+ sentToCloud: false,
+ storedInDigest: false,
+ },
+ },
+ out: List(),
+ } else {
+ state: {
+ ...n,
+ lastNotifId: notifId,
+ storedCount: nextStored,
+ lastDecision: {
+ notifId: notifId,
+ appId: appId,
+ sensitivity: sensitivity,
+ bundle: bundle,
+ source: chosen,
+ summaryLen: bounded,
+ sentToCloud: usesCloud,
+ storedInDigest: true,
+ },
+ },
+ out: effects,
+ }
+```
+
+## Story: Enforce fail-closed privacy, RAM guardrails, and bounded summaries
+
+> As the owner, I want machine-checked proofs that sensitive notifications never
+> reach cloud inference or digest storage, opted-out apps are never processed,
+> local inference respects the 8 GB device RAM guardrail, and every summary stays
+> within a concise single-line bound.
+
+### Sensitive notifications are always redacted and never sent to cloud or stored in the digest
+
+```quint
+pure def alwaysSensitiveNeverExfiltratedOrStored(n: NotificationState): bool =
+ isSensitive(n.lastDecision.sensitivity) implies (
+ n.lastDecision.source == SourceRedacted
+ and not(n.lastDecision.sentToCloud)
+ and not(n.lastDecision.storedInDigest)
+ and n.lastDecision.summaryLen == 0
+ )
+```
+
+### Summary length, stored digest count, RAM metrics, and notification ids stay bounded and non-negative
+
+```quint
+pure def alwaysSummaryAndDigestBounded(n: NotificationState): bool =
+ n.lastNotifId >= 0
+ and n.health.freeRamMb >= 0
+ and n.storedCount >= 0
+ and n.storedCount <= maxStoredDigest
+ and n.lastDecision.summaryLen >= 0
+ and n.lastDecision.summaryLen <= maxSummaryChars
+ and (n.lastDecision.source == SourceRedacted implies (
+ not(n.lastDecision.sentToCloud) and not(n.lastDecision.storedInDigest) and n.lastDecision.summaryLen == 0
+ ))
+```
+
+### Every emitted inference, adjustment, and storage effect obeys privacy, opt-out, RAM, and mode rules
+
+```quint
+pure def stepPrivacyAndRoutingEnforced(
+ before: NotificationState,
+ via: str,
+ after: NotificationState,
+ out: List[NotifEffect],
+): bool =
+ (via == "processNotification" and (
+ isSensitive(after.lastDecision.sensitivity)
+ or not(before.policy.summarizationEnabled)
+ or before.policy.optedOutApps.contains(after.lastDecision.appId)
+ ) implies (
+ out.length() == 0
+ and after.storedCount == before.storedCount
+ and after.lastDecision.source == SourceRedacted
+ and not(after.lastDecision.sentToCloud)
+ and not(after.lastDecision.storedInDigest)
+ ))
+ and out.every(e => match e {
+ | CallLocalLlm(c) =>
+ via == "processNotification"
+ and before.policy.summarizationEnabled
+ and before.mode != ModeOffline
+ and localLlmReady(before.health)
+ and not(before.policy.optedOutApps.contains(c.appId))
+ and not(isSensitive(after.lastDecision.sensitivity))
+ | CallCloudLlm(c) =>
+ via == "processNotification"
+ and before.policy.summarizationEnabled
+ and before.policy.cloudFallbackEnabled
+ and before.health.cloudAvailable
+ and before.mode != ModeLocalOnly
+ and before.mode != ModeOffline
+ and not(before.policy.optedOutApps.contains(c.appId))
+ and not(isSensitive(after.lastDecision.sensitivity))
+ | AttachAdjustment(a) =>
+ via == "processNotification"
+ and before.policy.summarizationEnabled
+ and a.source != SourceRedacted
+ and a.summaryLen >= 0
+ and a.summaryLen <= maxSummaryChars
+ and not(isSensitive(after.lastDecision.sensitivity))
+ | RecordDigest(r) =>
+ via == "processNotification"
+ and before.policy.summarizationEnabled
+ and not(before.policy.optedOutApps.contains(r.appId))
+ and r.summaryLen >= 0
+ and r.summaryLen <= maxSummaryChars
+ and not(isSensitive(after.lastDecision.sensitivity))
+ })
+```
+
+### Routing laws hold for all policy, RAM, mode, and sensitivity inputs
+
+```quint
+pure def lawSensitiveAlwaysRedacted(
+ policy: NotificationPolicy,
+ mode: RouterMode,
+ health: RouterHealth,
+ appId: int,
+ sensitivity: Sensitivity,
+): bool =
+ isSensitive(sensitivity) implies selectSummarySource(policy, mode, health, appId, sensitivity) == SourceRedacted
+
+pure def lawOptedOutNeverSummarized(
+ policy: NotificationPolicy,
+ mode: RouterMode,
+ health: RouterHealth,
+ appId: int,
+ sensitivity: Sensitivity,
+): bool =
+ policy.optedOutApps.contains(appId) implies selectSummarySource(policy, mode, health, appId, sensitivity) == SourceRedacted
+
+pure def lawLowRamNeverRunsLocalLlm(
+ policy: NotificationPolicy,
+ mode: RouterMode,
+ health: RouterHealth,
+ appId: int,
+ sensitivity: Sensitivity,
+): bool =
+ (not(health.localInstalled) or health.freeRamMb < minLocalRamMb)
+ implies selectSummarySource(policy, mode, health, appId, sensitivity) != SourceLocalLlm
+
+pure def lawLocalOnlyNeverUsesCloud(
+ policy: NotificationPolicy,
+ health: RouterHealth,
+ appId: int,
+ sensitivity: Sensitivity,
+): bool =
+ selectSummarySource(policy, ModeLocalOnly, health, appId, sensitivity) != SourceCloudLlm
+
+pure def lawOfflineNeverUsesLlm(
+ policy: NotificationPolicy,
+ health: RouterHealth,
+ appId: int,
+ sensitivity: Sensitivity,
+): bool =
+ val chosen = selectSummarySource(policy, ModeOffline, health, appId, sensitivity)
+ chosen == SourceRedacted or chosen == SourceDeterministic
+
+pure def lawClampedSummaryBounded(rawLen: int): bool =
+ val bounded = clampSummaryLen(rawLen)
+ bounded >= 0 and bounded <= maxSummaryChars
+```
+
+### The model reaches local Gemma summarization, cloud fallback, deterministic offline fallback, sensitive redaction, and per-app opt-out
+
+```quint
+pure def sometimesLocalSummary(n: NotificationState): bool =
+ n.lastDecision.source == SourceLocalLlm and n.lastDecision.storedInDigest
+
+pure def sometimesCloudFallbackSummary(n: NotificationState): bool =
+ n.lastDecision.source == SourceCloudLlm and n.lastDecision.sentToCloud
+
+pure def sometimesDeterministicFallback(n: NotificationState): bool =
+ n.lastDecision.source == SourceDeterministic and not(n.lastDecision.sentToCloud)
+
+pure def sometimesSensitiveRedacted(n: NotificationState): bool =
+ n.lastDecision.notifId > 0 and isSensitive(n.lastDecision.sensitivity) and n.lastDecision.source == SourceRedacted
+
+pure def sometimesOptedOutSkipped(n: NotificationState): bool =
+ n.lastDecision.notifId > 0 and n.policy.optedOutApps.contains(n.lastDecision.appId) and n.lastDecision.source == SourceRedacted
+
+pure val eval_witness_sometimesLocalSummary = (
+ ("updateHealth", true, 1400, false, Router),
+ ("processNotification", 1, 1, Clear, BundleConversation, 64, System),
+)
+
+pure val eval_witness_sometimesCloudFallbackSummary = (
+ ("updateHealth", false, 512, true, Router),
+ ("processNotification", 1, 1, Clear, BundleNews, 220, System),
+)
+
+pure val eval_witness_sometimesDeterministicFallback =
+ ("processNotification", 1, 1, Clear, BundlePromo, 64, System)
+
+pure val eval_witness_sometimesSensitiveRedacted = (
+ ("updateHealth", true, 1400, true, Router),
+ ("processNotification", 1, 1, OtpCode, BundleConversation, 64, System),
+)
+
+pure val eval_witness_sometimesOptedOutSkipped = (
+ ("optOutApp", 1, Owner),
+ ("updateHealth", true, 1400, true, Router),
+ ("processNotification", 1, 1, Clear, BundleSocial, 64, System),
+)
+
+pure val eval_witness_canOptInApp = (
+ ("optOutApp", 1, Owner),
+ ("optInApp", 1, Owner),
+)
+
+pure val eval_witness_canSetSummarizationEnabled =
+ ("setSummarizationEnabled", false, Owner)
+
+pure val eval_witness_canSetCloudFallback =
+ ("setCloudFallback", false, Owner)
+
+pure val eval_witness_canSetRouterMode =
+ ("setRouterMode", ModeLocalOnly, Owner)
+```
diff --git a/spec/app/playStore/index.md b/spec/app/playStore/index.md
new file mode 100644
index 0000000000..ed7962f0b3
--- /dev/null
+++ b/spec/app/playStore/index.md
@@ -0,0 +1,465 @@
+# Sandboxed Google Play
+
+How the owner installs, audits, and removes Sandboxed Google Play under
+GrapheneOS `GmsCompat` on Alpha OS without granting any privileged system
+permission to Google packages. Installation fails closed unless `GmsCompat`
+and `AlphaPlayInstaller` are present, the release manifest and official Google
+signing certificate verify, every package installs strictly in
+`GSF -> GMS -> Play Store` order into `/data/app`, and zero privileged Google
+grants exist.
+
+## Story: Install Sandboxed Google Play in strict verified order
+
+> As the owner, I want one-tap Sandboxed Google Play installation that verifies
+> official Google packages, installs GSF then GMS then Play Store as ordinary
+> sandboxed user apps with zero privileged grants, and fails closed on any
+> verification or isolation error.
+
+### The state tracks the fail-closed install phase, GmsCompat readiness, per-package installation progress, and sandbox isolation
+
+```quint
+type Actor = Owner | Phone
+type PlayPhase = Idle | Verifying | InstallingGsf | InstallingGms | InstallingStore | Installed | Failed
+type PlayPackage = PkgGsf | PkgGms | PkgStore
+type FailureCode =
+ NoFailure
+ | GmsCompatUnavailable
+ | VerificationFailed
+ | GsfInstallFailed
+ | GmsInstallFailed
+ | StoreInstallFailed
+ | PrivilegedGrantDetected
+ | UninstallFailed
+
+type PlayEffect =
+ | CheckSandboxStatus({ reqId: int })
+ | VerifyPlayRelease({ reqId: int })
+ | InstallPlayPackage({ reqId: int, pkg: PlayPackage })
+ | UninstallPlaySuite({ reqId: int })
+
+type PlayStoreState = {
+ phase: PlayPhase,
+ gmsCompatReady: bool,
+ manifestVerified: bool,
+ gsfInstalled: bool,
+ gmsInstalled: bool,
+ storeInstalled: bool,
+ googlePrivAppGrants: int,
+ sandboxedInDataApp: bool,
+ removing: bool,
+ failure: FailureCode,
+ lastTicket: int,
+}
+
+type PlayMoved = { state: PlayStoreState, out: List[PlayEffect] }
+
+pure val initial: PlayStoreState = {
+ phase: Idle,
+ gmsCompatReady: false,
+ manifestVerified: false,
+ gsfInstalled: false,
+ gmsInstalled: false,
+ storeInstalled: false,
+ googlePrivAppGrants: 0,
+ sandboxedInDataApp: true,
+ removing: false,
+ failure: NoFailure,
+ lastTicket: 0,
+}
+
+pure def isMidInstall(p: PlayPhase): bool =
+ p == Verifying or p == InstallingGsf or p == InstallingGms or p == InstallingStore
+
+pure val reqIdValues = Set(0, 1, 2, 3)
+pure val privGrantsValues = Set(0, 1)
+pure val weight_requestRefresh = 10
+pure val weight_reportStatus = 20
+pure val weight_requestInstall = 20
+pure val weight_verificationDone = 20
+pure val weight_gsfDone = 20
+pure val weight_gmsDone = 20
+pure val weight_storeDone = 20
+pure val weight_requestUninstall = 15
+pure val weight_uninstallDone = 15
+```
+
+### Checking sandbox status reports whether GmsCompat is present and fails closed if any privileged Google grant or non-user partition is detected
+
+```quint
+pure def canRequestRefresh(s: PlayStoreState, by: Actor): bool =
+ (by == Owner or by == Phone) and not(isMidInstall(s.phase)) and not(s.removing)
+
+pure def requestRefresh(s: PlayStoreState, by: Actor): PlayMoved =
+ val nextTicket = s.lastTicket + 1
+ {
+ state: { ...s, lastTicket: nextTicket },
+ out: List(CheckSandboxStatus({ reqId: nextTicket })),
+ }
+
+pure def canReportStatus(
+ s: PlayStoreState,
+ reqId: int,
+ gmsCompatReady: bool,
+ gsf: bool,
+ gms: bool,
+ store: bool,
+ privGrants: int,
+ inDataApp: bool,
+ by: Actor,
+): bool =
+ by == Phone
+ and reqId == s.lastTicket
+ and not(isMidInstall(s.phase))
+ and not(s.removing)
+ and privGrants >= 0
+ and (gms implies gsf)
+ and (store implies gms)
+
+pure def reportStatus(
+ s: PlayStoreState,
+ reqId: int,
+ gmsCompatReady: bool,
+ gsf: bool,
+ gms: bool,
+ store: bool,
+ privGrants: int,
+ inDataApp: bool,
+ by: Actor,
+): PlayMoved =
+ val anyGoogle = gsf or gms or store
+ val sandboxBreach = privGrants > 0 or (anyGoogle and not(inDataApp))
+ if (sandboxBreach) {
+ state: {
+ ...s,
+ phase: Failed,
+ gmsCompatReady: gmsCompatReady,
+ manifestVerified: false,
+ gsfInstalled: false,
+ gmsInstalled: false,
+ storeInstalled: false,
+ googlePrivAppGrants: privGrants,
+ sandboxedInDataApp: false,
+ failure: PrivilegedGrantDetected,
+ },
+ out: List(),
+ } else if (gmsCompatReady and gsf and gms and store) {
+ state: {
+ ...s,
+ phase: Installed,
+ gmsCompatReady: true,
+ manifestVerified: true,
+ gsfInstalled: true,
+ gmsInstalled: true,
+ storeInstalled: true,
+ googlePrivAppGrants: 0,
+ sandboxedInDataApp: true,
+ failure: NoFailure,
+ },
+ out: List(),
+ } else {
+ state: {
+ ...s,
+ phase: Idle,
+ gmsCompatReady: gmsCompatReady,
+ manifestVerified: false,
+ gsfInstalled: gsf,
+ gmsInstalled: gms,
+ storeInstalled: store,
+ googlePrivAppGrants: 0,
+ sandboxedInDataApp: true,
+ failure: if (not(gmsCompatReady)) GmsCompatUnavailable else NoFailure,
+ },
+ out: List(),
+ }
+```
+
+### Only the owner may trigger installation when GmsCompat is ready and zero privileged grants exist, starting with manifest and signature verification
+
+```quint
+pure def canRequestInstall(s: PlayStoreState, by: Actor): bool =
+ by == Owner
+ and (s.phase == Idle or s.phase == Failed)
+ and not(s.removing)
+ and s.gmsCompatReady
+ and s.googlePrivAppGrants == 0
+ and s.sandboxedInDataApp
+
+pure def requestInstall(s: PlayStoreState, by: Actor): PlayMoved =
+ val nextTicket = s.lastTicket + 1
+ {
+ state: {
+ ...s,
+ phase: Verifying,
+ manifestVerified: false,
+ gsfInstalled: false,
+ gmsInstalled: false,
+ storeInstalled: false,
+ failure: NoFailure,
+ lastTicket: nextTicket,
+ },
+ out: List(VerifyPlayRelease({ reqId: nextTicket })),
+ }
+```
+
+### Passing cryptographic verification with zero privileged grants begins installing GSF first; any failure stops closed
+
+```quint
+pure def canVerificationDone(s: PlayStoreState, reqId: int, ok: bool, privGrants: int, by: Actor): bool =
+ by == Phone and s.phase == Verifying and reqId == s.lastTicket and privGrants >= 0
+
+pure def verificationDone(s: PlayStoreState, reqId: int, ok: bool, privGrants: int, by: Actor): PlayMoved =
+ if (ok and privGrants == 0) {
+ state: {
+ ...s,
+ phase: InstallingGsf,
+ manifestVerified: true,
+ googlePrivAppGrants: 0,
+ failure: NoFailure,
+ },
+ out: List(InstallPlayPackage({ reqId: s.lastTicket, pkg: PkgGsf })),
+ } else {
+ state: {
+ ...s,
+ phase: Failed,
+ manifestVerified: false,
+ googlePrivAppGrants: privGrants,
+ failure: if (privGrants > 0) PrivilegedGrantDetected else VerificationFailed,
+ },
+ out: List(),
+ }
+```
+
+### GSF must complete inside the user app sandbox with zero privileged grants before GMS installation starts
+
+```quint
+pure def canGsfDone(s: PlayStoreState, reqId: int, ok: bool, inDataApp: bool, privGrants: int, by: Actor): bool =
+ by == Phone and s.phase == InstallingGsf and reqId == s.lastTicket and privGrants >= 0
+
+pure def gsfDone(s: PlayStoreState, reqId: int, ok: bool, inDataApp: bool, privGrants: int, by: Actor): PlayMoved =
+ if (ok and inDataApp and privGrants == 0) {
+ state: {
+ ...s,
+ phase: InstallingGms,
+ gsfInstalled: true,
+ failure: NoFailure,
+ },
+ out: List(InstallPlayPackage({ reqId: s.lastTicket, pkg: PkgGms })),
+ } else {
+ state: {
+ ...s,
+ phase: Failed,
+ googlePrivAppGrants: privGrants,
+ sandboxedInDataApp: inDataApp,
+ failure: if (privGrants > 0 or not(inDataApp)) PrivilegedGrantDetected else GsfInstallFailed,
+ },
+ out: List(),
+ }
+```
+
+### GMS must complete inside the user app sandbox with zero privileged grants before Play Store installation starts
+
+```quint
+pure def canGmsDone(s: PlayStoreState, reqId: int, ok: bool, inDataApp: bool, privGrants: int, by: Actor): bool =
+ by == Phone and s.phase == InstallingGms and reqId == s.lastTicket and privGrants >= 0
+
+pure def gmsDone(s: PlayStoreState, reqId: int, ok: bool, inDataApp: bool, privGrants: int, by: Actor): PlayMoved =
+ if (ok and inDataApp and privGrants == 0) {
+ state: {
+ ...s,
+ phase: InstallingStore,
+ gmsInstalled: true,
+ failure: NoFailure,
+ },
+ out: List(InstallPlayPackage({ reqId: s.lastTicket, pkg: PkgStore })),
+ } else {
+ state: {
+ ...s,
+ phase: Failed,
+ googlePrivAppGrants: privGrants,
+ sandboxedInDataApp: inDataApp,
+ failure: if (privGrants > 0 or not(inDataApp)) PrivilegedGrantDetected else GmsInstallFailed,
+ },
+ out: List(),
+ }
+```
+
+### Completing Play Store inside the user app sandbox with zero privileged grants marks Sandboxed Google Play installed
+
+```quint
+pure def canStoreDone(s: PlayStoreState, reqId: int, ok: bool, inDataApp: bool, privGrants: int, by: Actor): bool =
+ by == Phone and s.phase == InstallingStore and reqId == s.lastTicket and privGrants >= 0
+
+pure def storeDone(s: PlayStoreState, reqId: int, ok: bool, inDataApp: bool, privGrants: int, by: Actor): PlayMoved =
+ if (ok and inDataApp and privGrants == 0) {
+ state: {
+ ...s,
+ phase: Installed,
+ storeInstalled: true,
+ failure: NoFailure,
+ },
+ out: List(),
+ } else {
+ state: {
+ ...s,
+ phase: Failed,
+ googlePrivAppGrants: privGrants,
+ sandboxedInDataApp: inDataApp,
+ failure: if (privGrants > 0 or not(inDataApp)) PrivilegedGrantDetected else StoreInstallFailed,
+ },
+ out: List(),
+ }
+```
+
+### The owner can remove sandboxed Google Play packages and return to idle when no privileged grants exist
+
+```quint
+pure def canRequestUninstall(s: PlayStoreState, by: Actor): bool =
+ by == Owner
+ and not(s.removing)
+ and s.googlePrivAppGrants == 0
+ and (s.phase == Installed or (s.phase == Failed and (s.gsfInstalled or s.gmsInstalled or s.storeInstalled)))
+
+pure def requestUninstall(s: PlayStoreState, by: Actor): PlayMoved =
+ val nextTicket = s.lastTicket + 1
+ {
+ state: { ...s, removing: true, lastTicket: nextTicket },
+ out: List(UninstallPlaySuite({ reqId: nextTicket })),
+ }
+
+pure def canUninstallDone(s: PlayStoreState, reqId: int, ok: bool, by: Actor): bool =
+ by == Phone and s.removing and reqId == s.lastTicket
+
+pure def uninstallDone(s: PlayStoreState, reqId: int, ok: bool, by: Actor): PlayMoved =
+ if (ok) {
+ state: {
+ ...s,
+ phase: Idle,
+ removing: false,
+ manifestVerified: false,
+ gsfInstalled: false,
+ gmsInstalled: false,
+ storeInstalled: false,
+ sandboxedInDataApp: true,
+ failure: NoFailure,
+ },
+ out: List(),
+ } else {
+ state: {
+ ...s,
+ phase: Failed,
+ removing: false,
+ failure: UninstallFailed,
+ },
+ out: List(),
+ }
+```
+
+## Story: Enforce zero privileged Google grants and strict dependency order
+
+> As the owner, I want formal proof that Google packages are never installed
+> out of GSF -> GMS -> Play Store order, never installed without verification,
+> and never allowed when any privileged Google grant is present.
+
+### Zero privileged Google grants and `/data/app` sandboxing always hold during installation and once installed
+
+```quint
+pure def alwaysZeroPrivGrantsWhenActive(s: PlayStoreState): bool =
+ s.googlePrivAppGrants >= 0
+ and s.lastTicket >= 0
+ and (isMidInstall(s.phase) implies not(s.removing))
+ and ((isMidInstall(s.phase) or s.phase == Installed) implies (
+ s.googlePrivAppGrants == 0 and s.sandboxedInDataApp and s.gmsCompatReady
+ ))
+```
+
+### Installed packages strictly preserve the GSF -> GMS -> Play Store dependency chain and match the active install phase
+
+```quint
+pure def alwaysStrictInstallOrder(s: PlayStoreState): bool =
+ (s.gmsInstalled implies s.gsfInstalled)
+ and (s.storeInstalled implies s.gmsInstalled)
+ and (s.phase == Verifying implies (not(s.manifestVerified) and not(s.gsfInstalled) and not(s.gmsInstalled) and not(s.storeInstalled)))
+ and (s.phase == InstallingGsf implies (s.manifestVerified and not(s.gsfInstalled) and not(s.gmsInstalled) and not(s.storeInstalled)))
+ and (s.phase == InstallingGms implies (s.manifestVerified and s.gsfInstalled and not(s.gmsInstalled) and not(s.storeInstalled)))
+ and (s.phase == InstallingStore implies (s.manifestVerified and s.gsfInstalled and s.gmsInstalled and not(s.storeInstalled)))
+ and (s.phase == Installed implies (s.manifestVerified and s.gsfInstalled and s.gmsInstalled and s.storeInstalled))
+```
+
+### Every emitted package install effect obeys exact verified GSF -> GMS -> Play Store ordering with zero privileged grants
+
+```quint
+pure def stepExactInstallOrdering(
+ before: PlayStoreState,
+ via: str,
+ after: PlayStoreState,
+ out: List[PlayEffect],
+): bool =
+ out.every(e => match e {
+ | InstallPlayPackage(p) =>
+ after.googlePrivAppGrants == 0
+ and after.sandboxedInDataApp
+ and after.manifestVerified
+ and (
+ if (p.pkg == PkgGsf)
+ via == "verificationDone" and before.phase == Verifying and after.phase == InstallingGsf and not(after.gsfInstalled)
+ else if (p.pkg == PkgGms)
+ via == "gsfDone" and before.phase == InstallingGsf and after.phase == InstallingGms and after.gsfInstalled and not(after.gmsInstalled)
+ else
+ via == "gmsDone" and before.phase == InstallingGms and after.phase == InstallingStore and after.gsfInstalled and after.gmsInstalled and not(after.storeInstalled)
+ )
+ | _ => true
+ })
+```
+
+### Any privileged Google grant or missing GmsCompat always refuses starting installation
+
+```quint
+pure def lawPrivilegedGrantRefusesInstall(s: PlayStoreState, by: Actor): bool =
+ (s.googlePrivAppGrants > 0 or not(s.sandboxedInDataApp) or not(s.gmsCompatReady))
+ implies not(canRequestInstall(s, by))
+```
+
+### The full verified install flow, verification refusal, privileged-grant refusal, and clean uninstall are all reachable
+
+```quint
+pure def sometimesInstalled(s: PlayStoreState): bool =
+ s.phase == Installed and s.gsfInstalled and s.gmsInstalled and s.storeInstalled and s.googlePrivAppGrants == 0
+
+pure def sometimesFailedVerification(s: PlayStoreState): bool =
+ s.phase == Failed and s.failure == VerificationFailed
+
+pure def sometimesFailedPrivGrant(s: PlayStoreState): bool =
+ s.phase == Failed and s.failure == PrivilegedGrantDetected
+
+pure def sometimesUninstalled(s: PlayStoreState): bool =
+ s.phase == Idle and s.gmsCompatReady and not(s.gsfInstalled) and s.lastTicket >= 2
+
+pure val eval_witness_sometimesInstalled = (
+ ("requestRefresh", Phone),
+ ("reportStatus", 1, true, false, false, false, 0, true, Phone),
+ ("requestInstall", Owner),
+ ("verificationDone", 2, true, 0, Phone),
+ ("gsfDone", 2, true, true, 0, Phone),
+ ("gmsDone", 2, true, true, 0, Phone),
+ ("storeDone", 2, true, true, 0, Phone),
+)
+
+pure val eval_witness_sometimesFailedVerification = (
+ ("requestRefresh", Phone),
+ ("reportStatus", 1, true, false, false, false, 0, true, Phone),
+ ("requestInstall", Owner),
+ ("verificationDone", 2, false, 0, Phone),
+)
+
+pure val eval_witness_sometimesFailedPrivGrant = (
+ ("requestRefresh", Phone),
+ ("reportStatus", 1, true, true, false, false, 1, true, Phone),
+)
+
+pure val eval_witness_sometimesUninstalled = (
+ ("requestRefresh", Phone),
+ ("reportStatus", 1, true, true, true, true, 0, true, Phone),
+ ("requestUninstall", Owner),
+ ("uninstallDone", 2, true, Phone),
+)
+```
diff --git a/spec/app/themes/index.md b/spec/app/themes/index.md
new file mode 100644
index 0000000000..20d49e05ba
--- /dev/null
+++ b/spec/app/themes/index.md
@@ -0,0 +1,291 @@
+# Curated full-OS theme packs and navigation policy
+
+How the owner switches between the six curated OKLCH full-OS theme packs
+(`Ink Dark` [default], `Crisp Light`, `Tokyo Night`, `Gruvbox`, `Catppuccin`,
+and `Everforest`) and toggles between stock Android Recents gesture navigation
+and focused Home + Back navigation via Android `OverlayManager` RRO overlays.
+Every switch runs one operation at a time and rolls back atomically on failure
+so the active theme or navigation policy never ends up half-applied.
+
+## Story: Switch curated full-OS theme packs and navigation mode atomically
+
+> As the owner, I want one-tap switching across six curated full-OS theme packs
+> and a clean toggle between stock Android Recents gestures and focused Home +
+> Back navigation, keeping my previous active configuration intact if Android
+> fails to apply an overlay.
+
+### The state tracks the active and pending theme pack, navigation mode, OS overlay capability, and operation tickets
+
+```quint
+type Actor = Owner | Phone
+type ThemePackId = InkDark | CrispLight | TokyoNight | Gruvbox | Catppuccin | Everforest
+type NavMode = StockRecents | FocusedHomeBack
+type ApplyStatus = Ready | Applying | ApplyFailed
+
+type ThemeEffect =
+ | ReadThemeStatus({ reqId: int })
+ | ApplyThemePack({ reqId: int, pack: ThemePackId })
+ | ApplyNavMode({ reqId: int, mode: NavMode })
+
+type ThemeState = {
+ activePack: ThemePackId,
+ pendingPack: ThemePackId,
+ applyingTheme: bool,
+ themeStatus: ApplyStatus,
+ activeNav: NavMode,
+ pendingNav: NavMode,
+ applyingNav: bool,
+ navStatus: ApplyStatus,
+ osOverlaysAvailable: bool,
+ lastThemeTicket: int,
+ lastNavTicket: int,
+ lastStatusTicket: int,
+}
+
+type ThemeMoved = { state: ThemeState, out: List[ThemeEffect] }
+
+pure val initial: ThemeState = {
+ activePack: InkDark,
+ pendingPack: InkDark,
+ applyingTheme: false,
+ themeStatus: Ready,
+ activeNav: StockRecents,
+ pendingNav: StockRecents,
+ applyingNav: false,
+ navStatus: Ready,
+ osOverlaysAvailable: false,
+ lastThemeTicket: 0,
+ lastNavTicket: 0,
+ lastStatusTicket: 0,
+}
+
+pure val reqIdValues = Set(0, 1, 2)
+pure val packValues = Set(InkDark, CrispLight, TokyoNight, Gruvbox, Catppuccin, Everforest)
+pure val modeValues = Set(StockRecents, FocusedHomeBack)
+pure val weight_requestStatus = 10
+pure val weight_reportStatus = 20
+pure val weight_chooseTheme = 25
+pure val weight_themeApplied = 25
+pure val weight_chooseNavMode = 20
+pure val weight_navModeApplied = 20
+```
+
+### Reading device theme status loads the persisted pack, navigation mode, and whether full-OS RRO overlays are available
+
+```quint
+pure def canRequestStatus(s: ThemeState, by: Actor): bool =
+ (by == Owner or by == Phone) and not(s.applyingTheme) and not(s.applyingNav)
+
+pure def requestStatus(s: ThemeState, by: Actor): ThemeMoved =
+ val nextTicket = s.lastStatusTicket + 1
+ {
+ state: { ...s, lastStatusTicket: nextTicket },
+ out: List(ReadThemeStatus({ reqId: nextTicket })),
+ }
+
+pure def canReportStatus(
+ s: ThemeState,
+ reqId: int,
+ pack: ThemePackId,
+ mode: NavMode,
+ osOverlays: bool,
+ by: Actor,
+): bool =
+ by == Phone and reqId == s.lastStatusTicket and not(s.applyingTheme) and not(s.applyingNav)
+
+pure def reportStatus(
+ s: ThemeState,
+ reqId: int,
+ pack: ThemePackId,
+ mode: NavMode,
+ osOverlays: bool,
+ by: Actor,
+): ThemeMoved =
+ {
+ state: {
+ ...s,
+ activePack: pack,
+ pendingPack: pack,
+ themeStatus: Ready,
+ activeNav: mode,
+ pendingNav: mode,
+ navStatus: Ready,
+ osOverlaysAvailable: osOverlays,
+ },
+ out: List(),
+ }
+```
+
+### Choosing a different theme pack applies one switch at a time, and any failure rolls back to the active pack
+
+```quint
+pure def canChooseTheme(s: ThemeState, pack: ThemePackId, by: Actor): bool =
+ by == Owner and not(s.applyingTheme) and pack != s.activePack
+
+pure def chooseTheme(s: ThemeState, pack: ThemePackId, by: Actor): ThemeMoved =
+ val nextTicket = s.lastThemeTicket + 1
+ {
+ state: {
+ ...s,
+ pendingPack: pack,
+ applyingTheme: true,
+ themeStatus: Applying,
+ lastThemeTicket: nextTicket,
+ },
+ out: List(ApplyThemePack({ reqId: nextTicket, pack: pack })),
+ }
+
+pure def canThemeApplied(s: ThemeState, reqId: int, ok: bool, by: Actor): bool =
+ by == Phone and s.applyingTheme and reqId == s.lastThemeTicket
+
+pure def themeApplied(s: ThemeState, reqId: int, ok: bool, by: Actor): ThemeMoved =
+ if (ok) {
+ state: {
+ ...s,
+ activePack: s.pendingPack,
+ applyingTheme: false,
+ themeStatus: Ready,
+ },
+ out: List(),
+ } else {
+ state: {
+ ...s,
+ pendingPack: s.activePack,
+ applyingTheme: false,
+ themeStatus: ApplyFailed,
+ },
+ out: List(),
+ }
+```
+
+### Toggling navigation policy between stock Android Recents and focused Home + Back runs one switch at a time and rolls back on failure
+
+```quint
+pure def canChooseNavMode(s: ThemeState, mode: NavMode, by: Actor): bool =
+ by == Owner and not(s.applyingNav) and mode != s.activeNav
+
+pure def chooseNavMode(s: ThemeState, mode: NavMode, by: Actor): ThemeMoved =
+ val nextTicket = s.lastNavTicket + 1
+ {
+ state: {
+ ...s,
+ pendingNav: mode,
+ applyingNav: true,
+ navStatus: Applying,
+ lastNavTicket: nextTicket,
+ },
+ out: List(ApplyNavMode({ reqId: nextTicket, mode: mode })),
+ }
+
+pure def canNavModeApplied(s: ThemeState, reqId: int, ok: bool, by: Actor): bool =
+ by == Phone and s.applyingNav and reqId == s.lastNavTicket
+
+pure def navModeApplied(s: ThemeState, reqId: int, ok: bool, by: Actor): ThemeMoved =
+ if (ok) {
+ state: {
+ ...s,
+ activeNav: s.pendingNav,
+ applyingNav: false,
+ navStatus: Ready,
+ },
+ out: List(),
+ } else {
+ state: {
+ ...s,
+ pendingNav: s.activeNav,
+ applyingNav: false,
+ navStatus: ApplyFailed,
+ },
+ out: List(),
+ }
+```
+
+## Story: Enforce atomic rollback and single-flight theme and navigation switching
+
+> As the owner, I want hard guarantees that failed overlay switches never alter
+> the active theme or navigation policy and that no redundant or concurrent
+> overlay mutations can overlap.
+
+### Idle pending selections always match active selections, and applying flags match apply status
+
+```quint
+pure def alwaysConsistentSelections(s: ThemeState): bool =
+ s.lastThemeTicket >= 0
+ and s.lastNavTicket >= 0
+ and s.lastStatusTicket >= 0
+ and (s.applyingTheme iff s.themeStatus == Applying)
+ and (s.applyingNav iff s.navStatus == Applying)
+ and (not(s.applyingTheme) implies s.pendingPack == s.activePack)
+ and (not(s.applyingNav) implies s.pendingNav == s.activeNav)
+ and (s.applyingTheme implies s.pendingPack != s.activePack)
+ and (s.applyingNav implies s.pendingNav != s.activeNav)
+```
+
+### Every failed theme or navigation switch preserves the prior active selection
+
+```quint
+pure def stepAtomicRollback(before: ThemeState, via: str, after: ThemeState, out: List[ThemeEffect]): bool =
+ ((via == "themeApplied" and after.themeStatus == ApplyFailed) implies (
+ after.activePack == before.activePack and after.pendingPack == before.activePack
+ ))
+ and ((via == "navModeApplied" and after.navStatus == ApplyFailed) implies (
+ after.activeNav == before.activeNav and after.pendingNav == before.activeNav
+ ))
+ and out.every(e => match e {
+ | ApplyThemePack(a) => via == "chooseTheme" and a.pack != before.activePack
+ | ApplyNavMode(a) => via == "chooseNavMode" and a.mode != before.activeNav
+ | ReadThemeStatus(_) => via == "requestStatus"
+ })
+```
+
+### Selecting the already-active theme pack or navigation mode is refused as a no-op, and only the owner may switch
+
+```quint
+pure def lawNoRedundantOrUnauthorizedSwitch(s: ThemeState, pack: ThemePackId, mode: NavMode, by: Actor): bool =
+ ((pack == s.activePack or by != Owner) implies not(canChooseTheme(s, pack, by)))
+ and ((mode == s.activeNav or by != Owner) implies not(canChooseNavMode(s, mode, by)))
+```
+
+### Switching to Tokyo Night, Crisp Light, focused Home + Back, and atomic rollback on failure are all reachable
+
+```quint
+pure def sometimesTokyoNightActive(s: ThemeState): bool =
+ s.activePack == TokyoNight and not(s.applyingTheme) and s.themeStatus == Ready
+
+pure def sometimesCrispLightActive(s: ThemeState): bool =
+ s.activePack == CrispLight and not(s.applyingTheme) and s.themeStatus == Ready
+
+pure def sometimesFocusedHomeBackActive(s: ThemeState): bool =
+ s.activeNav == FocusedHomeBack and not(s.applyingNav) and s.navStatus == Ready
+
+pure def sometimesThemeRollback(s: ThemeState): bool =
+ s.themeStatus == ApplyFailed and s.activePack == InkDark and not(s.applyingTheme)
+
+pure def sometimesNavRollback(s: ThemeState): bool =
+ s.navStatus == ApplyFailed and s.activeNav == StockRecents and not(s.applyingNav)
+
+pure val eval_witness_sometimesTokyoNightActive = (
+ ("chooseTheme", TokyoNight, Owner),
+ ("themeApplied", 1, true, Phone),
+)
+
+pure val eval_witness_sometimesCrispLightActive = (
+ ("chooseTheme", CrispLight, Owner),
+ ("themeApplied", 1, true, Phone),
+)
+
+pure val eval_witness_sometimesFocusedHomeBackActive = (
+ ("chooseNavMode", FocusedHomeBack, Owner),
+ ("navModeApplied", 1, true, Phone),
+)
+
+pure val eval_witness_sometimesThemeRollback = (
+ ("chooseTheme", Everforest, Owner),
+ ("themeApplied", 1, false, Phone),
+)
+
+pure val eval_witness_sometimesNavRollback = (
+ ("chooseNavMode", FocusedHomeBack, Owner),
+ ("navModeApplied", 1, false, Phone),
+)
+```