From bda011d38e67fe303c55553cfcc7b3d9642cd8bc Mon Sep 17 00:00:00 2001 From: Shaw Walters Date: Wed, 2 Dec 2026 16:09:07 -0800 Subject: [PATCH 001/193] Reconcile develop's spec for sign-off: proofs, prose to match Quint, owner decisions Goal: sign off develop's spec so CI on develop goes green. - Proofs: the Telegram route count in spec/agent/index.proof.dfy (23 routes), the window-in-front obligations in spec/app/shell/index.proof.dfy, and calendar sharing's editForm, which opened the form for a negative match count against its law (matches < 1 now means no match). - Review: the prose of 33 rules rewritten to say what their Quint says. - Owner decisions: the page no longer reaches /api/alpha/memory/{search, records,safari-action}, which nothing on the page calls; Maps funding is a pure def with a law that wrangler.vibe uses; Calendar's introduction lists creating an event on the phone again; the Apps story says Apps stays hidden on Home. --- apps/agent/host/routes.jsonl | 3 - apps/agent/src/main.vibe | 4 +- apps/agent/src/plugins/memory-graph.ts | 2 +- apps/app/src/platform/iosAgentRuntime.ts | 1 - apps/cloud/src/wrangler.vibe | 7 ++- spec/agent/index.md | 14 ++--- spec/agent/index.proof.dfy | 10 +-- spec/app/assistant/context.md | 6 +- spec/app/assistant/dock.md | 14 +++-- spec/app/assistant/index.md | 8 ++- spec/app/browser/safariCopilot.md | 8 +++ spec/app/calendar/actions.md | 16 ++--- spec/app/calendar/sharing.md | 6 +- spec/app/camera/index.md | 13 ++-- spec/app/clock/stopwatch.md | 5 +- spec/app/contacts/agent.md | 7 ++- spec/app/home/index.md | 15 +++-- spec/app/maps/index.md | 2 +- spec/app/messages/index.md | 4 +- spec/app/photos/memoryGraph.md | 2 + spec/app/settings/preferences.md | 8 +++ spec/app/shell/index.md | 12 ++-- spec/app/shell/index.proof.dfy | 80 ++++++++++++++++++++++++ spec/app/update/index.md | 12 +++- spec/app/workflows/list.md | 11 +++- spec/cloud/rollout.md | 20 ++++-- spec/release/index.md | 5 +- 27 files changed, 216 insertions(+), 79 deletions(-) diff --git a/apps/agent/host/routes.jsonl b/apps/agent/host/routes.jsonl index 62ec5c585f..2cf5fe163d 100644 --- a/apps/agent/host/routes.jsonl +++ b/apps/agent/host/routes.jsonl @@ -129,9 +129,6 @@ { "method": "POST", "path": "/api/alpha/local-llm/mode", "maxBodyBytes": 1024 } { "method": "POST", "path": "/api/alpha/local-llm/activate", "maxBodyBytes": 1024 } { "method": "POST", "path": "/api/alpha/local-llm/delete", "maxBodyBytes": 1024 } -{ "method": "GET", "path": "/api/alpha/memory/search" } -{ "method": "POST", "path": "/api/alpha/memory/records", "maxBodyBytes": 65536 } -{ "method": "POST", "path": "/api/alpha/memory/safari-action", "maxBodyBytes": 4096 } { "method": "GET", "path": "/api/slack/accounts" } { "method": "POST", "path": "/api/slack/oauth/start" } { "method": "POST", "path": "/api/slack/oauth/complete" } diff --git a/apps/agent/src/main.vibe b/apps/agent/src/main.vibe index e8353ec990..e6a64b2af4 100644 --- a/apps/agent/src/main.vibe +++ b/apps/agent/src/main.vibe @@ -7,7 +7,7 @@ import { deployment } from "@repo/deployment" import { packWorkerDir, packagedWorkflowWorker, pinnedCheckout, pinnedPack } from "@repo/eliza-harness" import { type Environment, type Manifest, browserNotesCleanup, browserNotesTranscription, browserNotesTranscriptionLimit, bundledPlugins, calendarEdits, characterAdmitted, cloudModel, controlLeaseLimit, controlLeasePath, controlStopLimit, controlStopPath, corePlugins, entryCarried, gmailChanges, googleAdmitted, - hostedPlugins, inputAdmitted, localEmbeddings, localLlmActivatePath, localLlmControlLimit, localLlmDeletePath, localLlmModePath, memoryRecordsLimit, memoryRecordsPath, memorySafariActionLimit, memorySafariActionPath, nativeControlInterrupt, nativeControlInterruptLimit, nativeControlObserve, nativeControlObserveLimit, nativeControlReceipt, nativeControlReceiptLimit, nativeDigestAck, nativeDigestAckLimit, nativeDigestQueries, nativeDigestScope, nativeNotesCleanup, nativeNotesCleanupLimit, nativeRoutes, nativeRoutesAdmitted, nativeSpeechRoutes, notesTrashDays, packAdmitted, packEntry, packedFor, packedPlugins, pageQueries, persistMemory, personalDetailSwap, + hostedPlugins, inputAdmitted, localEmbeddings, localLlmActivatePath, localLlmControlLimit, localLlmDeletePath, localLlmModePath, nativeControlInterrupt, nativeControlInterruptLimit, nativeControlObserve, nativeControlObserveLimit, nativeControlReceipt, nativeControlReceiptLimit, nativeDigestAck, nativeDigestAckLimit, nativeDigestQueries, nativeDigestScope, nativeNotesCleanup, nativeNotesCleanupLimit, nativeRoutes, nativeRoutesAdmitted, nativeSpeechRoutes, notesTrashDays, packAdmitted, packEntry, packedFor, packedPlugins, pageQueries, persistMemory, personalDetailSwap, launchViews, policyAdmitted, privacyAdmitted, productPluginName, proposalsAdmitted, refusedActions, routeListAdmitted, secretSwap, slackBrokerPath, slackRedirectUri, slackRegistrationPath, slackStandaloneRedirectUri, telegramIdentityGiven, telegramPageBodyLimits, viewPlugins, viewsAdmitted, walletGetsKey, walletSettings, } from "../gen/agent.effect.vibe" @@ -405,8 +405,6 @@ function routeBodyLimit(route: RouteLine, native: boolean): number | undefined { if (route.path === controlLeasePath) return controlLeaseLimit if (route.path === controlStopPath) return controlStopLimit if (route.path === localLlmModePath || route.path === localLlmActivatePath || route.path === localLlmDeletePath) return localLlmControlLimit - if (route.path === memoryRecordsPath) return memoryRecordsLimit - if (route.path === memorySafariActionPath) return memorySafariActionLimit return route.path === browserNotesCleanup ? nativeNotesCleanupLimit : telegramPageBodyLimits.find(({ path }) => path === route.path)?.bytes } if (route.path === nativeDigestAck) return nativeDigestAckLimit diff --git a/apps/agent/src/plugins/memory-graph.ts b/apps/agent/src/plugins/memory-graph.ts index 23853e5e61..12e36add7e 100644 --- a/apps/agent/src/plugins/memory-graph.ts +++ b/apps/agent/src/plugins/memory-graph.ts @@ -325,7 +325,7 @@ export function memoryGraphProvider(coordinator: AlphaMemoryGraphCoordinator): A }; } -/** Page-admitted HTTP routes for syncing and querying unified Safari and Photo Graph memory on the resident agent. */ +/** HTTP routes for syncing and querying unified Safari and Photo Graph memory on the resident agent; the page's host route list does not admit them. */ export function memoryGraphRoutes(coordinator: AlphaMemoryGraphCoordinator): readonly AgentRoute[] { return [ { diff --git a/apps/app/src/platform/iosAgentRuntime.ts b/apps/app/src/platform/iosAgentRuntime.ts index 7608076c63..908e230ae5 100644 --- a/apps/app/src/platform/iosAgentRuntime.ts +++ b/apps/app/src/platform/iosAgentRuntime.ts @@ -2956,7 +2956,6 @@ export class IosElizaAgentHost { } if (pathname === "/api/notifications") return { status: 200, data: { notifications: [] } }; if (pathname === "/api/workflow/workflows") return { status: 200, data: { workflows: [] } }; - if (pathname === "/api/alpha/memory/records") return { status: 200, data: { ok: true } }; return { status: 200, data: { ok: true } }; } diff --git a/apps/cloud/src/wrangler.vibe b/apps/cloud/src/wrangler.vibe index 0ed5918108..799ccd2854 100644 --- a/apps/cloud/src/wrangler.vibe +++ b/apps/cloud/src/wrangler.vibe @@ -3,7 +3,7 @@ // spec/cloud/rollout.md, "The rendered Alpha Cloud profile includes Maps with every valid plan" import type { CloudEnvironment, CloudProfile, EnvironmentProfile } from "@elizaos/cloud" import type { Registration } from "../gen/cloud.effect.vibe" -import { includesMapsFunding, renderAccepted, renderProblems, type ResourceId } from "../gen/cloud__rollout.effect.vibe" +import { renderAccepted, renderedMapsFunding, renderProblems, type ResourceId } from "../gen/cloud__rollout.effect.vibe" import { entryOf } from "./alpha.vibe" import { sha256Hex } from "./digest.ts" @@ -108,9 +108,12 @@ export interface RenderedEnvironment { readonly profile: string } +/** One environment's profile as it is bundled: its Maps provider, when configured, with the funding the spec renders for it. */ function includeMaps(settings: EnvironmentProfile): EnvironmentProfile { const maps = settings.maps - if (maps === undefined || maps.provider === "none" || includesMapsFunding(maps.funding ?? "")) return settings + if (maps === undefined || maps.provider === "none") return settings + const funding = renderedMapsFunding(true, maps.funding === "included" ? "Included" : "Unfunded") + if (funding === "Unfunded") return settings return { ...settings, maps: { ...maps, funding: "included" } } } diff --git a/spec/agent/index.md b/spec/agent/index.md index bddd9d69b1..87e5e253cb 100644 --- a/spec/agent/index.md +++ b/spec/agent/index.md @@ -424,7 +424,12 @@ page with that section of the account showing, so asking for the billing settings shows the plan and not the sign-in. Photos' two tabs follow Photos as views of their own, by a path inside Photos: Photo library and Photo albums, which the phone opens as Photos on that tab, so asking for the albums -shows the album list and not the tab Photos was last left on. The model chooses which view a request means, by one of +shows the album list and not the tab Photos was last left on. Some of these +views carry a few other names too, at most four, as a launch allows: Alarms +and Timers their singulars, the New Reminder form the reminder form and add +reminder, the photo library the photo grid and all photos, the album list +albums, Files' Trash trash, and each section of the account the words an +owner calls it by, such as the plan for Billing. The model chooses which view a request means, by one of these names; nothing matches the owner's words. Whether a prepared view opens is the phone's: an app the phone does not admit, or any app over a sensitive screen, stays closed (`spec/app/assistant/index.md`, "Story: Let @@ -673,9 +678,6 @@ pure val pageRoutesTasksWallet: List[Route] = List( { method: Post, path: "/api/alpha/local-llm/mode", stream: false }, { method: Post, path: "/api/alpha/local-llm/activate", stream: false }, { method: Post, path: "/api/alpha/local-llm/delete", stream: false }, - { method: Get, path: "/api/alpha/memory/search", stream: false }, - { method: Post, path: "/api/alpha/memory/records", stream: false }, - { method: Post, path: "/api/alpha/memory/safari-action", stream: false }, ) pure val controlLeasePath = "/api/alpha/control/lease" pure val controlStopPath = "/api/alpha/control/stop" @@ -685,10 +687,6 @@ pure val localLlmModePath = "/api/alpha/local-llm/mode" pure val localLlmActivatePath = "/api/alpha/local-llm/activate" pure val localLlmDeletePath = "/api/alpha/local-llm/delete" pure val localLlmControlLimit = 1024 -pure val memoryRecordsPath = "/api/alpha/memory/records" -pure val memoryRecordsLimit = 65536 -pure val memorySafariActionPath = "/api/alpha/memory/safari-action" -pure val memorySafariActionLimit = 4096 pure val pageRoutesMessaging: List[Route] = List( { method: Get, path: "/api/slack/accounts", stream: false }, { method: Post, path: "/api/slack/oauth/start", stream: false }, diff --git a/spec/agent/index.proof.dfy b/spec/agent/index.proof.dfy index 89cbdcec14..ae3b298f0a 100644 --- a/spec/agent/index.proof.dfy +++ b/spec/agent/index.proof.dfy @@ -198,13 +198,13 @@ lemma TelegramNotNativeA(i: int) } lemma TelegramNotNativeB(i: int) - requires 12 <= i < 22 + requires 12 <= i < 23 ensures pageRoutesTelegram[i] !in nativeSpeechRoutes ensures pageRoutesTelegram[i] !in nativeControlRoutes { if i == 12 { NotNativeSpeechOrControl(pageRoutesTelegram[12]); } else if i == 13 { NotNativeSpeechOrControl(pageRoutesTelegram[13]); } else if i == 14 { NotNativeSpeechOrControl(pageRoutesTelegram[14]); } else if i == 15 { NotNativeSpeechOrControl(pageRoutesTelegram[15]); } else if i == 16 { NotNativeSpeechOrControl(pageRoutesTelegram[16]); } - else if i == 17 { NotNativeSpeechOrControl(pageRoutesTelegram[17]); } else if i == 18 { NotNativeSpeechOrControl(pageRoutesTelegram[18]); } else if i == 19 { NotNativeSpeechOrControl(pageRoutesTelegram[19]); } else if i == 20 { NotNativeSpeechOrControl(pageRoutesTelegram[20]); } - else { NotNativeSpeechOrControl(pageRoutesTelegram[21]); } + else if i == 17 { NotNativeSpeechOrControl(pageRoutesTelegram[17]); } else if i == 18 { NotNativeSpeechOrControl(pageRoutesTelegram[18]); } else if i == 19 { NotNativeSpeechOrControl(pageRoutesTelegram[19]); } else if i == 20 { NotNativeSpeechOrControl(pageRoutesTelegram[20]); } else if i == 21 { NotNativeSpeechOrControl(pageRoutesTelegram[21]); } + else { NotNativeSpeechOrControl(pageRoutesTelegram[22]); } } lemma TelegramNotNative(route: Route) @@ -212,8 +212,8 @@ lemma TelegramNotNative(route: Route) ensures route !in nativeSpeechRoutes ensures route !in nativeControlRoutes { - assert |pageRoutesTelegram| == 22; - var i :| 0 <= i < 22 && pageRoutesTelegram[i] == route; + assert |pageRoutesTelegram| == 23; + var i :| 0 <= i < 23 && pageRoutesTelegram[i] == route; if i < 12 { TelegramNotNativeA(i); } else { TelegramNotNativeB(i); } } diff --git a/spec/app/assistant/context.md b/spec/app/assistant/context.md index f3e4696792..946a5978b5 100644 --- a/spec/app/assistant/context.md +++ b/spec/app/assistant/context.md @@ -423,9 +423,9 @@ pure def lawAPageBrowserWithheldIsNeverSent(peer: Peer): bool = not(sendsPage(tr ### A turn describes the view in front by its labeled controls and visible text, never a sensitive or withheld view, a secret field, the assistant's own chat or a review card -Every told turn, typed or spoken, from Home and from every view, carries a -description of what the view in front draws as the turn is sent, beside the -observation and bound to its view and revision +Every told turn, typed or spoken, from Home and from every view, carries to +a peer that takes the screen a description of what the view in front draws +as the turn is sent, beside the observation and bound to its view and revision (eliza's turn context, `spec/agent/conversation/turnContext.md` there, has its form and bounds). Alpha reads it from the view's own accessibility tree, with no code of the view's own: each control a person could press or fill, by its role diff --git a/spec/app/assistant/dock.md b/spec/app/assistant/dock.md index c024989633..9c2de5071b 100644 --- a/spec/app/assistant/dock.md +++ b/spec/app/assistant/dock.md @@ -66,12 +66,14 @@ being typed in, it only leaves the field, which rests the bar once. ### A released drag lands on the bar, a sheet at a height, or the full screen -Near the top it fills the screen and near the floor it goes to the bar; -the zones are 120 points deep, or a third of the travel when that is less. -An open sheet flicked up fills the screen and flicked down goes to the bar. -Pulled down from the bar or typing, it stays on the bar detent and tucks to -the compact pill. Between the zones a sheet keeps the height it was left at; -height 0 is its fitted height. +Near the top it fills the screen, and an open sheet let go near the floor +goes to the bar; the zones are 120 points deep, or a third of the travel +when that is less. An open sheet flicked up fills the screen and flicked +down goes to the bar. Raised from the bar or typing, it opens at the +sheet's fitted height when flicked or let go near the floor. Pulled down +from the bar or typing, it stays on the bar detent and tucks to the compact +pill. Between the zones a sheet keeps the height it was left at; height 0 +is its fitted height. ```quint import shell as S from "../shell" diff --git a/spec/app/assistant/index.md b/spec/app/assistant/index.md index 02e06e9bc6..7ef9a9752e 100644 --- a/spec/app/assistant/index.md +++ b/spec/app/assistant/index.md @@ -64,7 +64,8 @@ pure def ended(t: Turn): bool = A::ended(t.send) and t.reply != Streaming ### The conversation knows whether the agent can be reached and takes the screen, what the screen is, how a stopped reply was checked, and the view opened for a reply -The check of a stopped reply is under way while its one read is loading. +The check of a stopped reply is under way while the agent is asked to abort +and while its one read is loading. ```quint type Showing = Home | App({ view: S::View }) @@ -138,7 +139,7 @@ pure def lost(t: Turn): Turn = ### What the simulator tries Tickets as far as twenty events can count them, the first holds and card -prompts, two days, and Home, Calendar and Notes. Files continuations try +prompts, two days, and Home, Calendar, Notes and Contacts. Files continuations try empty and occupied trails, low and open panels, and recent route numbers. ```quint @@ -909,7 +910,8 @@ only on an Alpha image, and Contacts only where that image admits it image, and Contacts only where that image admits it"). So each turn that carries the view claim also names, by the id the agent declares each view by, Home and every app this shell has now, with Clock's four tabs beside -Clock and the New Reminder form beside Reminders (`uiViews`, `spec/agent/views.md` in eliza). The agent refuses any other view before it replies, so on a +Clock, the New Reminder form beside Reminders, and Files' places, Photos' +tabs and the account's sections beside Files, Photos and Settings (`uiViews`, `spec/agent/views.md` in eliza). The agent refuses any other view before it replies, so on a browser preview "open my messages" is answered that Messages can't open here, instead of a promise that it is opening. Which view a request means stays the model's choice; nothing matches the owner's words. diff --git a/spec/app/browser/safariCopilot.md b/spec/app/browser/safariCopilot.md index 299ce70518..51d18f61f2 100644 --- a/spec/app/browser/safariCopilot.md +++ b/spec/app/browser/safariCopilot.md @@ -69,6 +69,9 @@ pure val weight_completeAction = 15 ### The host binds availability, and losing the extension clears active tab, analysis, and pending actions +Only the phone reports whether the extension is present. Losing it also +drops an action already approved, so its late outcome is refused. + ```quint pure def canBind(s: SafariCopilot, present: bool, by: Actor): bool = by == Phone and s.available != present @@ -88,6 +91,9 @@ pure def bind(s: SafariCopilot, present: bool, by: Actor): SafariCopilot = ### Only the owner changes passive capture and overlay pill policy +The owner changes it only while the extension is available, and the new +policy is saved. + ```quint pure def canSetPolicy(s: SafariCopilot, passiveCapture: bool, overlayPill: bool, by: Actor): bool = by == Owner and s.available and (s.passiveCapture != passiveCapture or s.overlayPill != overlayPill) @@ -101,6 +107,8 @@ pure def setPolicy(s: SafariCopilot, passiveCapture: bool, overlayPill: bool, by ### Updating the active tab clears pending or approved actions when the tab turns sensitive or disappears +It stops an analysis under way too, so its late reply is ignored. + ```quint pure def canSyncTab(s: SafariCopilot, hasTab: bool, sensitive: bool, by: Actor): bool = by == Phone and s.available and (s.hasActiveTab != hasTab or s.sensitiveTab != sensitive) diff --git a/spec/app/calendar/actions.md b/spec/app/calendar/actions.md index a7c6cc46cb..9b39464891 100644 --- a/spec/app/calendar/actions.md +++ b/spec/app/calendar/actions.md @@ -1,13 +1,15 @@ # The agent's Calendar actions on the phone -The agent can ask to read the next event, and read, change or delete the -event the owner has open in [Calendar](./index.md); a new event it proposes -only opens Calendar's own new-event form, which the owner saves -([editor](./editor.md)). None of these runs directly: each needs the owner's +The agent can ask to create an event in the phone's own calendar, read the +next event, and read, change or delete the event the owner has open in +[Calendar](./index.md). None of these runs directly: each needs the owner's card in the conversation, which the approvals area shows, then the phone's -own review in Android, which the owner may cancel. What the phone offers -the agent and what it tells it back are the [sharing](./sharing.md) rules; -this is Calendar's part of each action. +own review in Android, which the owner may cancel. A new event the agent +only proposes, or a change to an event the owner pointed at, is not one of +these actions: it opens Calendar's own form, which the owner saves +([editor](./editor.md)). What the phone offers the agent and what it tells +it back are the [sharing](./sharing.md) rules; this is Calendar's part of +each action. ## Story: Let the agent change my phone's calendar only through my reviews diff --git a/spec/app/calendar/sharing.md b/spec/app/calendar/sharing.md index 7d76c5a150..90d3b6ba88 100644 --- a/spec/app/calendar/sharing.md +++ b/spec/app/calendar/sharing.md @@ -210,8 +210,8 @@ change (a new start, day, length, title, place or notes). It runs with no card. Calendar reads the day given, or today, again from every source it may read, and looks among the events it shows: on the day given, else on the first day from today that has a match; starting at the time given; -titled exactly as given where any is, else holding those words. Exactly one match that Calendar's own form -may change opens in that form, in front beside Ask Alpha, holding the +titled exactly as given where any is, else holding those words. Exactly one match, where Calendar's own +form may change it, opens in that form, in front beside Ask Alpha, holding the change as its first edit: the event keeps its day, its length and every other field unless the owner changed it, and an all-day event moves only to another day. Nothing is saved until the owner saves the form. The agent @@ -229,7 +229,7 @@ type EditForm = FormOpened | NoEventMatches | SeveralEventsMatch | EventReadOnly pure def editForm(access: bool, draftKept: bool, matches: int, editable: bool): EditForm = if (not(access)) CalendarNeedsAccess else if (draftKept) DraftInTheWay - else if (matches == 0) NoEventMatches + else if (matches < 1) NoEventMatches else if (matches > 1) SeveralEventsMatch else if (not(editable)) EventReadOnly else FormOpened diff --git a/spec/app/camera/index.md b/spec/app/camera/index.md index 4d221b78bd..78cca2edfa 100644 --- a/spec/app/camera/index.md +++ b/spec/app/camera/index.md @@ -33,11 +33,12 @@ import agent as G from "./agent" ### What the viewfinder holds -Photo or Video mode, the back or front lens, the flash, and zoom in tenths: -from half to ten times on the back lens, one time on the front, which has no -flash. A preview is off, starting, ready or failed. Ask Alpha covering Camera -keeps the preview for ten seconds. A banner tells the owner of a photo not -taken or a video not saved. When Camera fails the agent's request it names +Photo or Video mode, the back or front lens, the flash off, auto or on, a +browser camera's light, and zoom in tenths: from half to ten times on the back +lens, one time on the front, which has no flash. A preview is off, starting, +ready or failed. Ask Alpha covering Camera keeps the preview for ten seconds. +A banner tells the owner of a photo not taken, a video not saved or a light +the camera would not change. When Camera fails the agent's request it names the cause. ```quint @@ -1004,7 +1005,7 @@ pure def alwaysTheRequestWaitsOnTheCamera(s: Camera): bool = ### A request fails only for a cause Camera names: left, no access, a failed preview, a busy camera or a protected screen -The phone reports Busy when it cannot fire the shutter on the reviewed viewfinder. +Camera answers Busy when it cannot fire the shutter on the reviewed viewfinder. ```quint pure def stepTheAgentFailsOnlyForCause(before: Camera, via: str, after: Camera): bool = diff --git a/spec/app/clock/stopwatch.md b/spec/app/clock/stopwatch.md index f1edd44ed9..ff3771843a 100644 --- a/spec/app/clock/stopwatch.md +++ b/spec/app/clock/stopwatch.md @@ -107,8 +107,9 @@ The phone takes the agent's stopwatch whole, as it takes its timers, and only when that stopwatch keeps the invariants below: its times are not negative, a reset stopwatch is empty, and its laps are numbered in order with splits that add up. It takes it only when the agent's stamp -supersedes the one the phone's stopwatch carries. The phone keeps that -stamp with the stopwatch across restarts, gives it a new revision only +supersedes the one the phone's stopwatch carries; that stamp is the +shell's, kept beside the stopwatch these rules hold, not part of it. The +phone keeps that stamp across restarts, gives it a new revision only when the owner changed the stopwatch since it was last sent or taken, and a stopwatch never sent or taken carries revision 0, so the agent's first stopwatch command is taken. diff --git a/spec/app/contacts/agent.md b/spec/app/contacts/agent.md index 0f48f2e12d..3dd838c83d 100644 --- a/spec/app/contacts/agent.md +++ b/spec/app/contacts/agent.md @@ -361,6 +361,9 @@ pure def lawOnlyTheTextRowApproves(row: ReviewRow): bool = rowApproves(row) iff ### Only a text to a number the owner wrote names the number at once +A call to a number the owner wrote names it at once too; a call or a text +to a contact names a number only once the owner picks it. + ```quint pure def alwaysAnAddressedRequestReachesANumber(r: Request): bool = r.addressed implies reachesANumber(r.ask) pure def sometimesAnAddressedText(r: Request): bool = r.stage == Shown and r.ask == Text and r.addressed @@ -432,8 +435,8 @@ request ended: saved or deleted when done; not found; unchanged, where the contact already held those details; cancelled, where the owner declined or left the review unanswered for two minutes, after which it is withdrawn; failed where the phone refused the write; and unavailable where the search -failed. An unsure ending answers nothing, so the action stays unsettled in -the agent's history and is never repeated. +failed. The answer to an unsure ending carries no outcome, so the action +stays unsettled in the agent's history and is never repeated. ```quint pure def canActed(r: Request, id: int, by: Actor): bool = by == Device and r.stage == Acting and A::canConclude(r.attempt, id) diff --git a/spec/app/home/index.md b/spec/app/home/index.md index 50193ebe67..c38c420204 100644 --- a/spec/app/home/index.md +++ b/spec/app/home/index.md @@ -116,6 +116,9 @@ pure def alwaysNothingIsToldBeforeTheStart(h: Home): bool = h.tiles.load.status ### Once the saved tiles are read, the phone's apps are read if Home holds an installed app, and a record that could not be read is told +The apps are read this way only on the phone, and only if they have not +been asked for yet. + ```quint pure def thenReadApps(out: List[Effect], h: Home, quiet: bool): Moved = val installed = P::askApps(h.installed, quiet) @@ -280,8 +283,11 @@ pure def stepReadingsAreTicketed(before: Home, via: str, after: Home, out: List[ ## Story: Find an installed app in Apps -> As the owner, I want to open Apps on my phone, see the current launcher -> catalog, and try again if it could not be read. +> As the owner, I want Home to offer no Apps tile or Apps drawer for now, +> and wherever the shell does hold the drawer open, I want it to list +> Alpha's apps that are not on Home and open one as its tile would, to +> let me add an app to Home or see its App info, and to try again if the +> phone's apps could not be read. ### The Apps tile and Apps drawer are suppressed on Home @@ -440,7 +446,8 @@ pure def stepNothingOpensWhileEditing(before: Home, via: str, after: Home, out: The reason is Android's: the app has gone, is turned off, its profile is locked, Alpha is not in front, or Android was unable. An opening that -succeeded is not announced. +succeeded is not announced. A refused shade is told the same way, and +reads no apps. ```quint pure def canAnswered(h: Home, ticket: int): bool = N::canAnswered(h.handoff, ticket) @@ -671,7 +678,7 @@ pure def showHidden(h: Home, shell: S::Shell, beside: bool, by: Actor): Home = { Back closes the Add sheet first. With Ask Alpha open and no Add sheet, Back lowers Ask Alpha and leaves Home in edit mode. On bare Home, Back -then ends editing. Home ends editing. +then ends editing. Done ends editing and closes Add to Home with it. ```quint pure def canBackOut(h: Home): bool = h.adding or h.editing diff --git a/spec/app/maps/index.md b/spec/app/maps/index.md index 911c857a27..bcc31045f8 100644 --- a/spec/app/maps/index.md +++ b/spec/app/maps/index.md @@ -1806,7 +1806,7 @@ while its turn runs, over eliza's Maps relay: the shell brings Maps forward, waits up to fifteen seconds for a provider to work, and answers each request with where the screen stands or why it could not. A route the phone cannot propose, with location not allowed, shows the place on its card instead and -is answered as waiting for a start. +is answered as waiting for the phone's location. ```quint pure def canProposeRoute(m: Maps, place: int, origin: N::Origin, lat: int, lng: int): bool = diff --git a/spec/app/messages/index.md b/spec/app/messages/index.md index 0ea7c18d32..463e361998 100644 --- a/spec/app/messages/index.md +++ b/spec/app/messages/index.md @@ -208,8 +208,8 @@ pure def retryThreads(s: Messages): Moved = askThreads(false, s) The bar searches the list as it is typed, but what is sent from it goes to Alpha as a question, not a search: sending it drops the search at once, so -the list reads every conversation again and no chip is left naming the -question. +the list is read again at once without it, under the filter chip it had, +and no chip is left naming the question. ```quint pure def canSearchAsked(s: Messages): bool = canSearch(s, false) and s.sought diff --git a/spec/app/photos/memoryGraph.md b/spec/app/photos/memoryGraph.md index 7b86cdc21e..d0fdc0598c 100644 --- a/spec/app/photos/memoryGraph.md +++ b/spec/app/photos/memoryGraph.md @@ -70,6 +70,8 @@ pure val weight_answerMemory = 15 ### Availability is bound by the host, and losing the plugin cancels pending scan and question state +Losing the plugin also leaves no geofence counted as armed. + ```quint pure def canBind(s: PhotoGraph, present: bool): bool = s.available != present diff --git a/spec/app/settings/preferences.md b/spec/app/settings/preferences.md index ad3ed8a1b2..21fc12df63 100644 --- a/spec/app/settings/preferences.md +++ b/spec/app/settings/preferences.md @@ -194,6 +194,11 @@ pure def sometimesNotSaved(s: Preferences): bool = s.notice == NotSaved and s.ke ### Text is 75, 100, 115, 130 or 150 percent, applied by the phone, one change or read at a time +Asked for larger or smaller text, the agent asks for the next of the five +in that direction, and for none past the largest or the smallest; asked +for a percentage, it asks for the nearest of the five, the smaller of two +as near. + ```quint pure val sizes: List[int] = List(75, 100, 115, 130, 150) pure val percentValues = Set(0, 90, 100, 150) @@ -658,6 +663,9 @@ pure def start(s: Preferences, at: int, kept: Theme, keptLegible: bool, readable ### The appearance kept changes only when the phone kept the owner's choice, or when Alpha starts with what it kept +A choice the agent made because the owner asked it to is the owner's +choice here. + ```quint pure def stepTheKeptAppearanceIsTheOwners(before: Preferences, via: str, after: Preferences): bool = after.kept != before.kept implies ((via == "themeKept" and after.kept == before.theme) or via == "start") diff --git a/spec/app/shell/index.md b/spec/app/shell/index.md index 1181494327..cc489e0e0a 100644 --- a/spec/app/shell/index.md +++ b/spec/app/shell/index.md @@ -23,7 +23,8 @@ rises over Home, which stays where the owner left it and takes no input underneath; an app opened from another takes that app's place at once, with nothing of Home between them; going back takes the app away at once. Home shows under a rising app only until the rise is over, whether it ran -to its end or stopped early. +to its end or stopped early. The shell also holds which window Android last +put in front: Home's own, or an app's task. ```quint type View = Phone | Messages | Inbox | Telegram | Slack | Calendar | Clock | Reminders | Browser | Camera | Photos | Maps | Notes | Contacts | Files | Workflows | Wallet | Settings @@ -500,9 +501,9 @@ earlier build left in Recents opens Home instead. ### Android bringing an app's window forward shows that app, with Ask Alpha where it was -The trail goes back to that app where it is on the trail, or holds that -app alone, and the Apps drawer closes. Home's window in front empties the -trail. +The trail goes back to that app where it is last on the trail, or holds +that app alone, and the Apps drawer closes. Home's window in front empties +the trail and closes the drawer too. ```quint type TrailWalk = { seen: List[View], kept: List[View] } @@ -530,6 +531,9 @@ pure def stepAWindowInFrontKeepsAskAlpha(before: Shell, via: str, after: Shell): ### The app drawn is the one whose window is in front +Once Android brings an app's window forward, that app is on top of the +trail and its window is the one in front. + ```quint pure def lawTheAppInFrontIsOnTop(s: Shell, view: View): bool = val shown = appInFront(s, view) diff --git a/spec/app/shell/index.proof.dfy b/spec/app/shell/index.proof.dfy index 08eb8d9a14..7300179786 100644 --- a/spec/app/shell/index.proof.dfy +++ b/spec/app/shell/index.proof.dfy @@ -13,6 +13,7 @@ lemma openView_ensures(s: Shell, view: View) ensures (inv(s) ==> canOpenView(s, view) ==> stepSpokenRouteMarksTheWriter(s, "openView", openView(s, view))) ensures (inv(s) ==> canOpenView(s, view) ==> stepBackClosesOneLayer(s, "openView", openView(s, view))) ensures (inv(s) ==> canOpenView(s, view) ==> stepHomeIsBare(s, "openView", openView(s, view))) + ensures (inv(s) ==> canOpenView(s, view) ==> stepAWindowInFrontKeepsAskAlpha(s, "openView", openView(s, view))) ensures (inv(s) ==> canOpenView(s, view) ==> stepClosedTextAskKeepsTheAdmittedTicket(s, "openView", openView(s, view))) { if inv(s) && canOpenView(s, view) { @@ -40,6 +41,7 @@ lemma agentOpenView_ensures(s: Shell, view: View) ensures (inv(s) ==> canAgentOpenView(s, view) ==> stepSpokenRouteMarksTheWriter(s, "agentOpenView", agentOpenView(s, view))) ensures (inv(s) ==> canAgentOpenView(s, view) ==> stepBackClosesOneLayer(s, "agentOpenView", agentOpenView(s, view))) ensures (inv(s) ==> canAgentOpenView(s, view) ==> stepHomeIsBare(s, "agentOpenView", agentOpenView(s, view))) + ensures (inv(s) ==> canAgentOpenView(s, view) ==> stepAWindowInFrontKeepsAskAlpha(s, "agentOpenView", agentOpenView(s, view))) ensures (inv(s) ==> canAgentOpenView(s, view) ==> stepClosedTextAskKeepsTheAdmittedTicket(s, "agentOpenView", agentOpenView(s, view))) { if inv(s) && canAgentOpenView(s, view) { @@ -67,6 +69,7 @@ lemma agentShowView_ensures(s: Shell, view: View) ensures (inv(s) ==> canAgentShowView(s, view) ==> stepSpokenRouteMarksTheWriter(s, "agentShowView", agentShowView(s, view))) ensures (inv(s) ==> canAgentShowView(s, view) ==> stepBackClosesOneLayer(s, "agentShowView", agentShowView(s, view))) ensures (inv(s) ==> canAgentShowView(s, view) ==> stepHomeIsBare(s, "agentShowView", agentShowView(s, view))) + ensures (inv(s) ==> canAgentShowView(s, view) ==> stepAWindowInFrontKeepsAskAlpha(s, "agentShowView", agentShowView(s, view))) ensures (inv(s) ==> canAgentShowView(s, view) ==> stepClosedTextAskKeepsTheAdmittedTicket(s, "agentShowView", agentShowView(s, view))) { if inv(s) && canAgentShowView(s, view) { @@ -98,6 +101,7 @@ lemma agentOpenSpoken_ensures(s: Shell, view: View, route: int) ensures (inv(s) ==> canAgentOpenSpoken(s, view, route) ==> stepSpokenRouteMarksTheWriter(s, "agentOpenSpoken", agentOpenSpoken(s, view, route))) ensures (inv(s) ==> canAgentOpenSpoken(s, view, route) ==> stepBackClosesOneLayer(s, "agentOpenSpoken", agentOpenSpoken(s, view, route))) ensures (inv(s) ==> canAgentOpenSpoken(s, view, route) ==> stepHomeIsBare(s, "agentOpenSpoken", agentOpenSpoken(s, view, route))) + ensures (inv(s) ==> canAgentOpenSpoken(s, view, route) ==> stepAWindowInFrontKeepsAskAlpha(s, "agentOpenSpoken", agentOpenSpoken(s, view, route))) ensures (inv(s) ==> canAgentOpenSpoken(s, view, route) ==> stepClosedTextAskKeepsTheAdmittedTicket(s, "agentOpenSpoken", agentOpenSpoken(s, view, route))) { agentOpenView_ensures(s, view); @@ -118,6 +122,7 @@ lemma agentShowSpoken_ensures(s: Shell, view: View, route: int) ensures (inv(s) ==> canAgentShowSpoken(s, view, route) ==> stepSpokenRouteMarksTheWriter(s, "agentShowSpoken", agentShowSpoken(s, view, route))) ensures (inv(s) ==> canAgentShowSpoken(s, view, route) ==> stepBackClosesOneLayer(s, "agentShowSpoken", agentShowSpoken(s, view, route))) ensures (inv(s) ==> canAgentShowSpoken(s, view, route) ==> stepHomeIsBare(s, "agentShowSpoken", agentShowSpoken(s, view, route))) + ensures (inv(s) ==> canAgentShowSpoken(s, view, route) ==> stepAWindowInFrontKeepsAskAlpha(s, "agentShowSpoken", agentShowSpoken(s, view, route))) ensures (inv(s) ==> canAgentShowSpoken(s, view, route) ==> stepClosedTextAskKeepsTheAdmittedTicket(s, "agentShowSpoken", agentShowSpoken(s, view, route))) { agentShowView_ensures(s, view); @@ -138,6 +143,7 @@ lemma goBack_ensures(s: Shell) ensures (inv(s) ==> canGoBack(s) ==> stepSpokenRouteMarksTheWriter(s, "goBack", goBack(s))) ensures (inv(s) ==> canGoBack(s) ==> stepBackClosesOneLayer(s, "goBack", goBack(s))) ensures (inv(s) ==> canGoBack(s) ==> stepHomeIsBare(s, "goBack", goBack(s))) + ensures (inv(s) ==> canGoBack(s) ==> stepAWindowInFrontKeepsAskAlpha(s, "goBack", goBack(s))) ensures (inv(s) ==> canGoBack(s) ==> stepClosedTextAskKeepsTheAdmittedTicket(s, "goBack", goBack(s))) { if inv(s) && canGoBack(s) { @@ -164,6 +170,7 @@ lemma returnCommsView_ensures(s: Shell, previous: View) ensures (inv(s) ==> canReturnCommsView(s, previous) ==> stepSpokenRouteMarksTheWriter(s, "returnCommsView", returnCommsView(s, previous))) ensures (inv(s) ==> canReturnCommsView(s, previous) ==> stepBackClosesOneLayer(s, "returnCommsView", returnCommsView(s, previous))) ensures (inv(s) ==> canReturnCommsView(s, previous) ==> stepHomeIsBare(s, "returnCommsView", returnCommsView(s, previous))) + ensures (inv(s) ==> canReturnCommsView(s, previous) ==> stepAWindowInFrontKeepsAskAlpha(s, "returnCommsView", returnCommsView(s, previous))) ensures (inv(s) ==> canReturnCommsView(s, previous) ==> stepClosedTextAskKeepsTheAdmittedTicket(s, "returnCommsView", returnCommsView(s, previous))) { if inv(s) && canReturnCommsView(s, previous) { @@ -190,6 +197,7 @@ lemma openCommsView_ensures(s: Shell, view: View) ensures (inv(s) ==> canOpenCommsView(s, view) ==> stepSpokenRouteMarksTheWriter(s, "openCommsView", openCommsView(s, view))) ensures (inv(s) ==> canOpenCommsView(s, view) ==> stepBackClosesOneLayer(s, "openCommsView", openCommsView(s, view))) ensures (inv(s) ==> canOpenCommsView(s, view) ==> stepHomeIsBare(s, "openCommsView", openCommsView(s, view))) + ensures (inv(s) ==> canOpenCommsView(s, view) ==> stepAWindowInFrontKeepsAskAlpha(s, "openCommsView", openCommsView(s, view))) ensures (inv(s) ==> canOpenCommsView(s, view) ==> stepClosedTextAskKeepsTheAdmittedTicket(s, "openCommsView", openCommsView(s, view))) { if inv(s) && canOpenCommsView(s, view) { @@ -217,6 +225,7 @@ lemma agentOpenFilesFrom_ensures(s: Shell, source: seq, panel: Detent, rou ensures (inv(s) ==> canAgentOpenFilesFrom(s, source, panel, route, spoken) ==> stepSpokenRouteMarksTheWriter(s, "agentOpenFilesFrom", agentOpenFilesFrom(s, source, panel, route, spoken))) ensures (inv(s) ==> canAgentOpenFilesFrom(s, source, panel, route, spoken) ==> stepBackClosesOneLayer(s, "agentOpenFilesFrom", agentOpenFilesFrom(s, source, panel, route, spoken))) ensures (inv(s) ==> canAgentOpenFilesFrom(s, source, panel, route, spoken) ==> stepHomeIsBare(s, "agentOpenFilesFrom", agentOpenFilesFrom(s, source, panel, route, spoken))) + ensures (inv(s) ==> canAgentOpenFilesFrom(s, source, panel, route, spoken) ==> stepAWindowInFrontKeepsAskAlpha(s, "agentOpenFilesFrom", agentOpenFilesFrom(s, source, panel, route, spoken))) ensures (inv(s) ==> canAgentOpenFilesFrom(s, source, panel, route, spoken) ==> stepClosedTextAskKeepsTheAdmittedTicket(s, "agentOpenFilesFrom", agentOpenFilesFrom(s, source, panel, route, spoken))) { if inv(s) && canAgentOpenFilesFrom(s, source, panel, route, spoken) { @@ -239,6 +248,7 @@ lemma agentShowInside_ensures(s: Shell, view: View) ensures (inv(s) ==> canAgentShowInside(s, view) ==> stepSpokenRouteMarksTheWriter(s, "agentShowInside", agentShowInside(s, view))) ensures (inv(s) ==> canAgentShowInside(s, view) ==> stepBackClosesOneLayer(s, "agentShowInside", agentShowInside(s, view))) ensures (inv(s) ==> canAgentShowInside(s, view) ==> stepHomeIsBare(s, "agentShowInside", agentShowInside(s, view))) + ensures (inv(s) ==> canAgentShowInside(s, view) ==> stepAWindowInFrontKeepsAskAlpha(s, "agentShowInside", agentShowInside(s, view))) ensures (inv(s) ==> canAgentShowInside(s, view) ==> stepClosedTextAskKeepsTheAdmittedTicket(s, "agentShowInside", agentShowInside(s, view))) { if inv(s) && canAgentShowInside(s, view) { @@ -266,7 +276,77 @@ lemma agentShowInsideSpoken_ensures(s: Shell, view: View, route: int) ensures (inv(s) ==> canAgentShowInsideSpoken(s, view, route) ==> stepSpokenRouteMarksTheWriter(s, "agentShowInsideSpoken", agentShowInsideSpoken(s, view, route))) ensures (inv(s) ==> canAgentShowInsideSpoken(s, view, route) ==> stepBackClosesOneLayer(s, "agentShowInsideSpoken", agentShowInsideSpoken(s, view, route))) ensures (inv(s) ==> canAgentShowInsideSpoken(s, view, route) ==> stepHomeIsBare(s, "agentShowInsideSpoken", agentShowInsideSpoken(s, view, route))) + ensures (inv(s) ==> canAgentShowInsideSpoken(s, view, route) ==> stepAWindowInFrontKeepsAskAlpha(s, "agentShowInsideSpoken", agentShowInsideSpoken(s, view, route))) ensures (inv(s) ==> canAgentShowInsideSpoken(s, view, route) ==> stepClosedTextAskKeepsTheAdmittedTicket(s, "agentShowInsideSpoken", agentShowInsideSpoken(s, view, route))) { agentShowInside_ensures(s, view); } + +lemma appInFront_ensures(s: Shell, view: View) + ensures (inv(s) ==> canAppInFront(s, view) ==> alwaysHomeDrawsAskAlpha(appInFront(s, view))) + ensures (inv(s) ==> canAppInFront(s, view) ==> alwaysTrailIsBounded(appInFront(s, view))) + ensures (inv(s) ==> canAppInFront(s, view) ==> alwaysTrailIsAdmitted(appInFront(s, view))) + ensures (inv(s) ==> canAppInFront(s, view) ==> alwaysTextAskIsFull(appInFront(s, view))) + ensures (inv(s) ==> canAppInFront(s, view) ==> stepRouteHasItsOwnNumber(s, appInFront(s, view))) + ensures (inv(s) ==> canAppInFront(s, view) ==> stepACommsReturnPreservesTheSheet(s, "appInFront", appInFront(s, view))) + ensures (inv(s) ==> canAppInFront(s, view) ==> stepACommsOpeningPreservesTheSheet(s, "appInFront", appInFront(s, view))) + ensures (inv(s) ==> canAppInFront(s, view) ==> stepAgentNavigationKeepsAssistant(s, "appInFront", appInFront(s, view))) + ensures (inv(s) ==> canAppInFront(s, view) ==> stepAgentNavigationLeavesItsViewInSight(s, "appInFront", appInFront(s, view))) + ensures (inv(s) ==> canAppInFront(s, view) ==> stepAPageInsideAViewKeepsASheet(s, "appInFront", appInFront(s, view))) + ensures (inv(s) ==> canAppInFront(s, view) ==> stepAnAgentsPageLowersAskAlpha(s, "appInFront", appInFront(s, view))) + ensures (inv(s) ==> canAppInFront(s, view) ==> stepSpokenRouteMarksTheWriter(s, "appInFront", appInFront(s, view))) + ensures (inv(s) ==> canAppInFront(s, view) ==> stepBackClosesOneLayer(s, "appInFront", appInFront(s, view))) + ensures (inv(s) ==> canAppInFront(s, view) ==> stepHomeIsBare(s, "appInFront", appInFront(s, view))) + ensures (inv(s) ==> canAppInFront(s, view) ==> stepAWindowInFrontKeepsAskAlpha(s, "appInFront", appInFront(s, view))) + ensures (inv(s) ==> canAppInFront(s, view) ==> stepClosedTextAskKeepsTheAdmittedTicket(s, "appInFront", appInFront(s, view))) +{ + if inv(s) && canAppInFront(s, view) { + var after := appInFront(s, view); + KeptToFacts(s.trail, view); + forall v | v in after.trail ensures available(after, v) { + assert v in s.trail || v == view; + assert available(after, v) == available(s, v); + } + } +} + +lemma lawTheAppInFrontIsOnTop_ensures(s: Shell, view: View) + ensures (lawTheAppInFrontIsOnTop(s, view) == true) +{ + KeptToFacts(s.trail, view); +} + +lemma WalkKeepsAPrefixEndingAtTheView(w0: TrailWalk, xs: seq, view: View) + requires |w0.kept| <= |w0.seen| && w0.kept == w0.seen[..|w0.kept|] + requires |w0.kept| == 0 || w0.kept[|w0.kept| - 1] == view + ensures Std.Collections.Seq.FoldLeft((walk: TrailWalk, at: View) => walkTo(walk, at, view), w0, xs).seen == w0.seen + xs + ensures |Std.Collections.Seq.FoldLeft((walk: TrailWalk, at: View) => walkTo(walk, at, view), w0, xs).kept| <= |w0.seen + xs| + ensures Std.Collections.Seq.FoldLeft((walk: TrailWalk, at: View) => walkTo(walk, at, view), w0, xs).kept == (w0.seen + xs)[..|Std.Collections.Seq.FoldLeft((walk: TrailWalk, at: View) => walkTo(walk, at, view), w0, xs).kept|] + ensures |Std.Collections.Seq.FoldLeft((walk: TrailWalk, at: View) => walkTo(walk, at, view), w0, xs).kept| == 0 || Std.Collections.Seq.FoldLeft((walk: TrailWalk, at: View) => walkTo(walk, at, view), w0, xs).kept[|Std.Collections.Seq.FoldLeft((walk: TrailWalk, at: View) => walkTo(walk, at, view), w0, xs).kept| - 1] == view + decreases |xs| +{ + if |xs| > 0 { + var w1 := walkTo(w0, xs[0], view); + assert w1.seen == w0.seen + [xs[0]]; + assert w1.seen[..|w0.seen|] == w0.seen; + assert w1.kept == w1.seen[..|w1.kept|]; + WalkKeepsAPrefixEndingAtTheView(w1, xs[1..], view); + assert w1.seen + xs[1..] == w0.seen + xs; + } +} + +lemma KeptToFacts(trail: seq, view: View) + ensures |keptTo(trail, view)| <= |trail| || keptTo(trail, view) == [view] + ensures forall v :: v in keptTo(trail, view) ==> v in trail || v == view + ensures |keptTo(trail, view)| > 0 && keptTo(trail, view)[|keptTo(trail, view)| - 1] == view +{ + WalkKeepsAPrefixEndingAtTheView(trailUnwalked, trail, view); + var kept := keptTo(trail, view); + if kept != [view] { + assert kept == trail[..|kept|]; + forall v | v in kept ensures v in trail { + var i :| 0 <= i < |kept| && kept[i] == v; + assert trail[i] == v; + } + } +} diff --git a/spec/app/update/index.md b/spec/app/update/index.md index 6303bc2daa..b6e479fa61 100644 --- a/spec/app/update/index.md +++ b/spec/app/update/index.md @@ -215,6 +215,8 @@ pure def stepTheInstalledVersionOnlyAdvances(before: Updates, via: str, after: U ### The saved offer is always the launcher signed by this phone's root, or waits for the phone's first report after a restart +It is always a well-formed release. + ```quint pure def alwaysTheOfferIsThisPhones(s: Updates): bool = saved(s.offer) implies @@ -239,8 +241,8 @@ pure def sometimesAnOfferApplies(s: Updates): bool = applies(s) The installed version, the signing root, the permission and the activity are read again, after a reboot too, when Android may be starting once more and the installed Alpha may be another. Until the phone has reported, no -offer applies. A check under way is taken as failed, so -its late answer is refused; an offer kept from before waits for a check +offer applies. A check under way is closed as failed, so +its late answer is refused, though it adds no failed check; an offer kept from before waits for a check that succeeds before an automatic update. A state kept before Alpha counted the failed checks is read with one failed check if its last check failed, and with none otherwise. @@ -641,7 +643,8 @@ pure def stepARefusalForThePermissionOffersAllow(before: Updates, via: str, afte ### An automatic update Android put off is tried again after a minute, then two, four and eight, and then every fifteen Android puts one off while it is still starting, while its permission is -missing, or while the phone is busy; trying again at once would only be put +missing, where it cannot install Alpha's updates itself, or while the phone +is busy; trying again at once would only be put off again. ```quint @@ -822,6 +825,9 @@ pure def installLabel(s: Updates): str = if (downloading(s)) "Downloading update ### Check for updates says when it is checking +Only a check asked for in Settings changes its label; one Alpha started on +its own does not. + ```quint pure def checking(s: Updates): bool = s.check.status == R::Loading and s.asked diff --git a/spec/app/workflows/list.md b/spec/app/workflows/list.md index 07204027d9..8349ee699e 100644 --- a/spec/app/workflows/list.md +++ b/spec/app/workflows/list.md @@ -48,11 +48,16 @@ pure val noDigestNotice: DigestNotice = { runId: "", workflowId: "", workflowVer ### The list is read from the agent for the owner signed in, one reading at a time +The list is read only with an owner signed in, and never while a reading +is under way. Only the newest reading's answer is taken; one that fails +keeps the count shown before, and a list is complete only when a reading +succeeds with nothing missing. + A reply of Ask Alpha whose workflow action created, changed or ran a workflow, a scheduled prompt or a scheduled task reads the list again -while it is idle on its rows, so what the agent saved from chat shows here -and on Home's card without leaving and returning; a reply that only read -or was refused reads nothing. +while it is idle on its rows or a row's detail, so what the agent saved +from chat shows here and on Home's card without leaving and returning; a +reply that only read or was refused reads nothing. ```quint pure def canReadList(l: Listing): bool = l.list.status != R::Loading and l.owner >= 1 diff --git a/spec/cloud/rollout.md b/spec/cloud/rollout.md index dde1018b3b..f0a8ea0612 100644 --- a/spec/cloud/rollout.md +++ b/spec/cloud/rollout.md @@ -188,14 +188,22 @@ pure def renderAccepted(problems: List[RenderProblem], namesElizaCloud: bool): b ### The rendered Alpha Cloud profile includes Maps with every valid plan -Both hosted environments use Eliza's included Maps funding for a configured -provider. Alpha Cloud pays the provider costs for Maps on the free plan and -on paid plans. Maps use draws no account credits or allowance. The renderer -sets this policy before it bundles and pins the profile, including for -operator profiles saved before the policy was added. +Before it bundles and pins the profile, the renderer gives each hosted +environment's Maps provider Eliza's included funding: a configured provider +renders with its funding included, whatever funding the operator's saved +profile holds, including a profile saved before this policy; an environment +with no Maps provider renders with no Maps funding. What included funding +means is Eliza's: Alpha Cloud pays the provider costs for Maps on the free +plan and on paid plans, and Maps use draws no account credits or allowance. ```quint -pure def includesMapsFunding(funding: str): bool = funding == "included" +type MapsFunding = Unfunded | Included + +pure def renderedMapsFunding(providerConfigured: bool, saved: MapsFunding): MapsFunding = + if (providerConfigured) Included else Unfunded + +pure def lawConfiguredMapsAreIncluded(providerConfigured: bool, saved: MapsFunding): bool = + (renderedMapsFunding(providerConfigured, saved) == Included) iff providerConfigured ``` ## Story: Serve one reviewed profile from the API Worker diff --git a/spec/release/index.md b/spec/release/index.md index ac0a1c9b43..3176dd8244 100644 --- a/spec/release/index.md +++ b/spec/release/index.md @@ -413,7 +413,10 @@ pure def lawOverlongNotesAreRefused(name: int, notes: int): bool = notes > maxNo ### The channel is healthy only while its manifest names a launcher of Alpha's one key, above the retired channel and the last recorded release, at an address it keeps, served with exactly its size and digest -`pnpm release status` reads the channel anonymously, as a phone does. +`pnpm release status` reads the channel anonymously, as a phone does. A +manifest that still names the last recorded release itself is healthy; one +naming the retired channel's version 75 or below, or a release older than the +last recorded one, is not. ```quint type Served = { launcher: bool, signer: bool, version: int, recorded: int, kept: bool, exact: bool } From 2aed4581d198945ce3eb467764d5556af30b8ae0 Mon Sep 17 00:00:00 2001 From: lalalune <18633264+lalalune@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:40:41 -0500 Subject: [PATCH 002/193] Reconcile model and fixture discrepancies before acceptance --- apps/app/src/update/updates.vibe | 9 +++++---- apps/app/test/image.test.ts | 3 ++- apps/app/test/screen-control.test.tsx | 4 ++-- spec/agent/index.md | 5 +++-- spec/app/assistant/index.md | 4 +++- spec/app/update/index.md | 16 +++++++++------- spec/release/index.md | 4 ++-- 7 files changed, 26 insertions(+), 19 deletions(-) diff --git a/apps/app/src/update/updates.vibe b/apps/app/src/update/updates.vibe index 5b22aefe1b..92f1a214be 100644 --- a/apps/app/src/update/updates.vibe +++ b/apps/app/src/update/updates.vibe @@ -63,6 +63,8 @@ const whole = (value: number) => (Number.isSafeInteger(value) && value > 0 ? val effect function releaseOf(row: Row): Release!!UpdateNames { const named = try UpdateNames const { https, credentials } = address(row.apkUrl) + const versionName = row.versionName !== undefined && isPlainName(row.versionName) ? row.versionName : "" + const releaseNotes = row.notes ?? "" return { variant: row.variant === "launcher" ? "Launcher" : "OtherVariant", signer: hex64.test(row.signerSha256) ? try named.number(row.signerSha256) : 0, @@ -70,10 +72,9 @@ effect function releaseOf(row: Row): Release!!UpdateNames { digest: hex64.test(row.sha256) ? try named.number(row.sha256) : 0, bytes: whole(row.sizeBytes), https, credentials, url: row.apkUrl.length, - name: row.versionName !== undefined && isPlainName(row.versionName) ? row.versionName.length : 0, - notes: row.notes?.length ?? 0, - versionName: row.versionName !== undefined && isPlainName(row.versionName) ? row.versionName : "", - releaseNotes: row.notes ?? "", + name: [...versionName].length, + notes: [...releaseNotes].length, + versionName, releaseNotes, } } diff --git a/apps/app/test/image.test.ts b/apps/app/test/image.test.ts index 918a4d01c0..b11c944178 100644 --- a/apps/app/test/image.test.ts +++ b/apps/app/test/image.test.ts @@ -511,11 +511,12 @@ with patch("subprocess.run", side_effect=github): expect(long.ok ? "" : long.said).toContain("notes of at most 500"); }); - it("reports the channel healthy only for a launcher of Alpha's one key above every floor, kept and served exactly (spec/release/index.md, \"The channel is healthy only while its manifest names a launcher of Alpha's one key, above the retired channel and the last recorded release, at an address it keeps, served with exactly its size and digest\")", async () => { + it("reports the channel healthy only for a launcher of Alpha's one key that meets the version floors, kept and served exactly (spec/release/index.md, \"The channel is healthy only while its manifest names a launcher of Alpha's one key, above the retired channel and at least the last recorded release, at an address it keeps, served with exactly its size and digest\")", async () => { const apk = json("alpha 122"); const offer = { schema: "alpha-update/v1", variant: "launcher", versionCode: 122, signerSha256: enrolledSigner.signerSha256, apkUrl: apkUrl(122), sha256: digestOf(apk), sizeBytes: apk.length }; const status = (manifest: unknown, recordFile?: string) => releasedOver(channelAt({ "alpha-update-stable.json": json(manifest), "alpha-phone-122.apk": apk }, recordFile).port)("status"); expect(await status(offer)).toMatchObject({ ok: true, value: { versionCode: 122, kept: true, exact: true } }); + expect(await status(offer, testSignerRecord(scratch(), 122))).toMatchObject({ ok: true, value: { versionCode: 122 } }); expect(await status(offer, testSignerRecord(scratch(), 123))).toMatchObject({ ok: false, tag: "ReleaseRefused" }); for (const unhealthy of [{ signerSha256: digest("another key") }, { variant: "companion" }, { sha256: digest("other bytes") }]) { const checked = await status({ ...offer, ...unhealthy }); diff --git a/apps/app/test/screen-control.test.tsx b/apps/app/test/screen-control.test.tsx index ace6ebc228..421071e8ee 100644 --- a/apps/app/test/screen-control.test.tsx +++ b/apps/app/test/screen-control.test.tsx @@ -139,7 +139,7 @@ describe("screen-dom and screen-control security hardening", () => { try { page.setAttribute("inert", ""); - const pressed = await runtime.runPromise(screenAction({ type: "screen_press", label: "Next" }, () => Promise.resolve(true), false)); + const pressed = await runtime.runPromise(screenAction({ type: "screen_press", label: "Next" }, () => Promise.resolve(true), undefined)); expect(pressed).toEqual({ kind: "applied" }); expect(clicks).toBe(1); page.removeAttribute("inert"); @@ -152,7 +152,7 @@ describe("screen-dom and screen-control security hardening", () => { expect(isScreenTargetProtected(hiddenBtn)).toBe(true); page.querySelector("main")?.setAttribute("data-screen-withheld-view", ""); - const afterWithheld = await runtime.runPromise(screenAction({ type: "screen_press", label: "Next" }, () => Promise.resolve(true), false)); + const afterWithheld = await runtime.runPromise(screenAction({ type: "screen_press", label: "Next" }, () => Promise.resolve(true), undefined)); expect(afterWithheld).toEqual({ kind: "refused", code: NOT_DISPATCHED }); expect(clicks).toBe(1); } finally { diff --git a/spec/agent/index.md b/spec/agent/index.md index 834179fc86..4f74e31850 100644 --- a/spec/agent/index.md +++ b/spec/agent/index.md @@ -613,8 +613,9 @@ retained page after storing it, using the final result's cursor and run ID. Notes reads the same owner identity and calls the Notes module to read and edit notes, erase Trash and finish recording cleanup. The scanner hands the owner’s reviewed scan text to Notes through that module. The approvals area lists the agent's proposals and resolves one -through the approvals module. Ask Alpha completes a reviewed Messages read only -for the exact owner turn after the agent acknowledges its device receipt. +through the approvals module. Ask Alpha completes a device read such as +Messages or call history for the exact owner turn after the agent acknowledges +its device receipt. Wallet reads the wallet module's status, holdings, waiting requests and activity, makes and switches the wallet, asks for a transfer, and opens and decides its review. Settings reads and updates Alpha's on-device local LLM diff --git a/spec/app/assistant/index.md b/spec/app/assistant/index.md index 187774202a..e6c81d9ea3 100644 --- a/spec/app/assistant/index.md +++ b/spec/app/assistant/index.md @@ -877,11 +877,13 @@ turn runs ([Maps](../maps/index.md), "The agent may propose a route to a place from coordinates, another place or the phone, which is put to the owner when it arrives"). The phone tells the conversation which view the turn is bringing before it moves the screen, and only for the turn it is -awaiting, never over a sensitive screen. +awaiting, never over a sensitive screen. Repeating a claim for that view +keeps the same view. ```quint pure def canBring(c: Conversation, ticket: int, view: S::View): bool = ticket == c.turn.send.id and awaited(c.turn) and not(c.context.sensitive) + and (c.turn.brings == BringsNothing or c.turn.brings == Brings({ view: view })) pure def bring(c: Conversation, ticket: int, view: S::View): Moved = { state: { ...c, turn: { ...c.turn, brings: Brings({ view: view }) } }, out: List() } diff --git a/spec/app/update/index.md b/spec/app/update/index.md index 76a18cbb47..01068c59a8 100644 --- a/spec/app/update/index.md +++ b/spec/app/update/index.md @@ -187,8 +187,9 @@ pure def applies(s: Updates): bool = A running Alpha is one installed package, so while it runs a report of a lower version or another root is refused. A page lives within one boot, so -once the phone has reported the permission as required or supported it is -not starting any more. What a restart finds is another matter: the owner +once the phone has reported the permission as required or supported it +keeps one of those two statuses during that run. What a restart finds is +another matter: the owner may have removed Alpha's updates in Android's settings, or flashed an image whose Alpha is older or signed by another key, so the first report after a restart is taken as it is, and a saved offer signed for another root than @@ -199,7 +200,7 @@ pure def booted(p: Permission): bool = p == Required or p == Supported pure def canObservePhone(s: Updates, installed: int, signer: int, permission: Permission): bool = installed >= s.installed and signer > 0 and (s.signer == 0 or signer == s.signer) - and not(permission == Starting and booted(s.permission)) + and (booted(s.permission) implies booted(permission)) pure def observePhone(s: Updates, installed: int, signer: int, permission: Permission): Updates = { @@ -210,7 +211,7 @@ pure def observePhone(s: Updates, installed: int, signer: int, permission: Permi pure def stepTheInstalledVersionOnlyAdvances(before: Updates, via: str, after: Updates): bool = via != "restart" implies (after.installed >= before.installed and (before.signer != 0 implies after.signer == before.signer) - and (booted(before.permission) implies after.permission != Starting)) + and (booted(before.permission) implies booted(after.permission))) ``` ### The saved offer is always the launcher signed by this phone's root, or waits for the phone's first report after a restart @@ -583,8 +584,9 @@ pure def stepAnAutomaticInstallWaitsForIdle(before: Updates, after: Updates, out Android puts an install off while it is still starting, while its permission is missing, where it cannot install Alpha's updates itself, or -for a reason of its own; the first three say what Android's permission is -now. A changed offer, and one Android took, waits for a new check before an +for a reason of its own. The first three report Android's permission, with +starting and unsupported reports kept only before the phone has finished +starting. A changed offer, and one Android took, waits for a new check before an automatic update, so that Alpha never hands Android the same release twice from one check, whether the owner or Alpha started the first; a withdrawn one is removed, and a check falls due at once. @@ -597,7 +599,7 @@ pure def putOff(ending: Ending): bool = pure def permissionAfter(p: Permission, ending: Ending): Permission = if (ending == WithoutPermission) Required - else if (ending == WithoutSupport) Unsupported + else if (ending == WithoutSupport and not(booted(p))) Unsupported else if (ending == WhileStarting and not(booted(p))) Starting else p diff --git a/spec/release/index.md b/spec/release/index.md index ac0a1c9b43..afd1a4b7b3 100644 --- a/spec/release/index.md +++ b/spec/release/index.md @@ -400,7 +400,7 @@ pure def alwaysRecordedAfterReadBack(s: Channel): bool = ### A manifest names the release by a version name of 1 to 64 characters with no control character, and by notes of at most 500, as phones show them A name or notes a phone would not show are refused when the manifest is -written, not published for phones to drop. +written, not published for phones to drop. The limits count Unicode code points. ```quint pure val maxName = 64 @@ -411,7 +411,7 @@ pure def manifestNamed(name: int, control: bool, notes: int): bool = name >= 1 a pure def lawOverlongNotesAreRefused(name: int, notes: int): bool = notes > maxNotes implies not(manifestNamed(name, false, notes)) ``` -### The channel is healthy only while its manifest names a launcher of Alpha's one key, above the retired channel and the last recorded release, at an address it keeps, served with exactly its size and digest +### The channel is healthy only while its manifest names a launcher of Alpha's one key, above the retired channel and at least the last recorded release, at an address it keeps, served with exactly its size and digest `pnpm release status` reads the channel anonymously, as a phone does. From 8abb784c01b14cbe4bb8e5c9794aaaf4bd284b06 Mon Sep 17 00:00:00 2001 From: lalalune <18633264+lalalune@users.noreply.github.com> Date: Wed, 2 Dec 2026 19:44:36 -0500 Subject: [PATCH 003/193] Document cached map tiles during a Cloud hold --- spec/app/maps/connection.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/spec/app/maps/connection.md b/spec/app/maps/connection.md index 1a65199a31..49f6f95fb3 100644 --- a/spec/app/maps/connection.md +++ b/spec/app/maps/connection.md @@ -151,10 +151,10 @@ account changes nothing. While a wait holds, the owner reads "Maps request limit reached. Try again in N minutes." for a rate limit, "You have used your Maps allowance for this period. It resets in N days." for a spent allowance, and "Maps request limit reached. Try again later." for any other -wait; the number is Cloud's, the sentence Alpha's. Nothing is searched, -routed or read again, and the shell answers any tile, copyright, reroute or -route from a fix asked in that time as failed without asking Cloud. The wait -ends at its time, or with the account. +wait; the number is Cloud's, the sentence Alpha's. Alpha sends no new search, +route, tile or copyright request to Cloud during the wait. The shell can +still draw a cached tile, and answers an uncached tile, copyright, reroute or +route from a fix as failed. The wait ends at its time, or with the account. ```quint type Wait = RateLimited | AllowanceSpent | Unnamed From da7284f60f253830e34e797d12db64d69f92c8ad Mon Sep 17 00:00:00 2001 From: lalalune <18633264+lalalune@users.noreply.github.com> Date: Wed, 2 Dec 2026 23:19:11 -0500 Subject: [PATCH 004/193] feat(android): add private scheduled Messages read transport Use the split Messages role owner for bounded reads over a signature-gated Binder link. The native service uses the upstream ScheduledMessageReader and requires the live workflow scope before returning text. The Eliza reader is a prerequisite for integration. This change leaves the product pin and scheduled workflow wiring for that integration. --- .../ipc/IAlphaScheduledMessagesReader.aidl | 8 + .../ipc/IAlphaScheduledMessagesScope.aidl | 6 + .../ipc/AlphaScheduledMessagesReader.java | 177 +++++++++ .../ipc/ScheduledMessagesWire.java | 163 +++++++++ apps/app/android/suite/generate-suite.ts | 10 +- apps/app/android/suite/thin-app/build.gradle | 7 + .../ThinScheduledMessagesReaderService.java | 169 +++++++++ .../ThinScheduledMessagesReaderTest.java | 344 ++++++++++++++++++ 8 files changed, 881 insertions(+), 3 deletions(-) create mode 100644 apps/app/android/alpha-ipc/src/main/aidl/ai/alphacompute/ipc/IAlphaScheduledMessagesReader.aidl create mode 100644 apps/app/android/alpha-ipc/src/main/aidl/ai/alphacompute/ipc/IAlphaScheduledMessagesScope.aidl create mode 100644 apps/app/android/alpha-ipc/src/main/java/ai/alphacompute/ipc/AlphaScheduledMessagesReader.java create mode 100644 apps/app/android/alpha-ipc/src/main/java/ai/alphacompute/ipc/ScheduledMessagesWire.java create mode 100644 apps/app/android/suite/thin-app/src/plugins/scheduled-messages/java/ai/alphacompute/thinapp/ThinScheduledMessagesReaderService.java create mode 100644 apps/app/android/suite/thin-app/src/testMessages/java/ai/alphacompute/thinapp/ThinScheduledMessagesReaderTest.java diff --git a/apps/app/android/alpha-ipc/src/main/aidl/ai/alphacompute/ipc/IAlphaScheduledMessagesReader.aidl b/apps/app/android/alpha-ipc/src/main/aidl/ai/alphacompute/ipc/IAlphaScheduledMessagesReader.aidl new file mode 100644 index 0000000000..8c1a94faaf --- /dev/null +++ b/apps/app/android/alpha-ipc/src/main/aidl/ai/alphacompute/ipc/IAlphaScheduledMessagesReader.aidl @@ -0,0 +1,8 @@ +package ai.alphacompute.ipc; + +import ai.alphacompute.ipc.IAlphaScheduledMessagesScope; + +interface IAlphaScheduledMessagesReader { + oneway void read(long startAt, long endAt, long deadline, IAlphaScheduledMessagesScope scope); + oneway void cancel(IAlphaScheduledMessagesScope scope); +} diff --git a/apps/app/android/alpha-ipc/src/main/aidl/ai/alphacompute/ipc/IAlphaScheduledMessagesScope.aidl b/apps/app/android/alpha-ipc/src/main/aidl/ai/alphacompute/ipc/IAlphaScheduledMessagesScope.aidl new file mode 100644 index 0000000000..c004f2a24e --- /dev/null +++ b/apps/app/android/alpha-ipc/src/main/aidl/ai/alphacompute/ipc/IAlphaScheduledMessagesScope.aidl @@ -0,0 +1,6 @@ +package ai.alphacompute.ipc; + +interface IAlphaScheduledMessagesScope { + boolean current(); + oneway void answered(String result); +} diff --git a/apps/app/android/alpha-ipc/src/main/java/ai/alphacompute/ipc/AlphaScheduledMessagesReader.java b/apps/app/android/alpha-ipc/src/main/java/ai/alphacompute/ipc/AlphaScheduledMessagesReader.java new file mode 100644 index 0000000000..75bd3d8c27 --- /dev/null +++ b/apps/app/android/alpha-ipc/src/main/java/ai/alphacompute/ipc/AlphaScheduledMessagesReader.java @@ -0,0 +1,177 @@ +package ai.alphacompute.ipc; + +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.content.ServiceConnection; +import android.os.Binder; +import android.os.CancellationSignal; +import android.os.IBinder; +import android.os.Process; +import android.os.RemoteException; +import android.os.SystemClock; +import android.provider.Telephony; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.BooleanSupplier; + +import static ai.alphacompute.ipc.ScheduledMessagesWire.MESSAGES; +import static ai.alphacompute.ipc.ScheduledMessagesWire.Reason.PROVIDER_UNAVAILABLE; +import static ai.alphacompute.ipc.ScheduledMessagesWire.Reason.SCOPE_ENDED; + +public final class AlphaScheduledMessagesReader { + private static final ComponentName READER = new ComponentName(MESSAGES, ScheduledMessagesWire.SERVICE); + private static final ScheduledMessagesWire.Unavailable ENDED = new ScheduledMessagesWire.Unavailable(SCOPE_ENDED); + private static final ScheduledMessagesWire.Unavailable UNAVAILABLE = new ScheduledMessagesWire.Unavailable(PROVIDER_UNAVAILABLE); + + private AlphaScheduledMessagesReader() {} + + public static CompletableFuture read(Context context, + ScheduledMessagesWire.Window window, BooleanSupplier current, CancellationSignal cancellation) { + Context app = context.getApplicationContext(); + if (!AlphaIpcContract.CORE_PACKAGE.equals(app.getPackageName()) || + !ScheduledMessagesWire.exactCaller(app, Process.myUid(), AlphaIpcContract.CORE_PACKAGE) || + !window.valid()) { + return CompletableFuture.completedFuture(UNAVAILABLE); + } + Request request = new Request(app, window, current, cancellation); + request.start(); + return request.result; + } + + private static final class Request implements ServiceConnection { + private final Context context; + private final ScheduledMessagesWire.Window window; + private final BooleanSupplier current; + private final CancellationSignal cancellation; + private final int roleUid; + private final long deadline = SystemClock.elapsedRealtime() + ScheduledMessagesWire.TIMEOUT_MS; + private final AtomicBoolean bound = new AtomicBoolean(); + private final CompletableFuture result = new CompletableFuture<>(); + private volatile IAlphaScheduledMessagesReader reader; + + private final IAlphaScheduledMessagesScope scope = new IAlphaScheduledMessagesScope.Stub() { + @Override public boolean current() { + if (!roleCaller()) return false; + long identity = Binder.clearCallingIdentity(); + try { return authorized(); } + finally { Binder.restoreCallingIdentity(identity); } + } + + @Override public void answered(String encoded) { + if (!roleCaller()) return; + long identity = Binder.clearCallingIdentity(); + try { + if (!authorized()) { + result.complete(ENDED); + return; + } + var decoded = ScheduledMessagesWire.decode(encoded, window); + result.complete(authorized() ? decoded : ENDED); + } finally { + Binder.restoreCallingIdentity(identity); + } + } + }; + + Request(Context context, ScheduledMessagesWire.Window window, BooleanSupplier current, + CancellationSignal cancellation) { + this.context = context; + this.window = window; + this.current = current; + this.cancellation = cancellation; + this.roleUid = ScheduledMessagesWire.packageUid(context, MESSAGES); + } + + void start() { + if (!hasRole()) { + result.complete(UNAVAILABLE); + return; + } + if (!authorized()) { + result.complete(ENDED); + return; + } + cancellation.setOnCancelListener(() -> result.complete(ENDED)); + var timeout = ScheduledMessagesWire.expire(deadline, () -> result.complete(ENDED)); + result.whenCompleteAsync((ignored, failed) -> { + timeout.cancel(false); + cancellation.setOnCancelListener(null); + close(); + }); + if (!authorized()) { + result.complete(ENDED); + return; + } + try { + if (context.bindService(new Intent().setComponent(READER), this, Context.BIND_AUTO_CREATE)) { + bound.set(true); + if (result.isDone()) close(); + } else result.complete(UNAVAILABLE); + } catch (RuntimeException unavailable) { + result.complete(UNAVAILABLE); + } + } + + private boolean hasRole() { + try { + return ScheduledMessagesWire.exactCaller(context, roleUid, MESSAGES) && + MESSAGES.equals(Telephony.Sms.getDefaultSmsPackage(context)); + } catch (RuntimeException unavailable) { + return false; + } + } + + private boolean roleCaller() { + return Binder.getCallingUid() == roleUid && + ScheduledMessagesWire.exactCaller(context, roleUid, MESSAGES); + } + + private boolean authorized() { + try { + return !result.isDone() && !cancellation.isCanceled() && ScheduledMessagesWire.current(deadline) && + hasRole() && current.getAsBoolean(); + } catch (RuntimeException unavailable) { + return false; + } + } + + @Override public void onServiceConnected(ComponentName name, IBinder service) { + if (!READER.equals(name) || !hasRole()) { + result.complete(UNAVAILABLE); + return; + } + reader = IAlphaScheduledMessagesReader.Stub.asInterface(service); + if (reader == null || !authorized()) { + result.complete(ENDED); + return; + } + try { + reader.read(window.startAt(), window.endAt(), deadline, scope); + if (result.isDone()) cancel(); + } catch (RemoteException | RuntimeException unavailable) { + result.complete(UNAVAILABLE); + } + } + + @Override public void onServiceDisconnected(ComponentName name) { result.complete(UNAVAILABLE); } + @Override public void onBindingDied(ComponentName name) { result.complete(UNAVAILABLE); } + @Override public void onNullBinding(ComponentName name) { result.complete(UNAVAILABLE); } + + private void cancel() { + IAlphaScheduledMessagesReader held = reader; + if (held != null) { + try { held.cancel(scope); } + catch (RemoteException | RuntimeException ignored) {} + } + } + + private void close() { + cancel(); + if (bound.compareAndSet(true, false)) { + try { context.unbindService(this); } + catch (IllegalArgumentException ignored) {} + } + } + } +} diff --git a/apps/app/android/alpha-ipc/src/main/java/ai/alphacompute/ipc/ScheduledMessagesWire.java b/apps/app/android/alpha-ipc/src/main/java/ai/alphacompute/ipc/ScheduledMessagesWire.java new file mode 100644 index 0000000000..a3c5dbac16 --- /dev/null +++ b/apps/app/android/alpha-ipc/src/main/java/ai/alphacompute/ipc/ScheduledMessagesWire.java @@ -0,0 +1,163 @@ +package ai.alphacompute.ipc; + +import android.content.Context; +import android.content.pm.PackageManager; +import android.os.SystemClock; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Executors; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; +import java.util.regex.Pattern; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONTokener; + +public final class ScheduledMessagesWire { + public static final String MESSAGES = "ai.alphacompute.messages"; + public static final String SERVICE = "ai.alphacompute.thinapp.ThinScheduledMessagesReaderService"; + public static final long TIMEOUT_MS = 10_000; + private static final long MAX_WINDOW_MS = 26 * 60 * 60 * 1000L; + private static final int MAX_BODY_BYTES = 16_384; + private static final Pattern POSITIVE_ROW = Pattern.compile("[1-9][0-9]{0,18}"); + private static final Unavailable INVALID = new Unavailable(Reason.PROVIDER_UNAVAILABLE); + private static final ScheduledExecutorService DEADLINES = Executors.newSingleThreadScheduledExecutor(work -> { + Thread thread = new Thread(work, "alpha-scheduled-messages-deadline"); + thread.setDaemon(true); + return thread; + }); + + public record Window(long startAt, long endAt) { + public boolean valid() { + return startAt >= 0 && endAt > startAt && endAt - startAt <= MAX_WINDOW_MS && + endAt <= System.currentTimeMillis(); + } + + public boolean contains(long date) { + return date >= startAt && date < endAt; + } + } + + public enum Reason { SCOPE_ENDED, PERMISSION_DENIED, PROVIDER_UNAVAILABLE } + public sealed interface Result permits Read, Unavailable {} + public record Unavailable(Reason reason) implements Result {} + public record Read(List texts, boolean partial) implements Result { + public Read { texts = Collections.unmodifiableList(new ArrayList<>(texts)); } + } + public record Text(String id, String threadId, String kind, String direction, long date, String body, + int attachments) {} + + private ScheduledMessagesWire() {} + + public static boolean current(long deadline) { + long now = SystemClock.elapsedRealtime(); + return deadline > now && deadline - now <= TIMEOUT_MS; + } + + public static ScheduledFuture expire(long deadline, Runnable work) { + return DEADLINES.schedule(work, Math.max(0, deadline - SystemClock.elapsedRealtime()), TimeUnit.MILLISECONDS); + } + + public static boolean exactCaller(Context context, int uid, String expected) { + if (uid < 0) return false; + PackageManager packages = context.getPackageManager(); + try { + String[] names = packages.getPackagesForUid(uid); + return names != null && names.length == 1 && expected.equals(names[0]) && + packages.getApplicationInfo(expected, 0).uid == uid && + packages.checkSignatures(context.getPackageName(), expected) == PackageManager.SIGNATURE_MATCH; + } catch (PackageManager.NameNotFoundException | SecurityException unknown) { + return false; + } + } + + public static int packageUid(Context context, String name) { + try { + return context.getPackageManager().getApplicationInfo(name, 0).uid; + } catch (PackageManager.NameNotFoundException | SecurityException unknown) { + return -1; + } + } + + public static String encode(Result result) { + try { + if (result instanceof Unavailable unavailable) { + return new JSONObject().put("reason", unavailable.reason().name()).toString(); + } + Read read = (Read) result; + JSONArray texts = new JSONArray(); + int bytes = 64; + boolean partial = read.partial(); + for (Text text : read.texts()) { + JSONObject row = new JSONObject().put("id", text.id()).put("threadId", text.threadId()) + .put("kind", text.kind()).put("direction", text.direction()).put("date", text.date()) + .put("body", text.body()).put("attachments", text.attachments()); + bytes += row.toString().getBytes(StandardCharsets.UTF_8).length + 1; + if (bytes > MAX_BODY_BYTES) { + partial = true; + break; + } + texts.put(row); + } + return new JSONObject().put("texts", texts).put("partial", partial).toString(); + } catch (JSONException invalid) { + return "{\"reason\":\"PROVIDER_UNAVAILABLE\"}"; + } + } + + public static Result decode(String encoded, Window window) { + if (encoded == null || encoded.length() > MAX_BODY_BYTES || + encoded.getBytes(StandardCharsets.UTF_8).length > MAX_BODY_BYTES) { + return INVALID; + } + try { + JSONTokener payload = new JSONTokener(encoded); + JSONObject envelope = new JSONObject(payload); + if (payload.nextClean() != '\0') return INVALID; + if (envelope.length() == 1 && envelope.opt("reason") instanceof String reason) { + return new Unavailable(Reason.valueOf(reason)); + } + if (envelope.length() != 2 || !(envelope.opt("partial") instanceof Boolean partial) || + !(envelope.opt("texts") instanceof JSONArray rows)) { + return INVALID; + } + List texts = new ArrayList<>(rows.length()); + for (int i = 0; i < rows.length(); i++) { + JSONObject row = rows.getJSONObject(i); + if (row.length() != 7 || !(row.opt("id") instanceof String id) || + !(row.opt("threadId") instanceof String thread) || !(row.opt("kind") instanceof String kind) || + !(row.opt("direction") instanceof String direction) || !(row.opt("body") instanceof String body) || + !(row.opt("attachments") instanceof Integer attachments) || + !validId(thread, "thread:") || !validMessageId(id, kind) || + !("INCOMING".equals(direction) || "OUTGOING".equals(direction)) || + body.length() > 500 || attachments < 0) { + return INVALID; + } + Object timestamp = row.opt("date"); + long date = timestamp instanceof Integer value ? value.longValue() + : timestamp instanceof Long value ? value : -1; + if (!window.contains(date)) return INVALID; + texts.add(new Text(id, thread, kind, direction, date, body, attachments)); + } + return new Read(texts, partial); + } catch (JSONException | IllegalArgumentException invalid) { + return INVALID; + } + } + + private static boolean validMessageId(String id, String kind) { + return switch (kind) { + case "SMS" -> validId(id, "sms:"); + case "MMS" -> validId(id, "mms:"); + default -> false; + }; + } + + private static boolean validId(String id, String prefix) { + return id.startsWith(prefix) && POSITIVE_ROW.matcher(id.substring(prefix.length())).matches(); + } +} diff --git a/apps/app/android/suite/generate-suite.ts b/apps/app/android/suite/generate-suite.ts index a3b95dcc19..cfbc707331 100644 --- a/apps/app/android/suite/generate-suite.ts +++ b/apps/app/android/suite/generate-suite.ts @@ -247,7 +247,7 @@ const FLAVOR_PLUGIN_PROFILES: Readonly> = { }, messages: { modules: [":eliza-messages", ":eliza-phone", ":eliza-contacts", ":eliza-action-journal"], - sourceDirs: ["src/plugins/telephony/java", "src/plugins/contacts/java"], + sourceDirs: ["src/plugins/telephony/java", "src/plugins/contacts/java", "src/plugins/scheduled-messages/java"], pluginClasses: [ "ai.alphacompute.thinapp.ThinTelephonyPlugin", "ai.alphacompute.thinapp.ThinContactsPlugin", @@ -464,7 +464,7 @@ function renderQueries(registry: SuiteRegistry, app: SuiteAppEntry): readonly st ]; } -function renderFlavorComponents(app: SuiteAppEntry): readonly string[] { +function renderFlavorComponents(app: SuiteAppEntry, ipcPermission: string): readonly string[] { if (app.id === "browser") { return [ ` `, ` `, @@ -892,7 +896,7 @@ function renderThinManifest(registry: SuiteRegistry, app: SuiteAppEntry): string const slackCallback = app.id === "slack" ? app.intentFilters.find((filter) => filter.scheme === "alphaphone" && filter.host === "slack" && filter.path === "/oauth/standalone") : undefined; const extraFilters = app.intentFilters.filter((filter) => filter !== slackCallback).map(renderIntentFilter); - const flavorComponents = renderFlavorComponents(app); + const flavorComponents = renderFlavorComponents(app, registry.ipcPermission); return [ ``, diff --git a/apps/app/android/suite/thin-app/build.gradle b/apps/app/android/suite/thin-app/build.gradle index 0e9e590a81..877d93ec07 100644 --- a/apps/app/android/suite/thin-app/build.gradle +++ b/apps/app/android/suite/thin-app/build.gradle @@ -46,6 +46,8 @@ android { targetCompatibility JavaVersion.VERSION_21 } + testOptions.unitTests.includeAndroidResources = true + signingConfigs { debug { def debugKeystoreFile = resolveDebugKeystore() @@ -96,4 +98,9 @@ dependencies { implementation "androidx.core:core-splashscreen:${rootProject.hasProperty('coreSplashScreenVersion') ? rootProject.ext.coreSplashScreenVersion : '1.2.0'}" implementation "androidx.webkit:webkit:${rootProject.hasProperty('androidxWebkitVersion') ? rootProject.ext.androidxWebkitVersion : '1.17.1'}" testImplementation "junit:junit:${rootProject.hasProperty('junitVersion') ? rootProject.ext.junitVersion : '4.13.2'}" + testMessagesImplementation 'org.robolectric:robolectric:4.16.1' +} + +tasks.withType(Test).configureEach { + systemProperty 'robolectric.dependency.repo.url', 'https://maven-central.storage-download.googleapis.com/maven2' } diff --git a/apps/app/android/suite/thin-app/src/plugins/scheduled-messages/java/ai/alphacompute/thinapp/ThinScheduledMessagesReaderService.java b/apps/app/android/suite/thin-app/src/plugins/scheduled-messages/java/ai/alphacompute/thinapp/ThinScheduledMessagesReaderService.java new file mode 100644 index 0000000000..925edace82 --- /dev/null +++ b/apps/app/android/suite/thin-app/src/plugins/scheduled-messages/java/ai/alphacompute/thinapp/ThinScheduledMessagesReaderService.java @@ -0,0 +1,169 @@ +package ai.alphacompute.thinapp; + +import ai.alphacompute.ipc.AlphaIpcContract; +import ai.alphacompute.ipc.IAlphaScheduledMessagesReader; +import ai.alphacompute.ipc.IAlphaScheduledMessagesScope; +import ai.alphacompute.ipc.ScheduledMessagesWire; +import ai.eliza.plugins.messages.ScheduledMessageReader; +import android.Manifest; +import android.app.Service; +import android.app.role.RoleManager; +import android.content.Intent; +import android.os.Binder; +import android.os.CancellationSignal; +import android.os.IBinder; +import android.os.Process; +import android.os.RemoteException; +import android.os.UserManager; +import androidx.core.content.PermissionChecker; +import java.util.ArrayList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicReference; + +import static ai.alphacompute.ipc.ScheduledMessagesWire.Reason.PERMISSION_DENIED; +import static ai.alphacompute.ipc.ScheduledMessagesWire.Reason.PROVIDER_UNAVAILABLE; +import static ai.alphacompute.ipc.ScheduledMessagesWire.Reason.SCOPE_ENDED; + +public final class ThinScheduledMessagesReaderService extends Service { + private final ExecutorService reads = Executors.newSingleThreadExecutor(); + private final AtomicReference active = new AtomicReference<>(); + + private final IAlphaScheduledMessagesReader.Stub service = new IAlphaScheduledMessagesReader.Stub() { + @Override public void read(long startAt, long endAt, long deadline, IAlphaScheduledMessagesScope scope) { + int coreUid = Binder.getCallingUid(); + if (!coreCaller(coreUid) || scope == null) return; + var window = new ScheduledMessagesWire.Window(startAt, endAt); + if (!window.valid() || !ScheduledMessagesWire.current(deadline)) { + answer(scope, new ScheduledMessagesWire.Unavailable(SCOPE_ENDED)); + return; + } + Read read = new Read(coreUid, window, deadline, scope); + if (!active.compareAndSet(null, read)) { + answer(scope, new ScheduledMessagesWire.Unavailable(PROVIDER_UNAVAILABLE)); + return; + } + try { + read.binder.linkToDeath(read.death, 0); + reads.execute(read::perform); + } catch (RemoteException | RuntimeException unavailable) { + active.compareAndSet(read, null); + read.cancellation.cancel(); + read.unlink(); + answer(scope, new ScheduledMessagesWire.Unavailable(SCOPE_ENDED)); + } + } + + @Override public void cancel(IAlphaScheduledMessagesScope scope) { + if (!coreCaller(Binder.getCallingUid()) || scope == null) return; + Read read = active.get(); + if (read != null && read.binder.equals(scope.asBinder())) read.cancellation.cancel(); + } + }; + + @Override public IBinder onBind(Intent intent) { + return ScheduledMessagesWire.MESSAGES.equals(getPackageName()) && + ScheduledMessagesWire.exactCaller(this, Process.myUid(), ScheduledMessagesWire.MESSAGES) ? service : null; + } + + @Override public void onDestroy() { + Read read = active.get(); + if (read != null) read.cancellation.cancel(); + reads.shutdown(); + super.onDestroy(); + } + + private boolean coreCaller(int uid) { + return ScheduledMessagesWire.MESSAGES.equals(getPackageName()) && + ScheduledMessagesWire.exactCaller(this, uid, AlphaIpcContract.CORE_PACKAGE); + } + + private boolean canRead() { + try { + RoleManager roles = getSystemService(RoleManager.class); + UserManager users = getSystemService(UserManager.class); + return roles != null && roles.isRoleHeld(RoleManager.ROLE_SMS) && users != null && users.isUserUnlocked() && + PermissionChecker.checkSelfPermission(this, Manifest.permission.READ_SMS) == PermissionChecker.PERMISSION_GRANTED; + } catch (RuntimeException unavailable) { + return false; + } + } + + private static void answer(IAlphaScheduledMessagesScope scope, ScheduledMessagesWire.Result result) { + try { scope.answered(ScheduledMessagesWire.encode(result)); } + catch (RemoteException | RuntimeException ignored) {} + } + + private final class Read { + private final int coreUid; + private final ScheduledMessagesWire.Window window; + private final long deadline; + private final IAlphaScheduledMessagesScope scope; + private final IBinder binder; + private final CancellationSignal cancellation = new CancellationSignal(); + private final IBinder.DeathRecipient death = cancellation::cancel; + + Read(int coreUid, ScheduledMessagesWire.Window window, long deadline, IAlphaScheduledMessagesScope scope) { + this.coreUid = coreUid; + this.window = window; + this.deadline = deadline; + this.scope = scope; + binder = scope.asBinder(); + } + + private boolean current() { + if (!live()) return false; + try { return scope.current() && live(); } + catch (RemoteException | RuntimeException gone) { return false; } + } + + private boolean live() { + return !reads.isShutdown() && !cancellation.isCanceled() && ScheduledMessagesWire.current(deadline) && + coreCaller(coreUid) && canRead(); + } + + void unlink() { + try { binder.unlinkToDeath(death, 0); } + catch (RuntimeException ignored) {} + } + + void perform() { + var timeout = ScheduledMessagesWire.expire(deadline, cancellation::cancel); + String encoded; + boolean containsTexts; + try { + var result = collect(); + containsTexts = result instanceof ScheduledMessagesWire.Read; + encoded = ScheduledMessagesWire.encode(result); + } catch (RuntimeException unavailable) { + containsTexts = false; + encoded = ScheduledMessagesWire.encode(new ScheduledMessagesWire.Unavailable(PROVIDER_UNAVAILABLE)); + } finally { + active.compareAndSet(this, null); + unlink(); + } + try { + if (containsTexts && !current()) answer(scope, new ScheduledMessagesWire.Unavailable(SCOPE_ENDED)); + else scope.answered(encoded); + } catch (RemoteException | RuntimeException gone) {} finally { + timeout.cancel(false); + } + } + + private ScheduledMessagesWire.Result collect() { + if (!canRead()) return new ScheduledMessagesWire.Unavailable(PERMISSION_DENIED); + var found = ScheduledMessageReader.read(ThinScheduledMessagesReaderService.this, + new ScheduledMessageReader.Window(window.startAt(), window.endAt()), this::current, cancellation); + if (found instanceof ScheduledMessageReader.Unavailable unavailable) { + return new ScheduledMessagesWire.Unavailable(ScheduledMessagesWire.Reason.valueOf(unavailable.reason().name())); + } + var snapshot = (ScheduledMessageReader.Snapshot) found; + var texts = new ArrayList(snapshot.texts().size()); + for (var text : snapshot.texts()) { + texts.add(new ScheduledMessagesWire.Text(text.id(), text.threadId(), text.kind().name(), + text.direction().name(), text.date(), text.body(), text.attachments())); + } + return new ScheduledMessagesWire.Read(texts, snapshot.partial()); + } + } +} diff --git a/apps/app/android/suite/thin-app/src/testMessages/java/ai/alphacompute/thinapp/ThinScheduledMessagesReaderTest.java b/apps/app/android/suite/thin-app/src/testMessages/java/ai/alphacompute/thinapp/ThinScheduledMessagesReaderTest.java new file mode 100644 index 0000000000..b3c8692703 --- /dev/null +++ b/apps/app/android/suite/thin-app/src/testMessages/java/ai/alphacompute/thinapp/ThinScheduledMessagesReaderTest.java @@ -0,0 +1,344 @@ +package ai.alphacompute.thinapp; + +import static ai.alphacompute.ipc.AlphaIpcContract.CORE_PACKAGE; +import static ai.alphacompute.ipc.ScheduledMessagesWire.MESSAGES; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.robolectric.Shadows.shadowOf; + +import ai.alphacompute.ipc.AlphaScheduledMessagesReader; +import ai.alphacompute.ipc.IAlphaScheduledMessagesReader; +import ai.alphacompute.ipc.IAlphaScheduledMessagesScope; +import ai.alphacompute.ipc.ScheduledMessagesWire; +import android.Manifest; +import android.app.AppOpsManager; +import android.app.Application; +import android.app.role.RoleManager; +import android.content.ComponentName; +import android.content.ContentProvider; +import android.content.ContentValues; +import android.content.Context; +import android.content.ContextWrapper; +import android.content.Intent; +import android.content.ServiceConnection; +import android.content.pm.ApplicationInfo; +import android.content.pm.PackageInfo; +import android.content.pm.ProviderInfo; +import android.content.pm.Signature; +import android.database.Cursor; +import android.database.MatrixCursor; +import android.net.Uri; +import android.os.Binder; +import android.os.CancellationSignal; +import android.os.IBinder; +import android.os.Parcel; +import android.os.Process; +import android.os.RemoteException; +import android.os.SystemClock; +import android.os.UserManager; +import android.provider.Telephony; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.robolectric.Robolectric; +import org.robolectric.RobolectricTestRunner; +import org.robolectric.RuntimeEnvironment; +import org.robolectric.annotation.Config; +import org.robolectric.annotation.Implementation; +import org.robolectric.annotation.Implements; +import org.robolectric.shadows.ShadowBinder; +import org.robolectric.shadows.ShadowProcess; + +@RunWith(RobolectricTestRunner.class) +@Config(sdk = {29, 35}, shadows = {ThinScheduledMessagesReaderTest.SmsRole.class, ThinScheduledMessagesReaderTest.Caller.class}) +public final class ThinScheduledMessagesReaderTest { + private static final int CORE_UID = 11323; + private static final int ROLE_UID = 11324; + private static final int OTHER_UID = 11325; + private static final String SAME_SIGNER = "0102"; + private static final ScheduledMessagesWire.Window WINDOW = new ScheduledMessagesWire.Window(1_000, 5_000); + private static final ScheduledMessagesWire.Text MESSAGE = + new ScheduledMessagesWire.Text("sms:2", "thread:1", "SMS", "INCOMING", 3_000, "synthetic text", 0); + private static final ScheduledMessagesWire.Read READ = new ScheduledMessagesWire.Read(List.of(MESSAGE), false); + private static final ScheduledMessagesWire.Unavailable DENIED = + new ScheduledMessagesWire.Unavailable(ScheduledMessagesWire.Reason.PERMISSION_DENIED); + private static final ScheduledMessagesWire.Unavailable ENDED = + new ScheduledMessagesWire.Unavailable(ScheduledMessagesWire.Reason.SCOPE_ENDED); + private static final ScheduledMessagesWire.Unavailable UNAVAILABLE = + new ScheduledMessagesWire.Unavailable(ScheduledMessagesWire.Reason.PROVIDER_UNAVAILABLE); + private Application app; + + @Before public void packages() { + app = RuntimeEnvironment.getApplication(); + assertEquals(MESSAGES, app.getPackageName()); + ShadowProcess.setUid(ROLE_UID); + install(MESSAGES, ROLE_UID, SAME_SIGNER); + install(CORE_PACKAGE, CORE_UID, SAME_SIGNER); + install("ai.alphacompute.other", OTHER_UID, SAME_SIGNER); + SmsRole.owner = MESSAGES; + } + + // spec/app/messages/index.md, "The agent reads only the recent texts the owner asked about, and changes nothing" + @Test public void onlyCurrentCoreCanReadAndOnlyFromThePermittedMessagesRole() throws Exception { + registerTextProviders(); + var controller = Robolectric.buildService(ThinScheduledMessagesReaderService.class).create(); + try { + var server = IAlphaScheduledMessagesReader.Stub.asInterface(remote(controller.get().onBind(new Intent()))); + var unauthorized = new Scope(); + Caller.uid.set(OTHER_UID); + request(server, unauthorized); + assertNull(unauthorized.replies.poll(100, TimeUnit.MILLISECONDS)); + Caller.uid.set(CORE_UID); + install(CORE_PACKAGE, CORE_UID, "0304"); + request(server, unauthorized); + assertNull(unauthorized.replies.poll(100, TimeUnit.MILLISECONDS)); + install(CORE_PACKAGE, CORE_UID, SAME_SIGNER); + shadowOf(app.getPackageManager()).setPackagesForUid(CORE_UID, CORE_PACKAGE, "ai.alphacompute.other"); + request(server, unauthorized); + assertNull(unauthorized.replies.poll(100, TimeUnit.MILLISECONDS)); + shadowOf(app.getPackageManager()).setPackagesForUid(CORE_UID, CORE_PACKAGE); + + var denied = new Scope(); + request(server, denied); + assertEquals(DENIED, denied.result()); + shadowOf(app.getSystemService(RoleManager.class)).addHeldRole(RoleManager.ROLE_SMS); + shadowOf(app.getSystemService(UserManager.class)).setUserUnlocked(true); + shadowOf(app).grantPermissions(Manifest.permission.READ_SMS); + var ops = shadowOf(app.getSystemService(AppOpsManager.class)); + ops.setMode(AppOpsManager.OPSTR_READ_SMS, ROLE_UID, MESSAGES, AppOpsManager.MODE_IGNORED); + var appOpsDenied = new Scope(); + request(server, appOpsDenied); + assertEquals(DENIED, appOpsDenied.result()); + assertEquals(0, SyntheticTexts.reads.get()); + + ops.setMode(AppOpsManager.OPSTR_READ_SMS, ROLE_UID, MESSAGES, AppOpsManager.MODE_ALLOWED); + var expired = new Scope(); + server.read(WINDOW.startAt(), WINDOW.endAt(), SystemClock.elapsedRealtime(), expired); + assertEquals(ENDED, expired.result()); + var oversized = new Scope(); + server.read(WINDOW.startAt(), Long.MAX_VALUE, SystemClock.elapsedRealtime() + 8_000, oversized); + assertEquals(ENDED, oversized.result()); + var accepted = new Scope(); + request(server, accepted); + assertEquals(READ, accepted.result()); + assertEquals(2, SyntheticTexts.reads.get()); + } finally { controller.destroy(); } + } + + // spec/app/messages/index.md, "Access that arrives reads the pane again, and access that goes forgets what it showed" + @Test public void canceledOrRevokedWorkerWithholdsRowsItAlreadyRead() throws Exception { + registerTextProviders(); + shadowOf(app.getSystemService(RoleManager.class)).addHeldRole(RoleManager.ROLE_SMS); + shadowOf(app.getSystemService(UserManager.class)).setUserUnlocked(true); + shadowOf(app).grantPermissions(Manifest.permission.READ_SMS); + shadowOf(app.getSystemService(AppOpsManager.class)).setMode(AppOpsManager.OPSTR_READ_SMS, ROLE_UID, MESSAGES, + AppOpsManager.MODE_ALLOWED); + var controller = Robolectric.buildService(ThinScheduledMessagesReaderService.class).create(); + try { + var server = IAlphaScheduledMessagesReader.Stub.asInterface(remote(controller.get().onBind(new Intent()))); + Caller.uid.set(CORE_UID); + var accepted = new Scope(); + SyntheticTexts.onMms.set(() -> { + cancelAs(OTHER_UID, server, accepted); + cancelAs(CORE_UID, server, new Scope()); + }); + request(server, accepted); + assertEquals(READ, accepted.result()); + + var revoked = new Scope(); + SyntheticTexts.onMms.set(() -> revoked.live.set(false)); + request(server, revoked); + assertEquals(ENDED, revoked.result()); + + var canceled = new Scope(); + SyntheticTexts.onMms.set(() -> cancelAs(CORE_UID, server, canceled)); + request(server, canceled); + assertEquals(ENDED, canceled.result()); + } finally { controller.destroy(); } + } + + // spec/app/workflows/index.md, "An open workflow belongs to the signed-in owner" + @Test public void coreWithholdsUntrustedLateOrMalformedReplies() throws Exception { + ShadowProcess.setUid(CORE_UID); + var core = new CoreContext(app); + var ticket = new AtomicBoolean(true); + var cancellation = new CancellationSignal(); + var pending = AlphaScheduledMessagesReader.read(core, WINDOW, ticket::get, cancellation); + var reply = core.callback(); + Caller.uid.set(OTHER_UID); + assertFalse(reply.current()); + reply.answered(ScheduledMessagesWire.encode(READ)); + assertFalse(pending.isDone()); + Caller.uid.set(ROLE_UID); + assertTrue(reply.current()); + install(MESSAGES, ROLE_UID, "0304"); + assertFalse(reply.current()); + reply.answered(ScheduledMessagesWire.encode(READ)); + assertFalse(pending.isDone()); + install(MESSAGES, ROLE_UID, SAME_SIGNER); + ticket.set(false); + assertFalse(reply.current()); + reply.answered(ScheduledMessagesWire.encode(READ)); + assertEquals(ENDED, pending.get(3, TimeUnit.SECONDS)); + + ticket.set(true); + var scoped = AlphaScheduledMessagesReader.read(core, WINDOW, ticket::get, new CancellationSignal()); + core.callback().answered(ScheduledMessagesWire.encode(READ).replace("3000", "5000")); + assertEquals(UNAVAILABLE, scoped.get(3, TimeUnit.SECONDS)); + + var allowed = AlphaScheduledMessagesReader.read(core, WINDOW, ticket::get, new CancellationSignal()); + core.callback().answered(ScheduledMessagesWire.encode(READ)); + assertEquals(READ, allowed.get(3, TimeUnit.SECONDS)); + + var clipped = AlphaScheduledMessagesReader.read(core, WINDOW, ticket::get, new CancellationSignal()); + var longer = new ScheduledMessagesWire.Text("sms:3", "thread:1", "SMS", "OUTGOING", 3_000, + "夜".repeat(500), 0); + core.callback().answered(ScheduledMessagesWire.encode(new ScheduledMessagesWire.Read( + java.util.Collections.nCopies(30, longer), false))); + assertTrue(clipped.get(3, TimeUnit.SECONDS) instanceof ScheduledMessagesWire.Read batch && + batch.partial() && batch.texts().size() > 0 && batch.texts().size() < 30); + + var inFlight = new CancellationSignal(); + var canceled = AlphaScheduledMessagesReader.read(core, WINDOW, ticket::get, inFlight); + var late = core.callback(); + inFlight.cancel(); + late.answered(ScheduledMessagesWire.encode(READ)); + assertEquals(ENDED, canceled.get(3, TimeUnit.SECONDS)); + SmsRole.owner = CORE_PACKAGE; + assertEquals(UNAVAILABLE, AlphaScheduledMessagesReader.read(core, WINDOW, ticket::get, new CancellationSignal()) + .get(3, TimeUnit.SECONDS)); + } + + private static void request(IAlphaScheduledMessagesReader server, Scope scope) throws RemoteException { + server.read(WINDOW.startAt(), WINDOW.endAt(), SystemClock.elapsedRealtime() + 8_000, scope); + } + + private static void cancelAs(int uid, IAlphaScheduledMessagesReader server, Scope scope) { + Caller.uid.set(uid); + try { server.cancel(scope); } + catch (RemoteException error) { throw new AssertionError(error); } + finally { Caller.uid.remove(); } + } + + private void install(String name, int uid, String signer) { + PackageInfo info = new PackageInfo(); + info.packageName = name; + info.applicationInfo = new ApplicationInfo(); + info.applicationInfo.packageName = name; + info.applicationInfo.uid = uid; + info.signatures = new Signature[]{new Signature(signer)}; + var packages = shadowOf(app.getPackageManager()); + packages.installPackage(info); + packages.setPackagesForUid(uid, name); + } + + private static IBinder remote(IBinder target) { + assertNotNull(target); + return new Binder() { + @Override protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { + return target.transact(code, data, reply, flags); + } + }; + } + + private static void registerTextProviders() { + SyntheticTexts.reads.set(0); + SyntheticTexts.onMms.set(() -> {}); + for (String scheme : List.of("sms", "mms")) { + ProviderInfo provider = new ProviderInfo(); + provider.authority = scheme; + Robolectric.buildContentProvider(SyntheticTexts.class).create(provider); + } + } + + private static final class Scope extends IAlphaScheduledMessagesScope.Stub { + final AtomicBoolean live = new AtomicBoolean(true); + final BlockingQueue replies = new LinkedBlockingQueue<>(); + + @Override public boolean current() { return live.get(); } + @Override public void answered(String encoded) { replies.add(encoded); } + + ScheduledMessagesWire.Result result() throws InterruptedException { + String reply = replies.poll(3, TimeUnit.SECONDS); + assertNotNull(reply); + return ScheduledMessagesWire.decode(reply, WINDOW); + } + } + + private static final class CoreContext extends ContextWrapper { + private final BlockingQueue callbacks = new LinkedBlockingQueue<>(); + private final IAlphaScheduledMessagesReader.Stub role = new IAlphaScheduledMessagesReader.Stub() { + @Override public void read(long start, long end, long deadline, IAlphaScheduledMessagesScope scope) { + assertEquals(WINDOW, new ScheduledMessagesWire.Window(start, end)); + assertTrue(ScheduledMessagesWire.current(deadline)); + callbacks.add(IAlphaScheduledMessagesScope.Stub.asInterface(remote(scope.asBinder()))); + } + @Override public void cancel(IAlphaScheduledMessagesScope scope) {} + }; + + CoreContext(Context context) { super(context); } + @Override public String getPackageName() { return CORE_PACKAGE; } + @Override public Context getApplicationContext() { return this; } + + @Override public boolean bindService(Intent intent, ServiceConnection connection, int flags) { + assertEquals(new ComponentName(MESSAGES, ScheduledMessagesWire.SERVICE), intent.getComponent()); + connection.onServiceConnected(intent.getComponent(), remote(role)); + return true; + } + + @Override public void unbindService(ServiceConnection connection) {} + + IAlphaScheduledMessagesScope callback() throws InterruptedException { + var callback = callbacks.poll(3, TimeUnit.SECONDS); + assertNotNull(callback); + return callback; + } + } + + @Implements(Telephony.Sms.class) + public static class SmsRole { + static String owner; + @Implementation protected static String getDefaultSmsPackage(Context context) { return owner; } + } + + @Implements(Binder.class) + public static class Caller extends ShadowBinder { + static final ThreadLocal uid = new ThreadLocal<>(); + + @Implementation protected static int getCallingUid() { + Integer caller = uid.get(); + return caller == null ? Process.myUid() : caller; + } + } + + public static final class SyntheticTexts extends ContentProvider { + static final AtomicInteger reads = new AtomicInteger(); + static final AtomicReference onMms = new AtomicReference<>(); + + @Override public boolean onCreate() { return true; } + @Override public Cursor query(Uri uri, String[] columns, String selector, String[] bounds, String order) { + reads.incrementAndGet(); + assertFalse(Arrays.asList(columns).contains("address")); + var rows = new MatrixCursor(columns); + if ("sms".equals(uri.getAuthority())) { + rows.addRow(new Object[]{2L, 1L, 3_000L, 1, "synthetic text"}); + } else onMms.get().run(); + return rows; + } + @Override public String getType(Uri uri) { return null; } + @Override public Uri insert(Uri uri, ContentValues values) { throw new AssertionError(); } + @Override public int delete(Uri uri, String select, String[] args) { throw new AssertionError(); } + @Override public int update(Uri uri, ContentValues values, String select, String[] args) { throw new AssertionError(); } + } +} From 23e86e8907c911522eceb2df857ba4ef1ae12f47 Mon Sep 17 00:00:00 2001 From: Shaw Walters Date: Wed, 2 Dec 2026 21:56:42 -0800 Subject: [PATCH 005/193] Fit the tasks-and-wallet route proof to the 38 routes left after the memory routes --- spec/agent/index.proof.dfy | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/spec/agent/index.proof.dfy b/spec/agent/index.proof.dfy index ae3b298f0a..332855b07c 100644 --- a/spec/agent/index.proof.dfy +++ b/spec/agent/index.proof.dfy @@ -138,13 +138,12 @@ lemma TasksWalletNotNativeC(i: int) } lemma TasksWalletNotNativeD(i: int) - requires 30 <= i < 41 + requires 30 <= i < 38 ensures pageRoutesTasksWallet[i] !in nativeSpeechRoutes ensures pageRoutesTasksWallet[i] !in nativeControlRoutes { if i == 30 { NotNativeSpeechOrControl(pageRoutesTasksWallet[30]); } else if i == 31 { NotNativeSpeechOrControl(pageRoutesTasksWallet[31]); } else if i == 32 { NotNativeSpeechOrControl(pageRoutesTasksWallet[32]); } else if i == 33 { NotNativeSpeechOrControl(pageRoutesTasksWallet[33]); } - else if i == 34 { NotNativeSpeechOrControl(pageRoutesTasksWallet[34]); } else if i == 35 { NotNativeSpeechOrControl(pageRoutesTasksWallet[35]); } else if i == 36 { NotNativeSpeechOrControl(pageRoutesTasksWallet[36]); } else if i == 37 { NotNativeSpeechOrControl(pageRoutesTasksWallet[37]); } - else if i == 38 { NotNativeSpeechOrControl(pageRoutesTasksWallet[38]); } else if i == 39 { NotNativeSpeechOrControl(pageRoutesTasksWallet[39]); } else { NotNativeSpeechOrControl(pageRoutesTasksWallet[40]); } + else if i == 34 { NotNativeSpeechOrControl(pageRoutesTasksWallet[34]); } else if i == 35 { NotNativeSpeechOrControl(pageRoutesTasksWallet[35]); } else if i == 36 { NotNativeSpeechOrControl(pageRoutesTasksWallet[36]); } else { NotNativeSpeechOrControl(pageRoutesTasksWallet[37]); } } lemma TasksWalletNotNative(route: Route) @@ -152,8 +151,8 @@ lemma TasksWalletNotNative(route: Route) ensures route !in nativeSpeechRoutes ensures route !in nativeControlRoutes { - assert |pageRoutesTasksWallet| == 41; - var i :| 0 <= i < 41 && pageRoutesTasksWallet[i] == route; + assert |pageRoutesTasksWallet| == 38; + var i :| 0 <= i < 38 && pageRoutesTasksWallet[i] == route; if i < 10 { TasksWalletNotNativeA(i); } else if i < 20 { TasksWalletNotNativeB(i); } else if i < 30 { TasksWalletNotNativeC(i); } else { TasksWalletNotNativeD(i); } } From 82c08d258e064fdfc1aec56092d63b2adeede6ee Mon Sep 17 00:00:00 2001 From: lalalune <18633264+lalalune@users.noreply.github.com> Date: Thu, 3 Dec 2026 00:58:43 -0500 Subject: [PATCH 006/193] Connect the resident Messages reader to the signed Android role service --- .../ipc/AlphaScheduledMessagesReader.java | 5 ++++ .../alphaphone/AlphaAgentService.java | 23 +++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/apps/app/android/alpha-ipc/src/main/java/ai/alphacompute/ipc/AlphaScheduledMessagesReader.java b/apps/app/android/alpha-ipc/src/main/java/ai/alphacompute/ipc/AlphaScheduledMessagesReader.java index 75bd3d8c27..b1323591d1 100644 --- a/apps/app/android/alpha-ipc/src/main/java/ai/alphacompute/ipc/AlphaScheduledMessagesReader.java +++ b/apps/app/android/alpha-ipc/src/main/java/ai/alphacompute/ipc/AlphaScheduledMessagesReader.java @@ -137,6 +137,11 @@ private boolean authorized() { } @Override public void onServiceConnected(ComponentName name, IBinder service) { + CompletableFuture.runAsync(() -> connect(name, service)); + } + + private void connect(ComponentName name, IBinder service) { + if (result.isDone()) return; if (!READER.equals(name) || !hasRole()) { result.complete(UNAVAILABLE); return; diff --git a/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaAgentService.java b/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaAgentService.java index b5c84246b7..af6a9b0293 100644 --- a/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaAgentService.java +++ b/apps/app/android/app/src/main/java/ai/alphacompute/alphaphone/AlphaAgentService.java @@ -5,6 +5,8 @@ import ai.alphacompute.alphaphone.overlay.AlphaControlRuntimeBridge; import ai.alphacompute.alphaphone.runtime.RuntimeUpdatePause; import ai.alphacompute.ipc.AlphaIpcContract; +import ai.alphacompute.ipc.AlphaScheduledMessagesReader; +import ai.alphacompute.ipc.ScheduledMessagesWire; import ai.alphacompute.localllm.AlphaLocalInferenceHost; import ai.alphacompute.localllm.AlphaLocalLlmCatalog; import ai.alphacompute.localllm.AlphaLocalModelManager; @@ -14,6 +16,7 @@ import ai.eliza.os.agent.AgentService; import ai.eliza.os.agent.ChannelPolicy.CallerKind; import ai.eliza.os.agent.ChannelPolicy.Outcome; +import ai.eliza.os.agent.ScheduledMessagesTransport; import ai.eliza.os.agent.inference.InferenceHost; import ai.eliza.plugins.signin.CredentialReader; import ai.eliza.plugins.signin.DeviceCustody; @@ -24,9 +27,11 @@ import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; +import android.os.CancellationSignal; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; @@ -61,6 +66,24 @@ public final class AlphaAgentService extends AgentService { private record SpeechHost(String name, InferenceHost host) {} + @Override protected ScheduledMessagesTransport.Reader scheduledMessagesReader() { + Context app = getApplicationContext(); + return (window, current, cancelled) -> { + var cancellation = new CancellationSignal(); + cancelled.whenComplete((ignored, failure) -> cancellation.cancel()); + return AlphaScheduledMessagesReader.read(app, new ScheduledMessagesWire.Window(window.startAt(), window.endAt()), + current, cancellation).thenApply(result -> { + if (!(result instanceof ScheduledMessagesWire.Read read)) return ScheduledMessagesTransport.Unavailable.INSTANCE; + var texts = new ArrayList(read.texts().size()); + for (var text : read.texts()) { + texts.add(new ScheduledMessagesTransport.Text(ScheduledMessagesTransport.Kind.valueOf(text.kind()), + ScheduledMessagesTransport.Direction.valueOf(text.direction()), text.date(), text.body())); + } + return new ScheduledMessagesTransport.Read(texts, read.partial()); + }); + }; + } + private AgentCredentials.Account launchAccount() { try { AgentCredentials.Active active = credentials().current(); From a6bf0c675037309e8d7d343482178790fa4f9127 Mon Sep 17 00:00:00 2001 From: lalalune <18633264+lalalune@users.noreply.github.com> Date: Thu, 3 Dec 2026 01:14:24 -0500 Subject: [PATCH 007/193] Carry Messages decisions only over the native host routes --- apps/agent/src/main.vibe | 2 ++ apps/agent/test/agent.test.vibe | 3 +++ spec/agent/index.md | 9 +++++++++ 3 files changed, 14 insertions(+) diff --git a/apps/agent/src/main.vibe b/apps/agent/src/main.vibe index bb1ca27740..e4a99e6394 100644 --- a/apps/agent/src/main.vibe +++ b/apps/agent/src/main.vibe @@ -6,6 +6,7 @@ import { decodeLaunchDocument, defineRoutes } from "@elizaos/agent" import { deployment } from "@repo/deployment" import { packWorkerDir, packagedWorkflowWorker, pinnedCheckout, pinnedPack } from "@repo/eliza-harness" import { + nativeMessagesReview, nativeMessagesReviewLimit, nativeMessagesReviewPrepare, type Environment, type Manifest, browserNotesCleanup, browserNotesTranscription, browserNotesTranscriptionLimit, bundledPlugins, calendarEdits, characterAdmitted, cloudModel, controlLeaseLimit, controlLeasePath, controlStopLimit, controlStopPath, corePlugins, entryCarried, gmailChanges, googleAdmitted, hostedPlugins, inputAdmitted, localEmbeddings, localLlmActivatePath, localLlmControlLimit, localLlmDeletePath, localLlmModePath, memoryRecordsLimit, memoryRecordsPath, memorySafariActionLimit, memorySafariActionPath, nativeControlInterrupt, nativeControlInterruptLimit, nativeControlObserve, nativeControlObserveLimit, nativeControlReceipt, nativeControlReceiptLimit, nativeDigestAck, nativeDigestAckLimit, nativeDigestQueries, nativeDigestScope, nativeNotesCleanup, nativeNotesCleanupLimit, nativeRoutes, nativeRoutesAdmitted, nativeSpeechRoutes, notesTrashDays, packAdmitted, packEntry, packedFor, packedPlugins, pageQueries, persistMemory, personalDetailSwap, launchViews, policyAdmitted, privacyAdmitted, productPluginName, proposalsAdmitted, refusedActions, routeListAdmitted, secretSwap, slackBrokerPath, slackRedirectUri, slackRegistrationPath, slackStandaloneRedirectUri, @@ -393,6 +394,7 @@ function routeBodyLimit(route: RouteLine, native: boolean): number | undefined { if (route.path === nativeControlObserve) return nativeControlObserveLimit if (route.path === nativeControlReceipt) return nativeControlReceiptLimit if (route.path === nativeControlInterrupt) return nativeControlInterruptLimit + if (route.path === nativeMessagesReview || route.path === nativeMessagesReviewPrepare) return nativeMessagesReviewLimit return route.path === nativeNotesCleanup ? nativeNotesCleanupLimit : undefined } diff --git a/apps/agent/test/agent.test.vibe b/apps/agent/test/agent.test.vibe index 8fc13772a0..325b051190 100644 --- a/apps/agent/test/agent.test.vibe +++ b/apps/agent/test/agent.test.vibe @@ -146,8 +146,11 @@ describe("Build the pack only from the pinned eliza", () => { { method: "GET", path: "/api/alpha-control/next", stream: false }, { method: "POST", path: "/api/alpha-control/receipt", stream: false, maxBodyBytes: 65536 }, { method: "POST", path: "/api/alpha-control/interrupt", stream: false, maxBodyBytes: 2048 }, + { method: "POST", path: "/api/host/scheduled-messages-review/prepare", stream: false, maxBodyBytes: 4096 }, + { method: "POST", path: "/api/host/scheduled-messages-review", stream: false, maxBodyBytes: 4096 }, ]) expect(listed().some(({ path }) => ["/api/alpha-speech/scope", "/api/asr/local-inference/live", "/api/alpha-runtime/scope", "/api/alpha-runtime/notes-recording-cleanup", "/api/notes/trash/recordings/complete", "/api/alpha-control/observe", "/api/alpha-control/next", "/api/alpha-control/receipt", "/api/alpha-control/interrupt"].includes(path))).toBe(false) + expect(listed().some(({ path }) => path === "/api/host/scheduled-messages-review" || path === "/api/host/scheduled-messages-review/prepare")).toBe(false) expect(plugins.product).toBe(productPluginName) expect(registered).toContain("TELEGRAM_MESSAGES_TODAY") expect(entryCarried(built.packages.map(({ name }) => name))).toBe(true) diff --git a/spec/agent/index.md b/spec/agent/index.md index a238673276..1f22dc5d9f 100644 --- a/spec/agent/index.md +++ b/spec/agent/index.md @@ -1010,10 +1010,17 @@ from the phone's durable removal evidence. In either phase the resident requires its current reserved receipt with no saved references. The Notes service clears the receipt only after receiving its proof in that request. The page can read pending receipts. It cannot complete them. +Android also uses the native channel to prepare and confirm a Phone Messages +review for an exact scheduled recap. The resident verifies the two native +proofs. The page receives neither route, and the native routes accept +buffered POST requests with at most 4096 bytes. ```quint pure val nativeNotesCleanup = "/api/alpha-runtime/notes-recording-cleanup" pure val nativeNotesCleanupLimit = 2048 +pure val nativeMessagesReview = "/api/host/scheduled-messages-review" +pure val nativeMessagesReviewPrepare = "/api/host/scheduled-messages-review/prepare" +pure val nativeMessagesReviewLimit = 4096 pure val nativeControlObserve = "/api/alpha-control/observe" pure val nativeControlNext = "/api/alpha-control/next" pure val nativeControlReceipt = "/api/alpha-control/receipt" @@ -1040,6 +1047,8 @@ pure val nativeRoutes: List[Route] = List( { method: Get, path: nativeControlNext, stream: false }, { method: Post, path: nativeControlReceipt, stream: false }, { method: Post, path: nativeControlInterrupt, stream: false }, + { method: Post, path: nativeMessagesReviewPrepare, stream: false }, + { method: Post, path: nativeMessagesReview, stream: false }, ) pure def nativeRoutesAdmitted(listed: List[Route]): bool = listed.length() == nativeRoutes.length() and listed.every(route => nativeRoutes.includes(route)) From 1ce1a756b368525365ac9a4d1e88ba3311b8d1c0 Mon Sep 17 00:00:00 2001 From: Shaw Walters Date: Wed, 2 Dec 2026 22:15:55 -0800 Subject: [PATCH 008/193] Say in each reviewed rule's prose what its Quint enforces Reviewers compared the 838 review items at 2ecc1b3dac7 with their Quint; a second reader confirmed 80 rules whose prose claimed more or less than the model. Prose only: no Quint block changes and no rule is weakened. Two headings that still overstated their Quint now say what it checks, with their citations. --- apps/app/src/settings/preferences.vibe | 4 +- apps/app/test/image.test.ts | 2 +- apps/app/test/settings.test.tsx | 2 +- spec/agent/index.md | 52 +++++++++++++++------ spec/app/account/provider.md | 11 +++-- spec/app/assistant/cards.md | 15 +++--- spec/app/assistant/composer.md | 10 ++-- spec/app/assistant/context.md | 12 ++++- spec/app/assistant/dock.md | 50 ++++++++++++++------ spec/app/assistant/index.md | 44 +++++++++++++---- spec/app/assistant/reply.md | 3 +- spec/app/browser/safariCopilot.md | 16 +++++++ spec/app/calendar/sharing.md | 28 ++++++----- spec/app/camera/index.md | 36 ++++++++++---- spec/app/clock/stopwatch.md | 12 ++--- spec/app/contacts/agent.md | 27 +++++++---- spec/app/contacts/index.md | 19 +++++--- spec/app/home/cards.md | 22 ++++++--- spec/app/home/index.md | 6 ++- spec/app/image/index.md | 6 +-- spec/app/messages/index.md | 13 ++++-- spec/app/notes/editor.md | 43 ++++++++++------- spec/app/photos/index.md | 65 ++++++++++++++++++++------ spec/app/photos/memoryGraph.md | 6 +++ spec/app/reminders/editor.md | 7 +-- spec/app/settings/index.md | 2 +- spec/app/settings/preferences.md | 18 +++++-- spec/app/shell/index.md | 21 ++++++--- spec/app/update/index.md | 14 +++--- spec/app/voice/index.md | 24 +++++++--- spec/cloud/rollout.md | 13 ++++-- spec/release/index.md | 12 ++++- 32 files changed, 432 insertions(+), 183 deletions(-) diff --git a/apps/app/src/settings/preferences.vibe b/apps/app/src/settings/preferences.vibe index bf4f4e62de..458c008567 100644 --- a/apps/app/src/settings/preferences.vibe +++ b/apps/app/src/settings/preferences.vibe @@ -48,7 +48,7 @@ effect function keepTheme(keep: number, chosen: Theme, legible: boolean): Event! return { type: "themeKept", keep, ok } } -// spec/app/settings/preferences.md, "What the phone could not read is taken as asking first, loading no images and sharing nothing"; spec/app/settings/preferences.md, "The device preferences are read when Alpha starts, when Settings opens, when Alpha comes back while Settings shows, and after a change the phone did not answer in time, with ten seconds to answer, never while a change or a recovery is in flight" +// spec/app/settings/preferences.md, "What the phone could not read is taken as asking first, loading no images and sharing nothing"; spec/app/settings/preferences.md, "The device preferences are read when Alpha starts, when Settings opens, when Alpha comes back while Settings shows, after a change the phone did not answer in time and when that recovery ends, with ten seconds to answer, never while a change or a recovery is in flight" effect function readChoices(): (Choices | undefined)!KeyValueStore.KeyValueStoreError!KeyValueStore.KeyValueStore { const store = try KeyValueStore.KeyValueStore const own = try store.get(keys.choices) @@ -137,7 +137,7 @@ function timers(state: Prefs.Preferences): ReadonlyArray showing(shell, "Settings"), Prefs.Machine, (shown): Event | undefined => (shown ? { type: "opened", at: untimed } : undefined), From.phone) const resumed = hearing( diff --git a/apps/app/test/image.test.ts b/apps/app/test/image.test.ts index 9db706c2ed..b785b4e1ab 100644 --- a/apps/app/test/image.test.ts +++ b/apps/app/test/image.test.ts @@ -511,7 +511,7 @@ with patch("subprocess.run", side_effect=github): expect(long.ok ? "" : long.said).toContain("notes of at most 500"); }); - it("reports the channel healthy only for a launcher of Alpha's one key above every floor, kept and served exactly (spec/release/index.md, \"The channel is healthy only while its manifest names a launcher of Alpha's one key, above the retired channel and the last recorded release, at an address it keeps, served with exactly its size and digest\")", async () => { + it("reports the channel healthy only for a launcher of Alpha's one key above every floor, kept and served exactly (spec/release/index.md, \"The channel is healthy only while its manifest names a launcher of Alpha's one key, above the retired channel and no older than the last recorded release, at an address it keeps, served with exactly its size and digest\")", async () => { const apk = json("alpha 122"); const offer = { schema: "alpha-update/v1", variant: "launcher", versionCode: 122, signerSha256: enrolledSigner.signerSha256, apkUrl: apkUrl(122), sha256: digestOf(apk), sizeBytes: apk.length }; const status = (manifest: unknown, recordFile?: string) => releasedOver(channelAt({ "alpha-update-stable.json": json(manifest), "alpha-phone-122.apk": apk }, recordFile).port)("status"); diff --git a/apps/app/test/settings.test.tsx b/apps/app/test/settings.test.tsx index fde8ff660e..f279cc2b10 100644 --- a/apps/app/test/settings.test.tsx +++ b/apps/app/test/settings.test.tsx @@ -958,7 +958,7 @@ describe("Settings", () => { await vi.waitFor(() => expect(world.settings.consents.at(-1)).toEqual({ gmailChanges: true, calendarEdits: true })); }); - it('A phone updated from the previous Alpha keeps its choices (spec/app/settings/preferences.md, "The device preferences are read when Alpha starts, when Settings opens, when Alpha comes back while Settings shows, and after a change the phone did not answer in time, with ten seconds to answer, never while a change or a recovery is in flight")', async () => { + it('A phone updated from the previous Alpha keeps its choices (spec/app/settings/preferences.md, "The device preferences are read when Alpha starts, when Settings opens, when Alpha comes back while Settings shows, after a change the phone did not answer in time and when that recovery ends, with ten seconds to answer, never while a change or a recovery is in flight")', async () => { localStorage.setItem("alpha.browser.device.v1", JSON.stringify({ askBeforeAgentActions: false, agentLocationEnabled: false, autoLoadMailImages: true })); const { alpha } = await open({ ...scene(), phone: true }); await until(alpha, alpha.runtime, Prefs.Machine, (s) => s.document.read.status === "Loaded"); diff --git a/spec/agent/index.md b/spec/agent/index.md index a238673276..d065c1e3d5 100644 --- a/spec/agent/index.md +++ b/spec/agent/index.md @@ -277,7 +277,9 @@ Slack's module registers `SLACK_LIST_CONVERSATIONS`, `SLACK_READ_MESSAGES`, while the owner is signed in to a workspace; a send waits for the owner's approval of the exact text before it is posted. Telegram's account module registers `TELEGRAM_LIST_CHATS`, `TELEGRAM_READ_MESSAGES`, -`TELEGRAM_SEARCH_MESSAGES` and `TELEGRAM_SEND_MESSAGE`. The owner can ask +`TELEGRAM_SEARCH_MESSAGES`, `TELEGRAM_SEND_MESSAGE` and +`TELEGRAM_MESSAGES_TODAY`, which answers who messaged the owner today as +the next rule says. The owner can ask in a general Ask Alpha conversation or while looking at Telegram. A signed-out request says how to sign in when the phone supports sign-in; only a signed-in account can read or propose a send for the owner to @@ -330,8 +332,8 @@ pure def policyAdmitted(allowed: List[str], refused: List[str], loaded: List[str The owner's signed-in Telegram module answers who messaged them today from the phone's local day, including already-read messages and archived -chats. The read checks up to fifty chats in each list and up to fifty -messages in each of twelve chats that need their history, and says when +chats. The read checks up to fifty chats in each list and reads a bounded +page of history in each of up to twelve chats that need it, and says when those bounds or an unavailable page leave some of the day unread. Only incoming messages in that day contribute sender names. The agent reads the original account and credential revision again before reporting any @@ -638,15 +640,23 @@ streamed and asks the agent to stop a turn by its room; the assistant also asks the agent to warm its model before the owner's first turn. The assistant (`apps/app/src/assistant/assistant.vibe`) lists conversations, reads a conversation's messages, forks one, searches messages, asks the agent's -health and which device steps it takes, and claims and reports assistant view -interactions (`apps/app/src/assistant/views.vibe`). Voice warms the cloud +health and status and which device steps it takes, and claims and reports assistant view +interactions (`apps/app/src/assistant/views.vibe`). The phone registers +and revokes itself as a client device, reads its device context, lists the +agent's device proposals, and decides, claims, sends the receipt for and +reconciles one. Voice warms the cloud connection (`apps/app/src/platform/voice.vibe`) and Messages requests reply -drafts (`apps/app/src/messages/composer.vibe`). Home and Calendar +drafts (`apps/app/src/messages/composer.vibe`). The page reads the agent's +notifications and marks one read. Home and Calendar (`apps/app/src/home/cards.vibe`, `apps/app/src/calendar/agent.vibe`, `apps/app/src/calendar/link.vibe`) read the calendar feed and the calendars, create, change, answer and delete events, and read and update linked calendar sync control, destinations and -event links through the calendar plugin. Workflows reads the owner identity, +event links through the calendar plugin. Clock reads and replaces its +state, creates, changes and deletes alarms and timers, snoozes and +dismisses alarms, and adds and deletes world clocks. Reminders reads its +state, creates, changes and deletes lists, and creates, changes, deletes, +completes, reopens, snoozes and restores items. Workflows reads the owner identity, active and removed workflows, prompts, scheduled tasks, definitions, execution and approval receipts. It sends the owner's exact-version approval, lifecycle and run decisions and reads back their outcomes. @@ -659,14 +669,18 @@ one query key, `clientId`, with the pinned provider's identifier pattern a page. Workflows sends reviewed schedule changes and acknowledges a retained page after storing it, using the final result's cursor and run ID. Notes reads the same owner identity and calls the Notes module to -read and edit notes, erase Trash and finish recording cleanup. The scanner +read and edit notes, erase Trash and finish recording cleanup, and the +local browser asks for a note's transcription as the next rule says. The scanner hands the owner’s reviewed scan text to Notes through that module. The approvals area lists the agent's proposals and resolves one through the approvals module. Ask Alpha completes a reviewed Messages read only for the exact owner turn after the agent acknowledges its device receipt. Wallet reads the wallet module's status, holdings, waiting requests and activity, makes and switches the wallet, asks for a transfer, and opens and -decides its review. Settings reads and updates Alpha's on-device local LLM +decides its review. Device control's overlay reads the control state, and +takes and stops a control lease. Settings reads and updates Alpha's on-device local LLM status, pinned model catalog, AI routing mode, active model, and model removal. +Memory searches the owner's memory, stores records and reports a Safari +action. Slack (`apps/app/src/slack/desk.vibe`) reads the owner's workspaces and whether sign-in is offered, starts a sign-in and hands back what the phone's consent hop returned, signs a workspace out, lists a section's @@ -681,8 +695,16 @@ chats by filter, folder and search, reads a chat's history and a current account or chat photo, searches messages, sends, edits, deletes, reacts, marks read, mutes, says which chat is in front, finds a person by name, and reads and approves or declines -the agent's proposals. Before an account write reaches Telegram's module, -the phone applies the module's request body limit in bytes. A route an area +the agent's proposals. The phone applies a request body limit in bytes +before each of these writes reaches the agent: +- control lease: 4096 +- control stop: 1024 +- each local-LLM mode, activate and delete request: 1024 +- memory records: 65536 +- Safari action: 4096 +- each Telegram account write: the Telegram module's own limit + +A route an area fakes for want of an agent plugin is not listed: none does today. Each line of `apps/agent/host/routes.jsonl` is one route; the pack is refused unless that list is this one, and eliza's route gate admits each of its routes. @@ -925,9 +947,11 @@ pure def routeListAdmitted(listed: List[Route]): bool = ### The local browser can request a private transcription of a reviewed note -A browser on the local machine can send a window of the reviewed recording to -a local transcription model. The agent does not offer the route when it is -running Alpha's native speech engine. A response contains only the recognized +The page's route list carries the transcription route for GET and POST, +and neither streams. A browser on the local machine can send a window of the +reviewed recording to a local transcription model. It is offered only for a +window that is not empty and is at most 1,100,000 bytes. The agent does not +offer the route when it is running Alpha's native speech engine. A response contains only the recognized text for that window. Nothing is published as a live voice event. ```quint diff --git a/spec/app/account/provider.md b/spec/app/account/provider.md index 928146d1f4..eac5057cc1 100644 --- a/spec/app/account/provider.md +++ b/spec/app/account/provider.md @@ -317,10 +317,13 @@ pure def sometimesAKeyReplacedBesideCloud(s: Provider): bool = s.text and s.mode > seeing what each sends, and to remove a key without Alpha quietly > sending my requests elsewhere. -A direct, whole request from the owner in Ask Alpha may choose local or -Alpha Cloud voice. It uses the same independent voice preference as Account -AI. Selecting Cloud reports the selection, and a signed-out owner still -needs to sign in before Cloud voice can be used. +From Account or from the assistant's card, the owner sees what a +provider sends before choosing it, and only a choice the owner confirmed +is carried out. This page models no choice between local and Cloud +voice: it knows only whether the owner's voice key is saved. A request in +Ask Alpha to use local or Cloud voice is the assistant's voice mode +command ([assistant](../assistant/index.md), "An explicit voice mode +command can answer on this phone"), and does not pass through this page. ### Choosing shows what that provider sends, from Account or from the assistant's card, and only a choice the owner confirmed for the provider as it is now is carried out diff --git a/spec/app/assistant/cards.md b/spec/app/assistant/cards.md index 05292f5e72..73c07c6051 100644 --- a/spec/app/assistant/cards.md +++ b/spec/app/assistant/cards.md @@ -100,12 +100,15 @@ pure def lawADrawnTurnAlwaysAnchorsItsReviewCard(offerReplyDrawn: bool, requestD ### At most one pending open-page review waits in a conversation, and asking for the same page again keeps its card -When a pending open-page review is already waiting in the conversation and -a later turn proposes the same canonical page (ignoring case, a leading -`www.`, or a trailing slash on the root path), the existing card stays in -place with a tap-Open prompt instead of adding a second card. When a later -turn proposes a different page, the newer review replaces the earlier -unanswered open-page card; a decision already in flight is never replaced. +When a pending open-page review is already waiting in the conversation, no +decision on it is in flight, and a later turn proposes the same canonical +page (ignoring case, a leading `www.`, or a trailing slash on the root +path), the existing card stays in place with a tap-Open prompt instead of +adding a second card. The shell decides whether two pages are the same. +When a later turn proposes a different page, the newer review replaces the +earlier unanswered open-page card. A card whose decision is already in +flight is never reused or replaced: a later proposal, even for the same +page, adds a card of its own. ```quint type PageReviewChoice = AddPageCard | ReusePageCard | ReplacePageCard diff --git a/spec/app/assistant/composer.md b/spec/app/assistant/composer.md index 11f977bdfa..f2145a15b9 100644 --- a/spec/app/assistant/composer.md +++ b/spec/app/assistant/composer.md @@ -534,9 +534,13 @@ it. A mark holds the message's text once. As the message leaves, Alpha keeps its send key beside the slot. Edits are saved as they are made, so a save is often on its way when the -owner presses Send. Send stays offered while one is, and is held as soon as -that save is answered, on the terms above as they then stand: a save in -flight never turns Send away, and the mark is never written over it. +owner presses Send. Send stays offered while one is, on the terms above as +if that save had landed: a save in flight never turns Send away by itself. +The message is never held while the save is on its way, so the mark is never +written over it. A Send pressed meanwhile is kept by the screen, not the +composer, which asks to hold the message once that save is answered; it is +held only if the terms above then allow it, so a save that comes back as a +second copy, or with storage failing, leaves the message in the composer. ```quint pure def content(m: Message): bool = m.text or attachments(m) > 0 diff --git a/spec/app/assistant/context.md b/spec/app/assistant/context.md index 08a2d592a4..abdb4de8a9 100644 --- a/spec/app/assistant/context.md +++ b/spec/app/assistant/context.md @@ -484,11 +484,13 @@ pure def lawAPageBrowserWithheldIsNeverSent(peer: Peer): bool = not(sendsPage(tr ### A turn describes the view in front by its labeled controls and visible text, never a sensitive or withheld view, a secret field, the assistant's own chat or a review card -Every told turn, typed or spoken, from Home and from every view, carries a +Every told turn, typed or spoken, from Home and from every view, sent to an +agent that said, on this connection, that it takes the screen, carries a description of what the view in front draws as the turn is sent, beside the observation and bound to its view and revision (eliza's turn context, `spec/agent/conversation/turnContext.md` there, has -its form and bounds). Alpha reads it from the view's own accessibility tree, with no code +its form and bounds); an agent that does not take the screen gets no +description. Alpha reads it from the view's own accessibility tree, with no code of the view's own: each control a person could press or fill, by its role (button, field, toggle, tab, link or option) and its accessible name (its `aria-label`, the element that labels it, its `