Device mutation journal and baseline reset contract¶
Delivery boundary¶
The journal (#14359, under #14358) defines the contract, persistence, planning and tool recording. It does not gate keep-booted reset admission; iOS (#14361) and Android (#14364) own platform cleaning and reset wiring.
DEVICE_MUTATION_TOOL_COVERAGE assigns every control tool one status:
journaled (production dispatch attempts record-before-act), pending-adapter
(no production adapter yet), notJournaled (intentional host-only or transient
UI/prompt exemption). Pending/exempt entries carry reasons; a registry
enumeration test (including mixed, hidden and SDK tools) rejects a new control
tool without a justification. Neither pending-adapter nor notJournaled implies
journaling.
- Journaled data/provider adapters include
setKeyValue,removeKeyValue,clearKeyValueFile,setPreference,sqlQuery,mockNetwork,clearMockNetwork,sendSms,phoneCall,resetAppLogs,deviceSnapshot. - Appearance adapters journal
statusBaroverrides and AndroidmanufacturerProfileapplication. Keyboard-only personas recordkeyboard:profile; kill/display facets also record a fallback opaque intent because their in-memory restore receipts bypass the recorded dispatcher. Missing or unknown persona ids defensively record fallback intent too; the tool schema enum normally rejects them. Intent is recorded before the handler runs, so anapplylater refused (for exampleroute_to_real_device) still falls back; this is an accepted cost. - Recording and reset use one typed
mutationIncarnationconstructor. Android uses[resourceId, stableDeviceId, bootId]; iOS retains[scopeKey, allocationIndex, stableDeviceId]. Android binds an interim null boot ID at readiness, then rebinds the recorder with the captured boot ID before applying the device profile. Session UUIDs isolate successive session rows. - Reset checks for journal rows from the same device and session under different incarnations and fails closed, including legacy Android generation-shaped rows. No migration is needed: daemon restart loses the Android in-memory baseline and already fails closed; resource retirement prunes old tuples by element zero.
Keep-booted baseline cleaning is on its own page:
Identity and persistence¶
SqliteBindingRegistry.deviceMutationJournal() shares the host registry SQLite
connection. Migration 2026_10_21_012_device_mutation_journal adds
device_mutation_journal and device_mutation_baselines to the store’s static
migration set (not the per-daemon database migrations).
- Identity is
(sessionUuid, deviceId, incarnation). The incarnation must be a durable native resource generation that survives restarts and changes when the device is replaced; a process-local counter or reusable serial is insufficient. Sessions of one incarnation share baselines; a replacement never shares them. applyJournaledMutationis a standalone helper with no production dispatch caller. First write per(scope, kind, key)wins.appliedAtstamps intent, not device acknowledgement. SQLite’s sequence gives deterministic reverse order regardless of clock. Failed/ambiguous mutations keep their intent so recovery can retry.- Prior value is a tagged JSON value:
{ state: "absent" }is distinct from JSON null and the string"absent". Unknown kinds stay durable and are non-revertible in the planner (schema evolution must not discard them).
Platform port obligations¶
DeviceMutationResetPort.canRevertqualifies kind, key and prior payload.revertsets the original absolute state, tolerates already-absent resources, and is idempotent on replay. Compound priors may carry app-group identities or legacy restore metadata; adapters preserve platform-required ordering inside a step and may map steps to apply/verify/revert profiles (#14067). The contract contains no platform commands.- Every device I/O dispatch awaits
context.assertOwned()immediately before acting and honorscontext.signal, including after queued or delayed awaits. The runner checks ownership before each phase/step and after verification, and enforces one total budget via the injected Timer and an abort signal. A timeout does not stop an uncancellable native command: the adapter must fence or drain it before physical reuse. - Keep-booted bounds journal capture to the 30 s cleaning budget (or remaining preparation deadline if shorter); other strategies and fallback capture get the remaining preparation deadline. Fallback has its own budget and abort signal. After timeout/cancel the owner awaits cleaning/fallback settlement with a separate 2 s drain; an adapter that never settles exhausts it and fails without starting snapshot fallback, permitting destruction. Resource pruning is best-effort: database failures warn without retaining in-memory sessions or skipping teardown.
- The standalone runner returns
non_cleanfor unknown kinds, incomplete state, missing baselines, ownership failures, timeout, failed writes or failed readback. It is not a keep-booted gate and does not replace or prevent platform cleaning.
Baseline capture and verification¶
Capture with captureFirstDeviceBaseline under the reset ownership fence before the
first session uses a newly admitted pool device; first-write-wins, never replacing a
trusted baseline with an already-mutated device’s state. Callers bound initial
capture like other admission work.
- A snapshot holds
(kind, key, value)observations,completeKinds, and explicitunobservablereasons. A complete inventory is exhaustive (omitted key = absent, not unknown). For the standalone runner everyDEVICE_MUTATION_KINDSentry must be complete or explicitly unobservable; omission, missing/changing inventories, duplicate keys and unobservable state prevent its certification even when values match. Apart from the Android time zone, locale and account checks above, none of this gates or forces fallback in keep-booted resets. - Complete device settings cover all default-setting keys plus locale/appearance. Adapters must report blind spots (app data/containers, changes induced by UI, raw commands or the app under test) rather than call a partial scan complete; a cheap snapshot is not a complete erase substitute.
- The diff detects changes outside the tool surface. Only an app absent from the
baseline and an originally empty clipboard have generic revert rules (still
needing a qualified port); all other unjournaled changes are dirty. Journal
entries replay in reverse durable order, then generic steps; the standalone runner
returns
cleanonly when a fresh authoritative snapshot equals the baseline (a write receipt is not enough).
Legacy adapters and remaining wiring¶
importLegacySessionMutationsimports the six legacy cache restore payloads without clearing slots. The iOS network payload keeps the app rule’s owner-generation/revision metadata; its adapter must allocate a newer reset revision via the provider protocol, not replay an old one. Import is terminal-only: callers stop admission, drain session mutations and provideassertQuiescedunder the lifecycle fence, awaited before snapshotting and before every write. A conflicting reimport throws rather than keep stale metadata in a first-write-wins row. It is not a live write-through adapter or a gate.- Legacy-restorer import is not implemented. Shared
devicekeys hold incompatible values (tool clock priors{ instant, automaticTime }vsClockSessionState{ initialAutomaticTime, clockChangedByUs, rootedByUs }; tool network priorsvalues ?? observedValues ?? profilevs{ initialProfile, iosAppRule }). Those values would fail the deep-equality check, and a captured clock instant ages before restore. JournalDeviceSettingDefaultsPersistencewraps the defaults store: broker writes first record setting originals and broker reads use the journal’s first value; a null broker scope delegates unchanged. Legacy null (unset) maps toabsent. Legacy records stay for retry/next-acquisition behavior; legacy deletion does not remove journal data. The defaults service still swallows some persistence failures (legacy best-effort), while broker tool execution separately warns and proceeds on journal failure.- These adapters are opt-in and not wired into the session manager or tool handlers, so non-broker release is unchanged. Setup writes, readiness side effects, seeders, direct shell commands and pending adapters are incomplete journal coverage, not reuse prerequisites.
- Keep entries through interrupted/failed resets and final clean publication. Only
the reset owner calls
deleteSession, after verified cleanup and fenced broker settlement. Retirement pruning of baselines/journals and per-session recorder rows has no fenced native retirement owner here; pruning during capture could delete recovery state for an active incarnation. Baseline and prior payloads may contain sensitive device data: never log or report them.
Tool-surface recovery and compatibility¶
Data stores
- Identities keep app, store, Android user selector and key; set/remove and
name/fileNamealiases share a first-write identity. On iOS, key-value standard-store aliases (empty name, case-insensitivestandard, bundle ID) and UserDefaults standard-suite aliases (omitted suite,Standard) share one. Android omitted vs explicituserIdare not merged (default user is resolved dynamically, not necessarily 0). Identities are not merged across tools:setKeyValueandsetPreferenceon the same file get separate rows, so a future restorer must not assume otherwise. Store clearing records observed entries under a separate whole-store key. - Key-value priors use a connected SDK’s storage read path (encoded value and type
preserved). Missing key =
absent; an empty store ispresentwith no entries, not proof the file was absent. Unconnected providers, redacted/unknown entries and explicitly user-scoped Android calls recordunobservable. Preference priors reuseAppPreferences.getPreference(value, type, resolved user/store); redacted, lossy or possibly stale container-plist reads areunobservable. Read failures warn and still record intent. - SQL uses the read-only classifier: proven reads do not journal; mutations and unproven statements record opaque intent (no inferred inverse). Network mocks share a non-fallback opaque breadcrumb: NetworkState owns the rules, and session release clears them and pushes the cleared set to the device. Android and iOS SDK rule stores use process memory only, so reset’s reboot/app termination drops them. Accepted residual, not a journal concern: a release-time cleared-state push that fails, times out or is skipped while an SDK app keeps running leaves stale rules until the next sync or app restart. This is best-effort cleanup, the same class as every session-release cleanup. Telephony, log deletion (including rotated siblings) and snapshot restore record fallback opaque intent; snapshot capture/delete retain diagnostic opaque rows. None implement restorers or change cleaning; unreadable priors never block the action.
Other tools
- Journaled non-read calls with an empty adapter result record opaque
unobservableintent. ThescreenLockaction can capture an unsecured baseline but not an existing secure credential, so it recordsunobservablewithout storing secrets. Thepowertool recordsunobservablebecause its restore registry (restoreReceipt,powerRestore) owns the priors. Prior reads are skipped when the scoped(kind, key)already exists (one journal list per call). Rotation and screen-reader keys usedevice, matching legacy adapters; iOS rotation recordsunobservablerather than invent portrait or read Android orientation. - Keyboard open/close and biometric match/fail/cancel/error are
notJournaledtransient UI. KeyboardsetProfilepersists typing policy and records thelistProfilesactive profile underkeyboard:profile(orunobservable);tapImeKeyrecords opaqueunobservablesince a failed IME restore can leave the device switched. Selecting an installed IME and changing enrollment stay journaled. - Install intents resolve the artifact’s package/bundle identifier via the existing
metadata readers. In this slice
installed-apppriors needing an incarnation baseline areunobservable(recorder scope does not match baseline/reset scope); unknown metadata or incomplete inventory also recordsunobservable, never blocking install or cleaning. Install and uninstall keys share the baseline app identity when metadata is readable.
Recovery
- Uses the registry’s unique session-id index, not an all-receipts scan. Startup warns and continues for an unrecoverable session, marking a recording gap so its later mutations run unrecorded but its next keep-booted reset falls back. A fatal startup error closes the broker before releasing the host lock. A rebound session discards its old recorder and resolves the new native assignment before the next mutation.
- Derived-label sessions resolve their own recorder first (live session, then broker recovery). Without one, they resolve the base recorder the same way and use it only on the base’s device; journal writes and gaps belong to that base UUID. When the base recorder resolves to a different device, the call needs no recording and no gap. Resolution must recover the base to learn its device, so failed base recovery still marks a gap on the base UUID even if the derived call lands on another device. This is deliberate fail-closed over-escalation.
recoverSessionMutationRecorderreturning undefined for an active request with no live session is safe: the next call from the rehydrated session recovers again.
Schema compatibility: the unobservable tag is a compatibility boundary within
the current registry schema version: older daemons that accept the migration but not
the tag fail closed when listing those rows. Upgrade all daemons sharing a host
registry before new writers run; never discard or reinterpret an unknown prior as
absent. Migration 012 itself advances the boundary, so an older daemon refuses the
upgraded store; do not weaken the unsupported-schema check.