LifeMate — Personal, Family & Learning Companion

feat/learning-content-operations
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 540 lines 26.8 KB
Raw
1 import express from 'express';
2 import crypto from 'node:crypto';
3
4 const clampText = (value, max = 4000) =>
5 String(value ?? '').trim().slice(0, max);
6 const isUuid = (value) => typeof value === 'string' && /^[a-f0-9]{8}(-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
7
8 const modernGoalRequest = body => body && ['mutationId','expectedVersion','id'].some(key=>Object.hasOwn(body,key));
9 function normalizeGoalMutation(operation, id, body, legacy = false) {
10 const fields = new Set([...(legacy?[]:['mutationId','expectedVersion',...(operation==='create'?['id']:[])]),
11 ...(operation==='archive'?[]:['title','target','subjectId','status'])]);
12 if (!body || typeof body !== 'object' || Array.isArray(body) || Object.keys(body).some(key=>!fields.has(key)) ||
13 (!legacy && (!isUuid(body.mutationId) || !Number.isSafeInteger(body.expectedVersion) || body.expectedVersion<0 ||
14 body.expectedVersion>=2147483647 || (operation==='create' ? (!isUuid(body.id) || body.expectedVersion!==0) : body.expectedVersion===0))) ||
15 !isUuid(id)) return null;
16 const normalized = {operation,id:id.toLowerCase(),...(legacy?{}:{mutationId:body.mutationId.toLowerCase(),expectedVersion:body.expectedVersion})};
17 for (const field of ['title','target']) {
18 if (!Object.hasOwn(body,field)) continue;
19 if (field==='target' && body[field]===null) { normalized[field]=null; continue; }
20 if (typeof body[field]!=='string' || body[field].includes('\u0000') ||
21 body[field].trim().length>(field==='title'?240:1000) || (field==='title' && !body[field].trim())) return null;
22 normalized[field]=body[field].trim() || null;
23 }
24 if (operation==='create' && !normalized.title) return null;
25 if (Object.hasOwn(body,'subjectId')) {
26 if (body.subjectId!==null && !isUuid(body.subjectId)) return null;
27 normalized.subjectId=body.subjectId?.toLowerCase()??null;
28 }
29 if (Object.hasOwn(body,'status')) {
30 if (!['active','completed','archived'].includes(body.status) || (operation==='create' && body.status==='archived')) return null;
31 normalized.status=body.status;
32 }
33 if(operation==='update' && !['title','target','subjectId','status'].some(key=>Object.hasOwn(normalized,key))) return null;
34 return normalized;
35 }
36
37 function legacyGoalInputError(body) {
38 if(body && typeof body==='object' && !Array.isArray(body)) {
39 if(body.subjectId!=null && !isUuid(body.subjectId)) return 'invalid_subject_id';
40 if(Object.hasOwn(body,'status') && !['active','completed','archived'].includes(body.status)) return 'invalid_status';
41 }
42 return 'invalid_input';
43 }
44
45 async function goalSessionCurrent(client, identity) {
46 // Lock the session through commit so logout/revocation cannot race the final
47 // authorization decision. JWT expiry must also be checked after lock waits.
48 const session=await client.query(`select 1 from auth_session s join app_user u on u.id=s.user_id
49 where s.id=$1 and s.user_id=$2 and s.revoked_at is null
50 and s.expires_at>statement_timestamp() and u.disabled_at is null for share of s`,[identity.sid,identity.sub]);
51 return session.rowCount>0 && (identity.exp==null || identity.exp*1000>Date.now());
52 }
53
54 async function activeGoalSubject(client, id, owner) {
55 const subject=await client.query(`select s.id from subject s
56 join academic_term t on t.id=s.academic_term_id
57 join academic_year y on y.id=t.academic_year_id
58 join life_context l on l.id=y.life_context_id
59 where s.id=$1 and s.student_user_id=$2 and y.student_user_id=$2 and l.user_id=$2
60 and s.archived_at is null and t.active and y.active and l.active and l.kind='student'
61 for share of s,t,y,l`,[id,owner]);
62 return subject.rowCount>0;
63 }
64
65 async function legacyGoalWrite(pool, identity, operation) {
66 const client=await pool.connect();
67 try {
68 await client.query('begin');
69 const account=await client.query('select id from app_user where id=$1 and disabled_at is null for update',[identity.sub]);
70 if(!account.rowCount || !await goalSessionCurrent(client,identity)) {
71 await client.query('rollback'); return {status:401,body:{error:'session_invalid'}};
72 }
73 const result=await operation(client);
74 if(!await goalSessionCurrent(client,identity)) {
75 await client.query('rollback'); return {status:401,body:{error:'session_invalid'}};
76 }
77 await client.query('commit'); return result;
78 } catch(error) { await client.query('rollback').catch(()=>{}); throw error; }
79 finally { client.release(); }
80 }
81
82 async function mutateLearningGoal(pool, identity, operation, id, raw) {
83 const owner=identity.sub;
84 const body=normalizeGoalMutation(operation,id,raw);
85 if(!body) return {status:400,body:{error:'invalid_goal_mutation'}};
86 const hash=crypto.createHash('sha256').update(JSON.stringify(body)).digest('hex');
87 const client=await pool.connect();
88 const failure=(status,error)=>({status,body:{error}});
89 try {
90 await client.query('begin');
91 const active=await client.query('select id from app_user where id=$1 and disabled_at is null for update',[owner]);
92 if(!active.rowCount || !await goalSessionCurrent(client,identity)) { await client.query('rollback'); return failure(401,'session_invalid'); }
93 // Owner locks alone do not serialize two independent accounts that supply
94 // the same stable UUID. Lock that entity before checking/inserting it, then
95 // return the ordinary forbidden response instead of leaking a PK/500 race.
96 await client.query("select pg_advisory_xact_lock(hashtextextended('lifeguide:learning-goal:'||$1,0))",[body.id]);
97 const previous=(await client.query('select * from learning_goal_mutation where owner_user_id=$1 and mutation_id=$2',[owner,body.mutationId])).rows[0];
98 if(previous && previous.request_hash!==hash) { await client.query('rollback'); return failure(409,'mutation_id_reused'); }
99 let goal=(await client.query('select * from learning_goal where id=$1 and owner_user_id=$2 for update',[body.id,owner])).rows[0];
100 const acknowledgement = (row,ledger,status) => ({goal:row,acknowledgement:{mutationId:body.mutationId,
101 goalId:body.id,operation,appliedVersion:ledger.applied_version,acceptedAt:ledger.accepted_at,status}});
102 if(previous) {
103 // Return the current tombstone/current version, never resurrect an older response.
104 if(!goal) throw new Error('learning_goal_ledger_invariant');
105 if(!await goalSessionCurrent(client,identity)) { await client.query('rollback'); return failure(401,'session_invalid'); }
106 await client.query('commit');
107 return {status:200,body:acknowledgement(goal,previous,'already_applied')};
108 }
109 if(!goal) {
110 const foreign=await client.query('select 1 from learning_goal where id=$1',[body.id]);
111 if(foreign.rowCount || operation!=='create') { await client.query('rollback'); return failure(foreign.rowCount?403:404,foreign.rowCount?'goal_forbidden':'goal_not_found'); }
112 } else if(operation==='create') { await client.query('rollback'); return failure(409,'goal_id_exists'); }
113 if(goal && goal.status==='archived') { await client.query('rollback'); return failure(409,'goal_archived'); }
114 if(goal && goal.version!==body.expectedVersion) { await client.query('rollback'); return failure(409,'version_conflict'); }
115 if(body.subjectId!=null) {
116 if(!await activeGoalSubject(client,body.subjectId,owner)) { await client.query('rollback'); return failure(403,'subject_forbidden'); }
117 }
118 if(operation==='create') {
119 goal=(await client.query('insert into learning_goal(id,owner_user_id,subject_id,title,target,status) values($1,$2,$3,$4,$5,$6) returning *',
120 [body.id,owner,body.subjectId??null,body.title,body.target??null,body.status??'active'])).rows[0];
121 } else {
122 const status=operation==='archive'?'archived':body.status??goal.status;
123 goal=(await client.query(`update learning_goal set title=$3,target=$4,subject_id=$5,status=$6,
124 version=version+1,updated_at=now(),archived_at=case when $6='archived' then now() else null end
125 where id=$1 and owner_user_id=$2 returning *`,[body.id,owner,body.title??goal.title,
126 Object.hasOwn(body,'target')?body.target:goal.target,Object.hasOwn(body,'subjectId')?body.subjectId:goal.subject_id,status])).rows[0];
127 }
128 const ledger=(await client.query('insert into learning_goal_mutation(owner_user_id,mutation_id,goal_id,operation,request_hash,applied_version) values($1,$2,$3,$4,$5,$6) returning *',
129 [owner,body.mutationId,body.id,operation,hash,goal.version])).rows[0];
130 if(!await goalSessionCurrent(client,identity)) { await client.query('rollback'); return failure(401,'session_invalid'); }
131 await client.query('commit');
132 return {status:operation==='create'?201:200,body:acknowledgement(goal,ledger,'accepted')};
133 } catch(error) { await client.query('rollback').catch(()=>{}); throw error; }
134 finally { client.release(); }
135 }
136
137 function safetyClass(text) {
138 const value = text.toLowerCase();
139 if (/(خودکشی|خودم را بکشم|آسیب به خود|self[- ]?harm|suicide|kill myself)/i.test(value)) {
140 return 'urgent_review';
141 }
142 if (/(غمگین|اضطراب|استرس|نگران|sad|anxious|stress|worried)/i.test(value)) {
143 return 'supportive';
144 }
145 return 'ordinary';
146 }
147
148 function localGuide(kind, text, klass) {
149 if (klass === 'urgent_review') {
150 return 'من جای کمک فوری یا متخصص را نمی‌گیرم. اگر خطر فوری وجود دارد، همین حالا با یک فرد قابل اعتماد در نزدیکی خود یا خدمات اضطراری محلی تماس بگیر. می‌توانیم فقط روی قدم امن بعدی تمرکز کنیم.';
151 }
152 if (kind === 'study') {
153 return `پیشنهاد مطالعه: هدف را به یک بخش ۲۵ دقیقه‌ای کوچک تبدیل کن، بعد ۵ دقیقه استراحت و در پایان سه نکته را بدون نگاه‌کردن مرور کن. موضوع فعلی: ${text.slice(0, 180)}`;
154 }
155 if (kind === 'planner') {
156 return 'پیشنهاد برنامه‌ریزی: فقط سه اولویت امروز را انتخاب کن؛ کار سخت‌تر را به کوچک‌ترین اقدام قابل شروع بشکن و برای استراحت زمان واقعی نگه دار.';
157 }
158 return 'می‌توانم برای خودبازتابی، ارتباط سالم و عادت‌های حمایتی کمک کنم، نه تشخیص پزشکی. احساس را نام‌گذاری کن، شدت آن را بسنج و یک اقدام کوچک مثل آب، استراحت، حرکت کوتاه یا صحبت با فرد قابل اعتماد انتخاب کن.';
159 }
160
161 async function providerGuide(kind, text, klass) {
162 // External AI/voice is not authorized in this package, even if keys exist.
163 return localGuide(kind, text, klass);
164 }
165
166 async function guardianRelationship(pool, familyId, guardianUserId, minorUserId) {
167 const result = await pool.query(
168 'select is_active_guardian($1,$2,$3) as allowed',
169 [familyId, guardianUserId, minorUserId],
170 );
171 return result.rows[0]?.allowed === true;
172 }
173
174 export function createPhase4Router({ pool, auth, sensitiveFeaturesEnabled = process.env.ENABLE_SENSITIVE_FEATURES === 'true' }) {
175 const router = express.Router();
176 const sensitiveEnabled = sensitiveFeaturesEnabled === true;
177 const requireSensitive = (_req, res, next) => {
178 if (!sensitiveEnabled) return res.status(503).json({ error: 'sensitive_features_disabled' });
179 return next();
180 };
181 router.use(auth);
182
183 router.post('/learning/goals', async (req, res) => {
184 if(Object.keys(req.query).length) return res.status(400).json({error:'invalid_goal_mutation'});
185 if(modernGoalRequest(req.body)) {
186 const result=await mutateLearningGoal(pool,req.identity,'create',req.body.id,req.body);
187 return res.status(result.status).json(result.body);
188 }
189 const body=normalizeGoalMutation('create',crypto.randomUUID(),req.body,true);
190 if(!body) return res.status(400).json({error:legacyGoalInputError(req.body)});
191 const result=await legacyGoalWrite(pool,req.identity,async client=>{
192 if(body.subjectId!=null && !await activeGoalSubject(client,body.subjectId,req.identity.sub)) {
193 return {status:403,body:{error:'subject_forbidden'}};
194 }
195 const created=await client.query('insert into learning_goal(owner_user_id,subject_id,title,target,status) values($1,$2,$3,$4,$5) returning *',
196 [req.identity.sub,body.subjectId??null,body.title,body.target??null,body.status??'active']);
197 return {status:201,body:created.rows[0]};
198 });
199 res.status(result.status).json(result.body);
200 });
201
202 router.get('/learning/goals', async (req, res) => {
203 const result = await pool.query(
204 "select * from learning_goal where owner_user_id=$1 and status<>'archived' order by created_at desc",
205 [req.identity.sub],
206 );
207 res.json({ items: result.rows, fetchedAt: new Date().toISOString() });
208 });
209
210 router.get('/learning/goals/:id', async (req, res) => {
211 if (!isUuid(req.params.id)) return res.status(400).json({ error: 'invalid_goal_id' });
212 const result = await pool.query('select * from learning_goal where id=$1 and owner_user_id=$2', [req.params.id, req.identity.sub]);
213 if (!result.rowCount) return res.status(404).json({ error: 'goal_not_found' });
214 res.json(result.rows[0]);
215 });
216
217 router.patch('/learning/goals/:id', async (req, res) => {
218 if (!isUuid(req.params.id)) return res.status(400).json({ error: 'invalid_goal_id' });
219 if(Object.keys(req.query).length) return res.status(400).json({error:'invalid_goal_mutation'});
220 if(modernGoalRequest(req.body)) {
221 const result=await mutateLearningGoal(pool,req.identity,'update',req.params.id,req.body);
222 return res.status(result.status).json(result.body);
223 }
224 const body=normalizeGoalMutation('update',req.params.id,req.body,true);
225 if(!body) return res.status(400).json({error:legacyGoalInputError(req.body)});
226 const has = (field) => Object.hasOwn(body, field);
227 const result=await legacyGoalWrite(pool,req.identity,async client=>{
228 const goal = await client.query('select status from learning_goal where id=$1 and owner_user_id=$2 for update', [req.params.id, req.identity.sub]);
229 if (!goal.rowCount || goal.rows[0].status === 'archived') {
230 return {status:goal.rowCount?409:404,body:{error:goal.rowCount?'goal_archived':'goal_not_found'}};
231 }
232 if (body.subjectId != null) {
233 if(!await activeGoalSubject(client,body.subjectId,req.identity.sub)) return {status:403,body:{error:'subject_forbidden'}};
234 }
235 const updated = await client.query(
236 `update learning_goal set title=case when $3 then $4 else title end,
237 target=case when $5 then $6 else target end,
238 subject_id=case when $7 then $8::uuid else subject_id end,
239 status=coalesce($9,status),updated_at=now(),version=version+1,
240 archived_at=case when $9='archived' then now() else null end
241 where id=$1 and owner_user_id=$2 returning *`,
242 [req.params.id, req.identity.sub, has('title'), has('title') ? body.title.trim() : null,
243 has('target'), body.target?.trim() || null, has('subjectId'), body.subjectId ?? null, body.status ?? null],
244 );
245 return {status:200,body:updated.rows[0]};
246 });
247 res.status(result.status).json(result.body);
248 });
249
250 router.delete('/learning/goals/:id', async (req, res) => {
251 if (!isUuid(req.params.id)) return res.status(400).json({ error: 'invalid_goal_id' });
252 if(Object.keys(req.query).length) return res.status(400).json({error:'invalid_goal_mutation'});
253 if(modernGoalRequest(req.body)) {
254 const result=await mutateLearningGoal(pool,req.identity,'archive',req.params.id,req.body);
255 return res.status(result.status).json(result.body);
256 }
257 if(!normalizeGoalMutation('archive',req.params.id,req.body??{},true)) return res.status(400).json({error:'invalid_input'});
258 const result=await legacyGoalWrite(pool,req.identity,async client=>{
259 const archived = await client.query(
260 `update learning_goal set status='archived',
261 archived_at=coalesce(archived_at,now()),
262 version=case when status='archived' then version else version+1 end,
263 updated_at=case when status='archived' then updated_at else now() end
264 where id=$1 and owner_user_id=$2 returning id`,
265 [req.params.id, req.identity.sub],
266 );
267 return archived.rowCount?{status:204}:{status:404,body:{error:'goal_not_found'}};
268 });
269 if(result.body===undefined) return res.status(result.status).end();
270 res.status(result.status).json(result.body);
271 });
272
273 router.post('/wellbeing/checkins', requireSensitive, async (req, res) => {
274 const mood = Number(req.body.mood);
275 const energy = Number(req.body.energy);
276 const stress = Number(req.body.stress);
277 if (![mood, energy, stress].every((x) => Number.isInteger(x) && x >= 1 && x <= 5)) {
278 return res.status(400).json({ error: 'invalid_input' });
279 }
280 const visibility =
281 req.body.visibility === 'guardian_summary' ? 'guardian_summary' : 'private';
282 const result = await pool.query(
283 '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',
284 [
285 req.identity.sub,
286 mood,
287 energy,
288 stress,
289 clampText(req.body.note, 2000) || null,
290 visibility,
291 ],
292 );
293 res.status(201).json(result.rows[0]);
294 });
295
296 router.get('/wellbeing/checkins', requireSensitive, async (req, res) => {
297 const result = await pool.query(
298 'select id,mood,energy,stress,visibility,created_at from wellbeing_checkin where owner_user_id=$1 order by created_at desc limit 30',
299 [req.identity.sub],
300 );
301 res.json({ items: result.rows });
302 });
303
304 router.get('/families/:familyId/children/:minorUserId/wellbeing-summary', requireSensitive, async (req, res) => {
305 const allowed = await guardianRelationship(
306 pool,
307 req.params.familyId,
308 req.identity.sub,
309 req.params.minorUserId,
310 );
311 if (!allowed) return res.status(403).json({ error: 'forbidden' });
312
313 const summary = await pool.query(
314 `select
315 count(*)::int as checkin_count,
316 round(avg(mood)::numeric,2) as mood_average,
317 round(avg(energy)::numeric,2) as energy_average,
318 round(avg(stress)::numeric,2) as stress_average,
319 min(created_at) as window_start,
320 max(created_at) as window_end
321 from wellbeing_checkin
322 where owner_user_id=$1
323 and visibility='guardian_summary'
324 and created_at >= now()-interval '14 days'`,
325 [req.params.minorUserId],
326 );
327 const safety = await pool.query(
328 `select count(*)::int as open_urgent_count,max(created_at) as latest_urgent_at
329 from wellbeing_safety_event
330 where owner_user_id=$1 and status='open'`,
331 [req.params.minorUserId],
332 );
333 res.json({
334 summary: summary.rows[0],
335 safety: safety.rows[0],
336 rawNotesIncluded: false,
337 rawConversationIncluded: false,
338 medicalDiagnosis: false,
339 });
340 });
341
342 router.post('/families/:familyId/children/:minorUserId/family-guidance', requireSensitive, async (req, res) => {
343 const allowed = await guardianRelationship(
344 pool,
345 req.params.familyId,
346 req.identity.sub,
347 req.params.minorUserId,
348 );
349 if (!allowed) return res.status(403).json({ error: 'forbidden' });
350
351 const question = clampText(req.body.question, 2000);
352 if (!question) return res.status(400).json({ error: 'invalid_input' });
353
354 const [academic, wellbeing, safety] = await Promise.all([
355 pool.query(
356 `select
357 count(*) filter (
358 where kind in ('assignment','study_session')
359 and status not in ('completed','cancelled')
360 and due_at < now()
361 )::int as overdue,
362 count(*) filter (
363 where kind in ('assignment','study_session')
364 and status='completed'
365 and completed_at >= now()-interval '7 days'
366 )::int as completed_last_7_days,
367 coalesce(sum(duration_minutes) filter (
368 where kind='study_session'
369 and status='completed'
370 and completed_at >= now()-interval '7 days'
371 ),0)::int as study_minutes_last_7_days,
372 case when sum(grade_out_of) filter (
373 where grade_points is not null and grade_out_of is not null
374 ) > 0 then
375 round(
376 sum(grade_points) filter (where grade_points is not null and grade_out_of is not null)
377 /
378 sum(grade_out_of) filter (where grade_points is not null and grade_out_of is not null)
379 * 100,
380 1
381 )
382 end as grade_percent
383 from plan_item
384 where owner_user_id=$1 and can_view_plan_item($2,id)`,
385 [req.params.minorUserId, req.identity.sub],
386 ),
387 pool.query(
388 `select
389 count(*)::int as checkin_count,
390 round(avg(mood)::numeric,2) as mood_average,
391 round(avg(energy)::numeric,2) as energy_average,
392 round(avg(stress)::numeric,2) as stress_average
393 from wellbeing_checkin
394 where owner_user_id=$1
395 and visibility='guardian_summary'
396 and created_at >= now()-interval '14 days'`,
397 [req.params.minorUserId],
398 ),
399 pool.query(
400 `select count(*)::int as open_urgent_count
401 from wellbeing_safety_event
402 where owner_user_id=$1 and status='open'`,
403 [req.params.minorUserId],
404 ),
405 ]);
406
407 const context = {
408 academic: academic.rows[0],
409 wellbeing: wellbeing.rows[0],
410 safety: safety.rows[0],
411 privacy: {
412 rawNotesIncluded: false,
413 rawConversationIncluded: false,
414 },
415 };
416 const prompt = [
417 'You are advising a parent/guardian using only authorized aggregate data.',
418 'Do not diagnose the child and do not infer hidden mental state.',
419 'Give concrete, low-pressure family support ideas and questions the parent can ask.',
420 'If safety.open_urgent_count is above zero, prioritize immediate trusted-human support and local emergency resources.',
421 `Authorized summary: ${JSON.stringify(context)}`,
422 `Parent question: ${question}`,
423 ].join('\n');
424
425 const klass =
426 Number(context.safety.open_urgent_count ?? 0) > 0
427 ? 'urgent_review'
428 : safetyClass(question);
429 const advice = await providerGuide('wellbeing', prompt, klass);
430
431 await pool.query(
432 `insert into access_audit(actor_user_id,family_id,action,target_type,target_id,metadata)
433 values($1,$2,'parent.family_guidance.request','student',$3,$4::jsonb)`,
434 [
435 req.identity.sub,
436 req.params.familyId,
437 req.params.minorUserId,
438 JSON.stringify({ rawNotesIncluded: false, rawConversationIncluded: false }),
439 ],
440 );
441
442 res.json({
443 advice,
444 summary: context,
445 advisory: true,
446 medicalDiagnosis: false,
447 rawNotesIncluded: false,
448 rawConversationIncluded: false,
449 });
450 });
451
452 router.post('/ai/sessions', async (req, res) => {
453 const kind = ['study', 'planner', 'wellbeing'].includes(req.body.kind)
454 ? req.body.kind
455 : null;
456 if (!kind) return res.status(400).json({ error: 'invalid_kind' });
457 if (kind === 'wellbeing' && !sensitiveEnabled) return res.status(503).json({ error: 'sensitive_features_disabled' });
458 const result = await pool.query(
459 'insert into ai_guide_session(owner_user_id,guide_kind) values($1,$2) returning *',
460 [req.identity.sub, kind],
461 );
462 res.status(201).json(result.rows[0]);
463 });
464
465 router.post('/ai/sessions/:id/messages', async (req, res) => {
466 const text = clampText(req.body.message);
467 if (!text) return res.status(400).json({ error: 'invalid_input' });
468 const session = await pool.query(
469 "select * from ai_guide_session where id=$1 and owner_user_id=$2 and status='active'",
470 [req.params.id, req.identity.sub],
471 );
472 if (!session.rowCount) return res.status(404).json({ error: 'session_not_found' });
473 if (session.rows[0].guide_kind === 'wellbeing' && !sensitiveEnabled) return res.status(503).json({ error: 'sensitive_features_disabled' });
474
475 const klass = safetyClass(text);
476 await pool.query(
477 "insert into ai_guide_message(session_id,author,body,safety_class) values($1,'user',$2,$3)",
478 [req.params.id, text, klass],
479 );
480 if (klass === 'urgent_review' && sensitiveEnabled) {
481 await pool.query(
482 "insert into wellbeing_safety_event(owner_user_id,source_session_id,severity) values($1,$2,'urgent_review')",
483 [req.identity.sub, req.params.id],
484 );
485 }
486
487 const reply = await providerGuide(session.rows[0].guide_kind, text, klass);
488 const result = await pool.query(
489 "insert into ai_guide_message(session_id,author,body,safety_class) values($1,'assistant',$2,$3) returning id,body,safety_class,created_at",
490 [req.params.id, reply, klass],
491 );
492 res.json({
493 ...result.rows[0],
494 advisory: true,
495 medicalDiagnosis: false,
496 automaticAction: false,
497 providerMode: 'local_fallback',
498 });
499 });
500
501 router.post('/ai/proposals', async (req, res) => {
502 const title = clampText(req.body.title, 240);
503 if (!title || !req.body.proposal || typeof req.body.proposal !== 'object') {
504 return res.status(400).json({ error: 'invalid_input' });
505 }
506 if (req.body.sessionId) {
507 const session = await pool.query('select guide_kind from ai_guide_session where id=$1 and owner_user_id=$2', [req.body.sessionId, req.identity.sub]);
508 if (!session.rowCount) return res.status(403).json({ error: 'session_forbidden' });
509 if (session.rows[0].guide_kind === 'wellbeing' && !sensitiveEnabled) return res.status(503).json({ error: 'sensitive_features_disabled' });
510 }
511 const result = await pool.query(
512 'insert into ai_plan_proposal(owner_user_id,session_id,title,proposal) values($1,$2,$3,$4) returning *',
513 [req.identity.sub, req.body.sessionId || null, title, req.body.proposal],
514 );
515 res.status(201).json(result.rows[0]);
516 });
517
518 router.patch('/ai/proposals/:id', async (req, res) => {
519 const status = ['accepted', 'rejected'].includes(req.body.status)
520 ? req.body.status
521 : null;
522 if (!status) return res.status(400).json({ error: 'invalid_status' });
523 const proposal = await pool.query(
524 `select s.guide_kind from ai_plan_proposal p
525 left join ai_guide_session s on s.id=p.session_id
526 where p.id=$1 and p.owner_user_id=$2 and p.status='proposed'`,
527 [req.params.id, req.identity.sub],
528 );
529 if (!proposal.rowCount) return res.status(404).json({ error: 'proposal_not_found' });
530 if (proposal.rows[0].guide_kind === 'wellbeing' && !sensitiveEnabled) return res.status(503).json({ error: 'sensitive_features_disabled' });
531 const result = await pool.query(
532 "update ai_plan_proposal set status=$3,decided_at=now() where id=$1 and owner_user_id=$2 and status='proposed' returning *",
533 [req.params.id, req.identity.sub, status],
534 );
535 if (!result.rowCount) return res.status(404).json({ error: 'proposal_not_found' });
536 res.json(result.rows[0]);
537 });
538
539 return router;
540 }