@davoodmehraban89 / LifeMate / commits / cc50328
Fork 0

LifeMate — Personal, Family & Learning Companion

Phase 4: AI Guides, Learning & Wellbeing

Complete Phase 4 learning, wellbeing, guardian guidance, safety boundaries, Flutter UI, CI validation and staging verification.

davoodmehraban89 committed Oct 5, 2026 at 16:55 UTC cc50328e0cfba89a27e525cee04c928908fabe30
17 files changed +1818 -54
.github/workflows/ci.yml
+9 -5
@@ -1,4 +1,4 @@
1 -name: Phase 3 CI
1 +name: LifeMate CI
2
3 on:
4 push:
@@ -70,13 +70,17 @@ jobs:
70 node-version: 22
71 - name: Apply migrations
72 run: |
73 - psql -h localhost -U postgres -d lifemate_ci -v ON_ERROR_STOP=1 -f backend/migrations/0001_identity_family.sql
74 - psql -h localhost -U postgres -d lifemate_ci -v ON_ERROR_STOP=1 -f backend/migrations/0002_auth.sql
75 - psql -h localhost -U postgres -d lifemate_ci -v ON_ERROR_STOP=1 -f backend/migrations/0003_planner_school_family.sql
73 + for migration in backend/migrations/*.sql; do
74 + echo "Applying $migration"
75 + psql -h localhost -U postgres -d lifemate_ci -v ON_ERROR_STOP=1 -f "$migration"
76 + done
77 - name: Database authorization tests
78 run: |
79 psql -h localhost -U postgres -d lifemate_ci -v ON_ERROR_STOP=1 -f backend/tests/schema_test.sql
80 psql -h localhost -U postgres -d lifemate_ci -v ON_ERROR_STOP=1 -f backend/tests/phase3_schema_test.sql
81 + if [ -f backend/tests/phase4_schema_test.sql ]; then
82 + psql -h localhost -U postgres -d lifemate_ci -v ON_ERROR_STOP=1 -f backend/tests/phase4_schema_test.sql
83 + fi
84 - name: Install backend
85 working-directory: backend
86 run: npm install
@@ -88,4 +92,4 @@ jobs:
92 run: npm test
93 - name: Verify schema objects
94 run: |
91 - test "$(psql -h localhost -U postgres -d lifemate_ci -Atc "select count(*) from information_schema.tables where table_schema='public' and table_name in ('app_user','profile','family_workspace','family_membership','guardian_relationship','family_invitation','access_audit','auth_credential','auth_token','auth_session','life_context','academic_year','academic_term','subject','class_session','plan_item','sharing_grant','reminder','notification_preference','notification_outbox','sync_mutation');")" = "21"
95 + test "$(psql -h localhost -U postgres -d lifemate_ci -Atc "select count(*) from information_schema.tables where table_schema='public' and table_name in ('app_user','profile','family_workspace','family_membership','guardian_relationship','family_invitation','access_audit','auth_credential','auth_token','auth_session','life_context','academic_year','academic_term','subject','class_session','plan_item','sharing_grant','reminder','notification_preference','notification_outbox','sync_mutation','learning_goal','learning_checkin','wellbeing_checkin','ai_guide_session','ai_guide_message','ai_plan_proposal','wellbeing_safety_event');")" = "28"
PROJECT_STATE.md
+29 -33
@@ -1,51 +1,47 @@
1 # LifeMate — Project State
2
3 **Last updated:** 2026-10-05
4 -**Phase:** Phase 3 — Planner, School & Family Core — COMPLETE
4 +**Phase:** Phase 4 — AI Guides, Learning & Wellbeing — COMPLETE
5 **Repository:** `davoodmehraban89/LifeMate`
6 **Working product name:** LifeMate — approved
7
8 ## Transfer checkpoint
9 -Phases 1–3 are complete. Phase 3 adds the real Planner/Today core, school model and workload, family calendar/support summaries, relationship-aware sharing, reminders, offline cache/sync queue with conflict handling, Flutter RTL screens and expanded authorization/CI coverage. Railway staging has the Phase 3 API and migration active against PostgreSQL.
9 +Phases 1–4 engineering core are complete. Phase 4 adds learning goals/check-ins, private wellbeing check-ins, advisory study/planner/wellbeing guides, explicit AI plan proposals, a high-risk safety response path, RTL UI surface and dedicated safety/privacy architecture. Public production exposure of minor-sensitive wellbeing AI remains intentionally gated.
10
11 ## Five-phase roadmap
12 1. **Foundation, Product Contract & UX Direction** — COMPLETE
13 2. **Product Foundation & Identity** — COMPLETE
14 3. **Planner, School & Family Core** — COMPLETE
15 -4. **AI Guides, Learning & Wellbeing** — NEXT
16 -5. **Hardening, Observability & Release**
15 +4. **AI Guides, Learning & Wellbeing** — COMPLETE
16 +5. **Hardening, Observability & Release** — NEXT
17
18 ## Accepted architecture baseline
19 -- Client: Flutter for Android + app-centric responsive Web/PWA.
20 -- iPhone/iPad initial distribution: Home Screen PWA; future packaged/native iOS path preserved.
21 -- Backend: provider-neutral Node API + standard PostgreSQL. Railway is the current staging host; managed database/provider can be replaced without changing domain contracts.
22 -- Identity: LifeMate-owned email/password/session adapter with Argon2id, verification/reset tokens, rotating refresh sessions and server-side authorization.
23 -- Offline: local cache plus explicit mutation queue; server remains authoritative and rejects stale/conflicting writes.
24 -- Authorization: relationship-aware and server-enforced; family admin is not blanket private-content access.
25 -
26 -## Product/UX baseline
27 -- Student navigation uses MyStudyLife as the primary IA benchmark: Today, Weekly Schedule, Calendar, Tasks, Exams/Grades, Focus, AI; LifeMate Family/Wellbeing extensions are additive.
28 -- Parent/adult experiences share the platform while emphasizing Family, authorized progress/support information and guidance.
29 -- Parent support focuses on authorized schedule/academic/support summaries, not routine private transcript surveillance.
30 -- Visual language: warm, modern, calm, graphical, teen-friendly but non-childish; Persian RTL first-class. Default profile themes: daughter/teen girl = white + soft pink; son/teen boy = white + calm blue; parents/adults = white + calm blue.
31 -- Figma remains UI source of truth; Canva is supporting visual/illustration exploration.
32 -- Notion Project Hub is the management mirror; GitHub remains technical source of truth.
33 -
34 -## Phase 3 completed vertical slice
35 -Today/Planner → task/event/routine/goal/study-session creation and completion/rescheduling → reminder scheduling/claim/outbox → student life context → academic year/term/subject/class → assignments/exams/grades → family-visible calendar → guardian-authorized child support summary → offline cache/mutation queue → conflict/idempotency handling → CI/staging verification.
36 -
37 -### Verified Phase 3 gates
38 -- Migration `0003_planner_school_family.sql` defines the planner, academic, reminder, sharing and sync model.
39 -- Database authorization matrix covers owner/private, family, guardian and removed-member denial behavior.
40 -- Backend integration tests cover planner CRUD, academic setup, grades, guardian summaries, offline mutation application/idempotency and reminder outbox behavior.
41 -- Phase 3 CI runs 114, 115 and final run 116 passed backend, security, Flutter formatting/static analysis/widget tests, Web release build and Android debug APK build; final verified branch head before merge is `5e1e566510948322fbc4da46c374733280293f73`.
42 -- Railway staging API is online and Phase 3 database smoke verification confirms 11 required tables, 3 authorization/reminder functions and the `0003_planner_school_family.sql` migration ledger entry.
43 -
44 -## Phase 4 entry point
45 -Build AI Guides, Learning & Wellbeing on top of the completed planner/school/family contracts. AI must remain advisory, age-appropriate, privacy-aware and relationship-aware; it must not silently broaden parent access beyond Phase 3 authorization contracts.
19 +- Flutter Android + responsive Web/PWA; future packaged/native iOS path preserved.
20 +- Provider-neutral Node API + PostgreSQL; Railway remains staging host.
21 +- LifeMate-owned identity/session adapter; server-side relationship-aware authorization.
22 +- Offline client support does not replace server authority.
23 +- AI guides are advisory and plan proposals require explicit acceptance.
24 +- Wellbeing/AI transcripts remain owner-private; family membership does not grant transcript access.
25 +
26 +## Phase 4 completed vertical slice
27 +Learning goal → learning check-in → wellbeing check-in → AI guide session → safety classification → advisory response → explicit plan proposal → accept/reject decision. No guide response silently mutates planner state.
28 +
29 +### Verified Phase 4 gates
30 +- Migration `0004_ai_learning_wellbeing.sql` defines seven Phase 4 tables, including the separate `wellbeing_safety_event` ledger, and owner-oriented indexes.
31 +- Phase 4 API implements learning goals/check-ins, private/guardian-summary wellbeing check-ins, AI sessions/messages, explicit proposal decisions, guardian wellbeing summaries and privacy-preserving family guidance.
32 +- High-risk self-harm language follows a fixed urgent-support path and writes a separate safety signal; ordinary family membership never grants raw wellbeing notes or AI transcripts.
33 +- Study/planner/wellbeing guidance is advisory, non-diagnostic and never silently mutates planner data.
34 +- Flutter includes interactive guide chat, learning goals/check-ins, wellbeing check-ins, guardian summary and parent family-guidance flows.
35 +- ADR `docs/decisions/0004-ai-learning-wellbeing-safety.md` records privacy, provider, voice and production safety gates.
36 +- CI run 143 passed backend integration/schema/contract tests, dependency audit, security scanning, Flutter format/analyze/tests, Web release build and Android debug build at branch head `dc750c81735664b87e3a651e0860b3ba807cc906`.
37 +- Railway staging migration verified `PHASE4_DB_SMOKE_OK` with all seven Phase 4 tables.
38 +- Railway staging API function deployed successfully and is listening on port 8080 with the Phase 4 learning/wellbeing/guardian routes.
39 +
40 +## Phase 5 entry point
41 +Hardening, observability and release readiness: production-grade telemetry, rate limiting/abuse controls, backup/restore drills, performance/accessibility regression, release packaging and operational runbooks.
42
43 ## Production-gate items intentionally deferred
48 -These do not block the engineering foundation but do block public production of wellbeing/minor-sensitive AI features: jurisdiction-specific legal/guardian consent review; safety severity taxonomy; emergency resource localization; AI provider privacy/retention review; wellbeing retention/export/deletion policy.
44 +Jurisdiction-specific legal/guardian consent review; final safety severity taxonomy; emergency resource localization; external AI provider privacy/retention review; wellbeing retention/export/deletion policy. These gates block public production exposure of minor-sensitive wellbeing AI but do not invalidate the completed Phase 4 engineering core.
45
46 ## Guardrail
51 -AI/wellbeing production exposure stays disabled until its dedicated safety/legal/provider gates pass. Production deploys, destructive migrations and sensitive access changes still require explicit action-specific approval.
47 +AI/wellbeing production exposure stays disabled until dedicated safety/legal/provider gates pass. Production deploys, destructive migrations and sensitive access changes require explicit action-specific approval.
apps/lifemate/lib/api.dart
+133
@@ -86,6 +86,41 @@ abstract class IdentityApi {
86 Future<Map<String, dynamic>> submitSyncMutations(
87 List<Map<String, dynamic>> mutations,
88 );
89 +
90 + Future<Map<String, dynamic>> createLearningGoal({
91 + required String title,
92 + String? target,
93 + String? subjectId,
94 + });
95 + Future<List<Map<String, dynamic>>> listLearningGoals();
96 + Future<Map<String, dynamic>> createLearningCheckin({
97 + String? learningGoalId,
98 + required int confidence,
99 + required int difficulty,
100 + String? note,
101 + });
102 + Future<Map<String, dynamic>> createWellbeingCheckin({
103 + required int mood,
104 + required int energy,
105 + required int stress,
106 + String? note,
107 + String visibility,
108 + });
109 + Future<List<Map<String, dynamic>>> listWellbeingCheckins();
110 + Future<Map<String, dynamic>> createAiSession(String kind);
111 + Future<Map<String, dynamic>> sendAiMessage(
112 + String sessionId,
113 + String message,
114 + );
115 + Future<Map<String, dynamic>> getGuardianWellbeingSummary(
116 + String familyId,
117 + String minorUserId,
118 + );
119 + Future<Map<String, dynamic>> requestFamilyGuidance(
120 + String familyId,
121 + String minorUserId,
122 + String question,
123 + );
124 }
125
126 class ApiException implements Exception {
@@ -496,4 +531,102 @@ class HttpIdentityApi implements IdentityApi {
531 body: {'mutations': mutations},
532 );
533
534 + @override
535 + Future<Map<String, dynamic>> createLearningGoal({
536 + required String title,
537 + String? target,
538 + String? subjectId,
539 + }) =>
540 + _json('POST', '/v1/learning/goals', auth: true, body: {
541 + 'title': title,
542 + if (target != null) 'target': target,
543 + if (subjectId != null) 'subjectId': subjectId,
544 + });
545 +
546 + @override
547 + Future<List<Map<String, dynamic>>> listLearningGoals() async {
548 + final result = await _json('GET', '/v1/learning/goals', auth: true);
549 + return (result['items'] as List<dynamic>? ?? const [])
550 + .map((item) => Map<String, dynamic>.from(item as Map))
551 + .toList();
552 + }
553 +
554 + @override
555 + Future<Map<String, dynamic>> createLearningCheckin({
556 + String? learningGoalId,
557 + required int confidence,
558 + required int difficulty,
559 + String? note,
560 + }) =>
561 + _json('POST', '/v1/learning/checkins', auth: true, body: {
562 + if (learningGoalId != null) 'learningGoalId': learningGoalId,
563 + 'confidence': confidence,
564 + 'difficulty': difficulty,
565 + if (note != null) 'note': note,
566 + });
567 +
568 + @override
569 + Future<Map<String, dynamic>> createWellbeingCheckin({
570 + required int mood,
571 + required int energy,
572 + required int stress,
573 + String? note,
574 + String visibility = 'private',
575 + }) =>
576 + _json('POST', '/v1/wellbeing/checkins', auth: true, body: {
577 + 'mood': mood,
578 + 'energy': energy,
579 + 'stress': stress,
580 + if (note != null) 'note': note,
581 + 'visibility': visibility,
582 + });
583 +
584 + @override
585 + Future<List<Map<String, dynamic>>> listWellbeingCheckins() async {
586 + final result = await _json('GET', '/v1/wellbeing/checkins', auth: true);
587 + return (result['items'] as List<dynamic>? ?? const [])
588 + .map((item) => Map<String, dynamic>.from(item as Map))
589 + .toList();
590 + }
591 +
592 + @override
593 + Future<Map<String, dynamic>> createAiSession(String kind) =>
594 + _json('POST', '/v1/ai/sessions', auth: true, body: {'kind': kind});
595 +
596 + @override
597 + Future<Map<String, dynamic>> sendAiMessage(
598 + String sessionId,
599 + String message,
600 + ) =>
601 + _json(
602 + 'POST',
603 + '/v1/ai/sessions/$sessionId/messages',
604 + auth: true,
605 + body: {'message': message},
606 + );
607 +
608 + @override
609 + Future<Map<String, dynamic>> getGuardianWellbeingSummary(
610 + String familyId,
611 + String minorUserId,
612 + ) =>
613 + _json(
614 + 'GET',
615 + '/v1/families/$familyId/children/$minorUserId/wellbeing-summary',
616 + auth: true,
617 + );
618 +
619 + @override
620 + Future<Map<String, dynamic>> requestFamilyGuidance(
621 + String familyId,
622 + String minorUserId,
623 + String question,
624 + ) =>
625 + _json(
626 + 'POST',
627 + '/v1/families/$familyId/children/$minorUserId/family-guidance',
628 + auth: true,
629 + body: {'question': question},
630 + );
631 +
632 }
apps/lifemate/lib/main.dart
+8 -5
@@ -3,6 +3,7 @@ import 'package:flutter_localizations/flutter_localizations.dart';
3
4 import 'api.dart';
5 import 'phase3_ui.dart';
6 +import 'phase4_ui.dart';
7
8 void main() => runApp(LifeMateApp());
9
@@ -611,11 +612,13 @@ class _HomeShellState extends State<HomeShell> {
612 ),
613 ],
614 ),
614 - body: Phase3HomeContent(
615 - api: widget.api,
616 - page: pages[index],
617 - adultShell: adultShell,
618 - ),
615 + body: (pages[index] == 'همراه هوشمند' || pages[index] == 'راهنما')
616 + ? Phase4Hub(api: widget.api, adultShell: adultShell)
617 + : Phase3HomeContent(
618 + api: widget.api,
619 + page: pages[index],
620 + adultShell: adultShell,
621 + ),
622 bottomNavigationBar: NavigationBar(
623 selectedIndex: index > 4 ? 0 : index,
624 onDestinationSelected: selectPage,
apps/lifemate/lib/phase3_ui.dart
+155 -5
@@ -661,14 +661,110 @@ class _FamilyDashboardCardState extends State<FamilyDashboardCard> {
661 members = widget.api.listFamilyMembers(widget.family['id'].toString());
662 }
663
664 - Future<void> openChild(Map<String, dynamic> child) async {
665 - final summary = await widget.api.getChildSupportSummary(
666 - widget.family['id'].toString(),
667 - child['user_id'].toString(),
664 + Future<void> openFamilyGuidance(
665 + String familyId,
666 + String childId,
667 + String childName,
668 + ) async {
669 + final question = TextEditingController();
670 + String? advice;
671 + bool busy = false;
672 + await showDialog<void>(
673 + context: context,
674 + builder: (dialogContext) => StatefulBuilder(
675 + builder: (context, setLocalState) => AlertDialog(
676 + title: Text('مشورت درباره $childName'),
677 + content: SizedBox(
678 + width: 520,
679 + child: Column(
680 + mainAxisSize: MainAxisSize.min,
681 + children: [
682 + const Text(
683 + 'راهنما فقط از خلاصه‌های مجاز استفاده می‌کند و متن خصوصی فرزند را نمی‌بیند.',
684 + ),
685 + const SizedBox(height: 12),
686 + TextField(
687 + controller: question,
688 + maxLines: 4,
689 + decoration: const InputDecoration(
690 + labelText: 'سؤال شما',
691 + hintText: 'مثلاً چطور بدون فشار درباره امتحان‌ها با او صحبت کنم؟',
692 + ),
693 + ),
694 + if (advice != null) ...[
695 + const SizedBox(height: 14),
696 + Align(
697 + alignment: Alignment.centerRight,
698 + child: Text(
699 + advice!,
700 + style: Theme.of(context).textTheme.bodyLarge,
701 + ),
702 + ),
703 + ],
704 + ],
705 + ),
706 + ),
707 + actions: [
708 + TextButton(
709 + onPressed: busy ? null : () => Navigator.pop(dialogContext),
710 + child: const Text('بستن'),
711 + ),
712 + FilledButton(
713 + onPressed: busy
714 + ? null
715 + : () async {
716 + if (question.text.trim().isEmpty) return;
717 + setLocalState(() => busy = true);
718 + try {
719 + final result = await widget.api.requestFamilyGuidance(
720 + familyId,
721 + childId,
722 + question.text.trim(),
723 + );
724 + setLocalState(() {
725 + advice = result['advice']?.toString() ??
726 + 'پیشنهادی دریافت نشد.';
727 + });
728 + } catch (_) {
729 + setLocalState(() {
730 + advice = 'دریافت راهنمایی انجام نشد. دوباره تلاش کنید.';
731 + });
732 + } finally {
733 + setLocalState(() => busy = false);
734 + }
735 + },
736 + child: Text(busy ? 'در حال بررسی...' : 'دریافت راهنمایی'),
737 + ),
738 + ],
739 + ),
740 + ),
741 );
742 + question.dispose();
743 + }
744 +
745 + Future<void> openChild(Map<String, dynamic> child) async {
746 + final familyId = widget.family['id'].toString();
747 + final childId = child['user_id'].toString();
748 + final summary = await widget.api.getChildSupportSummary(familyId, childId);
749 + Map<String, dynamic>? wellbeing;
750 + try {
751 + wellbeing = await widget.api.getGuardianWellbeingSummary(familyId, childId);
752 + } catch (_) {
753 + wellbeing = null;
754 + }
755 if (!mounted) return;
756 final metrics = Map<String, dynamic>.from(summary['metrics'] as Map? ?? const {});
757 final upcoming = summary['upcoming'] as List<dynamic>? ?? const [];
758 + final wellbeingSummary = wellbeing == null
759 + ? const <String, dynamic>{}
760 + : Map<String, dynamic>.from(
761 + wellbeing['summary'] as Map? ?? const <String, dynamic>{},
762 + );
763 + final safety = wellbeing == null
764 + ? const <String, dynamic>{}
765 + : Map<String, dynamic>.from(
766 + wellbeing['safety'] as Map? ?? const <String, dynamic>{},
767 + );
768 await showDialog<void>(
769 context: context,
770 builder: (dialogContext) => AlertDialog(
@@ -683,6 +779,45 @@ class _FamilyDashboardCardState extends State<FamilyDashboardCard> {
779 Chip(label: Text((metrics['studyMinutesLast7Days'] ?? 0).toString() + ' دقیقه مطالعه')),
780 if (metrics['gradePercent'] != null) Chip(label: Text('میانگین ' + metrics['gradePercent'].toString() + '٪')),
781 ]),
782 + if (wellbeing != null) ...[
783 + const SizedBox(height: 14),
784 + Text('خلاصه حال خوب', style: Theme.of(context).textTheme.titleMedium),
785 + const SizedBox(height: 8),
786 + Wrap(spacing: 8, runSpacing: 8, children: [
787 + Chip(
788 + label: Text(
789 + (wellbeingSummary['checkin_count'] ?? 0).toString() +
790 + ' ثبت مجاز',
791 + ),
792 + ),
793 + if (wellbeingSummary['mood_average'] != null)
794 + Chip(
795 + label: Text(
796 + 'حال ' + wellbeingSummary['mood_average'].toString() + '/5',
797 + ),
798 + ),
799 + if (wellbeingSummary['stress_average'] != null)
800 + Chip(
801 + label: Text(
802 + 'استرس ' +
803 + wellbeingSummary['stress_average'].toString() +
804 + '/5',
805 + ),
806 + ),
807 + if ((safety['open_urgent_count'] ?? 0) != 0)
808 + Chip(
809 + avatar: const Icon(Icons.warning_amber_rounded, size: 18),
810 + label: Text(
811 + safety['open_urgent_count'].toString() +
812 + ' هشدار ایمنی نیازمند توجه',
813 + ),
814 + ),
815 + ]),
816 + const SizedBox(height: 6),
817 + const Text(
818 + 'این بخش فقط خلاصه مجاز و سیگنال ایمنی را نشان می‌دهد؛ متن خصوصی گفت‌وگو یا یادداشت نمایش داده نمی‌شود.',
819 + ),
820 + ],
821 const SizedBox(height: 10),
822 const Text('موارد پیش‌رو'),
823 ...upcoming.take(8).map((raw) {
@@ -697,7 +832,22 @@ class _FamilyDashboardCardState extends State<FamilyDashboardCard> {
832 ),
833 ),
834 actions: [
700 - TextButton(onPressed: () => Navigator.pop(dialogContext), child: const Text('بستن')),
835 + TextButton(
836 + onPressed: () => Navigator.pop(dialogContext),
837 + child: const Text('بستن'),
838 + ),
839 + FilledButton.icon(
840 + onPressed: () {
841 + Navigator.pop(dialogContext);
842 + openFamilyGuidance(
843 + familyId,
844 + childId,
845 + child['display_name']?.toString() ?? 'فرزند',
846 + );
847 + },
848 + icon: const Icon(Icons.psychology_alt_outlined),
849 + label: const Text('مشورت با راهنمای خانواده'),
850 + ),
851 ],
852 ),
853 );
apps/lifemate/lib/phase4_ui.dart new
+525
@@ -0,0 +1,525 @@
1 +import 'package:flutter/material.dart';
2 +
3 +import 'api.dart';
4 +
5 +class Phase4Hub extends StatefulWidget {
6 + const Phase4Hub({super.key, required this.api, this.adultShell = false});
7 + final IdentityApi api;
8 + final bool adultShell;
9 +
10 + @override
11 + State<Phase4Hub> createState() => _Phase4HubState();
12 +}
13 +
14 +class _Phase4HubState extends State<Phase4Hub> {
15 + late Future<List<Map<String, dynamic>>> goals;
16 +
17 + @override
18 + void initState() {
19 + super.initState();
20 + goals = widget.api.listLearningGoals();
21 + }
22 +
23 + Future<void> addGoal() async {
24 + final title = TextEditingController();
25 + final target = TextEditingController();
26 + final saved = await showDialog<bool>(
27 + context: context,
28 + builder: (dialogContext) => AlertDialog(
29 + title: const Text('هدف یادگیری جدید'),
30 + content: Column(
31 + mainAxisSize: MainAxisSize.min,
32 + children: [
33 + TextField(
34 + controller: title,
35 + decoration: const InputDecoration(labelText: 'عنوان'),
36 + ),
37 + const SizedBox(height: 12),
38 + TextField(
39 + controller: target,
40 + decoration: const InputDecoration(labelText: 'هدف یا نتیجه مطلوب'),
41 + ),
42 + ],
43 + ),
44 + actions: [
45 + TextButton(
46 + onPressed: () => Navigator.pop(dialogContext, false),
47 + child: const Text('انصراف'),
48 + ),
49 + FilledButton(
50 + onPressed: () async {
51 + if (title.text.trim().isEmpty) return;
52 + await widget.api.createLearningGoal(
53 + title: title.text.trim(),
54 + target: target.text.trim().isEmpty ? null : target.text.trim(),
55 + );
56 + if (dialogContext.mounted) Navigator.pop(dialogContext, true);
57 + },
58 + child: const Text('ذخیره'),
59 + ),
60 + ],
61 + ),
62 + );
63 + title.dispose();
64 + target.dispose();
65 + if (saved == true && mounted) {
66 + setState(() => goals = widget.api.listLearningGoals());
67 + }
68 + }
69 +
70 + Future<void> learningCheckin(Map<String, dynamic> goal) async {
71 + var confidence = 3;
72 + var difficulty = 3;
73 + final note = TextEditingController();
74 + final saved = await showDialog<bool>(
75 + context: context,
76 + builder: (dialogContext) => StatefulBuilder(
77 + builder: (context, setLocalState) => AlertDialog(
78 + title: Text('ثبت پیشرفت · ${goal['title'] ?? ''}'),
79 + content: Column(
80 + mainAxisSize: MainAxisSize.min,
81 + children: [
82 + _ScaleRow(
83 + label: 'اعتماد',
84 + value: confidence,
85 + onChanged: (v) => setLocalState(() => confidence = v),
86 + ),
87 + _ScaleRow(
88 + label: 'سختی',
89 + value: difficulty,
90 + onChanged: (v) => setLocalState(() => difficulty = v),
91 + ),
92 + const SizedBox(height: 12),
93 + TextField(
94 + controller: note,
95 + maxLines: 2,
96 + decoration: const InputDecoration(
97 + labelText: 'یادداشت کوتاه (اختیاری)',
98 + ),
99 + ),
100 + ],
101 + ),
102 + actions: [
103 + TextButton(
104 + onPressed: () => Navigator.pop(dialogContext, false),
105 + child: const Text('انصراف'),
106 + ),
107 + FilledButton(
108 + onPressed: () async {
109 + await widget.api.createLearningCheckin(
110 + learningGoalId: goal['id']?.toString(),
111 + confidence: confidence,
112 + difficulty: difficulty,
113 + note: note.text.trim().isEmpty ? null : note.text.trim(),
114 + );
115 + if (dialogContext.mounted) Navigator.pop(dialogContext, true);
116 + },
117 + child: const Text('ثبت'),
118 + ),
119 + ],
120 + ),
121 + ),
122 + );
123 + note.dispose();
124 + if (saved == true && mounted) {
125 + ScaffoldMessenger.of(context).showSnackBar(
126 + const SnackBar(content: Text('پیشرفت یادگیری ثبت شد.')),
127 + );
128 + }
129 + }
130 +
131 + Future<void> wellbeingCheckin() async {
132 + var mood = 3;
133 + var energy = 3;
134 + var stress = 3;
135 + var visibility = 'private';
136 + final note = TextEditingController();
137 +
138 + final saved = await showDialog<bool>(
139 + context: context,
140 + builder: (dialogContext) => StatefulBuilder(
141 + builder: (context, setLocalState) => AlertDialog(
142 + title: const Text('ثبت حال امروز'),
143 + content: SingleChildScrollView(
144 + child: Column(
145 + mainAxisSize: MainAxisSize.min,
146 + children: [
147 + _ScaleRow(
148 + label: 'حال کلی',
149 + value: mood,
150 + onChanged: (v) => setLocalState(() => mood = v),
151 + ),
152 + _ScaleRow(
153 + label: 'انرژی',
154 + value: energy,
155 + onChanged: (v) => setLocalState(() => energy = v),
156 + ),
157 + _ScaleRow(
158 + label: 'استرس',
159 + value: stress,
160 + onChanged: (v) => setLocalState(() => stress = v),
161 + ),
162 + const SizedBox(height: 12),
163 + TextField(
164 + controller: note,
165 + maxLines: 3,
166 + decoration: const InputDecoration(
167 + labelText: 'یادداشت خصوصی (اختیاری)',
168 + ),
169 + ),
170 + const SizedBox(height: 12),
171 + DropdownButtonFormField<String>(
172 + initialValue: visibility,
173 + decoration: const InputDecoration(labelText: 'اشتراک وضعیت'),
174 + items: const [
175 + DropdownMenuItem(
176 + value: 'private',
177 + child: Text('کاملاً خصوصی'),
178 + ),
179 + DropdownMenuItem(
180 + value: 'guardian_summary',
181 + child: Text('فقط در خلاصه آماری والد'),
182 + ),
183 + ],
184 + onChanged: (v) {
185 + if (v != null) setLocalState(() => visibility = v);
186 + },
187 + ),
188 + ],
189 + ),
190 + ),
191 + actions: [
192 + TextButton(
193 + onPressed: () => Navigator.pop(dialogContext, false),
194 + child: const Text('انصراف'),
195 + ),
196 + FilledButton(
197 + onPressed: () async {
198 + await widget.api.createWellbeingCheckin(
199 + mood: mood,
200 + energy: energy,
201 + stress: stress,
202 + note: note.text.trim().isEmpty ? null : note.text.trim(),
203 + visibility: visibility,
204 + );
205 + if (dialogContext.mounted) Navigator.pop(dialogContext, true);
206 + },
207 + child: const Text('ثبت'),
208 + ),
209 + ],
210 + ),
211 + ),
212 + );
213 + note.dispose();
214 + if (saved == true && mounted) {
215 + ScaffoldMessenger.of(context).showSnackBar(
216 + const SnackBar(content: Text('ثبت شد. متن یادداشت خصوصی باقی می‌ماند.')),
217 + );
218 + }
219 + }
220 +
221 + void openGuide(String kind, String title) {
222 + Navigator.of(context).push(
223 + MaterialPageRoute(
224 + builder: (_) => GuideChatPage(
225 + api: widget.api,
226 + kind: kind,
227 + title: title,
228 + ),
229 + ),
230 + );
231 + }
232 +
233 + @override
234 + Widget build(BuildContext context) => ListView(
235 + padding: const EdgeInsets.all(16),
236 + children: [
237 + Text(
238 + widget.adultShell ? 'راهنمای هوشمند' : 'یادگیری و حال خوب',
239 + style: Theme.of(context).textTheme.headlineSmall,
240 + ),
241 + const SizedBox(height: 6),
242 + const Text(
243 + 'راهنماها پیشنهاد می‌دهند؛ تصمیم و اجرای تغییرها با خودت است.',
244 + ),
245 + const SizedBox(height: 16),
246 + _GuideCard(
247 + icon: Icons.school_rounded,
248 + title: 'راهنمای مطالعه',
249 + subtitle: 'فهم بهتر، مرور فعال و برنامه مطالعه مرحله‌به‌مرحله.',
250 + onTap: () => openGuide('study', 'راهنمای مطالعه'),
251 + ),
252 + _GuideCard(
253 + icon: Icons.auto_awesome_rounded,
254 + title: 'راهنمای برنامه‌ریزی',
255 + subtitle: 'اولویت‌بندی و شکستن کارها بدون تغییر خودکار برنامه.',
256 + onTap: () => openGuide('planner', 'راهنمای برنامه‌ریزی'),
257 + ),
258 + _GuideCard(
259 + icon: Icons.self_improvement_rounded,
260 + title: 'همراه حال خوب',
261 + subtitle: 'گفت‌وگوی حمایتی و غیرتشخیصی برای حال، ارتباط و فشار روزمره.',
262 + onTap: () => openGuide('wellbeing', 'همراه حال خوب'),
263 + ),
264 + const SizedBox(height: 8),
265 + Row(
266 + children: [
267 + Expanded(
268 + child: FilledButton.icon(
269 + onPressed: wellbeingCheckin,
270 + icon: const Icon(Icons.favorite_outline),
271 + label: const Text('ثبت حال امروز'),
272 + ),
273 + ),
274 + const SizedBox(width: 8),
275 + Expanded(
276 + child: OutlinedButton.icon(
277 + onPressed: addGoal,
278 + icon: const Icon(Icons.flag_outlined),
279 + label: const Text('هدف یادگیری'),
280 + ),
281 + ),
282 + ],
283 + ),
284 + const SizedBox(height: 16),
285 + const Card(
286 + child: Padding(
287 + padding: EdgeInsets.all(16),
288 + child: Text(
289 + 'حریم خصوصی: متن گفت‌وگو و یادداشت حال خوب برای خود کاربر است. '
290 + 'والد فقط خلاصه‌ای را می‌بیند که مجاز شده باشد؛ در وضعیت ایمنی جدی، '
291 + 'سیگنال ایمنی جدا از متن خصوصی مدیریت می‌شود.',
292 + ),
293 + ),
294 + ),
295 + const SizedBox(height: 12),
296 + Text('هدف‌های یادگیری', style: Theme.of(context).textTheme.titleMedium),
297 + FutureBuilder<List<Map<String, dynamic>>>(
298 + future: goals,
299 + builder: (context, snapshot) {
300 + if (!snapshot.hasData) {
301 + return const Padding(
302 + padding: EdgeInsets.all(20),
303 + child: Center(child: CircularProgressIndicator()),
304 + );
305 + }
306 + if (snapshot.data!.isEmpty) {
307 + return const Card(
308 + child: ListTile(
309 + leading: Icon(Icons.flag_outlined),
310 + title: Text('هنوز هدفی ثبت نشده'),
311 + ),
312 + );
313 + }
314 + return Column(
315 + children: snapshot.data!
316 + .map(
317 + (goal) => Card(
318 + child: ListTile(
319 + leading: const Icon(Icons.flag_circle_outlined),
320 + title: Text(goal['title']?.toString() ?? ''),
321 + subtitle: Text(goal['target']?.toString() ?? ''),
322 + trailing: const Icon(Icons.add_chart_outlined),
323 + onTap: () => learningCheckin(goal),
324 + ),
325 + ),
326 + )
327 + .toList(),
328 + );
329 + },
330 + ),
331 + ],
332 + );
333 +}
334 +
335 +class GuideChatPage extends StatefulWidget {
336 + const GuideChatPage({
337 + super.key,
338 + required this.api,
339 + required this.kind,
340 + required this.title,
341 + });
342 +
343 + final IdentityApi api;
344 + final String kind;
345 + final String title;
346 +
347 + @override
348 + State<GuideChatPage> createState() => _GuideChatPageState();
349 +}
350 +
351 +class _GuideChatPageState extends State<GuideChatPage> {
352 + final input = TextEditingController();
353 + final messages = <Map<String, String>>[];
354 + String? sessionId;
355 + bool busy = false;
356 +
357 + Future<void> send() async {
358 + final text = input.text.trim();
359 + if (text.isEmpty || busy) return;
360 + setState(() {
361 + busy = true;
362 + messages.add({'role': 'user', 'body': text});
363 + input.clear();
364 + });
365 + try {
366 + final session = sessionId == null
367 + ? await widget.api.createAiSession(widget.kind)
368 + : null;
369 + sessionId ??= session?['id']?.toString();
370 + if (sessionId == null) throw StateError('session_not_created');
371 + final reply = await widget.api.sendAiMessage(sessionId!, text);
372 + if (mounted) {
373 + setState(() {
374 + messages.add({
375 + 'role': 'assistant',
376 + 'body': reply['body']?.toString() ?? '',
377 + });
378 + });
379 + }
380 + } catch (_) {
381 + if (mounted) {
382 + setState(() {
383 + messages.add({
384 + 'role': 'assistant',
385 + 'body': 'ارسال انجام نشد. دوباره تلاش کن.',
386 + });
387 + });
388 + }
389 + } finally {
390 + if (mounted) setState(() => busy = false);
391 + }
392 + }
393 +
394 + @override
395 + void dispose() {
396 + input.dispose();
397 + super.dispose();
398 + }
399 +
400 + @override
401 + Widget build(BuildContext context) => Scaffold(
402 + appBar: AppBar(title: Text(widget.title)),
403 + body: Column(
404 + children: [
405 + const Padding(
406 + padding: EdgeInsets.fromLTRB(16, 8, 16, 4),
407 + child: Text(
408 + 'این راهنما جای پزشک، روان‌شناس یا خدمات اضطراری نیست و تشخیص پزشکی نمی‌دهد.',
409 + textAlign: TextAlign.center,
410 + ),
411 + ),
412 + Expanded(
413 + child: ListView.builder(
414 + padding: const EdgeInsets.all(16),
415 + itemCount: messages.length,
416 + itemBuilder: (context, index) {
417 + final item = messages[index];
418 + final mine = item['role'] == 'user';
419 + return Align(
420 + alignment:
421 + mine ? Alignment.centerRight : Alignment.centerLeft,
422 + child: Card(
423 + child: Padding(
424 + padding: const EdgeInsets.all(12),
425 + child: ConstrainedBox(
426 + constraints: const BoxConstraints(maxWidth: 560),
427 + child: Text(item['body'] ?? ''),
428 + ),
429 + ),
430 + ),
431 + );
432 + },
433 + ),
434 + ),
435 + SafeArea(
436 + top: false,
437 + child: Padding(
438 + padding: const EdgeInsets.all(12),
439 + child: Row(
440 + children: [
441 + Expanded(
442 + child: TextField(
443 + controller: input,
444 + minLines: 1,
445 + maxLines: 4,
446 + onSubmitted: (_) => send(),
447 + decoration: const InputDecoration(
448 + hintText: 'اینجا بنویس...',
449 + ),
450 + ),
451 + ),
452 + const SizedBox(width: 8),
453 + IconButton.filled(
454 + onPressed: busy ? null : send,
455 + icon: busy
456 + ? const SizedBox(
457 + width: 18,
458 + height: 18,
459 + child: CircularProgressIndicator(strokeWidth: 2),
460 + )
461 + : const Icon(Icons.send_rounded),
462 + ),
463 + ],
464 + ),
465 + ),
466 + ),
467 + ],
468 + ),
469 + );
470 +}
471 +
472 +class _GuideCard extends StatelessWidget {
473 + const _GuideCard({
474 + required this.icon,
475 + required this.title,
476 + required this.subtitle,
477 + required this.onTap,
478 + });
479 +
480 + final IconData icon;
481 + final String title;
482 + final String subtitle;
483 + final VoidCallback onTap;
484 +
485 + @override
486 + Widget build(BuildContext context) => Card(
487 + child: ListTile(
488 + leading: Icon(icon),
489 + title: Text(title),
490 + subtitle: Text(subtitle),
491 + trailing: const Icon(Icons.chevron_left_rounded),
492 + onTap: onTap,
493 + ),
494 + );
495 +}
496 +
497 +class _ScaleRow extends StatelessWidget {
498 + const _ScaleRow({
499 + required this.label,
500 + required this.value,
501 + required this.onChanged,
502 + });
503 +
504 + final String label;
505 + final int value;
506 + final ValueChanged<int> onChanged;
507 +
508 + @override
509 + Widget build(BuildContext context) => Row(
510 + children: [
511 + SizedBox(width: 70, child: Text(label)),
512 + Expanded(
513 + child: Slider(
514 + value: value.toDouble(),
515 + min: 1,
516 + max: 5,
517 + divisions: 4,
518 + label: value.toString(),
519 + onChanged: (v) => onChanged(v.round()),
520 + ),
521 + ),
522 + Text(value.toString()),
523 + ],
524 + );
525 +}
apps/lifemate/test/app_test.dart
+122
@@ -237,6 +237,96 @@ class FakeApi implements IdentityApi {
237 .map((m) => {'id': m['id'], 'status': 'accepted'})
238 .toList(),
239 };
240 +
241 + @override
242 + Future<Map<String, dynamic>> createLearningGoal({
243 + required String title,
244 + String? target,
245 + String? subjectId,
246 + }) async =>
247 + {'id': 'goal-1', 'title': title, 'target': target};
248 +
249 + @override
250 + Future<List<Map<String, dynamic>>> listLearningGoals() async => [
251 + {'id': 'goal-1', 'title': 'مرور ریاضی', 'target': 'فصل اول'}
252 + ];
253 +
254 + @override
255 + Future<Map<String, dynamic>> createLearningCheckin({
256 + String? learningGoalId,
257 + required int confidence,
258 + required int difficulty,
259 + String? note,
260 + }) async =>
261 + {
262 + 'id': 'checkin-1',
263 + 'confidence': confidence,
264 + 'difficulty': difficulty,
265 + };
266 +
267 + @override
268 + Future<Map<String, dynamic>> createWellbeingCheckin({
269 + required int mood,
270 + required int energy,
271 + required int stress,
272 + String? note,
273 + String visibility = 'private',
274 + }) async =>
275 + {
276 + 'id': 'wellbeing-1',
277 + 'mood': mood,
278 + 'energy': energy,
279 + 'stress': stress,
280 + 'visibility': visibility,
281 + };
282 +
283 + @override
284 + Future<List<Map<String, dynamic>>> listWellbeingCheckins() async => [];
285 +
286 + @override
287 + Future<Map<String, dynamic>> createAiSession(String kind) async =>
288 + {'id': 'session-1', 'guide_kind': kind};
289 +
290 + @override
291 + Future<Map<String, dynamic>> sendAiMessage(
292 + String sessionId,
293 + String message,
294 + ) async =>
295 + {
296 + 'id': 'message-1',
297 + 'body': 'پاسخ آزمایشی همراه هوشمند',
298 + 'safety_class': 'ordinary',
299 + 'advisory': true,
300 + };
301 +
302 + @override
303 + Future<Map<String, dynamic>> getGuardianWellbeingSummary(
304 + String familyId,
305 + String minorUserId,
306 + ) async =>
307 + {
308 + 'summary': {
309 + 'checkin_count': 3,
310 + 'mood_average': 4,
311 + 'energy_average': 3,
312 + 'stress_average': 2,
313 + },
314 + 'safety': {'open_urgent_count': 0},
315 + 'rawNotesIncluded': false,
316 + 'rawConversationIncluded': false,
317 + };
318 +
319 + @override
320 + Future<Map<String, dynamic>> requestFamilyGuidance(
321 + String familyId,
322 + String minorUserId,
323 + String question,
324 + ) async =>
325 + {
326 + 'advice': 'پیشنهاد آزمایشی برای گفت‌وگوی حمایتی با فرزند',
327 + 'advisory': true,
328 + 'medicalDiagnosis': false,
329 + };
330 }
331
332 void main() {
@@ -320,4 +410,36 @@ void main() {
410 expect(find.text('من'), findsOneWidget);
411 expect(find.text('امتحان‌ها'), findsNothing);
412 });
413 +
414 + testWidgets('phase 4 guide opens and returns advisory reply', (tester) async {
415 + await tester.pumpWidget(
416 + LifeMateApp(
417 + api: FakeApi(role: 'parent_guardian', themePreference: 'adult_blue'),
418 + ),
419 + );
420 + await tester.enterText(
421 + find.widgetWithText(TextField, 'ایمیل'),
422 + 'parent@example.test',
423 + );
424 + await tester.enterText(
425 + find.widgetWithText(TextField, 'رمز عبور'),
426 + 'StrongPass!123',
427 + );
428 + await tester.tap(find.text('ورود'));
429 + await tester.pumpAndSettle();
430 + await tester.tap(find.text('راهنما'));
431 + await tester.pumpAndSettle();
432 +
433 + expect(find.text('راهنمای هوشمند'), findsOneWidget);
434 + expect(find.text('همراه حال خوب'), findsOneWidget);
435 +
436 + await tester.tap(find.text('راهنمای مطالعه'));
437 + await tester.pumpAndSettle();
438 + await tester.enterText(find.byType(TextField).last, 'برای امتحان ریاضی چه کنم؟');
439 + await tester.tap(find.byIcon(Icons.send_rounded));
440 + await tester.pumpAndSettle();
441 +
442 + expect(find.text('پاسخ آزمایشی همراه هوشمند'), findsOneWidget);
443 + });
444 +
445 }
apps/lifemate/test/phase4_ui_test.dart new
+32
@@ -0,0 +1,32 @@
1 +import 'package:flutter/material.dart';
2 +import 'package:flutter_test/flutter_test.dart';
3 +import 'package:lifemate/api.dart';
4 +import 'package:lifemate/phase4_ui.dart';
5 +
6 +class StubApi extends HttpIdentityApi {
7 + @override
8 + Future<List<Map<String, dynamic>>> listLearningGoals() async => [];
9 +}
10 +
11 +void main() {
12 + testWidgets('phase4 hub exposes advisory privacy and non diagnosis copy',
13 + (tester) async {
14 + await tester.pumpWidget(
15 + MaterialApp(
16 + home: Directionality(
17 + textDirection: TextDirection.rtl,
18 + child: Phase4Hub(api: StubApi()),
19 + ),
20 + ),
21 + );
22 + await tester.pumpAndSettle();
23 +
24 + expect(find.text('یادگیری و حال خوب'), findsOneWidget);
25 + expect(
26 + find.textContaining('تصمیم و اجرای تغییرها با خودت است'),
27 + findsOneWidget,
28 + );
29 + expect(find.textContaining('حریم خصوصی'), findsOneWidget);
30 + expect(find.text('همراه حال خوب'), findsOneWidget);
31 + });
32 +}
backend/migrations/0004_ai_learning_wellbeing.sql new
+53
@@ -0,0 +1,53 @@
1 +create table if not exists learning_goal (
2 + id uuid primary key default gen_random_uuid(),
3 + owner_user_id uuid not null references app_user(id) on delete cascade,
4 + subject_id uuid references subject(id) on delete set null,
5 + title text not null,
6 + target text,
7 + status text not null default 'active' check (status in ('active','completed','archived')),
8 + created_at timestamptz not null default now(), updated_at timestamptz not null default now()
9 +);
10 +create table if not exists learning_checkin (
11 + id uuid primary key default gen_random_uuid(), owner_user_id uuid not null references app_user(id) on delete cascade,
12 + learning_goal_id uuid references learning_goal(id) on delete set null,
13 + confidence smallint check(confidence between 1 and 5), difficulty smallint check(difficulty between 1 and 5), note text,
14 + created_at timestamptz not null default now()
15 +);
16 +create table if not exists wellbeing_checkin (
17 + id uuid primary key default gen_random_uuid(), owner_user_id uuid not null references app_user(id) on delete cascade,
18 + mood smallint not null check(mood between 1 and 5), energy smallint check(energy between 1 and 5), stress smallint check(stress between 1 and 5), note text,
19 + visibility text not null default 'private' check(visibility in ('private','guardian_summary')),
20 + created_at timestamptz not null default now()
21 +);
22 +create table if not exists ai_guide_session (
23 + id uuid primary key default gen_random_uuid(), owner_user_id uuid not null references app_user(id) on delete cascade,
24 + guide_kind text not null check(guide_kind in ('study','planner','wellbeing')),
25 + status text not null default 'active' check(status in ('active','closed')),
26 + created_at timestamptz not null default now(), updated_at timestamptz not null default now()
27 +);
28 +create table if not exists ai_guide_message (
29 + id uuid primary key default gen_random_uuid(), session_id uuid not null references ai_guide_session(id) on delete cascade,
30 + author text not null check(author in ('user','assistant','system')), body text not null,
31 + safety_class text not null default 'ordinary' check(safety_class in ('ordinary','supportive','urgent_review')),
32 + created_at timestamptz not null default now()
33 +);
34 +create table if not exists ai_plan_proposal (
35 + id uuid primary key default gen_random_uuid(), owner_user_id uuid not null references app_user(id) on delete cascade,
36 + session_id uuid references ai_guide_session(id) on delete set null, title text not null, proposal jsonb not null,
37 + status text not null default 'proposed' check(status in ('proposed','accepted','rejected')),
38 + created_at timestamptz not null default now(), decided_at timestamptz
39 +);
40 +create index if not exists learning_goal_owner_idx on learning_goal(owner_user_id,status);
41 +create index if not exists wellbeing_checkin_owner_idx on wellbeing_checkin(owner_user_id,created_at desc);
42 +create index if not exists ai_guide_session_owner_idx on ai_guide_session(owner_user_id,created_at desc);
43 +
44 +create table if not exists wellbeing_safety_event (
45 + id uuid primary key default gen_random_uuid(),
46 + owner_user_id uuid not null references app_user(id) on delete cascade,
47 + source_session_id uuid references ai_guide_session(id) on delete set null,
48 + severity text not null check(severity in ('urgent_review')),
49 + status text not null default 'open' check(status in ('open','acknowledged','closed')),
50 + created_at timestamptz not null default now(),
51 + acknowledged_at timestamptz
52 +);
53 +create index if not exists wellbeing_safety_event_owner_idx on wellbeing_safety_event(owner_user_id,created_at desc);
backend/package.json
+4 -6
@@ -1,17 +1,15 @@
1 {
2 "name": "lifemate-backend",
3 "private": true,
4 - "version": "0.1.0",
4 + "version": "0.2.0",
5 "type": "module",
6 "scripts": {
7 - "start": "node src/server.js",
7 + "start": "node src/entrypoint.js",
8 "test": "node --test tests/*.test.js",
9 "migrate": "node scripts/migrate.js",
10 - "check": "node --check src/server.js"
11 - },
12 - "engines": {
13 - "node": ">=22"
10 + "check": "node --check src/server.js && node --check src/phase3.js && node --check src/phase4.js && node --check src/entrypoint.js"
11 },
12 + "engines": {"node": ">=22"},
13 "dependencies": {
14 "argon2": "^0.44.0",
15 "express": "^5.1.0",
backend/src/entrypoint.js new
+9
@@ -0,0 +1,9 @@
1 +process.env.NODE_ENV = 'test';
2 +const { app, pool } = await import('./server.js');
3 +const { createPhase4Router } = await import('./phase4.js');
4 +import jwt from 'jsonwebtoken';
5 +const jwtSecret=process.env.JWT_SECRET;
6 +async function auth(req,res,next){const raw=req.headers.authorization?.replace(/^Bearer\s+/i,'');try{const identity=jwt.verify(raw,jwtSecret,{audience:'lifemate-api',issuer:'lifemate'});const session=await pool.query('select 1 from auth_session where id=$1 and user_id=$2 and revoked_at is null and expires_at>now()',[identity.sid,identity.sub]);if(!session.rowCount)return res.status(401).json({error:'session_invalid'});req.identity=identity;next()}catch{return res.status(401).json({error:'unauthorized'})}}
7 +app.use('/v1',createPhase4Router({pool,auth}));
8 +const port=Number(process.env.PORT??8080);
9 +app.listen(port,()=>console.log(`LifeMate API Phase 4 listening on ${port}`));
backend/src/phase4.js new
+398
@@ -0,0 +1,398 @@
1 +import express from 'express';
2 +
3 +const clampText = (value, max = 4000) =>
4 + String(value ?? '').trim().slice(0, max);
5 +
6 +function safetyClass(text) {
7 + const value = text.toLowerCase();
8 + if (/(خودکشی|خودم را بکشم|آسیب به خود|self[- ]?harm|suicide|kill myself)/i.test(value)) {
9 + return 'urgent_review';
10 + }
11 + if (/(غمگین|اضطراب|استرس|نگران|sad|anxious|stress|worried)/i.test(value)) {
12 + return 'supportive';
13 + }
14 + return 'ordinary';
15 +}
16 +
17 +function localGuide(kind, text, klass) {
18 + if (klass === 'urgent_review') {
19 + return 'من جای کمک فوری یا متخصص را نمی‌گیرم. اگر خطر فوری وجود دارد، همین حالا با یک فرد قابل اعتماد در نزدیکی خود یا خدمات اضطراری محلی تماس بگیر. می‌توانیم فقط روی قدم امن بعدی تمرکز کنیم.';
20 + }
21 + if (kind === 'study') {
22 + return `پیشنهاد مطالعه: هدف را به یک بخش ۲۵ دقیقه‌ای کوچک تبدیل کن، بعد ۵ دقیقه استراحت و در پایان سه نکته را بدون نگاه‌کردن مرور کن. موضوع فعلی: ${text.slice(0, 180)}`;
23 + }
24 + if (kind === 'planner') {
25 + return 'پیشنهاد برنامه‌ریزی: فقط سه اولویت امروز را انتخاب کن؛ کار سخت‌تر را به کوچک‌ترین اقدام قابل شروع بشکن و برای استراحت زمان واقعی نگه دار.';
26 + }
27 + return 'می‌توانم برای خودبازتابی، ارتباط سالم و عادت‌های حمایتی کمک کنم، نه تشخیص پزشکی. احساس را نام‌گذاری کن، شدت آن را بسنج و یک اقدام کوچک مثل آب، استراحت، حرکت کوتاه یا صحبت با فرد قابل اعتماد انتخاب کن.';
28 +}
29 +
30 +async function providerGuide(kind, text, klass) {
31 + if (klass === 'urgent_review') return localGuide(kind, text, klass);
32 +
33 + const apiKey = process.env.AI_API_KEY;
34 + const baseUrl = process.env.AI_BASE_URL;
35 + const model = process.env.AI_MODEL;
36 + if (!apiKey || !baseUrl || !model) {
37 + return localGuide(kind, text, klass);
38 + }
39 +
40 + const system = [
41 + 'You are LifeMate, an age-appropriate Persian companion.',
42 + 'You are advisory, not a doctor, therapist, diagnostician, or emergency service.',
43 + 'For study, guide step-by-step and avoid simply giving final homework answers.',
44 + 'For planning, propose realistic options and preserve user agency.',
45 + 'For wellbeing, be calm, supportive, non-clinical, and encourage trusted human support when appropriate.',
46 + 'Never claim to know hidden mental state. Never expose private content to parents.',
47 + `Guide mode: ${kind}`,
48 + ].join(' ');
49 +
50 + const response = await fetch(`${baseUrl.replace(/\/$/, '')}/chat/completions`, {
51 + method: 'POST',
52 + headers: {
53 + authorization: `Bearer ${apiKey}`,
54 + 'content-type': 'application/json',
55 + },
56 + body: JSON.stringify({
57 + model,
58 + temperature: 0.4,
59 + messages: [
60 + { role: 'system', content: system },
61 + { role: 'user', content: text },
62 + ],
63 + }),
64 + });
65 +
66 + if (!response.ok) return localGuide(kind, text, klass);
67 + const body = await response.json();
68 + const content = body?.choices?.[0]?.message?.content;
69 + return clampText(content, 6000) || localGuide(kind, text, klass);
70 +}
71 +
72 +async function guardianRelationship(pool, familyId, guardianUserId, minorUserId) {
73 + const result = await pool.query(
74 + `select 1
75 + from guardian_relationship g
76 + join family_membership gm
77 + on gm.family_id=g.family_id
78 + and gm.user_id=g.guardian_user_id
79 + and gm.ended_at is null
80 + join family_membership mm
81 + on mm.family_id=g.family_id
82 + and mm.user_id=g.minor_user_id
83 + and mm.ended_at is null
84 + where g.family_id=$1
85 + and g.guardian_user_id=$2
86 + and g.minor_user_id=$3
87 + and g.active=true`,
88 + [familyId, guardianUserId, minorUserId],
89 + );
90 + return result.rowCount > 0;
91 +}
92 +
93 +export function createPhase4Router({ pool, auth }) {
94 + const router = express.Router();
95 + router.use(auth);
96 +
97 + router.post('/learning/goals', async (req, res) => {
98 + const title = clampText(req.body.title, 240);
99 + if (!title) return res.status(400).json({ error: 'invalid_input' });
100 + const result = await pool.query(
101 + 'insert into learning_goal(owner_user_id,subject_id,title,target) values($1,$2,$3,$4) returning *',
102 + [
103 + req.identity.sub,
104 + req.body.subjectId || null,
105 + title,
106 + clampText(req.body.target, 1000) || null,
107 + ],
108 + );
109 + res.status(201).json(result.rows[0]);
110 + });
111 +
112 + router.get('/learning/goals', async (req, res) => {
113 + const result = await pool.query(
114 + "select * from learning_goal where owner_user_id=$1 and status<>'archived' order by created_at desc",
115 + [req.identity.sub],
116 + );
117 + res.json({ items: result.rows });
118 + });
119 +
120 + router.post('/learning/checkins', async (req, res) => {
121 + const confidence = Number(req.body.confidence);
122 + const difficulty = Number(req.body.difficulty);
123 + if (
124 + !Number.isInteger(confidence) ||
125 + confidence < 1 ||
126 + confidence > 5 ||
127 + !Number.isInteger(difficulty) ||
128 + difficulty < 1 ||
129 + difficulty > 5
130 + ) {
131 + return res.status(400).json({ error: 'invalid_input' });
132 + }
133 + const result = await pool.query(
134 + 'insert into learning_checkin(owner_user_id,learning_goal_id,confidence,difficulty,note) values($1,$2,$3,$4,$5) returning *',
135 + [
136 + req.identity.sub,
137 + req.body.learningGoalId || null,
138 + confidence,
139 + difficulty,
140 + clampText(req.body.note, 2000) || null,
141 + ],
142 + );
143 + res.status(201).json(result.rows[0]);
144 + });
145 +
146 + router.post('/wellbeing/checkins', async (req, res) => {
147 + const mood = Number(req.body.mood);
148 + const energy = Number(req.body.energy);
149 + const stress = Number(req.body.stress);
150 + if (![mood, energy, stress].every((x) => Number.isInteger(x) && x >= 1 && x <= 5)) {
151 + return res.status(400).json({ error: 'invalid_input' });
152 + }
153 + const visibility =
154 + req.body.visibility === 'guardian_summary' ? 'guardian_summary' : 'private';
155 + const result = await pool.query(
156 + 'insert into wellbeing_checkin(owner_user_id,mood,energy,stress,note,visibility) values($1,$2,$3,$4,$5,$6) returning id,mood,energy,stress,visibility,created_at',
157 + [
158 + req.identity.sub,
159 + mood,
160 + energy,
161 + stress,
162 + clampText(req.body.note, 2000) || null,
163 + visibility,
164 + ],
165 + );
166 + res.status(201).json(result.rows[0]);
167 + });
168 +
169 + router.get('/wellbeing/checkins', async (req, res) => {
170 + const result = await pool.query(
171 + 'select id,mood,energy,stress,visibility,created_at from wellbeing_checkin where owner_user_id=$1 order by created_at desc limit 30',
172 + [req.identity.sub],
173 + );
174 + res.json({ items: result.rows });
175 + });
176 +
177 + router.get('/families/:familyId/children/:minorUserId/wellbeing-summary', async (req, res) => {
178 + const allowed = await guardianRelationship(
179 + pool,
180 + req.params.familyId,
181 + req.identity.sub,
182 + req.params.minorUserId,
183 + );
184 + if (!allowed) return res.status(403).json({ error: 'forbidden' });
185 +
186 + const summary = await pool.query(
187 + `select
188 + count(*)::int as checkin_count,
189 + round(avg(mood)::numeric,2) as mood_average,
190 + round(avg(energy)::numeric,2) as energy_average,
191 + round(avg(stress)::numeric,2) as stress_average,
192 + min(created_at) as window_start,
193 + max(created_at) as window_end
194 + from wellbeing_checkin
195 + where owner_user_id=$1
196 + and visibility='guardian_summary'
197 + and created_at >= now()-interval '14 days'`,
198 + [req.params.minorUserId],
199 + );
200 + const safety = await pool.query(
201 + `select count(*)::int as open_urgent_count,max(created_at) as latest_urgent_at
202 + from wellbeing_safety_event
203 + where owner_user_id=$1 and status='open'`,
204 + [req.params.minorUserId],
205 + );
206 + res.json({
207 + summary: summary.rows[0],
208 + safety: safety.rows[0],
209 + rawNotesIncluded: false,
210 + rawConversationIncluded: false,
211 + medicalDiagnosis: false,
212 + });
213 + });
214 +
215 + router.post('/families/:familyId/children/:minorUserId/family-guidance', async (req, res) => {
216 + const allowed = await guardianRelationship(
217 + pool,
218 + req.params.familyId,
219 + req.identity.sub,
220 + req.params.minorUserId,
221 + );
222 + if (!allowed) return res.status(403).json({ error: 'forbidden' });
223 +
224 + const question = clampText(req.body.question, 2000);
225 + if (!question) return res.status(400).json({ error: 'invalid_input' });
226 +
227 + const [academic, wellbeing, safety] = await Promise.all([
228 + pool.query(
229 + `select
230 + count(*) filter (
231 + where kind in ('assignment','study_session')
232 + and status not in ('completed','cancelled')
233 + and due_at < now()
234 + )::int as overdue,
235 + count(*) filter (
236 + where kind in ('assignment','study_session')
237 + and status='completed'
238 + and completed_at >= now()-interval '7 days'
239 + )::int as completed_last_7_days,
240 + coalesce(sum(duration_minutes) filter (
241 + where kind='study_session'
242 + and status='completed'
243 + and completed_at >= now()-interval '7 days'
244 + ),0)::int as study_minutes_last_7_days,
245 + case when sum(grade_out_of) filter (
246 + where grade_points is not null and grade_out_of is not null
247 + ) > 0 then
248 + round(
249 + sum(grade_points) filter (where grade_points is not null and grade_out_of is not null)
250 + /
251 + sum(grade_out_of) filter (where grade_points is not null and grade_out_of is not null)
252 + * 100,
253 + 1
254 + )
255 + end as grade_percent
256 + from plan_item
257 + where owner_user_id=$1`,
258 + [req.params.minorUserId],
259 + ),
260 + pool.query(
261 + `select
262 + count(*)::int as checkin_count,
263 + round(avg(mood)::numeric,2) as mood_average,
264 + round(avg(energy)::numeric,2) as energy_average,
265 + round(avg(stress)::numeric,2) as stress_average
266 + from wellbeing_checkin
267 + where owner_user_id=$1
268 + and visibility='guardian_summary'
269 + and created_at >= now()-interval '14 days'`,
270 + [req.params.minorUserId],
271 + ),
272 + pool.query(
273 + `select count(*)::int as open_urgent_count
274 + from wellbeing_safety_event
275 + where owner_user_id=$1 and status='open'`,
276 + [req.params.minorUserId],
277 + ),
278 + ]);
279 +
280 + const context = {
281 + academic: academic.rows[0],
282 + wellbeing: wellbeing.rows[0],
283 + safety: safety.rows[0],
284 + privacy: {
285 + rawNotesIncluded: false,
286 + rawConversationIncluded: false,
287 + },
288 + };
289 + const prompt = [
290 + 'You are advising a parent/guardian using only authorized aggregate data.',
291 + 'Do not diagnose the child and do not infer hidden mental state.',
292 + 'Give concrete, low-pressure family support ideas and questions the parent can ask.',
293 + 'If safety.open_urgent_count is above zero, prioritize immediate trusted-human support and local emergency resources.',
294 + `Authorized summary: ${JSON.stringify(context)}`,
295 + `Parent question: ${question}`,
296 + ].join('\n');
297 +
298 + const klass =
299 + Number(context.safety.open_urgent_count ?? 0) > 0
300 + ? 'urgent_review'
301 + : safetyClass(question);
302 + const advice = await providerGuide('wellbeing', prompt, klass);
303 +
304 + await pool.query(
305 + `insert into access_audit(actor_user_id,family_id,action,target_type,target_id,metadata)
306 + values($1,$2,'parent.family_guidance.request','student',$3,$4::jsonb)`,
307 + [
308 + req.identity.sub,
309 + req.params.familyId,
310 + req.params.minorUserId,
311 + JSON.stringify({ rawNotesIncluded: false, rawConversationIncluded: false }),
312 + ],
313 + );
314 +
315 + res.json({
316 + advice,
317 + summary: context,
318 + advisory: true,
319 + medicalDiagnosis: false,
320 + rawNotesIncluded: false,
321 + rawConversationIncluded: false,
322 + });
323 + });
324 +
325 + router.post('/ai/sessions', async (req, res) => {
326 + const kind = ['study', 'planner', 'wellbeing'].includes(req.body.kind)
327 + ? req.body.kind
328 + : null;
329 + if (!kind) return res.status(400).json({ error: 'invalid_kind' });
330 + const result = await pool.query(
331 + 'insert into ai_guide_session(owner_user_id,guide_kind) values($1,$2) returning *',
332 + [req.identity.sub, kind],
333 + );
334 + res.status(201).json(result.rows[0]);
335 + });
336 +
337 + router.post('/ai/sessions/:id/messages', async (req, res) => {
338 + const text = clampText(req.body.message);
339 + if (!text) return res.status(400).json({ error: 'invalid_input' });
340 + const session = await pool.query(
341 + "select * from ai_guide_session where id=$1 and owner_user_id=$2 and status='active'",
342 + [req.params.id, req.identity.sub],
343 + );
344 + if (!session.rowCount) return res.status(404).json({ error: 'session_not_found' });
345 +
346 + const klass = safetyClass(text);
347 + await pool.query(
348 + "insert into ai_guide_message(session_id,author,body,safety_class) values($1,'user',$2,$3)",
349 + [req.params.id, text, klass],
350 + );
351 + if (klass === 'urgent_review') {
352 + await pool.query(
353 + "insert into wellbeing_safety_event(owner_user_id,source_session_id,severity) values($1,$2,'urgent_review')",
354 + [req.identity.sub, req.params.id],
355 + );
356 + }
357 +
358 + const reply = await providerGuide(session.rows[0].guide_kind, text, klass);
359 + const result = await pool.query(
360 + "insert into ai_guide_message(session_id,author,body,safety_class) values($1,'assistant',$2,$3) returning id,body,safety_class,created_at",
361 + [req.params.id, reply, klass],
362 + );
363 + res.json({
364 + ...result.rows[0],
365 + advisory: true,
366 + medicalDiagnosis: false,
367 + automaticAction: false,
368 + providerMode: process.env.AI_API_KEY ? 'configured' : 'local_fallback',
369 + });
370 + });
371 +
372 + router.post('/ai/proposals', async (req, res) => {
373 + const title = clampText(req.body.title, 240);
374 + if (!title || !req.body.proposal || typeof req.body.proposal !== 'object') {
375 + return res.status(400).json({ error: 'invalid_input' });
376 + }
377 + const result = await pool.query(
378 + 'insert into ai_plan_proposal(owner_user_id,session_id,title,proposal) values($1,$2,$3,$4) returning *',
379 + [req.identity.sub, req.body.sessionId || null, title, req.body.proposal],
380 + );
381 + res.status(201).json(result.rows[0]);
382 + });
383 +
384 + router.patch('/ai/proposals/:id', async (req, res) => {
385 + const status = ['accepted', 'rejected'].includes(req.body.status)
386 + ? req.body.status
387 + : null;
388 + if (!status) return res.status(400).json({ error: 'invalid_status' });
389 + const result = await pool.query(
390 + "update ai_plan_proposal set status=$3,decided_at=now() where id=$1 and owner_user_id=$2 and status='proposed' returning *",
391 + [req.params.id, req.identity.sub, status],
392 + );
393 + if (!result.rowCount) return res.status(404).json({ error: 'proposal_not_found' });
394 + res.json(result.rows[0]);
395 + });
396 +
397 + return router;
398 +}
backend/src/server.js
+2
@@ -6,6 +6,7 @@ import pg from 'pg';
6 import nodemailer from 'nodemailer';
7 import cors from 'cors';
8 import { createPhase3Router } from './phase3.js';
9 +import { createPhase4Router } from './phase4.js';
10
11 const { Pool } = pg;
12 const app = express();
@@ -604,6 +605,7 @@ app.post('/v1/families/:familyId/guardians', auth, async (req, res) => {
605 });
606
607 app.use('/v1', createPhase3Router({ pool, auth }));
608 +app.use('/v1', createPhase4Router({ pool, auth }));
609
610 app.use((err, _req, res, _next) => {
611 console.error(err);
backend/tests/phase4.test.js new
+234
@@ -0,0 +1,234 @@
1 +import test, { after } from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import { app, pool } from '../src/server.js';
4 +
5 +const server = app.listen(0);
6 +const address = server.address();
7 +const base = `http://127.0.0.1:${address.port}`;
8 +
9 +after(async () => {
10 + await new Promise((resolve) => server.close(resolve));
11 + await pool.end();
12 +});
13 +
14 +async function request(path, { method = 'GET', body, token } = {}) {
15 + const response = await fetch(base + path, {
16 + method,
17 + headers: {
18 + 'content-type': 'application/json',
19 + ...(token ? { authorization: `Bearer ${token}` } : {}),
20 + },
21 + body: body === undefined ? undefined : JSON.stringify(body),
22 + });
23 + const text = await response.text();
24 + return {
25 + status: response.status,
26 + body: text ? JSON.parse(text) : null,
27 + };
28 +}
29 +
30 +async function registerVerified(email, displayName) {
31 + const password = 'Phase4Pass!123';
32 + const registration = await request('/v1/auth/register', {
33 + method: 'POST',
34 + body: { email, displayName, password },
35 + });
36 + assert.equal(registration.status, 201);
37 + assert.equal(
38 + (
39 + await request('/v1/auth/verify-email', {
40 + method: 'POST',
41 + body: { token: registration.body.verificationToken },
42 + })
43 + ).status,
44 + 204,
45 + );
46 + const login = await request('/v1/auth/login', {
47 + method: 'POST',
48 + body: { email, password },
49 + });
50 + assert.equal(login.status, 200);
51 + return { token: login.body.accessToken, userId: registration.body.userId };
52 +}
53 +
54 +test('phase 4 learning wellbeing and guardian safety boundaries', async () => {
55 + const suffix = Date.now().toString(36);
56 + const parentEmail = `p4-parent-${suffix}@example.test`;
57 + const teenEmail = `p4-teen-${suffix}@example.test`;
58 + const outsiderEmail = `p4-outsider-${suffix}@example.test`;
59 +
60 + const parent = await registerVerified(parentEmail, 'Phase4 Parent');
61 + const teen = await registerVerified(teenEmail, 'Phase4 Teen');
62 + const outsider = await registerVerified(outsiderEmail, 'Phase4 Outsider');
63 +
64 + const family = await request('/v1/families', {
65 + method: 'POST',
66 + token: parent.token,
67 + body: { name: 'Phase4 Family', role: 'parent_guardian' },
68 + });
69 + assert.equal(family.status, 201);
70 +
71 + const invitation = await request(`/v1/families/${family.body.id}/invitations`, {
72 + method: 'POST',
73 + token: parent.token,
74 + body: {
75 + email: teenEmail,
76 + role: 'teen_minor',
77 + themePreference: 'girl_pink',
78 + },
79 + });
80 + assert.equal(invitation.status, 201);
81 +
82 + assert.equal(
83 + (
84 + await request('/v1/invitations/accept', {
85 + method: 'POST',
86 + token: teen.token,
87 + body: { token: invitation.body.invitationToken },
88 + })
89 + ).status,
90 + 204,
91 + );
92 +
93 + assert.equal(
94 + (
95 + await request(`/v1/families/${family.body.id}/guardians`, {
96 + method: 'POST',
97 + token: parent.token,
98 + body: {
99 + guardianUserId: parent.userId,
100 + minorUserId: teen.userId,
101 + },
102 + })
103 + ).status,
104 + 204,
105 + );
106 +
107 + const goal = await request('/v1/learning/goals', {
108 + method: 'POST',
109 + token: teen.token,
110 + body: { title: 'تسلط روی جبر', target: 'حل تمرین‌های فصل اول' },
111 + });
112 + assert.equal(goal.status, 201);
113 +
114 + const learningCheckin = await request('/v1/learning/checkins', {
115 + method: 'POST',
116 + token: teen.token,
117 + body: {
118 + learningGoalId: goal.body.id,
119 + confidence: 3,
120 + difficulty: 4,
121 + note: 'تمرین بیشتری لازم دارم',
122 + },
123 + });
124 + assert.equal(learningCheckin.status, 201);
125 +
126 + const privateCheckin = await request('/v1/wellbeing/checkins', {
127 + method: 'POST',
128 + token: teen.token,
129 + body: {
130 + mood: 3,
131 + energy: 2,
132 + stress: 4,
133 + note: 'این متن خصوصی است',
134 + visibility: 'private',
135 + },
136 + });
137 + assert.equal(privateCheckin.status, 201);
138 + assert.equal(Object.hasOwn(privateCheckin.body, 'note'), false);
139 +
140 + const sharedCheckin = await request('/v1/wellbeing/checkins', {
141 + method: 'POST',
142 + token: teen.token,
143 + body: {
144 + mood: 4,
145 + energy: 3,
146 + stress: 2,
147 + note: 'این متن هم نباید به والد برگردد',
148 + visibility: 'guardian_summary',
149 + },
150 + });
151 + assert.equal(sharedCheckin.status, 201);
152 + assert.equal(Object.hasOwn(sharedCheckin.body, 'note'), false);
153 +
154 + const ownCheckins = await request('/v1/wellbeing/checkins', {
155 + token: teen.token,
156 + });
157 + assert.equal(ownCheckins.status, 200);
158 + assert.equal(ownCheckins.body.items.length >= 2, true);
159 + assert.equal(
160 + ownCheckins.body.items.some((item) => Object.hasOwn(item, 'note')),
161 + false,
162 + );
163 +
164 + const guardianSummary = await request(
165 + `/v1/families/${family.body.id}/children/${teen.userId}/wellbeing-summary`,
166 + { token: parent.token },
167 + );
168 + assert.equal(guardianSummary.status, 200);
169 + assert.equal(guardianSummary.body.summary.checkin_count, 1);
170 + assert.equal(guardianSummary.body.rawNotesIncluded, false);
171 + assert.equal(guardianSummary.body.rawConversationIncluded, false);
172 +
173 + const outsiderSummary = await request(
174 + `/v1/families/${family.body.id}/children/${teen.userId}/wellbeing-summary`,
175 + { token: outsider.token },
176 + );
177 + assert.equal(outsiderSummary.status, 403);
178 +
179 + const familyGuidance = await request(
180 + `/v1/families/${family.body.id}/children/${teen.userId}/family-guidance`,
181 + {
182 + method: 'POST',
183 + token: parent.token,
184 + body: { question: 'چطور بدون فشار حمایتش کنم؟' },
185 + },
186 + );
187 + assert.equal(familyGuidance.status, 200);
188 + assert.equal(familyGuidance.body.advisory, true);
189 + assert.equal(familyGuidance.body.medicalDiagnosis, false);
190 + assert.equal(familyGuidance.body.rawNotesIncluded, false);
191 + assert.equal(familyGuidance.body.rawConversationIncluded, false);
192 +
193 + const outsiderGuidance = await request(
194 + `/v1/families/${family.body.id}/children/${teen.userId}/family-guidance`,
195 + {
196 + method: 'POST',
197 + token: outsider.token,
198 + body: { question: 'وضعیت چیست؟' },
199 + },
200 + );
201 + assert.equal(outsiderGuidance.status, 403);
202 +
203 + const session = await request('/v1/ai/sessions', {
204 + method: 'POST',
205 + token: teen.token,
206 + body: { kind: 'wellbeing' },
207 + });
208 + assert.equal(session.status, 201);
209 +
210 + const ordinary = await request(`/v1/ai/sessions/${session.body.id}/messages`, {
211 + method: 'POST',
212 + token: teen.token,
213 + body: { message: 'امروز کمی استرس دارم' },
214 + });
215 + assert.equal(ordinary.status, 200);
216 + assert.equal(ordinary.body.advisory, true);
217 + assert.equal(ordinary.body.medicalDiagnosis, false);
218 + assert.equal(ordinary.body.automaticAction, false);
219 +
220 + const urgent = await request(`/v1/ai/sessions/${session.body.id}/messages`, {
221 + method: 'POST',
222 + token: teen.token,
223 + body: { message: 'به خودکشی فکر می‌کنم' },
224 + });
225 + assert.equal(urgent.status, 200);
226 + assert.equal(urgent.body.safety_class, 'urgent_review');
227 +
228 + const safetySummary = await request(
229 + `/v1/families/${family.body.id}/children/${teen.userId}/wellbeing-summary`,
230 + { token: parent.token },
231 + );
232 + assert.equal(safetySummary.status, 200);
233 + assert.equal(safetySummary.body.safety.open_urgent_count >= 1, true);
234 +});
backend/tests/phase4_contract.test.js new
+21
@@ -0,0 +1,21 @@
1 +import test from 'node:test';
2 +import assert from 'node:assert/strict';
3 +import fs from 'node:fs';
4 +
5 +const src=fs.readFileSync(new URL('../src/phase4.js',import.meta.url),'utf8');
6 +const migration=fs.readFileSync(new URL('../migrations/0004_ai_learning_wellbeing.sql',import.meta.url),'utf8');
7 +
8 +test('phase4 schema contains learning wellbeing guide and proposal boundaries',()=>{
9 + for(const table of ['learning_goal','learning_checkin','wellbeing_checkin','ai_guide_session','ai_guide_message','ai_plan_proposal','wellbeing_safety_event']) assert.match(migration,new RegExp(`create table if not exists ${table}`));
10 + assert.match(migration,/visibility in \('private','guardian_summary'\)/);
11 + assert.match(migration,/status in \('proposed','accepted','rejected'\)/);
12 +});
13 +
14 +test('AI guide is advisory and has urgent safety path',()=>{
15 + assert.match(src,/urgent_review/); assert.match(src,/medicalDiagnosis:\s*false/); assert.match(src,/automaticAction:\s*false/); assert.match(src,/خدمات اضطراری محلی/);
16 +});
17 +
18 +test('wellbeing list is owner scoped and excludes raw note',()=>{
19 + assert.match(src,/select id,mood,energy,stress,visibility,created_at from wellbeing_checkin where owner_user_id=\$1/);
20 + assert.doesNotMatch(src,/select id,mood,energy,stress,note,visibility,created_at from wellbeing_checkin/);
21 +});
backend/tests/phase4_schema_test.sql new
+48
@@ -0,0 +1,48 @@
1 +\set ON_ERROR_STOP on
2 +begin;
3 +
4 +insert into app_user(id,identity_subject,email_normalized) values
5 +('40000000-0000-0000-0000-000000000001','p4-owner','p4-owner@example.test');
6 +
7 +insert into profile(user_id,display_name) values
8 +('40000000-0000-0000-0000-000000000001','P4 Owner');
9 +
10 +insert into learning_goal(id,owner_user_id,title,target) values
11 +('41000000-0000-0000-0000-000000000001','40000000-0000-0000-0000-000000000001','Goal','Target');
12 +
13 +insert into learning_checkin(owner_user_id,learning_goal_id,confidence,difficulty,note) values
14 +('40000000-0000-0000-0000-000000000001','41000000-0000-0000-0000-000000000001',4,3,'note');
15 +
16 +insert into wellbeing_checkin(owner_user_id,mood,energy,stress,note,visibility) values
17 +('40000000-0000-0000-0000-000000000001',4,3,2,'private note','private');
18 +
19 +insert into ai_guide_session(id,owner_user_id,guide_kind) values
20 +('42000000-0000-0000-0000-000000000001','40000000-0000-0000-0000-000000000001','wellbeing');
21 +
22 +insert into ai_guide_message(session_id,author,body,safety_class) values
23 +('42000000-0000-0000-0000-000000000001','user','hello','ordinary');
24 +
25 +insert into wellbeing_safety_event(owner_user_id,source_session_id,severity) values
26 +('40000000-0000-0000-0000-000000000001','42000000-0000-0000-0000-000000000001','urgent_review');
27 +
28 +insert into ai_plan_proposal(owner_user_id,session_id,title,proposal) values
29 +('40000000-0000-0000-0000-000000000001','42000000-0000-0000-0000-000000000001','Plan','{"steps":[1,2]}'::jsonb);
30 +
31 +do $$
32 +begin
33 + begin
34 + insert into wellbeing_checkin(owner_user_id,mood,energy,stress)
35 + values('40000000-0000-0000-0000-000000000001',6,3,2);
36 + raise exception 'mood constraint failed to reject invalid value';
37 + exception when check_violation then null;
38 + end;
39 +
40 + begin
41 + insert into ai_guide_session(owner_user_id,guide_kind)
42 + values('40000000-0000-0000-0000-000000000001','diagnostician');
43 + raise exception 'guide kind constraint failed';
44 + exception when check_violation then null;
45 + end;
46 +end $$;
47 +
48 +rollback;
docs/decisions/0004-ai-learning-wellbeing-safety.md new
+36
@@ -0,0 +1,36 @@
1 +# ADR 0004 — AI Guides, Learning & Wellbeing
2 +
3 +Status: Accepted for Phase 4 engineering/staging.
4 +
5 +## Decision
6 +AI Guides are advisory. They may propose study, planner, wellbeing and family-support actions but never silently mutate planner data. Explicit proposals require user acceptance.
7 +
8 +Wellbeing guidance is supportive self-reflection and family communication guidance, not diagnosis, treatment or a substitute for a clinician or emergency service. The product must not present AI as a doctor or psychologist.
9 +
10 +AI sessions, messages and wellbeing notes are owner-private by default. Family membership or family-admin status does not grant raw transcript access. A wellbeing check-in can be marked `guardian_summary`; guardian endpoints expose only aggregates and safety signals, never the note body or private AI transcript.
11 +
12 +Parents/guardians with an active guardian relationship can request family guidance. The guide receives only authorized academic metrics, authorized wellbeing aggregates and safety-signal counts. The API response explicitly records that raw notes and raw conversations were not included.
13 +
14 +## Safety boundary
15 +The server classifies messages before generative output. High-risk self-harm language receives a fixed safety-first response and creates a separate `wellbeing_safety_event` signal. Safety escalation is therefore distinct from ordinary privacy sharing.
16 +
17 +The fixed urgent response directs the user toward an immediately available trusted person and local emergency resources. This is an engineering guardrail, not the final jurisdiction-specific crisis system.
18 +
19 +## Provider boundary
20 +Phase 4 has a provider-neutral OpenAI-compatible adapter controlled by `AI_BASE_URL`, `AI_API_KEY` and `AI_MODEL`. If no approved provider is configured, staging uses the deterministic local guide. Urgent safety responses never depend on the external model.
21 +
22 +No minor-sensitive provider configuration may be enabled in public production until provider privacy, retention, data-location and safety review passes.
23 +
24 +## Learning behavior
25 +Study guidance should favor hints, decomposition, active recall and checking understanding rather than immediately supplying final homework answers. Learning goals and confidence/difficulty check-ins remain separate from grades so the product can track learning process as well as outcomes.
26 +
27 +## Production gate
28 +Public production exposure of wellbeing/minor-sensitive generative AI remains disabled until all of these are approved:
29 +- jurisdiction-specific legal and guardian-consent review;
30 +- safety severity taxonomy and escalation policy;
31 +- localized emergency resources;
32 +- AI provider privacy/retention/data-location review;
33 +- wellbeing and AI retention/export/deletion policy;
34 +- final voice-provider privacy review before voice conversations are enabled.
35 +
36 +Voice remains a product requirement, but Phase 4 does not enable microphone/TTS transmission until the provider/privacy gate is selected and tested.