@davoodmehraban89 / LifeMate / commits / b457271
Fork 0

LifeMate — Personal, Family & Learning Companion

test(personal): gate user APK on isolated SQLite and Android alarm acceptance

Quinn White committed Oct 19, 2026 at 13:17 UTC b45727194140f573b4f8716042fc77ff31b9fca2
12 files changed +1624 -2
.github/workflows/standalone-personal-apk.yml new
+85
@@ -0,0 +1,85 @@
1 +name: LifeGuide personal Android APK (device-only)
2 +on:
3 + pull_request:
4 + paths:
5 + - '.github/workflows/standalone-personal-apk.yml'
6 + - 'apps/lifemate/lib/standalone/**'
7 + - 'apps/lifemate/lib/standalone_main.dart'
8 + - 'apps/lifemate/test/standalone*'
9 + - 'apps/lifemate/tool/*standalone*'
10 + - 'apps/lifemate/android/**'
11 + - 'apps/lifemate/pubspec*'
12 + workflow_dispatch:
13 +permissions:
14 + contents: read
15 +concurrency:
16 + group: lifeguide-personal-${{ github.ref }}
17 + cancel-in-progress: true
18 +jobs:
19 + personal-apk:
20 + runs-on: ubuntu-latest
21 + timeout-minutes: 35
22 + defaults:
23 + run:
24 + working-directory: apps/lifemate
25 + env:
26 + ORG_GRADLE_PROJECT_lifeguideDevicePlanner: 'true'
27 + steps:
28 + - uses: actions/checkout@v4
29 + - uses: actions/setup-java@v4
30 + with: {distribution: temurin, java-version: '17'}
31 + - uses: subosito/flutter-action@v2
32 + with: {flutter-version: '3.47.6', channel: stable, cache: true}
33 + - run: flutter pub get
34 + - name: Verify personal edition and test-tool safety
35 + run: |
36 + dart format --output=none --set-exit-if-changed lib/standalone lib/standalone_main.dart test/standalone* tool/standalone_acceptance_fixture.dart
37 + flutter analyze
38 + flutter test
39 + python3 -m unittest discover -s tool -p '*standalone*test.py' -v
40 + - name: Build actual user APK (no fixture and no INTERNET permission)
41 + run: |
42 + flutter build apk --debug --target=lib/standalone_main.dart --dart-define=LIFEGUIDE_STANDALONE=true --build-name=0.7.2-personal.1 --build-number=9
43 + cp build/app/outputs/flutter-apk/app-debug.apk build/LifeGuide.apk
44 + mkdir -p exports
45 + python3 tool/check_standalone_apk.py build/LifeGuide.apk > exports/standalone-apk-manifest.json
46 + SIGNER=$(find "$ANDROID_HOME/build-tools" -type f -name apksigner | sort -V | tail -1)
47 + "$SIGNER" verify --verbose --print-certs build/LifeGuide.apk > exports/standalone-apk-signature.txt
48 + sha256sum build/LifeGuide.apk > exports/standalone-apk-sha256.txt
49 + - name: Build same-signature synthetic fixture (never distributed)
50 + run: |
51 + flutter build apk --debug --target=tool/standalone_acceptance_fixture.dart --dart-define=LIFEGUIDE_STANDALONE=true --dart-define=LG_STANDALONE_ACCEPTANCE=true --build-name=0.7.2-personal.1 --build-number=9
52 + cp build/app/outputs/flutter-apk/app-debug.apk build/standalone-private-fixture.apk
53 + python3 tool/check_standalone_apk.py build/standalone-private-fixture.apk
54 + - name: Enable KVM for fresh synthetic emulator
55 + run: |
56 + test -c /dev/kvm
57 + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
58 + sudo udevadm control --reload-rules
59 + sudo udevadm trigger --name-match=kvm
60 + - name: Launch real user APK; verify SQLite and actual OS alarms
61 + uses: reactivecircus/android-emulator-runner@a421e43855164a8197daf9d8d40fe71c6996bb0d
62 + with:
63 + api-level: 35
64 + target: google_apis
65 + arch: x86_64
66 + profile: pixel_6
67 + emulator-port: 5554
68 + avd-name: lifeguide-personal-synthetic
69 + force-avd-creation: true
70 + emulator-options: -no-window -gpu swiftshader_indirect -no-snapshot -wipe-data -noaudio -no-boot-anim -camera-back none
71 + working-directory: apps/lifemate
72 + script: python3 tool/test_standalone_android.py --serial emulator-5554 --user-apk build/LifeGuide.apk --fixture-apk build/standalone-private-fixture.apk --allow-synthetic-emulator-reset --output exports/standalone-android.json
73 + - name: Deliver user APK only after acceptance passes
74 + uses: actions/upload-artifact@v4
75 + with:
76 + name: LifeGuide-personal-Android-0.7.2-9
77 + path: apps/lifemate/build/LifeGuide.apk
78 + if-no-files-found: error
79 + - name: Preserve sanitized verification output
80 + if: always()
81 + uses: actions/upload-artifact@v4
82 + with:
83 + name: LifeGuide-personal-verification
84 + path: apps/lifemate/exports/standalone-*
85 + if-no-files-found: warn
CHANGELOG.md
+7
@@ -1,5 +1,12 @@
1 # LifeGuide Changelog
2
3 +## Unreleased — personal Android 0.7.2-personal.1/code9 (Backend unchanged0.7.2)
4 +
5 +- Initial device-only debug edition in separate package; no URL, contacts, login, network permission or fake server acknowledgment.
6 +- Transactional private SQLite profile, recurring weekly plans with per-day times, stable occurrence IDs, independent ticks/edits/archives and durable restart behavior.
7 +- Explicit opt-in native reminder port from committed device rows, generic lock-screen message, persisted OFF choice, 28-day/128-reminder coverage and visible timing limitations.
8 +- Actual user-APK first-launch plus isolated SQLite/OS-alarm fixture acceptance gates; physical device, signing continuity and online family use remain UNVERIFIED.
9 +
10 ## 0.7.2 — 2026-10-18 — نامزد آزمون برنامهٔ هفتگی (منتشرنشده)
11
12 - برنامهٔ خصوصی روزانه، روزدرمیان و هفتگی با ساعت مستقل هر روز، پایان صریح، نوبت‌های واقعی PostgreSQL و تیک/ویرایش مستقل.
PROJECT_STATE.md
+8
@@ -1,5 +1,13 @@
1 # LifeGuide / لایف‌گاید — وضعیت واقعی پروژه
2
3 +## لایف‌گاید شخصی — ۲۰۲۶-۱۰-۱۹؛ اجرای بستهٔ مستقل
4 +
5 +مالک پس از توضیح مرز دادهٔ روی گوشی، تکمیل APK بدون API/URL را خواست و ادامه را تأیید کرد؛ **ADR0016 / D-A پذیرفته شد**. شاخهٔ `feat/standalone-weekly-planner` بستهٔ debug جدا `ir.lifeguide.app.device` را می‌سازد؛ برنامهٔ آنلاین و شناسهٔ انتشار `ir.lifeguide.app` تغییر نمی‌کنند. SQLite محلی برای برنامه/نوبت/پروفایل، تکرار/تیک/ویرایش/بایگانی و اعلان opt-in مستقل پیاده می‌شوند. هیچ ACK ساختگی، حساب یا سرور نمایشی جای اتصال قرار نمی‌گیرد.
6 +
7 +آزمون متمرکز یکپارچگی ذخیره/اعلان: **VERIFIED** با `flutter test test/standalone_coordinator_test.dart --reporter expanded`، خروجی `+2: All tests passed!`. آزمون Python گیت manifest و ابزار امن شبیه‌ساز: `python3 -m unittest discover -s tool -p '*standalone*test.py' -v`، `Ran 20 tests ... OK`. این‌ها اثبات ساخت/نصب APK نیستند. اجرای کامل Flutter، analyzer، build و پذیرش شبیه‌ساز در حال بررسی‌اند و تا receipt نهایی **UNVERIFIED** هستند. [راهنمای استفاده و محدودیت‌ها](docs/operations/PERSONAL_ANDROID.md).
8 +
9 +این بسته همگام‌سازی/نمای والد/بازیابی سرور ندارد؛ حذف داده/برنامه یا خرابی گوشی می‌تواند اطلاعات را از بین ببرد. کلید پایدار و ارتقای بدون حذف داده، دستگاه واقعی، صدا/Doze/reboot، PWA/Safari و شبکه ایران **UNVERIFIED** هستند. گزارش‌های پایین تاریخی‌اند؛ وضعیت PROPOSED قبلی ADR0016 با انتخاب فعلی جایگزین شد. هیچ merge/deploy/DNS/schema زنده تغییر نکرده است.
10 +
11 ## اعلان Android در شبیه‌ساز — ۲۰۲۶-۱۰-۱۹؛ APIآنلاین هنوز مانع تحویل است
12
13 [PR36](https://github.com/davoodmehraban89/LifeMate/pull/36)، شاخهٔ `test/android-reminder-acceptance`، فقط ابزار آزمون و مستندات است. Flutter/Android عملیاتی، Backend و APKتحویلی0.7.2+8 تغییر نکرده‌اند. fixture فقط debug، رکورد ساختگی و تأییدسرور صریحاً شبیه‌سازی‌شده دارد؛ دستگاه فیزیکی/بستهٔ نصب‌شده را رد می‌کند و APKآن توزیع نمی‌شود.
README.md
+4
@@ -4,6 +4,10 @@
4
5 این شاخه یک **نامزد آزمون آنلاین با داده ساختگی** است. نسخه کامل عملیاتی یا منتشرشده نیست. پذیرش Android/iPhone/Safari واقعی و دسترسی بدون VPN داخل ایران **UNVERIFIED** است. Backend موجود و Feature 1 ایران حفظ شده‌اند؛ حالت بدون ورودِ محلی جای سیستم چندکاربره نیست.
6
7 +## بستهٔ اولیهٔ شخصی Android — بدون URL
8 +
9 +برای استفادهٔ اولیهٔ روی یک گوشی، «لایف‌گاید شخصی» با SQLite واقعی و برنامهٔ هفته/تکرار/تیک/یادآوری مستقل آمادهٔ آزمون می‌شود. شناسهٔ جدا `.device`، بدون اینترنت/ورود و بدون همگام‌سازی خانواده است؛ جای نسخهٔ آنلاین را نمی‌گیرد. [نصب، محدودیت داده و کنترل‌های واقعی](docs/operations/PERSONAL_ANDROID.md). ساخت/نصب تا ثبت receipt همان تحویل **UNVERIFIED** است؛ حذف برنامهٔ قبلی لازم نیست و نباید برای رفع اختلاف امضا داده‌ای پاک شود.
10 +
11 ## برنامهٔ هفتگی0.7.2 — نامزد آزمون، منتشرنشده
12
13 نمای هفته، تکرار روزانه/روزدرمیان و ساعت مستقل هر روز، تیک مستقل نوبت‌ها و پورت اعلان Android روی API واقعی اضافه شده است. **VERIFIED محلی:** Backend308/308، Flutter277/277، analyze بدون مشکل و build وب موفق؛ [شواهد](docs/audits/evidence/weekly-planner-local-2026-10-18.json). APK debug0.7.2+8 واقعاً ساخته و manifest/hash بررسی شد؛ [CI و فایل](docs/audits/evidence/weekly-planner-ci-apk-2026-10-18.json). نصب/اعلان روی گوشی و بهره‌برداری خصوصی کودک هنوز UNVERIFIED/مسدود است. [راهنمای بسته و سناریوی گوشی](docs/operations/WEEKLY_PLANNER_ANDROID.md)، [تصمیم باز مسیر تحویل](docs/decisions/0016-initial-child-planner-delivery.md). هیچ merge/deploy/DNS یا schema زنده تغییر نکرده است.
apps/lifemate/tool/check_standalone_apk.py new
+58
@@ -0,0 +1,58 @@
1 +#!/usr/bin/env python3
2 +"""Inspect the device-only APK binary manifest. Signature/install are separate."""
3 +import argparse
4 +import hashlib
5 +import json
6 +from pathlib import Path
7 +from zipfile import ZipFile
8 +
9 +from check_apk_manifest import manifest_tags
10 +
11 +PACKAGE = 'ir.lifeguide.app.device'
12 +LABEL = 'لایف‌گاید شخصی'
13 +
14 +
15 +def check(apk):
16 + apk = Path(apk)
17 + with ZipFile(apk) as archive:
18 + tags = manifest_tags(archive.read('AndroidManifest.xml'))
19 + manifest = next(a for tag, a in tags if tag == 'manifest')
20 + application = next(a for tag, a in tags if tag == 'application')
21 + sdk = next(a for tag, a in tags if tag == 'uses-sdk')
22 + permissions = {a.get('name') for tag, a in tags if tag.startswith('uses-permission')}
23 + allowed = {'android.permission.POST_NOTIFICATIONS',
24 + 'android.permission.RECEIVE_BOOT_COMPLETED',
25 + 'android.permission.SCHEDULE_EXACT_ALARM',
26 + PACKAGE + '.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION'}
27 + if manifest.get('package') != PACKAGE or application.get('label') != LABEL:
28 + raise ValueError('Expected the separate LifeGuide personal device edition')
29 + if manifest.get('versionName') != '0.7.2-personal.1' or manifest.get('versionCode') != 9:
30 + raise ValueError('Unexpected personal APK version')
31 + if (application.get('debuggable') is not True or
32 + application.get('allowBackup') is not False or
33 + application.get('usesCleartextTraffic') is not False):
34 + raise ValueError('Personal debug, backup and network gates are required')
35 + if not permissions <= allowed or not (allowed - {PACKAGE + '.DYNAMIC_RECEIVER_NOT_EXPORTED_PERMISSION'}) <= permissions:
36 + raise ValueError('Unexpected or missing device edition permissions; INTERNET is forbidden')
37 + if sdk.get('minSdkVersion') != 24 or sdk.get('targetSdkVersion') != 36:
38 + raise ValueError('Unexpected Android SDK versions')
39 + activities = [a for tag, a in tags if tag == 'activity']
40 + if not any(a.get('name') == 'ir.lifeguide.app.MainActivity' and a.get('exported') is True for a in activities):
41 + raise ValueError('Personal APK must resolve the existing fully-qualified MainActivity')
42 + receivers = [a for tag, a in tags if tag == 'receiver']
43 + if not any(a.get('name') == 'ir.lifeguide.app.LocalReminderReceiver' and a.get('exported') is False for a in receivers):
44 + raise ValueError('Reminder receiver must remain private')
45 + return {'result': 'PASS', 'package': PACKAGE, 'label': LABEL,
46 + 'versionName': manifest['versionName'], 'versionCode': 9,
47 + 'debuggable': True, 'allowBackup': False, 'usesCleartextTraffic': False,
48 + 'internetPermission': False, 'permissions': sorted(permissions),
49 + 'minSdkVersion': 24, 'targetSdkVersion': 36,
50 + 'sha256': hashlib.sha256(apk.read_bytes()).hexdigest(),
51 + 'limitations': 'Debug initial personal edition; signature and actual lifecycle checked separately.'}
52 +
53 +
54 +if __name__ == '__main__':
55 + parser = argparse.ArgumentParser(description=__doc__)
56 + parser.add_argument('apk', type=Path)
57 + options = parser.parse_args()
58 + print(json.dumps(check(options.apk), ensure_ascii=False, indent=2))
apps/lifemate/tool/check_standalone_apk_test.py new
+73
@@ -0,0 +1,73 @@
1 +"""Packaging gates; test manifests are synthetic, not an APK build."""
2 +import tempfile
3 +import unittest
4 +from pathlib import Path
5 +from unittest.mock import patch
6 +from zipfile import ZipFile
7 +
8 +import check_standalone_apk as subject
9 +
10 +
11 +class StandaloneManifestTest(unittest.TestCase):
12 + def setUp(self):
13 + self.directory = tempfile.TemporaryDirectory()
14 + self.addCleanup(self.directory.cleanup)
15 + self.apk = Path(self.directory.name) / 'LifeGuide.apk'
16 + with ZipFile(self.apk, 'w') as archive:
17 + archive.writestr('AndroidManifest.xml', b'synthetic parser fixture')
18 + self.tags = [
19 + ('manifest', {'package': 'ir.lifeguide.app.device',
20 + 'versionName': '0.7.2-personal.1', 'versionCode': 9}),
21 + ('uses-sdk', {'minSdkVersion': 24, 'targetSdkVersion': 36}),
22 + ('application', {'label': 'لایف‌گاید شخصی', 'debuggable': True,
23 + 'allowBackup': False, 'usesCleartextTraffic': False}),
24 + ('activity', {'name': 'ir.lifeguide.app.MainActivity', 'exported': True}),
25 + ('receiver', {'name': 'ir.lifeguide.app.LocalReminderReceiver', 'exported': False}),
26 + ('uses-permission', {'name': 'android.permission.POST_NOTIFICATIONS'}),
27 + ('uses-permission', {'name': 'android.permission.RECEIVE_BOOT_COMPLETED'}),
28 + ('uses-permission', {'name': 'android.permission.SCHEDULE_EXACT_ALARM'}),
29 + ]
30 +
31 + def check(self):
32 + with patch.object(subject, 'manifest_tags', return_value=self.tags):
33 + return subject.check(self.apk)
34 +
35 + def test_separate_debug_device_edition_has_no_internet(self):
36 + result = self.check()
37 + self.assertEqual(result['result'], 'PASS')
38 + self.assertEqual(result['package'], 'ir.lifeguide.app.device')
39 + self.assertIs(result['internetPermission'], False)
40 + self.assertEqual(len(result['sha256']), 64)
41 +
42 + def test_online_identity_and_wrong_main_activity_are_rejected(self):
43 + self.tags[0][1]['package'] = 'ir.lifeguide.app'
44 + with self.assertRaises(ValueError):
45 + self.check()
46 + self.tags[0][1]['package'] = 'ir.lifeguide.app.device'
47 + self.tags[3][1]['name'] = 'ir.lifeguide.app.device.MainActivity'
48 + with self.assertRaises(ValueError):
49 + self.check()
50 +
51 + def test_internet_and_unexpected_permissions_are_rejected(self):
52 + for permission in ('android.permission.INTERNET', 'android.permission.READ_CONTACTS'):
53 + with self.subTest(permission=permission):
54 + self.tags.append(('uses-permission', {'name': permission}))
55 + with self.assertRaises(ValueError):
56 + self.check()
57 + self.tags.pop()
58 +
59 + def test_backup_cleartext_exported_receiver_or_wrong_version_are_rejected(self):
60 + for index, key, value in ((2, 'allowBackup', True),
61 + (2, 'usesCleartextTraffic', True),
62 + (2, 'debuggable', False),
63 + (4, 'exported', True), (0, 'versionCode', 8)):
64 + old = self.tags[index][1][key]
65 + with self.subTest(key=key):
66 + self.tags[index][1][key] = value
67 + with self.assertRaises(ValueError):
68 + self.check()
69 + self.tags[index][1][key] = old
70 +
71 +
72 +if __name__ == '__main__':
73 + unittest.main()
apps/lifemate/tool/standalone_acceptance_fixture.dart new
+417
@@ -0,0 +1,417 @@
1 +// Synthetic emulator-only entry point. This APK must never be distributed.
2 +// The user APK is launched first; the host then upgrades its own fresh install.
3 +import 'dart:convert';
4 +import 'dart:io';
5 +
6 +import 'package:flutter/foundation.dart';
7 +import 'package:flutter/material.dart';
8 +import 'package:lifemate/standalone/model.dart';
9 +import 'package:lifemate/standalone/reminders.dart';
10 +import 'package:lifemate/standalone/store.dart';
11 +import 'package:path/path.dart' as paths;
12 +import 'package:sqflite/sqflite.dart';
13 +
14 +const _database = 'standalone_acceptance.sqlite';
15 +const _companion = 'LifeGuide EMULATOR FIXTURE';
16 +const _canary = 'SYNTHETIC_PRIVATE_TASK_CANARY';
17 +const _weekly = '${_canary}_WEEK';
18 +const _alternate = '${_canary}_EVERY_TWO';
19 +const _once = '${_canary}_ONCE';
20 +const _near = '${_canary}_NEAR';
21 +
22 +void _require(bool condition) {
23 + if (!condition) throw StateError('synthetic_sqlite_assertion_failed');
24 +}
25 +
26 +Future<Database> _raw(String path, {bool readOnly = true}) =>
27 + databaseFactory.openDatabase(path,
28 + options:
29 + OpenDatabaseOptions(readOnly: readOnly, singleInstance: false));
30 +
31 +Future<Map<String, Object?>> _metadata(String path) async {
32 + final db = await _raw(path);
33 + try {
34 + return (await db.rawQuery('SELECT * FROM acceptance_meta')).single;
35 + } finally {
36 + await db.close();
37 + }
38 +}
39 +
40 +Future<void> _writeMetadata(String path, Map<String, Object?> values,
41 + {bool create = false}) async {
42 + final db = await _raw(path, readOnly: false);
43 + try {
44 + if (create) {
45 + await db.execute('''CREATE TABLE acceptance_meta (
46 + singleton INTEGER PRIMARY KEY CHECK(singleton = 1),
47 + base_date TEXT NOT NULL, first_weekly_id TEXT NOT NULL,
48 + second_weekly_id TEXT NOT NULL, near_id TEXT NOT NULL,
49 + second_near_id TEXT, phase TEXT NOT NULL)''');
50 + await db.insert('acceptance_meta', {'singleton': 1, ...values});
51 + } else {
52 + _require(
53 + await db.update('acceptance_meta', values, where: 'singleton = 1') ==
54 + 1);
55 + }
56 + } finally {
57 + await db.close();
58 + }
59 +}
60 +
61 +/// These queries run only after the application store has really closed. They
62 +/// inspect the actual file without UI state, model serialization or a fake API.
63 +Future<Map<String, bool>> _audit(String path) async {
64 + final db = await _raw(path);
65 + late final Map<String, Object?> meta;
66 + try {
67 + _require(
68 + (await db.rawQuery('PRAGMA quick_check')).single.values.single == 'ok');
69 + _require((await db.rawQuery('PRAGMA user_version')).single.values.single ==
70 + StandaloneStore.schemaVersion);
71 + final profiles = await db.rawQuery('SELECT * FROM local_profiles');
72 + _require(profiles.length == 1 &&
73 + profiles.single['display_name'] == 'EMULATOR SYNTHETIC ADULT' &&
74 + profiles.single['category'] == 'adult' &&
75 + profiles.single['companion_name'] == _companion);
76 + meta = (await db.rawQuery('SELECT * FROM acceptance_meta')).single;
77 + final phase = meta['phase'];
78 + _require(const {'seeded', 'changed', 'canceled'}.contains(phase));
79 + final plans = await db.rawQuery('SELECT * FROM local_plans');
80 + final weeklyPlan = plans.singleWhere((r) => r['title'] == _weekly);
81 + final everyPlan = plans.singleWhere((r) => r['title'] == _alternate);
82 + final oncePlan = plans.singleWhere((r) => r['title'] == _once);
83 + _require(weeklyPlan['recurrence'] == 'weekly' &&
84 + everyPlan['recurrence'] == 'everyTwoDays' &&
85 + oncePlan['recurrence'] == 'once');
86 + final slots = await db.rawQuery(
87 + 'SELECT * FROM local_weekly_slots WHERE plan_id = ? ORDER BY start_minute',
88 + [weeklyPlan['id']]);
89 + _require(slots.length == 2 &&
90 + slots[0]['start_minute'] == 600 &&
91 + slots[0]['end_minute'] == 630 &&
92 + slots[1]['start_minute'] == 900 &&
93 + slots[1]['end_minute'] == 945 &&
94 + slots[0]['weekday'] != slots[1]['weekday']);
95 + final rows = await db.rawQuery('SELECT * FROM local_occurrences');
96 + final first = rows.singleWhere((r) => r['id'] == meta['first_weekly_id']);
97 + final second = rows.singleWhere((r) => r['id'] == meta['second_weekly_id']);
98 + _require(first['plan_id'] == weeklyPlan['id'] &&
99 + second['plan_id'] == weeklyPlan['id'] &&
100 + first['occurrence_date'] != second['occurrence_date'] &&
101 + second['title'] == _weekly &&
102 + second['start_minute'] == 900 &&
103 + second['end_minute'] == 945 &&
104 + second['completed'] == 0 &&
105 + second['archived'] == 0);
106 + final changed = phase != 'seeded';
107 + _require(first['title'] == (changed ? '${_weekly}_EDIT' : _weekly) &&
108 + first['start_minute'] == (changed ? 610 : 600) &&
109 + first['end_minute'] == (changed ? 640 : 630) &&
110 + first['completed'] == (changed ? 1 : 0) &&
111 + first['archived'] == 0);
112 + final base = StandaloneDate.parse(meta['base_date'] as String);
113 + final everyRows = rows
114 + .where((r) => r['plan_id'] == everyPlan['id'])
115 + .toList()
116 + ..sort((a, b) => (a['occurrence_date'] as String)
117 + .compareTo(b['occurrence_date'] as String));
118 + _require(everyRows.length == 4);
119 + for (var i = 0; i < 4; i++) {
120 + _require(everyRows[i]['occurrence_date'] ==
121 + StandaloneDate.key(StandaloneDate.addDays(base, i * 2)));
122 + }
123 + final onceRows = rows.where((r) => r['plan_id'] == oncePlan['id']).toList();
124 + _require(onceRows.length == 1 &&
125 + onceRows.single['occurrence_date'] ==
126 + StandaloneDate.key(StandaloneDate.addDays(base, 1)));
127 + _require(rows.length == (changed ? 9 : 8));
128 + if (phase == 'canceled') {
129 + final canceled =
130 + rows.singleWhere((r) => r['id'] == meta['second_near_id']);
131 + _require(canceled['completed'] == 1 &&
132 + canceled['archived'] == 1 &&
133 + plans.singleWhere(
134 + (p) => p['id'] == canceled['plan_id'])['archived'] ==
135 + 1);
136 + }
137 + } finally {
138 + await db.close();
139 + }
140 + // Reopen through the product store as a second persistence check. No
141 + // occurrences() call here: inspection must not materialize additional rows.
142 + final reopened = await StandaloneStore.open(path: path);
143 + try {
144 + _require((await reopened.profile())?.companionName == _companion);
145 + _require((await reopened.occurrence(meta['second_weekly_id'] as String))
146 + ?.completed ==
147 + false);
148 + } finally {
149 + await reopened.close();
150 + }
151 + return {
152 + 'rawSqlAfterClose': true,
153 + 'profilePersists': true,
154 + 'weeklyDifferentTimes': true,
155 + 'onceAndEveryTwoDays': true,
156 + if (meta['phase'] != 'seeded') 'independentEditAndTick': true,
157 + if (meta['phase'] == 'canceled') 'archivePersists': true,
158 + };
159 +}
160 +
161 +Future<StandaloneOccurrence> _createNear(StandaloneStore store,
162 + {required String suffix}) async {
163 + final now = DateTime.now();
164 + // Host aligns the real device clock before launch. No injected clock or
165 + // arbitrary native reminder timestamp substitutes for this stored record.
166 + final at = DateTime(now.year, now.month, now.day, now.hour, now.minute + 1);
167 + _require(at.difference(now).inSeconds >= 30);
168 + final minute = at.hour * 60 + at.minute;
169 + final plan = await store.createPlan(StandalonePlanDraft(
170 + title: '$_near$suffix',
171 + kind: StandalonePlanKind.task,
172 + recurrence: StandaloneRecurrence.once,
173 + startDate: StandaloneDate.only(at),
174 + startMinute: minute,
175 + endMinute: minute + 1,
176 + reminderMinutes: 0));
177 + return (await store.occurrences(
178 + from: StandaloneDate.only(at), through: StandaloneDate.only(at)))
179 + .singleWhere((o) => o.planId == plan.id);
180 +}
181 +
182 +Future<void> _seed(String path) async {
183 + _require(!await File(path).exists());
184 + final store = await StandaloneStore.open(path: path);
185 + final base = StandaloneDate.addDays(DateTime.now(), -14);
186 + late final StandaloneOccurrence near;
187 + late final List<StandaloneOccurrence> weekly;
188 + try {
189 + _require(await store.profile() == null);
190 + await store.createProfile(
191 + displayName: 'EMULATOR SYNTHETIC ADULT',
192 + category: StandaloneProfileCategory.adult,
193 + companionName: _companion);
194 + final plan = await store.createPlan(StandalonePlanDraft(
195 + title: _weekly,
196 + kind: StandalonePlanKind.task,
197 + recurrence: StandaloneRecurrence.weekly,
198 + startDate: base,
199 + untilDate: StandaloneDate.addDays(base, 6),
200 + startMinute: 600,
201 + endMinute: 630,
202 + weeklySlots: [
203 + StandaloneWeeklySlot(
204 + weekday: base.weekday, startMinute: 600, endMinute: 630),
205 + StandaloneWeeklySlot(
206 + weekday: StandaloneDate.addDays(base, 2).weekday,
207 + startMinute: 900,
208 + endMinute: 945),
209 + ]));
210 + await store.createPlan(StandalonePlanDraft(
211 + title: _alternate,
212 + kind: StandalonePlanKind.routine,
213 + recurrence: StandaloneRecurrence.everyTwoDays,
214 + startDate: base,
215 + untilDate: StandaloneDate.addDays(base, 6),
216 + startMinute: 700,
217 + endMinute: 730));
218 + await store.createPlan(StandalonePlanDraft(
219 + title: _once,
220 + kind: StandalonePlanKind.event,
221 + recurrence: StandaloneRecurrence.once,
222 + startDate: StandaloneDate.addDays(base, 1),
223 + startMinute: 800,
224 + endMinute: 830));
225 + weekly = (await store.occurrences(
226 + from: base, through: StandaloneDate.addDays(base, 6)))
227 + .where((o) => o.planId == plan.id)
228 + .toList();
229 + _require(weekly.length == 2);
230 + near = await _createNear(store, suffix: '_FIRST');
231 + } finally {
232 + await store.close();
233 + }
234 + await _writeMetadata(
235 + path,
236 + {
237 + 'base_date': StandaloneDate.key(base),
238 + 'first_weekly_id': weekly[0].id,
239 + 'second_weekly_id': weekly[1].id,
240 + 'near_id': near.id,
241 + 'phase': 'seeded',
242 + },
243 + create: true);
244 +}
245 +
246 +Future<void> _change(String path) async {
247 + final meta = await _metadata(path);
248 + _require(meta['phase'] == 'seeded');
249 + final store = await StandaloneStore.open(path: path);
250 + late final StandaloneOccurrence near;
251 + try {
252 + await store.updateOccurrence(meta['first_weekly_id'] as String,
253 + title: '${_weekly}_EDIT',
254 + startMinute: 610,
255 + endMinute: 640,
256 + completed: true);
257 + _require((await store.occurrence(meta['second_weekly_id'] as String))
258 + ?.completed ==
259 + false);
260 + await store.updateOccurrence(meta['near_id'] as String, completed: true);
261 + near = await _createNear(store, suffix: '_SECOND');
262 + } finally {
263 + await store.close();
264 + }
265 + await _writeMetadata(path, {'second_near_id': near.id, 'phase': 'changed'});
266 +}
267 +
268 +Future<void> _cancel(String path) async {
269 + final meta = await _metadata(path);
270 + _require(meta['phase'] == 'changed');
271 + final store = await StandaloneStore.open(path: path);
272 + try {
273 + final near = await store.occurrence(meta['second_near_id'] as String);
274 + _require(near != null && near.remindAt!.isAfter(DateTime.now()));
275 + await store.updateOccurrence(near!.id, completed: true);
276 + await store.archiveOccurrence(near.id);
277 + await store.archivePlan(near.planId);
278 + } finally {
279 + await store.close();
280 + }
281 + await _writeMetadata(path, {'phase': 'canceled'});
282 +}
283 +
284 +/// This takes the pending occurrences back out of the actual SQLite store and
285 +/// sends only their identity, instant and generic companion name to Android.
286 +Future<StandaloneProfile> _profile(String path) async {
287 + final store = await StandaloneStore.open(path: path);
288 + try {
289 + final profile = await store.profile();
290 + _require(profile?.companionName == _companion);
291 + return profile!;
292 + } finally {
293 + await store.close();
294 + }
295 +}
296 +
297 +Future<DateTime?> _reconcile(String path, StandaloneReminderPort port,
298 + {bool enable = false}) async {
299 + final store = await StandaloneStore.open(path: path);
300 + try {
301 + final now = DateTime.now().toUtc();
302 + final rows = await store.pendingReminders(
303 + from: now, through: now.add(const Duration(minutes: 10)));
304 + _require(rows.length <= 1);
305 + final profile = await store.profile();
306 + _require(profile?.companionName == _companion);
307 + final reminders = rows
308 + .map((row) => LocalPersonalReminder(
309 + id: row.id,
310 + planItemId: row.id,
311 + profileId: profile!.id,
312 + scheduledAt: row.remindAt!.toUtc(),
313 + completed: row.completed,
314 + archived: row.archived))
315 + .toList();
316 + if (enable) {
317 + await port.enable(reminders,
318 + companionName: profile!.companionName, profileId: profile.id);
319 + } else {
320 + await port.reconcile(reminders,
321 + companionName: profile!.companionName, profileId: profile.id);
322 + }
323 + return rows.isEmpty ? null : rows.single.remindAt!.toUtc();
324 + } finally {
325 + await store.close();
326 + }
327 +}
328 +
329 +Future<Map<String, Object?>> runStandaloneFixture(String route,
330 + {required bool enabled, required bool debug, required bool android}) async {
331 + if (!enabled || !debug || !android) throw StateError('fixture_disabled');
332 + final uri = Uri.tryParse(route);
333 + const modes = {'/seed', '/inspect', '/change', '/cancel', '/off'};
334 + if (uri == null ||
335 + uri.hasScheme ||
336 + uri.hasAuthority ||
337 + uri.hasFragment ||
338 + !modes.contains(uri.path) ||
339 + uri.queryParametersAll.length != 1 ||
340 + uri.queryParametersAll['nonce']?.length != 1 ||
341 + !RegExp(r'^[0-9a-f]{8,32}$')
342 + .hasMatch(uri.queryParameters['nonce'] ?? '')) {
343 + throw ArgumentError('invalid_fixture_route');
344 + }
345 + final path = paths.join(await getDatabasesPath(), _database);
346 + final port = StandaloneReminderPort();
347 + DateTime? at;
348 + Map<String, bool> checks = {};
349 + switch (uri.path) {
350 + case '/seed':
351 + final status = await port.status();
352 + _require(status.supported && status.permissionGranted);
353 + await _seed(path);
354 + checks = await _audit(path);
355 + at = await _reconcile(path, port, enable: true);
356 + _require(at != null);
357 + case '/inspect':
358 + checks = await _audit(path);
359 + break; // No enable/activate/replace: preserve native delivered generation.
360 + case '/change':
361 + await port.suspendUntilReconcile(profileId: (await _profile(path)).id);
362 + await _change(path);
363 + checks = await _audit(path);
364 + at = await _reconcile(path, port);
365 + _require(at != null);
366 + case '/cancel':
367 + await port.suspendUntilReconcile(profileId: (await _profile(path)).id);
368 + await _cancel(path);
369 + checks = await _audit(path);
370 + _require(await _reconcile(path, port) == null);
371 + case '/off':
372 + await port.disable(profileId: (await _profile(path)).id);
373 + }
374 + final status = await port.status(profileId: (await _profile(path)).id);
375 + return {
376 + 'nonce': uri.queryParameters['nonce'],
377 + 'mode': uri.path.substring(1),
378 + 'syntheticDataOnly': true,
379 + 'database': _database,
380 + 'checks': checks,
381 + if (at != null) 'scheduledAtEpochMs': at.millisecondsSinceEpoch,
382 + 'status': {
383 + 'supported': status.supported,
384 + 'permissionGranted': status.permissionGranted,
385 + 'active': status.active,
386 + 'enabled': status.enabled,
387 + 'activeScope': status.activeScope,
388 + 'scheduledCount': status.scheduledCount,
389 + 'timing': status.timing,
390 + 'canScheduleExactAlarms': status.canScheduleExactAlarms,
391 + },
392 + };
393 +}
394 +
395 +Future<void> main() async {
396 + final binding = WidgetsFlutterBinding.ensureInitialized();
397 + final route = binding.platformDispatcher.defaultRouteName;
398 + const enabled = bool.fromEnvironment('LG_STANDALONE_ACCEPTANCE') &&
399 + bool.fromEnvironment('LIFEGUIDE_STANDALONE');
400 + final android = !kIsWeb && defaultTargetPlatform == TargetPlatform.android;
401 + runApp(const MaterialApp(
402 + initialRoute: '/',
403 + home: Scaffold(
404 + body: SafeArea(
405 + child: Padding(
406 + padding: EdgeInsets.all(24),
407 + child: Text(
408 + 'EMULATOR ONLY — SYNTHETIC DATA — NEVER DISTRIBUTE\n$_canary'))))));
409 + try {
410 + final result = await runStandaloneFixture(route,
411 + enabled: enabled, debug: kDebugMode, android: android);
412 + debugPrint('LG_STANDALONE_ACCEPTANCE ${jsonEncode(result)}');
413 + } catch (_) {
414 + // Arbitrary database exceptions, routes and private records are never logged.
415 + debugPrint('LG_STANDALONE_ACCEPTANCE_ERROR fixture_failed_closed');
416 + }
417 +}
apps/lifemate/tool/test_standalone_android.py new
+482
@@ -0,0 +1,482 @@
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"}
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+ 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 check_notification_record(dump, key):
140 + require(active_fixture_keys(key) == [key], "invalid_fixture_notification_key")
141 + records = re.split(r"(?m)(?=^[ \t]*NotificationRecord\()", dump)
142 + matches = [r for r in records if
143 + re.search(r"\bkey=" + re.escape(key) + r"(?=[\s):])", r) and
144 + re.search(r"\bpkg=" + re.escape(PACKAGE) + r"(?=[\s)])", r)]
145 + require(len(matches) == 1, "fixture_notification_record_missing_or_ambiguous")
146 + record = matches[0]
147 + titles = re.findall(r"android\.title=String \(([^\n]*)\)", record)
148 + bodies = re.findall(r"android\.text=String \(([^\n]*)\)", record)
149 + require(bool(titles) and all(t == COMPANION for t in titles), "fixture_notification_title_mismatch")
150 + require(bool(bodies) and all(b == GENERIC_BODY for b in bodies), "fixture_notification_body_mismatch")
151 + require(CANARY not in record, "fixture_notification_contains_private_canary")
152 + require(re.search(r"(?:channel=|mId=['\"]?)" + re.escape(CHANNEL) + r"(?=['\"\s,)])", record),
153 + "fixture_notification_channel_mismatch")
154 + return {"titleMatches": True, "genericBodyMatches": True, "privateCanaryAbsent": True}
155 +
156 +
157 +def parse_preferences(xml, *, expected_scope=None):
158 + """Validate the isolated synthetic native state, never publish raw XML."""
159 + try:
160 + require(len(xml) <= 32768 and "<!" not in xml, "unexpected_fixture_preferences")
161 + root = ET.fromstring(xml)
162 + require(root.tag == "map" and not root.attrib, "unexpected_fixture_preferences")
163 + if len(root) == 0:
164 + return None
165 + require(len(root) == 1 and root[0].tag == "string" and
166 + root[0].attrib == {"name": "active"} and len(root[0]) == 0, "unexpected_fixture_preferences")
167 + state = json.loads(root[0].text or "")
168 + require(isinstance(state, dict) and set(state) <= {
169 + "scope", "generation", "issuedAtEpochMs", "validUntilEpochMs", "reminders", "deliveryExpired", "leaseKind"}
170 + and re.fullmatch("device-planner:v1:" + UUID, state.get("scope", "")) is not None
171 + and (expected_scope is None or state["scope"] == expected_scope)
172 + and str(uuid.UUID(state["generation"], version=4)) == state["generation"]
173 + and _positive(state.get("issuedAtEpochMs")) and _positive(state.get("validUntilEpochMs"))
174 + and 0 < state["validUntilEpochMs"] - state["issuedAtEpochMs"] <= 31 * 86400000
175 + and state.get("leaseKind") == "device-planner-v1"
176 + and isinstance(state.get("reminders"), list) and len(state["reminders"]) <= 1,
177 + "unexpected_fixture_preferences")
178 + if "deliveryExpired" in state:
179 + require(type(state["deliveryExpired"]) is bool, "unexpected_fixture_preferences")
180 + for row in state["reminders"]:
181 + require(isinstance(row, dict) and set(row) <= {
182 + "id", "planItemId", "scheduledAtEpochMs", "companionName", "delivered"}
183 + and re.fullmatch(UUID, row.get("id", "")) is not None
184 + and re.fullmatch(UUID, row.get("planItemId", "")) is not None
185 + and row.get("companionName") == COMPANION and _positive(row.get("scheduledAtEpochMs"))
186 + and state["issuedAtEpochMs"] < row["scheduledAtEpochMs"] <= state["validUntilEpochMs"]
187 + and type(row.get("delivered", False)) is bool, "unexpected_fixture_preferences")
188 + return state
189 + except (ET.ParseError, ValueError, TypeError, KeyError, AttributeError):
190 + raise AcceptanceError("unexpected_fixture_preferences") from None
191 +
192 +
193 +class Harness:
194 + def __init__(self, *, serial, user_apk, fixture_apk, allow_reset, screenshot,
195 + adb=None, manifest_check=manifest_check, certificate_check=certificate_digest,
196 + clock=time.monotonic, sleep=time.sleep):
197 + self.serial, self.user_apk, self.fixture_apk = serial, Path(user_apk), Path(fixture_apk)
198 + self.allow_reset, self.screenshot = allow_reset, Path(screenshot)
199 + self.adb, self.manifest_check, self.certificate_check = adb, manifest_check, certificate_check
200 + self.clock, self.sleep = clock, sleep
201 + self.installed = self.user_launched = self.fixture_installed = False
202 + self.scope = None
203 + self.receipt = {"schemaVersion": 1, "result": "FAIL", "syntheticDataOnly": True,
204 + "scope": "fresh API35 emulator; actual isolated SQLite and native notification",
205 + "currentPhase": "preflight", "limitations": LIMITATIONS.copy(), "checks": {}}
206 +
207 + def install_user(self):
208 + validate_serial(self.serial)
209 + require(self.allow_reset is True, "synthetic_emulator_reset_flag_required")
210 + require(self.user_apk.is_file() and self.fixture_apk.is_file(), "two_apk_files_required")
211 + manifests, certificates = [], []
212 + for apk in (self.user_apk, self.fixture_apk):
213 + try:
214 + report = self.manifest_check(apk)
215 + require(isinstance(report, dict) and report.get("result") == "PASS" and
216 + report.get("package") == PACKAGE and report.get("label") == LABEL and
217 + report.get("debuggable") is True and report.get("internetPermission") is False and
218 + report.get("targetSdkVersion") == 36 and
219 + re.fullmatch(r"[0-9a-f]{64}", report.get("sha256", "")) is not None,
220 + "apk_manifest_rejected")
221 + certificate = self.certificate_check(apk)
222 + require(re.fullmatch(r"[0-9a-f]{64}", certificate or "") is not None, "apk_signature_rejected")
223 + except AcceptanceError:
224 + raise
225 + except Exception:
226 + raise AcceptanceError("apk_manifest_rejected") from None
227 + manifests.append(report)
228 + certificates.append(certificate)
229 + require(certificates[0] == certificates[1], "apk_certificates_differ")
230 + if self.adb is None:
231 + self.adb = Adb(self.serial)
232 + require(self.adb.command("get-state").strip() == "device", "emulator_not_ready")
233 + kernel = self.adb.shell("getprop", "ro.kernel.qemu").strip()
234 + boot = self.adb.shell("getprop", "ro.boot.qemu").strip()
235 + require("1" in (kernel, boot), "qemu_emulator_required")
236 + require(self.adb.shell("getprop", "ro.hardware").strip() in ("ranchu", "goldfish"), "android_emulator_hardware_required")
237 + require(re.fullmatch(r"sdk_(?:gphone|phone)[A-Za-z0-9_]*",
238 + self.adb.shell("getprop", "ro.product.name").strip()) is not None, "synthetic_sdk_product_required")
239 + require(self.adb.shell("getprop", "ro.build.version.sdk").strip() == "35", "api_35_required")
240 + require(not self.adb.shell("pm", "list", "packages", PACKAGE).strip(), "fresh_emulator_required_package_already_present")
241 + output = self.adb.command("install", str(self.user_apk))
242 + require("Success" in output.splitlines() and "Failure" not in output and "Error" not in output,
243 + "user_apk_install_failed")
244 + self.installed = True
245 + self.receipt["apks"] = {role: {name: report[name] for name in (
246 + "sha256", "package", "label", "debuggable", "internetPermission", "targetSdkVersion")}
247 + for role, report in zip(("user", "fixtureNeverDistribute"), manifests)}
248 + self.receipt["certificateSha256"] = certificates[0]
249 + self.receipt["checks"]["emulatorAndFreshInstallGates"] = "PASS"
250 +
251 + def _ready(self):
252 + require(self.installed, "package_not_installed_by_this_runner")
253 +
254 + def process_state(self):
255 + self._ready()
256 + state = self.adb.shell("sh", "-c", PID_QUERY).strip()
257 + require(state in ("PRESENT", "ABSENT"), "fixture_process_query_failed")
258 + return state
259 +
260 + def process_dead(self, *, before=None):
261 + self._ready()
262 + self.receipt.pop("processExit", None)
263 + self.adb.shell("input", "keyevent", "KEYCODE_HOME")
264 + until, attempts = self.clock() + 10, 0
265 + while True:
266 + self.adb.shell("am", "kill", PACKAGE)
267 + attempts += 1
268 + state = self.process_state()
269 + self.receipt["lastProcessState"] = state
270 + if state == "ABSENT":
271 + if before is not None:
272 + require(self.device_epoch_ms() + 1000 < before, "process_absence_missed_alarm_deadline")
273 + self.receipt["processExit"] = {"confirmedAbsent": True, "ordinaryKillAttempts": attempts}
274 + return
275 + require(self.clock() < until, "fixture_process_did_not_exit")
276 + self.sleep(0.25)
277 +
278 + def first_user_launch(self):
279 + self._ready()
280 + require(not self.fixture_installed, "fixture_cannot_prove_user_first_launch")
281 + self.receipt["currentPhase"] = "user_first_launch"
282 + output = self.adb.shell("am", "start", "-W", "-f", "0x10008000", "-n", COMPONENT)
283 + require("Error" not in output and "Exception" not in output, "user_activity_launch_failed")
284 + self.sleep(3)
285 + require(self.process_state() == "PRESENT", "user_first_launch_process_not_alive")
286 + # No UI interaction or profile creation occurs before this screenshot.
287 + try:
288 + result = subprocess.run(["adb", "-s", self.serial, "exec-out", "screencap", "-p"],
289 + capture_output=True, timeout=30, check=False)
290 + png = result.stdout
291 + require(result.returncode == 0 and 24 <= len(png) <= 16 * 1024 * 1024 and
292 + png[:8] == b"\x89PNG\r\n\x1a\n" and png[12:16] == b"IHDR", "user_screenshot_failed")
293 + width, height = struct.unpack(">II", png[16:24])
294 + require(100 <= width <= 4096 and 100 <= height <= 4096, "user_screenshot_failed")
295 + self.screenshot.parent.mkdir(parents=True, exist_ok=True)
296 + self.screenshot.write_bytes(png)
297 + except (OSError, subprocess.SubprocessError):
298 + raise AcceptanceError("user_screenshot_failed") from None
299 + ui = self.adb.shell("uiautomator", "dump", "/dev/tty", allow_failure=True)
300 + require(not any(text in ui for text in ("https://", "http://", "نشانی API", "آدرس API")),
301 + "user_launch_url_prompt_detected")
302 + self.receipt["userFirstLaunch"] = {"processAlive": True,
303 + "ordinaryLaunchNoExtras": True, "screenshotSha256": hashlib.sha256(png).hexdigest(),
304 + "screenshotFile": self.screenshot.name, "urlPromptDetected": False,
305 + "localWelcomeText": "PASS" if "جای کوچکی برای برنامه‌های تو" in ui else "UNVERIFIED"}
306 + self.user_launched = True
307 + self.receipt["checks"]["actualUserApkFirstLaunchScreenshot"] = "PASS"
308 +
309 + def install_fixture(self):
310 + self._ready()
311 + require(self.user_launched, "user_first_launch_not_verified")
312 + require(not self.fixture_installed, "fixture_already_installed")
313 + self.process_dead()
314 + output = self.adb.command("install", "-r", str(self.fixture_apk))
315 + require("Success" in output.splitlines() and "Failure" not in output and "Error" not in output,
316 + "owned_fixture_upgrade_failed")
317 + self.fixture_installed = True
318 + self.adb.shell("pm", "grant", PACKAGE, "android.permission.POST_NOTIFICATIONS")
319 + self.adb.shell("cmd", "appops", "set", PACKAGE, "SCHEDULE_EXACT_ALARM", "allow")
320 + self.receipt["checks"]["fixtureUpgradePreservesFreshUserData"] = "PASS"
321 +
322 + def launch(self, mode):
323 + require(self.fixture_installed and mode in MODES, "fixture_not_ready")
324 + self.receipt["currentPhase"] = "before_launch_" + mode
325 + self.process_dead()
326 + nonce = secrets.token_hex(8)
327 + route = "/" + mode + "?nonce=" + nonce
328 + output = self.adb.shell("am", "start", "-W", "-f", "0x10008000",
329 + "-n", COMPONENT, "--es", "route", route)
330 + require("Error" not in output and "Exception" not in output, "fixture_activity_launch_failed")
331 + self.receipt["currentPhase"] = "waiting_" + mode + "_marker"
332 + until = self.clock() + 30
333 + while True:
334 + logs = self.adb.command("logcat", "-d", "-v", "brief", "-s", "flutter:I")
335 + for line in logs.splitlines():
336 + marker = fixture_marker(line, nonce, mode)
337 + if marker is not None:
338 + self.receipt["currentPhase"] = "after_" + mode + "_marker"
339 + return marker
340 + require(self.clock() < until, "fixture_marker_timeout")
341 + self.sleep(0.5)
342 +
343 + def device_epoch_ms(self):
344 + value = self.adb.shell("date", "+%s").strip()
345 + require(re.fullmatch(r"[0-9]{10,}", value) is not None, "emulator_clock_unavailable")
346 + return int(value) * 1000
347 +
348 + def align_to_minute(self):
349 + # Product records have minute precision. At second 10..15, the next
350 + # whole minute is genuinely 45..50 seconds away, without a test clock.
351 + until = self.clock() + 65
352 + while True:
353 + second = self.device_epoch_ms() // 1000 % 60
354 + if 10 <= second <= 15:
355 + return
356 + require(self.clock() < until, "emulator_clock_alignment_timeout")
357 + self.sleep(min(1, (70 - second) % 60 or 1))
358 +
359 + def preferences(self):
360 + script = "if [ -f " + PREFERENCES + " ]; then cat " + PREFERENCES + "; else printf '<map/>'; fi"
361 + return parse_preferences(self.adb.shell("run-as", PACKAGE, "sh", "-c", script), expected_scope=self.scope)
362 +
363 + def active_keys(self):
364 + return active_fixture_keys(self.adb.shell("cmd", "notification", "list"))
365 +
366 + def assert_status(self, marker, *, active, count):
367 + status = marker["status"]
368 + require(status["permissionGranted"] is True and status["active"] is active and
369 + status["enabled"] is active and
370 + status["scheduledCount"] == count and status["timing"] == "exact" and
371 + status["canScheduleExactAlarms"] is True, "fixture_status_assertion_failed")
372 + if active:
373 + if self.scope is None:
374 + self.scope = status["activeScope"]
375 + require(status["activeScope"] == self.scope, "fixture_scope_changed")
376 +
377 + def assert_database(self, marker, names):
378 + require(all(marker["checks"].get(name) is True for name in names), "real_sqlite_assertion_failed")
379 + for name in names:
380 + self.receipt["checks"][name] = "PASS"
381 +
382 + def assert_scheduled(self, marker):
383 + self.assert_status(marker, active=True, count=1)
384 + at = marker.get("scheduledAtEpochMs")
385 + require(_positive(at) and 30000 < at - self.device_epoch_ms() <= 55000,
386 + "real_record_not_near_45_seconds")
387 + state = self.preferences()
388 + require(state is not None and len(state["reminders"]) == 1 and
389 + state["reminders"][0]["scheduledAtEpochMs"] == at and
390 + not state["reminders"][0].get("delivered", False), "real_record_schedule_not_persisted")
391 + require(not self.active_keys(), "unexpected_fixture_notification_before_deadline")
392 + return at, state
393 +
394 + def wait_for_post(self, at):
395 + until = self.clock() + max(0, (at - self.device_epoch_ms()) / 1000) + 30
396 + while True:
397 + keys = self.active_keys()
398 + if keys:
399 + require(self.device_epoch_ms() + 1000 >= at, "fixture_notification_posted_before_deadline")
400 + return keys[0]
401 + require(self.clock() < until, "fixture_notification_not_posted")
402 + self.sleep(1)
403 +
404 + def assert_no_post_through(self, at):
405 + until = self.clock() + max(0, (at - self.device_epoch_ms()) / 1000) + 5
406 + while True:
407 + require(not self.active_keys(), "canceled_fixture_notification_posted")
408 + if self.clock() >= until:
409 + return
410 + self.sleep(min(1, until - self.clock()))
411 +
412 + def run(self):
413 + self.install_user()
414 + self.first_user_launch()
415 + self.install_fixture()
416 + self.align_to_minute()
417 + seeded = self.launch("seed")
418 + self.assert_database(seeded, {"rawSqlAfterClose", "profilePersists", "weeklyDifferentTimes", "onceAndEveryTwoDays"})
419 + at, scheduled = self.assert_scheduled(seeded)
420 + self.process_dead(before=at)
421 + require(self.preferences() == scheduled and not self.active_keys(), "alarm_preceded_process_absence_proof")
422 + self.receipt["checks"]["processAbsentBeforeAlarm"] = "PASS"
423 + key = self.wait_for_post(at)
424 + require(key.split("|")[3] == "lifeguide-plan:" + scheduled["reminders"][0]["id"], "notification_not_from_sqlite_record")
425 + delivered = self.preferences()
426 + require(delivered is not None and delivered["generation"] == scheduled["generation"] and
427 + len(delivered["reminders"]) == 1 and delivered["reminders"][0].get("delivered") is True,
428 + "native_delivered_marker_missing")
429 + self.receipt["checks"]["notificationAfterProcessDeath"] = "PASS"
430 + self.receipt["checks"]["notificationContent"] = check_notification_record(
431 + self.adb.shell("dumpsys", "notification", "--noredact"), key)
432 + inspected = self.launch("inspect")
433 + self.assert_status(inspected, active=True, count=0)
434 + self.assert_database(inspected, {"rawSqlAfterClose", "profilePersists", "weeklyDifferentTimes", "onceAndEveryTwoDays"})
435 + require(self.preferences() == delivered and self.active_keys() == [key], "inspect_changed_delivered_state_or_post")
436 + self.receipt["checks"]["relaunchReadOnlyPreservesNativeGeneration"] = "PASS"
437 + self.align_to_minute()
438 + changed = self.launch("change")
439 + self.assert_database(changed, {"rawSqlAfterClose", "profilePersists", "independentEditAndTick"})
440 + canceled_at, _ = self.assert_scheduled(changed)
441 + canceled = self.launch("cancel")
442 + self.assert_status(canceled, active=True, count=0)
443 + self.assert_database(canceled, {"rawSqlAfterClose", "archivePersists", "independentEditAndTick"})
444 + require(self.device_epoch_ms() + 1000 < canceled_at, "fixture_cancellation_missed_deadline")
445 + state = self.preferences()
446 + require(state is not None and state["reminders"] == [] and not self.active_keys(), "archive_did_not_cancel_native_alarm")
447 + self.process_dead(before=canceled_at)
448 + self.assert_no_post_through(canceled_at)
449 + self.receipt["checks"]["archiveBeforeDeadlineHasNoOSPost"] = "PASS"
450 + off = self.launch("off")
451 + self.assert_status(off, active=False, count=0)
452 + require(self.preferences() is None and not self.active_keys(), "off_did_not_clear_native_state")
453 + self.receipt["checks"]["offClearsNativeState"] = "PASS"
454 + self.receipt["currentPhase"], self.receipt["result"] = "complete", "PASS"
455 + return self.receipt
456 +
457 +
458 +def main(argv=None):
459 + parser = argparse.ArgumentParser(description=__doc__)
460 + parser.add_argument("--user-apk", required=True, type=Path)
461 + parser.add_argument("--fixture-apk", required=True, type=Path)
462 + parser.add_argument("--serial", required=True)
463 + parser.add_argument("--allow-synthetic-emulator-reset", action="store_true")
464 + parser.add_argument("--output", required=True, type=Path)
465 + options = parser.parse_args(argv)
466 + harness = Harness(serial=options.serial, user_apk=options.user_apk,
467 + fixture_apk=options.fixture_apk, allow_reset=options.allow_synthetic_emulator_reset,
468 + screenshot=options.output.with_name("standalone-user-first-launch.png"))
469 + try:
470 + harness.run()
471 + except AcceptanceError as error:
472 + harness.receipt["error"] = str(error)
473 + except Exception:
474 + harness.receipt["error"] = "unexpected_acceptance_failure"
475 + options.output.parent.mkdir(parents=True, exist_ok=True)
476 + options.output.write_text(json.dumps(harness.receipt, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
477 + print(json.dumps({"result": harness.receipt["result"], "error": harness.receipt.get("error")}))
478 + return 0 if harness.receipt["result"] == "PASS" else 1
479 +
480 +
481 +if __name__ == "__main__":
482 + raise SystemExit(main())
apps/lifemate/tool/test_standalone_android_test.py new
+378
@@ -0,0 +1,378 @@
1 +"""Host safety tests; these are not evidence of Android or SQLite execution."""
2 +import contextlib
3 +import io
4 +import json
5 +import tempfile
6 +import unittest
7 +from pathlib import Path
8 +from unittest.mock import patch
9 +from urllib.parse import parse_qs, urlparse
10 +from xml.sax.saxutils import escape
11 +
12 +import test_standalone_android as subject
13 +
14 +
15 +class FakeAdb:
16 + def __init__(self, overrides=None):
17 + self.calls = []
18 + self.responses = {
19 + ("get-state",): "device\n",
20 + ("shell", "getprop", "ro.kernel.qemu"): "1\n",
21 + ("shell", "getprop", "ro.boot.qemu"): "1\n",
22 + ("shell", "getprop", "ro.hardware"): "ranchu\n",
23 + ("shell", "getprop", "ro.product.name"): "sdk_gphone64_x86_64\n",
24 + ("shell", "getprop", "ro.build.version.sdk"): "35\n",
25 + ("shell", "pm", "list", "packages", subject.PACKAGE): "",
26 + }
27 + self.responses.update(overrides or {})
28 +
29 + def command(self, *parts, allow_failure=False):
30 + self.calls.append(parts)
31 + if parts[0] == "install":
32 + return "Success\n"
33 + return self.responses.get(parts, "")
34 +
35 + def shell(self, *parts, allow_failure=False):
36 + return self.command("shell", *parts, allow_failure=allow_failure)
37 +
38 +
39 +class SafetyTest(unittest.TestCase):
40 + def setUp(self):
41 + self.directory = tempfile.TemporaryDirectory()
42 + self.addCleanup(self.directory.cleanup)
43 + self.user = Path(self.directory.name) / "user.apk"
44 + self.fixture = Path(self.directory.name) / "fixture.apk"
45 + self.user.write_bytes(b"user placeholder")
46 + self.fixture.write_bytes(b"fixture placeholder")
47 + self.manifest = {"result": "PASS", "package": subject.PACKAGE,
48 + "label": subject.LABEL, "debuggable": True, "internetPermission": False,
49 + "targetSdkVersion": 36, "sha256": "a" * 64}
50 +
51 + def harness(self, adb, **extra):
52 + values = dict(serial="emulator-5554", user_apk=self.user,
53 + fixture_apk=self.fixture, allow_reset=True, adb=adb,
54 + manifest_check=lambda path: self.manifest,
55 + certificate_check=lambda path: "b" * 64,
56 + screenshot=Path(self.directory.name) / "first-launch.png")
57 + values.update(extra)
58 + return subject.Harness(**values)
59 +
60 + def assert_read_only(self, adb):
61 + for parts in adb.calls:
62 + self.assertNotEqual(parts[0], "install")
63 + if parts[0] == "shell":
64 + self.assertIn(parts[1:3], [("getprop", "ro.kernel.qemu"),
65 + ("getprop", "ro.boot.qemu"), ("getprop", "ro.hardware"),
66 + ("getprop", "ro.product.name"), ("getprop", "ro.build.version.sdk"),
67 + ("pm", "list")])
68 +
69 + def test_physical_and_implicit_serial_refused_without_adb(self):
70 + for serial in ("", "R58PHONE", "emulator-5554;bad", "emulator-5555", "emulator-5554\n"):
71 + adb = FakeAdb()
72 + with self.subTest(serial=serial), self.assertRaises(subject.AcceptanceError):
73 + self.harness(adb, serial=serial).install_user()
74 + self.assertEqual(adb.calls, [])
75 +
76 + def test_confirmation_and_two_existing_apks_required_before_adb(self):
77 + for change in ({"allow_reset": False}, {"user_apk": self.user.with_name("absent")},
78 + {"fixture_apk": self.fixture.with_name("absent")}):
79 + adb = FakeAdb()
80 + with self.subTest(change=change), self.assertRaises(subject.AcceptanceError):
81 + self.harness(adb, **change).install_user()
82 + self.assertEqual(adb.calls, [])
83 +
84 + def test_both_manifest_and_same_certificate_checked_before_adb(self):
85 + for change in ({"debuggable": False}, {"internetPermission": True},
86 + {"label": "other"}, {"package": "ir.lifeguide.app"},
87 + {"targetSdkVersion": 35}):
88 + adb = FakeAdb()
89 + with self.subTest(change=change), self.assertRaises(subject.AcceptanceError):
90 + self.harness(adb, manifest_check=lambda path: self.manifest | change).install_user()
91 + self.assertEqual(adb.calls, [])
92 + adb = FakeAdb()
93 + with self.assertRaisesRegex(subject.AcceptanceError, "apk_certificates_differ"):
94 + self.harness(adb, certificate_check=lambda path: ("b" if path == self.user else "c") * 64).install_user()
95 + self.assertEqual(adb.calls, [])
96 +
97 + def test_all_emulator_gates_precede_writes(self):
98 + for override in ({("get-state",): "offline"},
99 + {("shell", "getprop", "ro.kernel.qemu"): "0", ("shell", "getprop", "ro.boot.qemu"): "0"},
100 + {("shell", "getprop", "ro.hardware"): "phone"},
101 + {("shell", "getprop", "ro.product.name"): "owner"},
102 + {("shell", "getprop", "ro.build.version.sdk"): "34"},
103 + {("shell", "pm", "list", "packages", subject.PACKAGE): "package:" + subject.PACKAGE}):
104 + adb = FakeAdb(override)
105 + with self.subTest(override=override), self.assertRaises(subject.AcceptanceError):
106 + self.harness(adb).install_user()
107 + self.assert_read_only(adb)
108 +
109 + def test_owned_upgrade_requires_actual_first_launch_proof(self):
110 + adb = FakeAdb()
111 + harness = self.harness(adb)
112 + harness.install_user()
113 + with self.assertRaisesRegex(subject.AcceptanceError, "user_first_launch_not_verified"):
114 + harness.install_fixture()
115 + installs = [call for call in adb.calls if call[0] == "install"]
116 + self.assertEqual(installs, [("install", str(self.user))])
117 + harness.user_launched = True
118 + adb.responses[("shell", "sh", "-c", subject.PID_QUERY)] = "ABSENT"
119 + harness.install_fixture()
120 + self.assertIn(("install", "-r", str(self.fixture)), adb.calls)
121 + commands = " ".join(" ".join(call) for call in adb.calls)
122 + for forbidden in ("uninstall", "force-stop", "kill-server", "logcat -c"):
123 + self.assertNotIn(forbidden, commands)
124 +
125 + def test_empty_pid_response_is_not_absence_and_late_absence_is_not_proof(self):
126 + adb = FakeAdb()
127 + harness = self.harness(adb)
128 + harness.installed = True
129 + with self.assertRaisesRegex(subject.AcceptanceError, "fixture_process_query_failed"):
130 + harness.process_dead()
131 + adb.responses[("shell", "sh", "-c", subject.PID_QUERY)] = "ABSENT"
132 + adb.responses[("shell", "date", "+%s")] = "1800000046"
133 + with self.assertRaisesRegex(subject.AcceptanceError, "process_absence_missed_alarm_deadline"):
134 + harness.process_dead(before=1800000045000)
135 + self.assertNotIn("processAbsentBeforeAlarm", harness.receipt["checks"])
136 +
137 + def test_cli_refusal_receipt_does_not_expose_raw_arguments(self):
138 + output = Path(self.directory.name) / "receipt.json"
139 + with patch.object(subject, "Adb") as adb, contextlib.redirect_stdout(io.StringIO()):
140 + code = subject.main(["--user-apk", str(self.user), "--fixture-apk", str(self.fixture),
141 + "--serial", "PRIVATE_PHONE", "--allow-synthetic-emulator-reset", "--output", str(output)])
142 + self.assertEqual(code, 1)
143 + adb.assert_not_called()
144 + self.assertNotIn("PRIVATE_PHONE", output.read_text())
145 +
146 +
147 +class ParsingTest(unittest.TestCase):
148 + def marker(self, mode="seed"):
149 + return {"nonce": "0123456789abcdef", "mode": mode, "syntheticDataOnly": True,
150 + "database": subject.DATABASE, "checks": {"rawSqlAfterClose": True,
151 + "profilePersists": True, "weeklyDifferentTimes": True,
152 + "onceAndEveryTwoDays": True},
153 + "status": {"supported": True, "permissionGranted": True, "active": True, "enabled": True,
154 + "activeScope": subject.SCOPE, "scheduledCount": 1,
155 + "timing": "exact", "canScheduleExactAlarms": True},
156 + "scheduledAtEpochMs": 1800000045000}
157 +
158 + def test_marker_whitelist_discards_arbitrary_private_fields(self):
159 + marker = self.marker() | {"private": "DO_NOT_PUBLISH"}
160 + marker["checks"]["private"] = "DO_NOT_PUBLISH"
161 + parsed = subject.fixture_marker(subject.MARKER + json.dumps(marker), marker["nonce"], "seed")
162 + self.assertNotIn("DO_NOT_PUBLISH", json.dumps(parsed))
163 + self.assertIsNone(subject.fixture_marker(subject.MARKER + json.dumps(marker), "a" * 16, "seed"))
164 +
165 + def test_marker_rejects_wrong_database_scope_or_fixture_label(self):
166 + for update in ({"database": "lifeguide_standalone_v1.sqlite"},
167 + {"syntheticDataOnly": False}, {"mode": "inspect"},
168 + {"status": self.marker()["status"] | {"activeScope": "private"}}):
169 + marker = self.marker() | update
170 + with self.subTest(update=update), self.assertRaises(subject.AcceptanceError):
171 + subject.fixture_marker(subject.MARKER + json.dumps(marker), marker["nonce"], "seed")
172 +
173 + def test_notification_parser_accepts_only_owned_uuid_tag(self):
174 + identifier = "33333333-3333-4333-8333-333333333333"
175 + key = f"0|{subject.PACKAGE}|1|lifeguide-plan:{identifier}|10123"
176 + self.assertEqual(subject.active_fixture_keys(key), [key])
177 + with self.assertRaisesRegex(subject.AcceptanceError, "unexpected_fixture_notification"):
178 + subject.active_fixture_keys(f"0|{subject.PACKAGE}|1|private-title|10123")
179 +
180 + def test_preferences_only_allow_synthetic_scope_and_companion(self):
181 + from xml.sax.saxutils import escape
182 + row = {"id": "33333333-3333-4333-8333-333333333333",
183 + "planItemId": "33333333-3333-4333-8333-333333333333",
184 + "scheduledAtEpochMs": 1800000045000, "companionName": subject.COMPANION}
185 + state = {"scope": subject.SCOPE, "generation": "44444444-4444-4444-8444-444444444444",
186 + "issuedAtEpochMs": 1800000000000, "validUntilEpochMs": 1800086400000,
187 + "reminders": [row], "leaseKind": "device-planner-v1"}
188 + def xml():
189 + return '<map><string name="active">' + escape(json.dumps(state)) + '</string></map>'
190 + self.assertEqual(subject.parse_preferences(xml()), state)
191 + row["companionName"] = "private user name"
192 + with self.assertRaises(subject.AcceptanceError) as caught:
193 + subject.parse_preferences(xml())
194 + self.assertNotIn("private user name", str(caught.exception))
195 +
196 + def test_fixture_source_has_separate_db_and_no_server_acknowledgement(self):
197 + source = Path(__file__).with_name("standalone_acceptance_fixture.dart").read_text()
198 + self.assertIn("LG_STANDALONE_ACCEPTANCE", source)
199 + self.assertIn("StandaloneStore.open", source)
200 + self.assertIn("rawQuery", source)
201 + self.assertIn(subject.DATABASE, source)
202 + self.assertNotIn("serverAcknowledged", source)
203 + self.assertNotIn("LocalOnlyApi", source)
204 +
205 +
206 +class SyntheticEmulator(FakeAdb):
207 + """A host model for orchestration checks, never Android acceptance evidence."""
208 + def __init__(self):
209 + super().__init__()
210 + self.elapsed = 0
211 + self.alive = self.posted = self.enabled = False
212 + self.state = None
213 + self.markers, self.modes = [], []
214 + self.refuse_kill = False
215 + self.pid_failure = False
216 + self.background_delay = 0
217 + self.background_ready = 0
218 + self.late_kill = False
219 + self.identifier = "33333333-3333-4333-8333-333333333333"
220 +
221 + def clock(self):
222 + return self.elapsed
223 +
224 + def epoch(self):
225 + return 1800000010000 + int(self.elapsed * 1000)
226 +
227 + def sleep(self, seconds):
228 + self.elapsed += seconds
229 + if self.state and self.state["reminders"]:
230 + row = self.state["reminders"][0]
231 + if not row.get("delivered") and row["scheduledAtEpochMs"] <= self.epoch():
232 + row["delivered"] = True
233 + self.posted = self.alive = True
234 +
235 + def key(self):
236 + return f"0|{subject.PACKAGE}|1|lifeguide-plan:{self.identifier}|10123"
237 +
238 + def command(self, *parts, allow_failure=False):
239 + if parts[0] == "install":
240 + return super().command(*parts, allow_failure=allow_failure)
241 + self.calls.append(parts)
242 + if parts == ("shell", "input", "keyevent", "KEYCODE_HOME"):
243 + self.background_ready = self.elapsed + self.background_delay
244 + return ""
245 + if parts == ("shell", "am", "kill", subject.PACKAGE):
246 + if self.late_kill and self.state and self.state["reminders"]:
247 + self.sleep(60)
248 + self.alive = self.refuse_kill or self.elapsed < self.background_ready
249 + return ""
250 + if parts == ("shell", "sh", "-c", subject.PID_QUERY):
251 + return "" if self.pid_failure else ("PRESENT" if self.alive else "ABSENT")
252 + if parts == ("shell", "date", "+%s"):
253 + return str(self.epoch() // 1000)
254 + if parts[0] == "logcat":
255 + return "\n".join(self.markers)
256 + if parts[:3] == ("shell", "run-as", subject.PACKAGE):
257 + return "<map/>" if self.state is None else ('<map><string name="active">' +
258 + escape(json.dumps(self.state)) + '</string></map>')
259 + if parts == ("shell", "cmd", "notification", "list"):
260 + return self.key() if self.posted else ""
261 + if parts[:3] == ("shell", "dumpsys", "notification"):
262 + return (f"NotificationRecord(pkg={subject.PACKAGE} key={self.key()}: "
263 + f"Notification(channel={subject.CHANNEL}))\n"
264 + f"android.title=String ({subject.COMPANION})\n"
265 + f"android.text=String ({subject.GENERIC_BODY})\n")
266 + if parts[:3] == ("shell", "am", "start"):
267 + self.alive = True
268 + if "--es" not in parts:
269 + return "Status: ok"
270 + route = urlparse(parts[-1])
271 + mode = route.path[1:]
272 + self.modes.append(mode)
273 + at = None
274 + if mode in ("seed", "change"):
275 + at = (self.epoch() // 60000 + 1) * 60000
276 + self.enabled, self.posted = True, False
277 + self.state = {"scope": subject.SCOPE,
278 + "generation": "44444444-4444-4444-8444-444444444444",
279 + "issuedAtEpochMs": self.epoch(), "validUntilEpochMs": self.epoch() + 31 * 86400000,
280 + "leaseKind": "device-planner-v1", "reminders": [{"id": self.identifier,
281 + "planItemId": self.identifier, "companionName": subject.COMPANION,
282 + "scheduledAtEpochMs": at}]}
283 + elif mode == "cancel":
284 + self.state["reminders"] = []
285 + self.posted = False
286 + elif mode == "off":
287 + self.enabled, self.posted, self.state = False, False, None
288 + status = {"supported": True, "permissionGranted": True,
289 + "active": self.state is not None, "enabled": self.enabled,
290 + "activeScope": subject.SCOPE if self.state else None,
291 + "scheduledCount": sum(r["scheduledAtEpochMs"] > self.epoch()
292 + for r in self.state["reminders"]) if self.state else 0,
293 + "timing": "exact", "canScheduleExactAlarms": True}
294 + marker = {"nonce": parse_qs(route.query)["nonce"][0], "mode": mode,
295 + "syntheticDataOnly": True, "database": subject.DATABASE, "status": status,
296 + "checks": {k: True for k in subject.CHECKS}}
297 + if at:
298 + marker["scheduledAtEpochMs"] = at
299 + self.markers.append(subject.MARKER + json.dumps(marker))
300 + return "Status: ok"
301 + return self.responses.get(parts, "")
302 +
303 +
304 +class LifecycleTest(unittest.TestCase):
305 + setUp = SafetyTest.setUp
306 +
307 + def harness(self, adb, **extra):
308 + values = {"clock": adb.clock, "sleep": adb.sleep}
309 + values.update(extra)
310 + return SafetyTest.harness(self, adb, **values)
311 +
312 + def first_launch(self, harness):
313 + # Real screenshot handling is separately tested below; this host model
314 + # cannot provide a genuine image from an Android display.
315 + harness.adb.shell("am", "start", "-W", "-f", "0x10008000", "-n", subject.COMPONENT)
316 + harness.user_launched = True
317 +
318 + def test_full_mode_sequence_and_sanitized_receipt(self):
319 + adb = SyntheticEmulator()
320 + harness = self.harness(adb)
321 + with patch.object(harness, "first_user_launch", side_effect=lambda: self.first_launch(harness)):
322 + receipt = harness.run()
323 + self.assertEqual(receipt["result"], "PASS")
324 + self.assertEqual(adb.modes, ["seed", "inspect", "change", "cancel", "off"])
325 + self.assertIsNone(adb.state)
326 + self.assertFalse(adb.posted)
327 + self.assertGreater(adb.elapsed, 95)
328 + self.assertTrue(all(value == "UNVERIFIED" for value in receipt["limitations"].values()))
329 + serialized = json.dumps(receipt)
330 + for forbidden in (subject.CANARY, "NotificationRecord", "<map", "nonce"):
331 + self.assertNotIn(forbidden, serialized)
332 + launches = [p for p in adb.calls if p[:3] == ("shell", "am", "start")]
333 + self.assertNotIn("--es", launches[0])
334 + for parts in launches:
335 + self.assertIn(subject.COMPONENT, parts)
336 + self.assertEqual(parts[parts.index("-f") + 1], "0x10008000")
337 + commands = " ".join(" ".join(call) for call in adb.calls)
338 + for forbidden in ("uninstall", "force-stop", "kill-server", "logcat -c"):
339 + self.assertNotIn(forbidden, commands)
340 +
341 + def test_real_first_launch_path_requires_present_pid_and_valid_png(self):
342 + import struct
343 + adb = SyntheticEmulator()
344 + harness = self.harness(adb)
345 + harness.install_user()
346 + png = b"\x89PNG\r\n\x1a\n" + b"\0\0\0\rIHDR" + struct.pack(">II", 1080, 1920)
347 + result = type("Result", (), {"returncode": 0, "stdout": png})()
348 + with patch.object(subject.subprocess, "run", return_value=result):
349 + harness.first_user_launch()
350 + self.assertTrue(harness.user_launched)
351 + self.assertEqual(harness.screenshot.read_bytes(), png)
352 + self.assertTrue(harness.receipt["userFirstLaunch"]["ordinaryLaunchNoExtras"])
353 +
354 + def test_background_transition_retries_and_failed_pid_never_claims_absence(self):
355 + adb = SyntheticEmulator()
356 + adb.background_delay = 1
357 + harness = self.harness(adb)
358 + harness.installed = True
359 + harness.process_dead()
360 + self.assertGreaterEqual(adb.elapsed, 1)
361 + self.assertGreater(harness.receipt["processExit"]["ordinaryKillAttempts"], 1)
362 + adb.pid_failure = True
363 + with self.assertRaisesRegex(subject.AcceptanceError, "fixture_process_query_failed"):
364 + harness.process_dead()
365 + self.assertNotIn("processExit", harness.receipt)
366 +
367 + def test_late_absence_cannot_claim_notification_after_process_death(self):
368 + adb = SyntheticEmulator()
369 + adb.late_kill = True
370 + harness = self.harness(adb)
371 + with patch.object(harness, "first_user_launch", side_effect=lambda: self.first_launch(harness)):
372 + with self.assertRaisesRegex(subject.AcceptanceError, "process_absence_missed_alarm_deadline"):
373 + harness.run()
374 + self.assertNotIn("processAbsentBeforeAlarm", harness.receipt["checks"])
375 +
376 +
377 +if __name__ == "__main__":
378 + unittest.main()
docs/decisions/0016-initial-child-planner-delivery.md
+6 -2
@@ -1,6 +1,6 @@
1 # 0016 — مسیر APK اولیهٔ برنامهٔ شخصی کودک
2
3 -وضعیت: PROPOSED — تصمیم مالک لازم است؛ کد مجوز یا سرویس زنده تغییر نکرده است.
3 +وضعیت: ACCEPTED برای D-A، صرفاً APK اولیهٔ شخصی — ۲۰۲۶-۱۰-۱۹. هویت/مجوز نسخهٔ آنلاین و سرویس زنده تغییر نمی‌کند.
4
5 مالک بستهٔ برنامهٔ هفتگی، تکرار، یادآوری، تیک مستقل و حفظ داده پس از بازگشایی را برای APK اولیه تأیید کرد. تأیید، مجوز deploy یا بازکردن برنامهٔ خصوصی برای نشست دعوت/بازیابی‌شدهٔ والد نیست. نشست محدود فعلی، برنامه‌ریز خصوصی را عمداً رد می‌کند؛ سرور آنلاین یکپارچه نیز برای تحویل این بسته هنوز آزموده نشده است.
6
@@ -9,4 +9,8 @@
9 | D-A — APK شخصی مستقل روی گوشی، پیشنهاد برای آزمون اولیه | بدون URL، پیامک یا سرور؛ دادهٔ واقعی فقط داخل همان گوشی، برنامهٔ هفتگی و اعلان محلی. رابط و ذخیره‌سازی واقعی، بدون دادهٔ ساختگی. جداسازی صریح از نسخهٔ آنلاین و بدون انتقال خودکار. | مشاهدهٔ والد، چنددستگاهی، همگام‌سازی و بازیابی از سرور ندارد. تکمیل هدف آنلاین خانواده محسوب نمی‌شود. انتخاب ساختار و بازیابی خصوصی کودک به نسخهٔ آنلاین موکول می‌شود. |
10 | D-B — فقط APK آنلاین | ساخت کلاینت روی API موجود؛ استفادهٔ کودک پس از تعیین سرور، تأیید ورود/حریم خصوصی و آزمون یکپارچه. دادهٔ محلی فقط کش/صف است. | بدون این پیش‌نیازها، APK نصب می‌شود ولی قابل بهره‌برداری کودک نیست؛ نشانی یا حساب نمایشی جای سرور واقعی قرار نمی‌گیرد. |
11
12 -تا پاسخ مالک، توسعهٔ مشترک برنامهٔ تکراری و پورت اعلان Android با دادهٔ ساختگی و آزمون محلی ادامه دارد. هیچ مسیر محلی جدید، انتشار عمومی، دادهٔ واقعی روی میزبان خارجی یا گسترش دسترسی نشست محدود فعال نمی‌شود. برای اعلان، مجوز سیستم، وضعیت دقیق/تقریبی و محدودیت باتری/توقف اجباری باید صریح نمایش و آزموده شود.
12 +مبنای تصمیم: مالک پس از توضیح مانع API گفت «اگر بدون api فایل apk کار نمیکنه پس کارایی نداره کامل کن و فایل صحیح رو بده». سپس محدودهٔ نسخهٔ مستقل روی گوشی، بدون URL و بدون همگام‌سازی خانواده در پاسخ توضیح داده شد و مالک گفت «ادامه بده». این تأیید برای بستهٔ اولیهٔ D-A ثبت می‌شود؛ هدف آنلاین خانواده همچنان باقی است.
13 +
14 +بستهٔ جدا با شناسهٔ آزمایشی `ir.lifeguide.app.device` و نام «لایف‌گاید شخصی» کنار APK قبلی نصب می‌شود. شناسهٔ نهایی نسخهٔ آنلاین `ir.lifeguide.app` حفظ می‌شود. دیتابیس SQLite خصوصی داخل همین بسته، مرجع واقعی نسخهٔ شخصی است؛ دادهٔ قبلی به‌صورت خودکار کپی/حذف/ارسال نمی‌شود. مجوز INTERNET از manifest نهایی نسخهٔ شخصی حذف و بررسی می‌شود. نشان محلی‌بودن و نبود بازیابی سروری در شروع/تنظیمات صریح است.
15 +
16 +دادهٔ تست فقط ساختگی است. ساخت و تحویل debug اولیه مجوز انتشار تجاری، merge، deploy، DNS، ارسال دادهٔ واقعی به میزبان خارجی یا گسترش دسترسی نشست کودک نیست. برای اعلان، مجوز سیستم، وضعیت دقیق/تقریبی و محدودیت باتری/توقف اجباری باید صریح نمایش و آزموده شود.
docs/operations/PERSONAL_ANDROID.md new
+45
@@ -0,0 +1,45 @@
1 +# لایف‌گاید شخصی — تحویل اولیهٔ Android
2 +
3 +این بسته طبق انتخاب D-A در ADR0016 برای استفادهٔ اولیهٔ شخصی روی یک گوشی است. API، URL، ورود، اینترنت و حساب آزمایشی نمی‌خواهد. برنامهٔ آنلاین خانواده تغییر نکرده است. این بسته نسخهٔ کامل خانوادگی یا انتشار رسمی نیست.
4 +
5 +## رفتار قابل بررسی
6 +
7 +- نام دلخواه و گروه پروفایل محلی؛ گروه، مجوز یا نقش خانوادگی نیست.
8 +- برنامهٔ یک‌باره، هر روز، یک روز در میان، یا روزهای انتخابی هفته با ساعت‌های متفاوت.
9 +- ساعت شروع/پایان و یادآوری اختیاری؛ تیک، ویرایش یک نوبت، بایگانی نوبت یا کل برنامه.
10 +- SQLite خصوصی و تراکنشی روی همان گوشی، UUID پایدار و نسخهٔ schema؛ خطای خواندن/نوشتن نمایش داده می‌شود و داده خودکار بازنشانی نمی‌شود.
11 +- سه مقصد «امروز / هفته / تنظیمات»، نام همراه و چهار تم قابل تغییر. تاریخ‌های این بسته میلادی‌اند و روزهای هفته فارسی هستند.
12 +- اعلان با انتخاب صریح کاربر و مجوز Android؛ نام همراه + متن عمومی، بدون عنوان خصوصی کار. حداکثر ۱۲۸ یادآوری نزدیک‌تر در ۲۸ روز؛ برای آماده‌شدن روزهای بعد برنامه را مرتب باز کنید.
13 +
14 +## نصب و پذیرش روی گوشی
15 +
16 +نام نصب «لایف‌گاید شخصی»، شناسهٔ جدا `ir.lifeguide.app.device`، نسخه `0.7.2-personal.1` / code9 است؛ برنامهٔ آنلاین `ir.lifeguide.app` و اطلاعات قبلی آن جدا می‌مانند. APK آزمایشی debug است؛ به‌عنوان release امضاشده معرفی نشود.
17 +
18 +۱. `LifeGuide.apk` همین تحویل را نصب کنید؛ برنامهٔ قبلی را پاک نکنید.
19 +۲. نام دلخواه و گروه را وارد کنید؛ آدرس سرور نباید پرسیده شود.
20 +۳. یک برنامهٔ هفتگی با دو روز و دو ساعت متفاوت بسازید، و یک عادت یک‌روزدرمیان.
21 +۴. تیک یک نوبت و ساعت نوبت دیگری را عوض کنید؛ برنامه را عادی ببندید و باز کنید. تغییرها باید بمانند.
22 +۵. در تنظیمات، اعلان را روشن و مجوز سیستم را تأیید کنید. برای آزمون، یک نوبت چند دقیقهٔ بعد و یادآوری «هنگام شروع» بسازید؛ برنامه را عادی ببندید و اعلان را بررسی کنید.
23 +۶. همان نوبت را پیش از موعد تیک بزنید/بایگانی کنید؛ اعلان نباید برای آن نمایش داده شود. خاموش‌کردن اعلان باید یادآوری‌های فعال را لغو کند.
24 +
25 +صدا/لرزش، Doze، reboot، مجوزهای سازنده، نصب/ارتقا و زمان‌بندی approximate روی گوشی واقعی **UNVERIFIED** هستند. زمان‌بندی دقیق به مجوز سیستم وابسته است؛ اعلان تضمین شنیدن آلارم نیست. Force-stop با بستن عادی فرق دارد و می‌تواند اعلان را متوقف کند.
26 +
27 +**داده فقط روی این گوشی است.** حذف برنامه، پاک‌کردن داده یا خرابی/گم‌شدن گوشی می‌تواند برنامه‌ها را از بین ببرد. بازیابی سرور، خروجی/backup و همگام‌سازی این بسته وجود ندارد. برای حل اختلاف امضا هرگز حذف داده/برنامه پیشنهاد نشود. حفظ کلید و مسیر ارتقای بدون حذف داده هنوز **UNVERIFIED** است؛ گواهی امضای این تحویل باید ثبت شود.
28 +
29 +## ساخت و کنترل محلی/CI
30 +
31 +```sh
32 +cd apps/lifemate
33 +flutter pub get
34 +flutter analyze
35 +flutter test
36 +python3 -m unittest discover -s tool -p '*standalone*test.py' -v
37 +ORG_GRADLE_PROJECT_lifeguideDevicePlanner=true flutter build apk --debug \
38 + --target=lib/standalone_main.dart --dart-define=LIFEGUIDE_STANDALONE=true \
39 + --build-name=0.7.2-personal.1 --build-number=9
40 +python3 tool/check_standalone_apk.py build/app/outputs/flutter-apk/app-debug.apk
41 +```
42 +
43 +Workflow `standalone-personal-apk.yml` ابتدا APK واقعی کاربر را می‌سازد و اولین اجرای آن را ثبت می‌کند؛ سپس فقط در AVD تازه، fixture هم‌امضا را روی همان نصب آزمایشی جایگزین می‌کند. fixture پایگاه جدا `standalone_acceptance.sqlite` دارد و هرگز توزیع نمی‌شود. آزمون آن SQLite واقعی + SQL مستقل بعد از close/reopen + مرگ عادی پردازش + NotificationManager واقعی + لغو پیش از موعد است. ساخت/اجرای واقعی و دستور/خروجی در receipt تحویل ثبت می‌شوند؛ تعریف workflow به‌تنهایی نتیجهٔ موفق نیست.
44 +
45 +هیچ merge، deploy، تغییر DNS یا دادهٔ واقعی مجاز نشده و در این بسته انجام نمی‌شود. PWA/Safari، خانوادهٔ آنلاین، ورود کودک/والد و محتوای درسی جزو پذیرش این APK شخصی نیستند.
docs/superpowers/plans/2026-10-19-standalone-weekly-planner.md new
+61
@@ -0,0 +1,61 @@
1 +# LifeGuide personal device planner — implementation plan
2 +
3 +> **For agentic workers:** Use isolated specialist ownership with integration and independent review by the root. Checkboxes record the bounded delivery, not release readiness.
4 +
5 +**Goal:** Deliver an Android APK usable immediately without API setup: private weekly planning, independent occurrence completion, local notifications and durable restart.
6 +**Architecture:** Separate debug-only Android package/entrypoint; authoritative transactional SQLite, no HTTP imports or INTERNET permission. Reuse the proven native alarm engine behind a distinct guarded device channel; keep online identity/permissions unchanged.
7 +**Tech stack:** Flutter3.47.6, Dart, sqflite, Android AlarmManager/NotificationManager.
8 +**Spec:** [ADR0016](../../decisions/0016-initial-child-planner-delivery.md), current owner instruction for a usable APK without API and subsequent continue after scoped explanation.
9 +
10 +## Global constraints
11 +
12 +- One local personal profile; profile_category never grants a family role. No phone/email/OTP/server account claims.
13 +- Separate `ir.lifeguide.app.device`, label «لایف‌گاید شخصی», version0.7.2-personal.1/code9; production `ir.lifeguide.app` unchanged. Debug is not a release.
14 +- SQLite v1 in app-private storage, backup disabled. No imports from online API/cache/auth. No sample rows in the user build; fixtures use separate database files.
15 +- No merge/deploy/DNS/foreign real child data. Tests synthetic; every runtime claim needs commands/output. Phone/Safari/Iran acceptance stays UNVERIFIED.
16 +
17 +## Review focus
18 +
19 +1. Save failures/corrupt DB must never report success or silently reset data.
20 +2. Repeated generation and restarts cannot duplicate occurrences or tick a different date.
21 +3. An OFF choice or edited/completed item must not reappear as a stale alarm after asynchronous work/restart.
22 +4. The user artifact must be the real standalone entrypoint, not a fixture or ordinary online APK.
23 +5. App update/install must not overwrite an older app/account/cache or require data deletion.
24 +
25 +## Task1 — Durable personal data (owner: standalone_storage)
26 +
27 +- [ ] Implement `lib/standalone/model.dart` and `store.dart` and actual file DB tests in `test/standalone_store_test.dart`.
28 +- [ ] Single editable profile; daily/every2days/weekday slots/one-off, independent occurrence edits, completion and archive.
29 +- [ ] Verify Create→Close→Reopen→Read→Update→Read→Archive; transactions, validation, stable IDs and generation uniqueness.
30 +
31 +## Task2 — Working RTL interface (owner: standalone_ui)
32 +
33 +- [ ] `standalone/app.dart`, `planner_ui.dart`, `settings_ui.dart`, focused widget tests. No account/server screens or inert feature cards.
34 +- [ ] Home, Saturday-first week, editable forms, per-occurrence details, explicit device-only setting, local profile/theme edits.
35 +- [ ] Before-write alarm invalidation, awaited save, after-write refresh; storage failures stay visible without clearing data.
36 +
37 +## Task3 — Local reminders (owner: standalone_reminders; native helper owns its Kotlin files)
38 +
39 +- [ ] Dedicated device-only types/channel; BuildConfig guard; no fabricated server acknowledgement.
40 +- [ ] Default OFF, explicit permission/opt-in, next28days/max128 nearest records with visible limit; generic lock-screen body and chosen companion name.
41 +- [ ] Native and Dart OFF choices fail closed; suspend before data writes and reconcile only from actual DB rows. Online24h lease remains unchanged; device lease capped31days.
42 +
43 +## Task4 — Isolation and delivery (owner: root)
44 +
45 +- [ ] Gradle debug-only package and highest-priority no-INTERNET manifest; isolated `standalone_main.dart`, actual reminder settings/coordinator.
46 +- [ ] Binary checker rejects online package, wrong version/activity, network/extra permissions, backup or exported reminder receiver.
47 +- [ ] CI builds user APK first, copies LifeGuide.apk, then builds never-distributed fixture. Guard filenames/entrypoints and verify both signatures/manifests.
48 +
49 +## Task5 — Android acceptance (owner: standalone_android_acceptance)
50 +
51 +- [ ] Fresh emulator only; refuse physical/preinstalled package before writes. Launch exact user APK and capture onboarding screenshot.
52 +- [ ] Replace only the just-installed synthetic fixture package with same-cert fixture; alternate fixture SQLite; real independent SQL reads and restart/tick/edit/archive.
53 +- [ ] Prove native alarm after ordinary process death, cancellation before deadline and OFF; no force-stop/manual notification and no false-death transport fallback.
54 +
55 +## Final gates (owner: root)
56 +
57 +- [ ] Run full Flutter suite/analyze/format, Python tool tests, JSON/naming/credential scans; preserve failing outputs and fixes.
58 +- [ ] Independent review; small dependent PR; actual CI logs, artifact digest/manifest/signature. No merge or deployment.
59 +- [ ] Preserve tracked source, evidence and correct downloadable LifeGuide.apk in /workspace; explain local-only scope and real-device gaps.
60 +
61 +Commands/results become VERIFIED only after execution; expected outcomes here are UNVERIFIED until the evidence report is written.