LifeMate — Personal, Family & Learning Companion

fix/personal-notification-controls
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
dart 417 lines 15.8 KB
Raw
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 }