LifeMate — Personal, Family & Learning Companion

test/personal-notification-settings
chore/phase1-repository-cleanup deploy/stable-web-apk deployment-static design/mobile-accessibility-v2 design/mobile-navigation-review docs/child-education-access-decision docs/offline-data-rescue-options docs/owner-guide-and-delivery-plan docs/phase1-policy-options docs/public-review-live-2026-10-15 feat/aparat-learning-library feat/child-device-safety feat/child-identity-schema feat/flutter-mobile-navigation feat/learning-content-operations feat/local-signing-preflight feat/online-family-stage0 feat/personal-encrypted-recovery feat/private-planner-series-api feat/public-review-page feat/standalone-weekly-planner feat/weekly-planner-android final-feature-1/iran-family-school fix/auth-abuse-expiry-safety fix/auth-expiry-after-lock fix/backend-request-safety fix/lifeguide-bootstrap-naming-ci fix/lifeguide-pages-qa-base-preflight fix/lifeguide-qa-pages-env-deployment fix/local-task-persistence fix/managed-child-session-boundary fix/personal-jalali-dates fix/personal-notification-controls fix/personal-upgrade-delivery-guard fix/sms-approval-gates fix/study-duration-display infra/cloudflare-neon-migration infra/lifeguide-cloudflare-qa infra/lifeguide-github-pages-qa infra/lifeguide-supabase-qa main phase-1/foundation-completion phase-2/product-foundation-identity phase-3/planner-school-family-core phase-4/ai-learning-wellbeing phase-5/hardening-observability-release test/android-reminder-acceptance test/personal-notification-settings test/personal-recovery-acceptance test/role-entry-apk
py 584 lines 30.9 KB
Raw
1 #!/usr/bin/env python3
2 """Bounded, synthetic acceptance of the real device-only SQLite/Android path.
3
4 Only a fresh API35 SDK emulator is accepted. Install the deliverable first and
5 capture its ordinary onboarding launch, then upgrade that owned install to the
6 separately built, never-distributed fixture with the identical certificate.
7 No uninstall, data clearing, force-stop, or network service is used.
8 """
9 import argparse
10 import hashlib
11 import json
12 import os
13 import re
14 import secrets
15 import shutil
16 import struct
17 import subprocess
18 import time
19 import uuid
20 import xml.etree.ElementTree as ET
21 from pathlib import Path
22
23 # Reuse transport and the strict serial boundary without changing the online
24 # acceptance tool's fixed application identity or its regression tests.
25 from test_native_reminders_android import Adb, AcceptanceError, require, validate_serial
26
27 PACKAGE = "ir.lifeguide.app.device"
28 COMPONENT = PACKAGE + "/ir.lifeguide.app.MainActivity"
29 LABEL = "لایف‌گاید شخصی"
30 SCOPE = "device-planner:v1:11111111-1111-4111-8111-111111111111"
31 DATABASE = "standalone_acceptance.sqlite"
32 COMPANION = "LifeGuide EMULATOR FIXTURE"
33 GENERIC_BODY = "برای دیدن برنامهٔ شخصی، لایف‌گاید را باز کنید."
34 CHANNEL = "lifeguide_personal_plan_v1"
35 CANARY = "SYNTHETIC_PRIVATE_TASK_CANARY"
36 MARKER = "LG_STANDALONE_ACCEPTANCE "
37 MODES = {"seed", "inspect", "change", "cancel", "off", "settings"}
38 CHECKS = {"rawSqlAfterClose", "profilePersists", "weeklyDifferentTimes",
39 "onceAndEveryTwoDays", "independentEditAndTick", "archivePersists"}
40 PREFERENCES = "shared_prefs/lifeguide_local_reminders_v1.xml"
41 UUID = r"[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}"
42 PID_QUERY = ("pids=$(pidof " + PACKAGE + "); code=$?; "
43 "if [ \"$code\" -eq 0 ] && [ -n \"$pids\" ]; then printf PRESENT; "
44 "elif [ \"$code\" -eq 1 ] && [ -z \"$pids\" ]; then printf ABSENT; "
45 "else exit 2; fi")
46 LIMITATIONS = {name: "UNVERIFIED" for name in (
47 "physicalDevice", "reboot", "Doze", "soundOrVibration", "permissionConsentUI",
48 "Safari", "signedRelease", "onlineFamilyOrSynchronization")}
49
50
51 def _positive(value):
52 return type(value) is int and value > 0
53
54
55 def manifest_check(apk):
56 # Kept lazy so host safety tests need no APK inspection/build dependency.
57 from check_standalone_apk import check
58 return check(apk)
59
60
61 def certificate_digest(apk):
62 signer = shutil.which("apksigner")
63 if signer is None:
64 for key in ("ANDROID_HOME", "ANDROID_SDK_ROOT"):
65 root = os.environ.get(key)
66 if root:
67 choices = sorted((Path(root) / "build-tools").glob("*/apksigner"))
68 if choices:
69 signer = str(choices[-1])
70 break
71 require(signer is not None, "apksigner_required")
72 try:
73 result = subprocess.run([signer, "verify", "--print-certs", str(apk)],
74 capture_output=True, text=True, timeout=30, check=False)
75 values = re.findall(r"(?m)^(?:Signer #\d+|V[1-4](?:\.\d+)? Signer:) certificate SHA-256 digest: ([0-9a-fA-F]{64})\s*$", result.stdout)
76 require(result.returncode == 0 and len(values) == 1, "apk_signature_rejected")
77 return values[0].lower()
78 except (OSError, subprocess.SubprocessError):
79 raise AcceptanceError("apk_signature_rejected") from None
80
81
82 def fixture_marker(line, nonce, mode):
83 require(re.fullmatch(r"[0-9a-f]{8,32}", nonce) is not None and mode in MODES,
84 "invalid_fixture_request")
85 if MARKER not in line:
86 return None
87 raw = line.split(MARKER, 1)[1]
88 try:
89 marker = json.loads(raw)
90 except ValueError:
91 if nonce in raw:
92 raise AcceptanceError("invalid_fixture_marker") from None
93 return None
94 if not isinstance(marker, dict) or marker.get("nonce") != nonce:
95 return None
96 require(marker.get("mode") == mode and marker.get("syntheticDataOnly") is True
97 and marker.get("database") == DATABASE, "invalid_fixture_marker")
98 status = marker.get("status")
99 required = {"supported", "permissionGranted", "active", "activeScope", "enabled",
100 "scheduledCount", "timing", "canScheduleExactAlarms"}
101 require(isinstance(status, dict) and required <= set(status), "invalid_fixture_status")
102 require(status["supported"] is True and
103 all(type(status[k]) is bool for k in ("permissionGranted", "active", "enabled", "canScheduleExactAlarms"))
104 and type(status["scheduledCount"]) is int and status["scheduledCount"] in (0, 1)
105 and status["timing"] in ("exact", "approximate")
106 and status["canScheduleExactAlarms"] == (status["timing"] == "exact")
107 and (re.fullmatch("device-planner:v1:" + UUID, status["activeScope"] or "") is not None
108 if status["active"] else status["activeScope"] is None)
109 and (status["active"] or status["scheduledCount"] == 0), "invalid_fixture_status")
110 checks = marker.get("checks")
111 require(isinstance(checks, dict) and all(type(checks.get(k)) is bool for k in CHECKS & checks.keys()),
112 "invalid_fixture_database_checks")
113 clean = {"nonce": nonce, "mode": mode, "syntheticDataOnly": True,
114 "database": DATABASE, "status": {k: status[k] for k in sorted(required)},
115 "checks": {k: checks[k] for k in sorted(CHECKS & checks.keys())}}
116 if "scheduledAtEpochMs" in marker:
117 require(mode in ("seed", "change") and _positive(marker["scheduledAtEpochMs"]),
118 "invalid_fixture_deadline")
119 clean["scheduledAtEpochMs"] = marker["scheduledAtEpochMs"]
120 return clean
121
122
123 def active_fixture_keys(output):
124 keys = []
125 for line in output.splitlines():
126 key = line.strip()
127 pieces = key.split("|")
128 if len(pieces) < 2 or pieces[1] != PACKAGE:
129 continue
130 require(len(pieces) == 5 and pieces[0] == "0" and pieces[2] == "1" and
131 re.fullmatch("lifeguide-plan:" + UUID, pieces[3]) is not None and
132 re.fullmatch(r"[0-9]+", pieces[4]) is not None and key not in keys,
133 "unexpected_fixture_notification")
134 keys.append(key)
135 require(len(keys) <= 1, "unexpected_fixture_notification")
136 return keys
137
138
139 def _settings_hierarchy(output):
140 if not isinstance(output, str) or len(output) > 65536 or '<!' in output:
141 return None
142 if output.count('<hierarchy') != 1 or output.count('</hierarchy>') != 1:
143 return None
144 start, end = output.index('<hierarchy'), output.index('</hierarchy>')
145 try:
146 root = ET.fromstring(output[start:end + len('</hierarchy>')])
147 except ET.ParseError:
148 return None
149 return root if root.tag == 'hierarchy' else None
150
151
152 def notification_settings_summary(output):
153 """Booleans/counts only; never publish arbitrary UI labels or XML."""
154 root = _settings_hierarchy(output)
155 nodes = list(root.iter('node')) if root is not None else []
156 return {
157 'outputChars': min(len(output), 65537) if isinstance(output, str) else 0,
158 'validHierarchy': root is not None,
159 'systemSettingsNodePresent': any(n.get('package') == 'com.android.settings' for n in nodes),
160 'channelTitlePresent': any(n.get('text') == 'یادآوری برنامهٔ شخصی' for n in nodes),
161 'verified': any(
162 node.get('package') == 'com.android.settings' and
163 node.get('text') == 'یادآوری برنامهٔ شخصی'
164 for node in nodes)}
165
166
167 def notification_settings_visible(output):
168 """Keep the strict same-node system-package/fixed-channel assertion."""
169 return notification_settings_summary(output)['verified']
170
171
172 def check_notification_record(dump, key):
173 require(active_fixture_keys(key) == [key], "invalid_fixture_notification_key")
174 records = re.split(r"(?m)(?=^[ \t]*NotificationRecord\()", dump)
175 matches = [r for r in records if
176 re.search(r"\bkey=" + re.escape(key) + r"(?=[\s):])", r) and
177 re.search(r"\bpkg=" + re.escape(PACKAGE) + r"(?=[\s)])", r)]
178 require(len(matches) == 1, "fixture_notification_record_missing_or_ambiguous")
179 record = matches[0]
180 titles = re.findall(r"android\.title=String \(([^\n]*)\)", record)
181 bodies = re.findall(r"android\.text=String \(([^\n]*)\)", record)
182 # Android dumps the private notification first and then its publicVersion.
183 # The latter deliberately uses the product name on the lock screen.
184 require(bool(titles) and titles[0] == COMPANION and
185 all(t == "LifeGuide" for t in titles[1:]), "fixture_notification_title_mismatch")
186 require(bool(bodies) and all(b == GENERIC_BODY for b in bodies), "fixture_notification_body_mismatch")
187 require(CANARY not in record, "fixture_notification_contains_private_canary")
188 require(re.search(r"(?:channel=|mId=['\"]?)" + re.escape(CHANNEL) + r"(?=['\"\s,)])", record),
189 "fixture_notification_channel_mismatch")
190 return {"titleMatches": True, "genericBodyMatches": True, "privateCanaryAbsent": True}
191
192
193 def parse_preferences(xml, *, expected_scope=None):
194 """Validate the isolated synthetic native state, never publish raw XML."""
195 try:
196 require(len(xml) <= 32768 and "<!" not in xml, "unexpected_fixture_preferences")
197 root = ET.fromstring(xml)
198 require(root.tag == "map" and not root.attrib, "unexpected_fixture_preferences")
199 if len(root) == 0:
200 return None
201 require(len(root) == 1 and root[0].tag == "string" and
202 root[0].attrib == {"name": "active"} and len(root[0]) == 0, "unexpected_fixture_preferences")
203 state = json.loads(root[0].text or "")
204 require(isinstance(state, dict) and set(state) <= {
205 "scope", "generation", "issuedAtEpochMs", "validUntilEpochMs", "reminders", "deliveryExpired", "leaseKind"}
206 and re.fullmatch("device-planner:v1:" + UUID, state.get("scope", "")) is not None
207 and (expected_scope is None or state["scope"] == expected_scope)
208 and str(uuid.UUID(state["generation"], version=4)) == state["generation"]
209 and _positive(state.get("issuedAtEpochMs")) and _positive(state.get("validUntilEpochMs"))
210 and 0 < state["validUntilEpochMs"] - state["issuedAtEpochMs"] <= 31 * 86400000
211 and state.get("leaseKind") == "device-planner-v1"
212 and isinstance(state.get("reminders"), list) and len(state["reminders"]) <= 1,
213 "unexpected_fixture_preferences")
214 if "deliveryExpired" in state:
215 require(type(state["deliveryExpired"]) is bool, "unexpected_fixture_preferences")
216 for row in state["reminders"]:
217 require(isinstance(row, dict) and set(row) <= {
218 "id", "planItemId", "scheduledAtEpochMs", "companionName", "delivered"}
219 and re.fullmatch(UUID, row.get("id", "")) is not None
220 and re.fullmatch(UUID, row.get("planItemId", "")) is not None
221 and row.get("companionName") == COMPANION and _positive(row.get("scheduledAtEpochMs"))
222 and state["issuedAtEpochMs"] < row["scheduledAtEpochMs"] <= state["validUntilEpochMs"]
223 and type(row.get("delivered", False)) is bool, "unexpected_fixture_preferences")
224 return state
225 except (ET.ParseError, ValueError, TypeError, KeyError, AttributeError):
226 raise AcceptanceError("unexpected_fixture_preferences") from None
227
228
229 class Harness:
230 def __init__(self, *, serial, user_apk, fixture_apk, allow_reset, screenshot,
231 adb=None, manifest_check=manifest_check, certificate_check=certificate_digest,
232 clock=time.monotonic, sleep=time.sleep):
233 self.serial, self.user_apk, self.fixture_apk = serial, Path(user_apk), Path(fixture_apk)
234 self.allow_reset, self.screenshot = allow_reset, Path(screenshot)
235 self.adb, self.manifest_check, self.certificate_check = adb, manifest_check, certificate_check
236 self.clock, self.sleep = clock, sleep
237 self.installed = self.user_launched = self.fixture_installed = False
238 self.scope = None
239 self.receipt = {"schemaVersion": 1, "result": "FAIL", "syntheticDataOnly": True,
240 "scope": "fresh API35 emulator; actual isolated SQLite and native notification",
241 "currentPhase": "preflight", "limitations": LIMITATIONS.copy(), "checks": {}}
242
243 def install_user(self):
244 validate_serial(self.serial)
245 require(self.allow_reset is True, "synthetic_emulator_reset_flag_required")
246 require(self.user_apk.is_file() and self.fixture_apk.is_file(), "two_apk_files_required")
247 manifests, certificates = [], []
248 for apk in (self.user_apk, self.fixture_apk):
249 try:
250 report = self.manifest_check(apk)
251 require(isinstance(report, dict) and report.get("result") == "PASS" and
252 report.get("package") == PACKAGE and report.get("label") == LABEL and
253 report.get("debuggable") is True and report.get("internetPermission") is False and
254 report.get("targetSdkVersion") == 36 and
255 re.fullmatch(r"[0-9a-f]{64}", report.get("sha256", "")) is not None,
256 "apk_manifest_rejected")
257 certificate = self.certificate_check(apk)
258 require(re.fullmatch(r"[0-9a-f]{64}", certificate or "") is not None, "apk_signature_rejected")
259 except AcceptanceError:
260 raise
261 except Exception:
262 raise AcceptanceError("apk_manifest_rejected") from None
263 manifests.append(report)
264 certificates.append(certificate)
265 require(certificates[0] == certificates[1], "apk_certificates_differ")
266 if self.adb is None:
267 self.adb = Adb(self.serial)
268 require(self.adb.command("get-state").strip() == "device", "emulator_not_ready")
269 kernel = self.adb.shell("getprop", "ro.kernel.qemu").strip()
270 boot = self.adb.shell("getprop", "ro.boot.qemu").strip()
271 require("1" in (kernel, boot), "qemu_emulator_required")
272 require(self.adb.shell("getprop", "ro.hardware").strip() in ("ranchu", "goldfish"), "android_emulator_hardware_required")
273 require(re.fullmatch(r"sdk_(?:gphone|phone)[A-Za-z0-9_]*",
274 self.adb.shell("getprop", "ro.product.name").strip()) is not None, "synthetic_sdk_product_required")
275 require(self.adb.shell("getprop", "ro.build.version.sdk").strip() == "35", "api_35_required")
276 require(not self.adb.shell("pm", "list", "packages", PACKAGE).strip(), "fresh_emulator_required_package_already_present")
277 output = self.adb.command("install", str(self.user_apk))
278 require("Success" in output.splitlines() and "Failure" not in output and "Error" not in output,
279 "user_apk_install_failed")
280 self.installed = True
281 self.receipt["apks"] = {role: {name: report[name] for name in (
282 "sha256", "package", "label", "debuggable", "internetPermission", "targetSdkVersion")}
283 for role, report in zip(("user", "fixtureNeverDistribute"), manifests)}
284 self.receipt["certificateSha256"] = certificates[0]
285 self.receipt["checks"]["emulatorAndFreshInstallGates"] = "PASS"
286
287 def _ready(self):
288 require(self.installed, "package_not_installed_by_this_runner")
289
290 def process_state(self):
291 self._ready()
292 state = self.adb.shell("sh", "-c", PID_QUERY).strip()
293 require(state in ("PRESENT", "ABSENT"), "fixture_process_query_failed")
294 return state
295
296 def process_dead(self, *, before=None):
297 self._ready()
298 self.receipt.pop("processExit", None)
299 self.adb.shell("input", "keyevent", "KEYCODE_HOME")
300 until, attempts = self.clock() + 10, 0
301 while True:
302 self.adb.shell("am", "kill", PACKAGE)
303 attempts += 1
304 state = self.process_state()
305 self.receipt["lastProcessState"] = state
306 if state == "ABSENT":
307 if before is not None:
308 require(self.device_epoch_ms() + 1000 < before, "process_absence_missed_alarm_deadline")
309 self.receipt["processExit"] = {"confirmedAbsent": True, "ordinaryKillAttempts": attempts}
310 return
311 require(self.clock() < until, "fixture_process_did_not_exit")
312 self.sleep(0.25)
313
314 def first_user_launch(self):
315 self._ready()
316 require(not self.fixture_installed, "fixture_cannot_prove_user_first_launch")
317 self.receipt["currentPhase"] = "user_first_launch"
318 output = self.adb.shell("am", "start", "-W", "-f", "0x10008000", "-n", COMPONENT)
319 require("Error" not in output and "Exception" not in output, "user_activity_launch_failed")
320 self.sleep(3)
321 require(self.process_state() == "PRESENT", "user_first_launch_process_not_alive")
322 # No UI interaction or profile creation occurs before this screenshot.
323 try:
324 result = subprocess.run(["adb", "-s", self.serial, "exec-out", "screencap", "-p"],
325 capture_output=True, timeout=30, check=False)
326 png = result.stdout
327 require(result.returncode == 0 and 24 <= len(png) <= 16 * 1024 * 1024 and
328 png[:8] == b"\x89PNG\r\n\x1a\n" and png[12:16] == b"IHDR", "user_screenshot_failed")
329 width, height = struct.unpack(">II", png[16:24])
330 require(100 <= width <= 4096 and 100 <= height <= 4096, "user_screenshot_failed")
331 self.screenshot.parent.mkdir(parents=True, exist_ok=True)
332 self.screenshot.write_bytes(png)
333 except (OSError, subprocess.SubprocessError):
334 raise AcceptanceError("user_screenshot_failed") from None
335 ui = self.adb.shell("uiautomator", "dump", "/dev/tty", allow_failure=True)
336 require(not any(text in ui for text in ("https://", "http://", "نشانی API", "آدرس API")),
337 "user_launch_url_prompt_detected")
338 self.receipt["userFirstLaunch"] = {"processAlive": True,
339 "ordinaryLaunchNoExtras": True, "screenshotSha256": hashlib.sha256(png).hexdigest(),
340 "screenshotFile": self.screenshot.name, "urlPromptDetected": False,
341 "localWelcomeText": "PASS" if "جای کوچکی برای برنامه‌های تو" in ui else "UNVERIFIED"}
342 self.user_launched = True
343 self.receipt["checks"]["actualUserApkFirstLaunchScreenshot"] = "PASS"
344
345 def install_fixture(self):
346 self._ready()
347 require(self.user_launched, "user_first_launch_not_verified")
348 require(not self.fixture_installed, "fixture_already_installed")
349 self.process_dead()
350 output = self.adb.command("install", "-r", str(self.fixture_apk))
351 require("Success" in output.splitlines() and "Failure" not in output and "Error" not in output,
352 "owned_fixture_upgrade_failed")
353 self.fixture_installed = True
354 self.adb.shell("pm", "grant", PACKAGE, "android.permission.POST_NOTIFICATIONS")
355 self.adb.shell("cmd", "appops", "set", PACKAGE, "SCHEDULE_EXACT_ALARM", "allow")
356 self.receipt["checks"]["ownedFreshInstallFixtureUpgrade"] = "PASS"
357
358 def launch(self, mode):
359 require(self.fixture_installed and mode in MODES, "fixture_not_ready")
360 self.receipt["currentPhase"] = "before_launch_" + mode
361 self.process_dead()
362 nonce = secrets.token_hex(8)
363 route = "/" + mode + "?nonce=" + nonce
364 output = self.adb.shell("am", "start", "-W", "-f", "0x10008000",
365 "-n", COMPONENT, "--es", "route", route)
366 require("Error" not in output and "Exception" not in output, "fixture_activity_launch_failed")
367 self.receipt["currentPhase"] = "waiting_" + mode + "_marker"
368 until = self.clock() + 30
369 while True:
370 logs = self.adb.command("logcat", "-d", "-v", "brief", "-s", "flutter:I")
371 for line in logs.splitlines():
372 marker = fixture_marker(line, nonce, mode)
373 if marker is not None:
374 self.receipt["currentPhase"] = "after_" + mode + "_marker"
375 return marker
376 require(self.clock() < until, "fixture_marker_timeout")
377 self.sleep(0.5)
378
379 def device_epoch_ms(self):
380 value = self.adb.shell("date", "+%s").strip()
381 require(re.fullmatch(r"[0-9]{10,}", value) is not None, "emulator_clock_unavailable")
382 return int(value) * 1000
383
384 def align_to_minute(self):
385 # Product records have minute precision. At second 10..15, the next
386 # whole minute is genuinely 45..50 seconds away, without a test clock.
387 until = self.clock() + 65
388 while True:
389 second = self.device_epoch_ms() // 1000 % 60
390 if 10 <= second <= 15:
391 return
392 require(self.clock() < until, "emulator_clock_alignment_timeout")
393 self.sleep(min(1, (70 - second) % 60 or 1))
394
395 def preferences(self):
396 script = "if [ -f " + PREFERENCES + " ]; then cat " + PREFERENCES + "; else printf '<map/>'; fi"
397 return parse_preferences(self.adb.shell("run-as", PACKAGE, "sh", "-c", script), expected_scope=self.scope)
398
399 def active_keys(self):
400 return active_fixture_keys(self.adb.shell("cmd", "notification", "list"))
401
402 def assert_status(self, marker, *, active, count):
403 status = marker["status"]
404 require(status["permissionGranted"] is True and status["active"] is active and
405 status["enabled"] is active and
406 status["scheduledCount"] == count and status["timing"] == "exact" and
407 status["canScheduleExactAlarms"] is True, "fixture_status_assertion_failed")
408 if active:
409 if self.scope is None:
410 self.scope = status["activeScope"]
411 require(status["activeScope"] == self.scope, "fixture_scope_changed")
412
413 def assert_database(self, marker, names):
414 require(all(marker["checks"].get(name) is True for name in names), "real_sqlite_assertion_failed")
415 for name in names:
416 self.receipt["checks"][name] = "PASS"
417
418 def assert_scheduled(self, marker):
419 self.assert_status(marker, active=True, count=1)
420 at = marker.get("scheduledAtEpochMs")
421 require(_positive(at) and 30000 < at - self.device_epoch_ms() <= 55000,
422 "real_record_not_near_45_seconds")
423 state = self.preferences()
424 require(state is not None and len(state["reminders"]) == 1 and
425 state["reminders"][0]["scheduledAtEpochMs"] == at and
426 not state["reminders"][0].get("delivered", False), "real_record_schedule_not_persisted")
427 require(not self.active_keys(), "unexpected_fixture_notification_before_deadline")
428 return at, state
429
430 def wait_for_post(self, at):
431 until = self.clock() + max(0, (at - self.device_epoch_ms()) / 1000) + 30
432 while True:
433 keys = self.active_keys()
434 if keys:
435 require(self.device_epoch_ms() + 1000 >= at, "fixture_notification_posted_before_deadline")
436 return keys[0]
437 require(self.clock() < until, "fixture_notification_not_posted")
438 self.sleep(1)
439
440 def assert_no_post_through(self, at):
441 until = self.clock() + max(0, (at - self.device_epoch_ms()) / 1000) + 5
442 while True:
443 require(not self.active_keys(), "canceled_fixture_notification_posted")
444 if self.clock() >= until:
445 return
446 self.sleep(min(1, until - self.clock()))
447
448 def settings_dump(self):
449 self._ready()
450 require(self.fixture_installed and self.user_launched, 'fixture_not_ready')
451 # /dev/tty may be absent when adb shell has no PTY. Use a unique file
452 # owned by this already-gated synthetic run, read it, and remove it.
453 path = '/data/local/tmp/lifeguide-settings-' + secrets.token_hex(8) + '.xml'
454 try:
455 self.adb.shell('uiautomator', 'dump', path, allow_failure=True)
456 return self.adb.shell('cat', path, allow_failure=True)
457 finally:
458 self.adb.shell('rm', '-f', path)
459
460 def capture_settings_screenshot(self):
461 self._ready()
462 require(self.fixture_installed and self.user_launched, 'fixture_not_ready')
463 try:
464 capture = subprocess.run(['adb', '-s', self.serial, 'exec-out', 'screencap', '-p'],
465 capture_output=True, timeout=30, check=False)
466 png = capture.stdout
467 require(capture.returncode == 0 and 24 <= len(png) <= 16 * 1024 * 1024 and
468 png[:8] == b'\x89PNG\r\n\x1a\n' and png[12:16] == b'IHDR', 'settings_screenshot_failed')
469 width, height = struct.unpack('>II', png[16:24])
470 require(100 <= width <= 4096 and 100 <= height <= 4096, 'settings_screenshot_failed')
471 path = self.screenshot.with_name('standalone-notification-settings.png')
472 path.parent.mkdir(parents=True, exist_ok=True)
473 path.write_bytes(png)
474 self.receipt['settingsScreenshot'] = {'status': 'VERIFIED_CAPTURE',
475 'file': path.name, 'sha256': hashlib.sha256(png).hexdigest()}
476 except (AcceptanceError, OSError, subprocess.SubprocessError):
477 self.receipt['settingsScreenshot'] = {'status': 'UNVERIFIED'}
478
479 def verify_notification_settings(self):
480 settings = self.launch('settings')
481 self.assert_status(settings, active=False, count=0)
482 self.assert_database(settings, CHECKS)
483 self.receipt['currentPhase'] = 'native_notification_settings'
484 legacy = self.adb.shell('uiautomator', 'dump', '/dev/tty', allow_failure=True)
485 observation = {'legacyTty': notification_settings_summary(legacy)}
486 self.receipt['settingsObservation'] = observation
487 until = self.clock() + 20
488 while True:
489 ui = self.settings_dump()
490 observation['file'] = notification_settings_summary(ui)
491 if notification_settings_visible(ui):
492 break
493 if self.clock() >= until:
494 self.capture_settings_screenshot()
495 raise AcceptanceError('notification_settings_screen_not_verified')
496 self.sleep(0.5)
497 # Repeat the legacy probe on the now-confirmed stable screen so initial
498 # UI readiness is not confused with the dump transport hypothesis.
499 legacy_after = self.adb.shell('uiautomator', 'dump', '/dev/tty', allow_failure=True)
500 observation['legacyTtyAfterFile'] = notification_settings_summary(legacy_after)
501 self.capture_settings_screenshot()
502 require(self.preferences() is None and not self.active_keys(),
503 'settings_changed_off_native_state')
504 self.adb.shell('input', 'keyevent', 'KEYCODE_BACK')
505 inspected = self.launch('inspect')
506 self.assert_status(inspected, active=False, count=0)
507 self.assert_database(inspected, CHECKS)
508 require(self.preferences() is None and not self.active_keys(),
509 'settings_return_changed_off_native_state')
510 self.receipt['checks']['nativeNotificationSettingsWhileOff'] = 'PASS'
511 self.receipt['checks']['sqliteAfterNotificationSettings'] = 'PASS'
512
513 def run(self):
514 self.install_user()
515 self.first_user_launch()
516 self.install_fixture()
517 self.align_to_minute()
518 seeded = self.launch("seed")
519 self.assert_database(seeded, {"rawSqlAfterClose", "profilePersists", "weeklyDifferentTimes", "onceAndEveryTwoDays"})
520 at, scheduled = self.assert_scheduled(seeded)
521 self.process_dead(before=at)
522 require(self.preferences() == scheduled and not self.active_keys(), "alarm_preceded_process_absence_proof")
523 self.receipt["checks"]["processAbsentBeforeAlarm"] = "PASS"
524 key = self.wait_for_post(at)
525 require(key.split("|")[3] == "lifeguide-plan:" + scheduled["reminders"][0]["id"], "notification_not_from_sqlite_record")
526 delivered = self.preferences()
527 require(delivered is not None and delivered["generation"] == scheduled["generation"] and
528 len(delivered["reminders"]) == 1 and delivered["reminders"][0].get("delivered") is True,
529 "native_delivered_marker_missing")
530 self.receipt["checks"]["notificationAfterProcessDeath"] = "PASS"
531 self.receipt["checks"]["notificationContent"] = check_notification_record(
532 self.adb.shell("dumpsys", "notification", "--noredact"), key)
533 inspected = self.launch("inspect")
534 self.assert_status(inspected, active=True, count=0)
535 self.assert_database(inspected, {"rawSqlAfterClose", "profilePersists", "weeklyDifferentTimes", "onceAndEveryTwoDays"})
536 require(self.preferences() == delivered and self.active_keys() == [key], "inspect_changed_delivered_state_or_post")
537 self.receipt["checks"]["relaunchReadOnlyPreservesNativeGeneration"] = "PASS"
538 self.align_to_minute()
539 changed = self.launch("change")
540 self.assert_database(changed, {"rawSqlAfterClose", "profilePersists", "independentEditAndTick"})
541 canceled_at, _ = self.assert_scheduled(changed)
542 canceled = self.launch("cancel")
543 self.assert_status(canceled, active=True, count=0)
544 self.assert_database(canceled, {"rawSqlAfterClose", "archivePersists", "independentEditAndTick"})
545 require(self.device_epoch_ms() + 1000 < canceled_at, "fixture_cancellation_missed_deadline")
546 state = self.preferences()
547 require(state is not None and state["reminders"] == [] and not self.active_keys(), "archive_did_not_cancel_native_alarm")
548 self.process_dead(before=canceled_at)
549 self.assert_no_post_through(canceled_at)
550 self.receipt["checks"]["archiveBeforeDeadlineHasNoOSPost"] = "PASS"
551 off = self.launch("off")
552 self.assert_status(off, active=False, count=0)
553 require(self.preferences() is None and not self.active_keys(), "off_did_not_clear_native_state")
554 self.receipt["checks"]["offClearsNativeState"] = "PASS"
555 self.verify_notification_settings()
556 self.receipt["currentPhase"], self.receipt["result"] = "complete", "PASS"
557 return self.receipt
558
559
560 def main(argv=None):
561 parser = argparse.ArgumentParser(description=__doc__)
562 parser.add_argument("--user-apk", required=True, type=Path)
563 parser.add_argument("--fixture-apk", required=True, type=Path)
564 parser.add_argument("--serial", required=True)
565 parser.add_argument("--allow-synthetic-emulator-reset", action="store_true")
566 parser.add_argument("--output", required=True, type=Path)
567 options = parser.parse_args(argv)
568 harness = Harness(serial=options.serial, user_apk=options.user_apk,
569 fixture_apk=options.fixture_apk, allow_reset=options.allow_synthetic_emulator_reset,
570 screenshot=options.output.with_name("standalone-user-first-launch.png"))
571 try:
572 harness.run()
573 except AcceptanceError as error:
574 harness.receipt["error"] = str(error)
575 except Exception:
576 harness.receipt["error"] = "unexpected_acceptance_failure"
577 options.output.parent.mkdir(parents=True, exist_ok=True)
578 options.output.write_text(json.dumps(harness.receipt, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
579 print(json.dumps({"result": harness.receipt["result"], "error": harness.receipt.get("error")}))
580 return 0 if harness.receipt["result"] == "PASS" else 1
581
582
583 if __name__ == "__main__":
584 raise SystemExit(main())