LifeMate — Personal, Family & Learning Companion

docs/offline-data-rescue-options
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 213 lines 19.8 KB
Raw
1 // Only public synthetic teaching fixtures; no real video is fetched or approved.
2 import test,{before,after} from 'node:test';
3 import assert from 'node:assert/strict';
4 import crypto from 'node:crypto';
5 import fs from 'node:fs/promises';
6 import os from 'node:os';
7 import path from 'node:path';
8 import pg from 'pg';
9 import {spawnSync} from 'node:child_process';
10 import {assessmentHash,assessmentContextHash} from '../src/learning_assessment.js';
11 import {inspectLearningContent,reviewLearningContent,videoMaterialHash,videoContextHash} from '../src/content_publication.js';
12
13 assert.ok(process.env.DATABASE_URL,'Use local synthetic PostgreSQL fixture credentials');
14 const source=new URL(process.env.TEST_FIXTURE_DATABASE_URL??process.env.DATABASE_URL);
15 assert.ok(['localhost','127.0.0.1','[::1]'].includes(source.hostname)&&(/test/.test(source.pathname)||source.pathname==='/lifemate_ci'),'Refuse nonlocal/nontest fixture');
16 const database='lifeguide_publication_test_'+crypto.randomBytes(6).toString('hex');
17 const admin=new pg.Client({connectionString:source.toString()});
18 const target=new URL(source);target.pathname='/'+database;
19 const env={CONTENT_REVIEW_DATABASE_URL:target.toString(),CONTENT_REVIEW_SYNTHETIC_ONLY:'true'};
20 const client=new pg.Client({connectionString:target.toString()});
21 const testRoles=['api','backup'].map(kind=>'lifeguide_publication_'+kind+'_test_'+crypto.randomBytes(6).toString('hex'));
22 const createdRoles=[];let databaseCreated=false,clientConnected=false;
23 before(async()=>{
24 await admin.connect();await admin.query(`create database "${database}"`);databaseCreated=true;
25 await client.connect();clientConnected=true;
26 // CI runs this before DB-role provisioning. Unique NOLOGIN fixture roles
27 // avoid any mutation of shared runtime/backup roles or their credentials.
28 for(const role of testRoles) {
29 await admin.query(`create role "${role}" nologin`);createdRoles.push(role);
30 }
31 // Stable foundation only. Do not migrate concurrently changing0016–0019 here.
32 const names=(await fs.readdir(new URL('../migrations/',import.meta.url))).filter(name=>/^00(?:0\d|1[0-5])_/.test(name)).sort();
33 for(const filename of [...names,'0020_content_publication_audit.sql']) {
34 const sql=await fs.readFile(new URL('../migrations/'+filename,import.meta.url),'utf8');await client.query(sql);
35 }
36 });
37 after(async()=>{
38 if(clientConnected) await client.end();
39 try {
40 if(databaseCreated) await admin.query(`drop database "${database}"`);
41 for(const role of createdRoles) await admin.query(`drop role "${role}"`);
42 } finally {await admin.end();}
43 });
44 const q=[{id:'q1',objectiveId:'counting',promptFa:'SYNTHETIC counting prompt',choices:[{id:'a',textFa:'۲'},{id:'b',textFa:'۳'}],correctChoiceId:'a',explanationFa:'SYNTHETIC explanation',remediationFa:'SYNTHETIC remediation'}];
45 async function fixture() {
46 const subject=crypto.randomUUID(),book=crypto.randomUUID(),unit=crypto.randomUUID(),video=crypto.randomUUID();
47 await client.query("insert into curriculum_subject(id,school_year,national_grade,code,name_fa) values($1,'1405-1406',1,$2,'SYNTHETIC publication subject')",[subject,'synthetic-publication-'+subject]);
48 await client.query("insert into textbook_catalog(id,curriculum_subject_id,title_fa,source_url,book_code,stable_book_key,edition_verification,source_evidence_url) values($1,$2,'SYNTHETIC publication textbook','https://chap.sch.ir/','999999',$3,'verified','https://chap.sch.ir/synthetic')",[book,subject,'synthetic-publication:'+book]);
49 await client.query("insert into learning_unit(id,textbook_id,unit_key,title_fa,order_index,index_kind,source_evidence_url) values($1,$2,'synthetic-counting','SYNTHETIC counting unit',1,'lesson','https://chap.sch.ir/synthetic-unit')",[unit,book]);
50 await client.query("insert into learning_video_resource(id,unit_id,aparat_id,title_fa,creator_name,creator_url,source_evidence_url,verification_status,duration_seconds,free_access,checked_at,quality_notes_fa,material_hash) values($1,$2,'SyN12','SYNTHETIC unobserved video','SYNTHETIC teacher','https://www.aparat.com/synthetic_teacher','https://www.aparat.com/v/SyN12','metadata_verified',60,true,'2026-10-01T00:00:00Z','SYNTHETIC only',$3)",[video,unit,'0'.repeat(64)]);
51 const row=(await client.query(`select v.*,u.unit_key,u.title_fa unit_title_fa,u.order_index,u.index_kind,u.source_evidence_url unit_evidence_url,u.active,
52 t.stable_book_key,t.title_fa book_title_fa,t.book_code,t.track_codes,t.variant,t.edition_verification,t.source_evidence_url book_evidence_url,s.school_year,s.national_grade
53 from learning_video_resource v join learning_unit u on u.id=v.unit_id join textbook_catalog t on t.id=u.textbook_id join curriculum_subject s on s.id=t.curriculum_subject_id where v.id=$1`,[video])).rows[0];
54 row.material_hash=videoMaterialHash(row);await client.query('update learning_video_resource set material_hash=$2 where id=$1',[video,row.material_hash]);
55 return {subject,book,unit,video,row};
56 }
57 const videoReview=row=>({evidenceScope:'SYNTHETIC_TEST_ONLY',reviewerName:'SYNTHETIC TEST REVIEWER — not real approval',reviewedAt:'2026-10-01T00:00:00Z',
58 bookCode:row.book_code,schoolYear:row.school_year,unitKey:row.unit_key,bookEvidenceUrl:row.book_evidence_url,unitEvidenceUrl:row.unit_evidence_url,
59 materialHash:row.material_hash,watchedEntireVideo:true,editionAligned:true,accuracyApproved:true,suitabilityApproved:true,embedRightsApproved:true,
60 questionCoverageReviewed:true,alignmentNotes:'SYNTHETIC alignment',accuracyNotes:'SYNTHETIC accuracy',suitabilityNotes:'SYNTHETIC suitability',
61 embedRightsEvidence:'SYNTHETIC rights',questionCoverageNotes:'SYNTHETIC questions'});
62 const publishVideo=f=>({schemaVersion:1,mutationId:crypto.randomUUID(),entityType:'video',entityId:f.video,operation:'publish',expectedStatus:'draft',
63 expectedContentHash:f.row.material_hash,expectedContextHash:videoContextHash(f.row),review:videoReview(f.row)});
64
65 test('inspection and complete synthetic dry-run perform zero persistent mutations',async()=>{
66 const f=await fixture(),body=publishVideo(f);
67 const inspected=await inspectLearningContent(client,'video',f.video,{env});assert.equal(inspected.publicationStatus,'draft');
68 assert.equal(inspected.contentHash,f.row.material_hash);
69 const before=(await client.query('select publication_status,pedagogical_review,review_record from learning_video_resource where id=$1',[f.video])).rows[0];
70 const result=await reviewLearningContent(client,body,{env});assert.equal(result.mode,'dry-run');assert.equal(result.proposedStatus,'published');
71 assert.deepEqual((await client.query('select publication_status,pedagogical_review,review_record from learning_video_resource where id=$1',[f.video])).rows[0],before);
72 assert.equal((await client.query('select count(*)::int n from content_publication_audit')).rows[0].n,0);
73 });
74
75 test('full review, metadata, edition and current context gates reject missing or stale approval without writes',async()=>{
76 const f=await fixture(),body=publishVideo(f);
77 for(const field of ['watchedEntireVideo','editionAligned','accuracyApproved','suitabilityApproved','embedRightsApproved','questionCoverageReviewed']) {
78 await assert.rejects(reviewLearningContent(client,{...body,review:{...body.review,[field]:false}},{env,apply:true}),e=>e.code==='incomplete_video_review');
79 }
80 await assert.rejects(reviewLearningContent(client,{...body,review:{...body.review,reviewedAt:'2026-02-30T00:00:00Z'}},{env,apply:true}));
81 await assert.rejects(reviewLearningContent(client,{...body,expectedContentHash:'a'.repeat(64)},{env,apply:true}),e=>e.code==='content_conflict');
82 await client.query("update textbook_catalog set edition_verification='unverified' where id=$1",[f.book]);
83 await assert.rejects(reviewLearningContent(client,body,{env,apply:true}),e=>e.code==='context_conflict'||e.code==='verified_edition_required');
84 await client.query("update textbook_catalog set edition_verification='verified' where id=$1",[f.book]);
85 await client.query("update learning_video_resource set title_fa='SYNTHETIC changed without refreshed hash' where id=$1",[f.video]);
86 await assert.rejects(reviewLearningContent(client,body,{env,apply:true}),e=>e.code==='material_hash_mismatch');
87 assert.equal((await client.query('select count(*)::int n from content_publication_audit where entity_id=$1',[f.video])).rows[0].n,0);
88 });
89
90 test('stable publication receipt replays current withdrawn state, and changed UUID intent is rejected',async()=>{
91 const f=await fixture(),body=publishVideo(f);
92 const applied=await reviewLearningContent(client,body,{env,apply:true});assert.equal(applied.acknowledgement.status,'accepted');assert.equal(applied.current.publicationStatus,'published');
93 const retry=await reviewLearningContent(client,body,{env,apply:true});assert.equal(retry.acknowledgement.status,'already_applied');
94 await assert.rejects(reviewLearningContent(client,{...body,review:{...body.review,accuracyNotes:'Changed intent'}},{env,apply:true}),e=>e.code==='mutation_id_reused');
95 const withdrawal={...body,mutationId:crypto.randomUUID(),operation:'withdraw',expectedStatus:'published'};delete withdrawal.review;
96 assert.equal((await reviewLearningContent(client,withdrawal,{env,apply:true})).current.publicationStatus,'withdrawn');
97 assert.equal((await reviewLearningContent(client,body,{env,apply:true})).current.publicationStatus,'withdrawn');
98 assert.equal((await client.query('select count(*)::int n from content_publication_audit where entity_id=$1',[f.video])).rows[0].n,2);
99 const columns=(await client.query("select column_name from information_schema.columns where table_name='content_publication_audit'")).rows.map(row=>row.column_name);
100 for(const forbidden of ['summary','review_record','questions','note','feedback_id','owner_user_id','chat']) assert.ok(!columns.includes(forbidden));
101 });
102
103 test('synthetic apply cannot publish real catalogue records or pretend a human reviewed them',async()=>{
104 const f=await fixture(),body=publishVideo(f);
105 await assert.rejects(reviewLearningContent(client,{...body,review:{...body.review,evidenceScope:'HUMAN_REVIEW',reviewerName:'Real reviewer'}},{env,apply:true}),e=>e.code==='synthetic_receipt_required');
106 await client.query("update textbook_catalog set stable_book_key=$2 where id=$1",[f.book,'IR-1-105-1405-1406-standard']);
107 await assert.rejects(reviewLearningContent(client,body,{env,apply:true}),e=>e.code==='synthetic_material_required');
108 assert.equal((await client.query('select publication_status from learning_video_resource where id=$1',[f.video])).rows[0].publication_status,'draft');
109 });
110
111 test('original assessment drafts are versioned, published definitions immutable, and old learner snapshots retained on revision',async()=>{
112 const f=await fixture(),id=crypto.randomUUID();
113 const draft={schemaVersion:1,mutationId:crypto.randomUUID(),entityType:'assessment',entityId:id,unitId:f.unit,operation:'draft_assessment',
114 expectedStatus:'absent',expectedVersion:0,expectedContentHash:null,expectedContextHash:assessmentContextHash(f.row),questions:q};
115 assert.equal((await reviewLearningContent(client,draft,{env})).mode,'dry-run');
116 assert.equal((await client.query('select count(*)::int n from learning_assessment where id=$1',[id])).rows[0].n,0);
117 const created=await reviewLearningContent(client,draft,{env,apply:true});assert.equal(created.current.version,1);assert.equal(created.current.contentHash,assessmentHash(q));
118 assert.equal((await reviewLearningContent(client,draft,{env,apply:true})).acknowledgement.status,'already_applied');
119 const review={evidenceScope:'SYNTHETIC_TEST_ONLY',reviewerName:'SYNTHETIC TEST REVIEWER',reviewedAt:'2026-10-01T00:00:00Z',accuracyApproved:true,suitabilityApproved:true,
120 editionAligned:true,objectiveCoverageApproved:true,contentHash:assessmentHash(q),contextHash:assessmentContextHash(f.row),reviewNotes:'SYNTHETIC question approval',
121 bookCode:f.row.book_code,schoolYear:f.row.school_year,unitKey:f.row.unit_key};
122 const publish={schemaVersion:1,mutationId:crypto.randomUUID(),entityType:'assessment',entityId:id,operation:'publish',expectedStatus:'draft',expectedVersion:1,
123 expectedContentHash:assessmentHash(q),expectedContextHash:assessmentContextHash(f.row),review};
124 assert.equal((await reviewLearningContent(client,publish,{env,apply:true})).current.publicationStatus,'published');
125 const owner=crypto.randomUUID();await client.query('insert into app_user(id,identity_subject,email_normalized) values($1,$2,$3)',[owner,'synthetic-publication:'+owner,'publication-'+owner+'@example.test']);
126 await client.query("insert into learning_assessment_attempt(owner_user_id,mutation_id,assessment_id,unit_id,assessment_version,request_hash,answers,confidence,question_snapshot,acknowledgement) values($1,$2,$3,$4,1,$5,'[]','unsure',$6,'{}')",
127 [owner,crypto.randomUUID(),id,f.unit,'a'.repeat(64),JSON.stringify(q)]);
128 const revised=[{...q[0],promptFa:'SYNTHETIC revised original question'}];
129 const revision={...draft,mutationId:crypto.randomUUID(),expectedStatus:'published',expectedVersion:1,expectedContentHash:assessmentHash(q),questions:revised};
130 await assert.rejects(reviewLearningContent(client,revision,{env,apply:true}),e=>e.code==='published_definition_immutable');
131 const withdrawal={...publish,mutationId:crypto.randomUUID(),operation:'withdraw',expectedStatus:'published'};delete withdrawal.review;
132 await reviewLearningContent(client,withdrawal,{env,apply:true});
133 const next=await reviewLearningContent(client,{...revision,mutationId:crypto.randomUUID(),expectedStatus:'withdrawn'},{env,apply:true});
134 assert.equal(next.current.version,2);assert.equal(next.current.publicationStatus,'draft');assert.equal(next.current.contentHash,assessmentHash(revised));
135 const stored=(await client.query('select questions,review_record from learning_assessment where id=$1',[id])).rows[0];assert.deepEqual(stored.questions,revised);assert.equal(stored.review_record,null);
136 assert.deepEqual((await client.query('select question_snapshot from learning_assessment_attempt where assessment_id=$1',[id])).rows[0].question_snapshot,q);
137 assert.equal((await reviewLearningContent(client,publish,{env,apply:true})).current.publicationStatus,'draft');
138 });
139
140 test('isolated runtime/backup permission fixtures cannot write teaching definitions or publication audit with SELECT-only grants',async()=>{
141 const f=await fixture(),body=publishVideo(f);
142 for(const role of testRoles) {
143 await client.query(`grant connect on database "${database}" to "${role}"`);
144 await client.query(`grant usage on schema public to "${role}"`);
145 await client.query(`grant select on all tables in schema public to "${role}"`);
146 await client.query(`set role "${role}"`);
147 try {
148 await assert.rejects(reviewLearningContent(client,body,{env,apply:true}),e=>e.code==='separate_operator_required');
149 await assert.rejects(client.query('update learning_video_resource set publication_status=publication_status where id=$1',[f.video]),e=>e.code==='42501');
150 await assert.rejects(client.query('delete from content_publication_audit'),e=>e.code==='42501');
151 } finally {await client.query('reset role');}
152 }
153 });
154
155 test('actual CLI inspection prints structural synthetic output, refuses remote env and hides driver secrets',async()=>{
156 const f=await fixture();
157 const inspected=spawnSync(process.execPath,['scripts/review-learning-content.js','inspect','video',f.video],{env:{...process.env,...env},encoding:'utf8'});
158 assert.equal(inspected.status,0,inspected.stderr);assert.equal(JSON.parse(inspected.stdout).publicationStatus,'draft');
159 const rejected=spawnSync(process.execPath,['scripts/review-learning-content.js','inspect','video',f.video],{env:{...process.env,...env,CONTENT_REVIEW_DATABASE_URL:'postgres://SECRET_PASSWORD@remote.example/lifeguide_test'},encoding:'utf8'});
160 assert.equal(rejected.status,1);assert.ok(!rejected.stderr.includes('SECRET_PASSWORD'));assert.equal(rejected.stdout,'');
161 });
162
163 test('actual CLI dry-run, apply, replay and withdrawal retain exactly two receipts without printing reviewer text',async()=>{
164 const f=await fixture(),body=publishVideo(f),directory=await fs.mkdtemp(path.join(os.tmpdir(),'lifeguide-publication-'));
165 const filename=path.join(directory,'operation.json');
166 const run=action=>spawnSync(process.execPath,['scripts/review-learning-content.js',action,filename],{env:{...process.env,...env},encoding:'utf8'});
167 try {
168 await fs.writeFile(filename,JSON.stringify(body),{mode:0o600});
169 let result=run('dry-run');assert.equal(result.status,0,result.stderr);assert.equal(JSON.parse(result.stdout).mode,'dry-run');
170 assert.equal((await client.query('select count(*)::int n from content_publication_audit where entity_id=$1',[f.video])).rows[0].n,0);
171 result=run('apply');assert.equal(result.status,0,result.stderr);assert.equal(JSON.parse(result.stdout).current.eligibleForLearners,true);
172 assert.equal(JSON.parse(result.stdout).acknowledgement.status,'accepted');assert.ok(!result.stdout.includes(body.review.reviewerName));
173 result=run('apply');assert.equal(result.status,0,result.stderr);assert.equal(JSON.parse(result.stdout).acknowledgement.status,'already_applied');
174 const withdrawal={...body,mutationId:crypto.randomUUID(),operation:'withdraw',expectedStatus:'published'};delete withdrawal.review;
175 await fs.writeFile(filename,JSON.stringify(withdrawal));
176 result=run('apply');assert.equal(result.status,0,result.stderr);assert.equal(JSON.parse(result.stdout).current.eligibleForLearners,false);
177 assert.equal((await client.query('select count(*)::int n from content_publication_audit where entity_id=$1',[f.video])).rows[0].n,2);
178 await fs.writeFile(filename,' '.repeat(1024*1024+1));
179 result=run('apply');assert.equal(result.status,1);assert.equal(JSON.parse(result.stderr).code,'invalid_operation_file');
180 assert.equal(result.stdout,'');
181 } finally {await fs.rm(directory,{recursive:true});}
182 });
183
184 test('concurrent exact publication retries serialize and produce one journal receipt',async()=>{
185 const f=await fixture(),body=publishVideo(f),other=new pg.Client({connectionString:target.toString()});
186 await other.connect();
187 try {
188 const results=await Promise.all([reviewLearningContent(client,body,{env,apply:true}),reviewLearningContent(other,body,{env,apply:true})]);
189 assert.deepEqual(results.map(result=>result.acknowledgement.status).sort(),['accepted','already_applied']);
190 assert.equal((await client.query('select count(*)::int n from content_publication_audit where mutation_id=$1',[body.mutationId])).rows[0].n,1);
191 assert.equal((await client.query('select publication_status from learning_video_resource where id=$1',[f.video])).rows[0].publication_status,'published');
192 } finally {await other.end();}
193 });
194
195 test('a catalogue correction committed while review waits invalidates its original approval context',async()=>{
196 const f=await fixture(),body=publishVideo(f),blocker=new pg.Client({connectionString:target.toString()});
197 await blocker.connect();
198 try {
199 const pid=(await client.query('select pg_backend_pid() pid')).rows[0].pid;
200 await blocker.query('begin');
201 await blocker.query("update learning_unit set title_fa='SYNTHETIC corrected during review' where id=$1",[f.unit]);
202 const pending=reviewLearningContent(client,body,{env,apply:true});
203 const rejected=assert.rejects(pending,error=>error.code==='context_conflict');
204 const deadline=Date.now()+3000;let observed=false;
205 while(Date.now()<deadline) {
206 if((await blocker.query('select cardinality(pg_blocking_pids($1))>0 blocked',[pid])).rows[0].blocked) {observed=true;break;}
207 await new Promise(resolve=>setTimeout(resolve,10));
208 }
209 await blocker.query('commit');await rejected;assert.equal(observed,true,'Observe the actual row-lock wait');
210 assert.equal((await client.query('select count(*)::int n from content_publication_audit where mutation_id=$1',[body.mutationId])).rows[0].n,0);
211 assert.equal((await client.query('select publication_status from learning_video_resource where id=$1',[f.video])).rows[0].publication_status,'draft');
212 } finally {await blocker.query('rollback').catch(()=>{});await blocker.end();}
213 });