LifeMate — Personal, Family & Learning Companion

phase-4/ai-learning-wellbeing
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
js 398 lines 14.9 KB
Raw
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 }