LifeMate — Personal, Family & Learning Companion
test(planner): verify compiled weekly flow with local HTTPS and PostgreSQL
Quinn White committed
Oct 18, 2026 at 21:56 UTC
b0b0b405e34b71044d17de26c1d946e71e19a193
6 files changed
+270
apps/lifemate/tool/test_weekly_planner_browser.cjs
new
+183
@@ -0,0 +1,183 @@
1
+// Compiled Flutter, verified local TLS, real HTTP/PostgreSQL. Synthetic only.
2
+// Credentials stay in the private fixture file; API responses are never mocked.
3
+const assert = require('node:assert/strict');
4
+const fs = require('node:fs');
5
+const path = require('node:path');
6
+const https = require('node:https');
7
+const crypto = require('node:crypto');
8
+const {execFileSync} = require('node:child_process');
9
+const {chromium} = require('playwright');
10
+const {Client} = require('../../../backend/node_modules/pg');
11
+
12
+const fixture = JSON.parse(fs.readFileSync(process.env.LG_WEEKLY_FIXTURE || '/tmp/lifeguide-weekly-browser-qa/fixture.json','utf8'));
13
+assert(fixture.syntheticOnly === true && fixture.email.endsWith('@example.test'));
14
+const database = new URL(fixture.databaseUrl);
15
+assert(database.hostname === '127.0.0.1' && database.port === '55449' &&
16
+ /^\/lifeguide_weekly_browser_test_[a-f0-9]{16}$/.test(database.pathname), 'Disposable loopback fixture only');
17
+const origin = process.env.LG_WEEKLY_ORIGIN || 'https://127.0.0.1:8449';
18
+assert.equal(new URL(origin).hostname,'127.0.0.1');
19
+assert.equal(new URL(origin).protocol,'https:');
20
+const ca = fs.readFileSync(process.env.LG_TEST_CA_FILE || '/tmp/lifeguide-weekly-browser-qa/ca.crt');
21
+const out = path.resolve(process.argv[2] || '/tmp/lifeguide-weekly-browser-evidence');
22
+fs.mkdirSync(out,{recursive:true});
23
+const root = path.resolve(__dirname,'../../..');
24
+const main = path.join(root,'apps/lifemate/build/web/main.dart.js');
25
+const compiledHash = () => crypto.createHash('sha256').update(fs.readFileSync(main)).digest('hex');
26
+const mainAtStart = compiledHash();
27
+const db = new Client({connectionString:database.href});
28
+const checks = [], errors = [], origins = new Set();
29
+let browser, page, stage = 'startup';
30
+const record = name => { checks.push({name,result:'PASS'}); console.log('PASS ' + name); };
31
+const weekdayNames = {1:'دوشنبه',2:'سهشنبه',3:'چهارشنبه',4:'پنجشنبه',5:'جمعه',6:'شنبه',7:'یکشنبه'};
32
+const localDay = new Intl.DateTimeFormat('en-CA',{timeZone:'Asia/Tehran',year:'numeric',month:'2-digit',day:'2-digit'}).format(new Date());
33
+const firstWeekday = new Date(localDay + 'T00:00:00Z').getUTCDay() || 7;
34
+const secondWeekday = (firstWeekday + 1) % 7 + 1;
35
+function api(method,endpoint,body,token) {
36
+ return new Promise((resolve,reject) => {
37
+ const data = body === undefined ? null : Buffer.from(JSON.stringify(body));
38
+ const req = https.request(origin + '/api' + endpoint,{method,ca,rejectUnauthorized:true,
39
+ headers:{...(data ? {'content-type':'application/json','content-length':data.length} : {}),
40
+ ...(token ? {authorization:'Bearer ' + token} : {})}},res => {
41
+ assert(res.socket.authorized); let text = '';
42
+ res.on('data',chunk => text += chunk); res.on('end',() => {
43
+ try { resolve({status:res.statusCode,body:JSON.parse(text)}); } catch { reject(Error('Non-JSON API response')); }
44
+ });
45
+ }); req.setTimeout(15000,() => req.destroy(Error('Local API timeout'))); req.on('error',reject); req.end(data);
46
+ });
47
+}
48
+async function click(locator) {
49
+ await locator.waitFor({state:'attached',timeout:20000});
50
+ // Flutter semantics activation; physical hit targets are checked separately.
51
+ await locator.evaluate(element => element.click());
52
+}
53
+const button = name => page.getByRole('button',{name,exact:typeof name === 'string'});
54
+async function enter(locator,value) {
55
+ await locator.focus();
56
+ await locator.press('ControlOrMeta+A');
57
+ await locator.press('Backspace');
58
+ // Real keyboard input keeps Flutter's controller and native semantics input
59
+ // in agreement across rebuilds; setting textarea.value alone is insufficient.
60
+ await locator.pressSequentially(value);
61
+}
62
+async function text(value) {
63
+ await page.waitForFunction(value => document.body.textContent.includes(value) ||
64
+ [...document.querySelectorAll('[aria-label]')].some(e => e.getAttribute('aria-label').includes(value)),value,{timeout:25000});
65
+}
66
+async function semantics() {
67
+ await page.waitForFunction(() => !document.getElementById('startup-status'),null,{timeout:60000});
68
+ const placeholder = page.locator('flt-semantics-placeholder');
69
+ if (await placeholder.count()) await placeholder.evaluate(e => e.click());
70
+}
71
+async function timeInput(locator,hour,minute) {
72
+ await click(locator);
73
+ await page.getByLabel('ساعت',{exact:true}).waitFor({state:'attached'});
74
+ await enter(page.getByLabel('ساعت',{exact:true}),String(hour).padStart(2,'0'));
75
+ await enter(page.getByLabel('دقیقه',{exact:true}),String(minute).padStart(2,'0'));
76
+ await click(button(/^(تأیید|تایید|OK)$/));
77
+ await page.getByLabel('ساعت',{exact:true}).waitFor({state:'detached'});
78
+}
79
+async function waitForDatabaseTitle(id,title) {
80
+ for (let i=0;i<60;i++) {
81
+ const row = (await db.query('select title from plan_item where id=$1',[id])).rows[0];
82
+ if (row?.title === title) return;
83
+ await new Promise(resolve => setTimeout(resolve,500));
84
+ }
85
+ throw Error('Server did not acknowledge offline occurrence edit');
86
+}
87
+(async () => {
88
+ await db.connect();
89
+ const owner = (await db.query('select identity_subject,is_managed_child from app_user where id=$1',[fixture.userId])).rows[0];
90
+ assert(owner?.identity_subject.startsWith('weekly-browser:') && owner.is_managed_child === false);
91
+ // The dedicated, verified fixture contains no user data. Make reruns isolated.
92
+ await db.query('delete from planner_series where owner_user_id=$1',[fixture.userId]);
93
+ const login = await api('POST','/v1/auth/login',{email:fixture.email,password:fixture.password});
94
+ assert.equal(login.status,200); const token = login.body.accessToken; assert.equal(typeof token,'string');
95
+ browser = await chromium.launch({executablePath:process.env.LIFEGUIDE_TEST_CHROMIUM_PATH || '/usr/bin/chromium',args:['--no-sandbox']});
96
+ const context = await browser.newContext({viewport:{width:390,height:844},timezoneId:'Asia/Tehran',ignoreHTTPSErrors:false});
97
+ page = await context.newPage();
98
+ page.on('pageerror',() => errors.push('JavaScript page error'));
99
+ page.on('request',request => { const u=new URL(request.url()); if (/^https?:/.test(u.protocol)) origins.add(u.origin); });
100
+ stage='login';
101
+ const response = await page.goto(origin,{waitUntil:'networkidle',timeout:60000}); assert.equal(response.status(),200); await semantics();
102
+ await page.getByLabel('ایمیل یا شماره تلفن',{exact:true}).fill(fixture.email);
103
+ await page.getByLabel('رمز عبور',{exact:true}).fill(fixture.password);
104
+ await click(button('ورود'));
105
+ await page.getByRole('tab',{name:'برنامه',exact:true}).waitFor({timeout:30000});
106
+ await text('قدم بعدی');
107
+ await page.screenshot({path:path.join(out,'LifeGuide-weekly-home.png')});
108
+ record('verified HTTPS login to compiled Flutter with synthetic standard minor account');
109
+
110
+ stage='weekly create';
111
+ await click(page.getByRole('tab',{name:'برنامه',exact:true}));
112
+ await click(button('برنامهٔ تکراری'));
113
+ const title = 'مدرسهٔ ساختگی هفتگی ' + Date.now().toString(36);
114
+ await enter(page.getByLabel('عنوان',{exact:true}),title);
115
+ await click(button(/^نوع/)); await click(page.getByRole('menuitem',{name:'رویداد',exact:true}));
116
+ await click(page.getByRole('checkbox',{name:weekdayNames[secondWeekday],exact:true}));
117
+ const firstGroup = page.getByRole('group',{name:weekdayNames[firstWeekday],exact:true});
118
+ const secondGroup = page.getByRole('group',{name:weekdayNames[secondWeekday],exact:true});
119
+ await timeInput(firstGroup.getByRole('button',{name:/^پایان:/}),12,0);
120
+ await timeInput(secondGroup.getByRole('button',{name:/^شروع:/}),10,0);
121
+ await timeInput(secondGroup.getByRole('button',{name:/^پایان:/}),14,0);
122
+ await click(button(/^یادآوری هر نوبت/)); await click(page.getByRole('menuitem',{name:'۵ دقیقه پیش از شروع',exact:true}));
123
+ await page.screenshot({path:path.join(out,'LifeGuide-weekly-editor.png')});
124
+ await click(button('ثبت برنامه')); await text(title);
125
+ const series = (await db.query('select id,frequency,slots,timezone from planner_series where owner_user_id=$1 and title=$2',[fixture.userId,title])).rows;
126
+ assert.equal(series.length,1); const seriesId=series[0].id;
127
+ assert.equal(series[0].frequency,'weekly'); assert.equal(series[0].timezone,'Asia/Tehran');
128
+ assert.deepEqual(series[0].slots,[{weekday:firstWeekday,start:'08:00',end:'12:00'},{weekday:secondWeekday,start:'10:00',end:'14:00'}].sort((a,b) => a.weekday-b.weekday));
129
+ const items = (await db.query('select p.*,p.original_occurrence_date::text as day from plan_item p where p.series_id=$1 order by p.original_occurrence_date',[seriesId])).rows;
130
+ let expectedCount=0;
131
+ for(let n=0;n<60;n++){const d=new Date(Date.parse(localDay+'T00:00:00Z')+n*86400000);if([firstWeekday,secondWeekday].includes(d.getUTCDay()||7))expectedCount++;}
132
+ assert.equal(items.length,expectedCount);
133
+ assert(items.every(i => i.owner_user_id===fixture.userId && i.visibility==='private' && i.family_id===null));
134
+ const occurrence=items.find(i=>i.day===localDay); assert(occurrence);
135
+ const read=await api('GET','/v1/plan-items/'+occurrence.id,undefined,token);
136
+ assert.equal(read.status,200);assert.equal(read.body.series_id,seriesId);assert.equal(read.body.ends_at,occurrence.ends_at.toISOString());
137
+ assert.equal((await db.query('select count(*)::int n from reminder r join plan_item p on p.id=r.plan_item_id where p.series_id=$1',[seriesId])).rows[0].n,expectedCount);
138
+ await page.screenshot({path:path.join(out,'LifeGuide-weekly-schedule.png')});
139
+ record('UI creates weekly school with different weekday hours; actual REST and PostgreSQL confirm private unique occurrences');
140
+
141
+ stage='complete one';await click(button('انجام شد'));await button('برگرداندن به برنامه').waitFor({timeout:20000});
142
+ assert.equal((await api('GET','/v1/plan-items/'+occurrence.id,undefined,token)).body.status,'completed');
143
+ assert.equal((await db.query("select count(*)::int n from plan_item where series_id=$1 and status='completed'",[seriesId])).rows[0].n,1);
144
+ record('ticking one occurrence leaves every other occurrence independently planned');
145
+
146
+ stage='restart';await page.reload({waitUntil:'networkidle'});await semantics();
147
+ await click(page.getByRole('tab',{name:'برنامه',exact:true}));await text(title);await button('برگرداندن به برنامه').waitFor();
148
+ record('page restart restores authenticated server-backed weekly record and completion');
149
+
150
+ stage='offline edit';
151
+ // ListTile navigation is a pointer target on Flutter's canvas; activate its
152
+ // visible center rather than dispatching a synthetic DOM click to its label.
153
+ await button(new RegExp('^'+title)).click({force:true});await text('جزئیات تکلیف');
154
+ await click(button('ویرایش تکلیف'));const edited=title+' ویرایش آفلاین';await enter(page.getByLabel('عنوان',{exact:true}),edited);
155
+ await context.setOffline(true);await click(button('ذخیره'));await text('در انتظار تأیید سرور');
156
+ assert.equal((await db.query('select title from plan_item where id=$1',[occurrence.id])).rows[0].title,title);
157
+ record('offline occurrence edit is durably pending while PostgreSQL remains unchanged');
158
+ await context.setOffline(false);await click(button('برگشتن').last());await waitForDatabaseTitle(occurrence.id,edited);
159
+ const fresh=await api('GET','/v1/plan-items/'+occurrence.id,undefined,token);assert.equal(fresh.body.title,edited);
160
+ assert.equal(fresh.body.status,'completed');assert.equal(fresh.body.series_id,seriesId);
161
+ const finalRows=(await db.query('select id,title,status,original_occurrence_date::text as day from plan_item where series_id=$1',[seriesId])).rows;
162
+ assert.equal(finalRows.length,expectedCount);assert.equal(new Set(finalRows.map(i=>i.day)).size,expectedCount);
163
+ assert.equal(finalRows.filter(i=>i.title===edited).length,1);assert.equal(finalRows.filter(i=>i.status==='completed').length,1);
164
+ await page.reload({waitUntil:'networkidle'});await semantics();await click(page.getByRole('tab',{name:'برنامه',exact:true}));await text(edited);
165
+ await page.screenshot({path:path.join(out,'LifeGuide-weekly-reopened.png')});
166
+ record('reconnect and subsequent restart retain one edited occurrence without duplicate generation');
167
+ assert.deepEqual(errors,[]);assert.deepEqual([...origins].filter(o=>o!==origin),[]);
168
+ assert.equal(compiledHash(),mainAtStart,'Compiled assets changed during acceptance; rerun the final build');
169
+ fs.writeFileSync(path.join(out,'verification.json'),JSON.stringify({status:'VERIFIED_LOCAL_SYNTHETIC_ONLY',
170
+ sourceHead:execFileSync('git',['rev-parse','HEAD'],{cwd:root,encoding:'utf8'}).trim(),
171
+ compiledMainSha256:mainAtStart,
172
+ browser:await browser.version(),tlsVerified:true,apiResponsesIntercepted:false,checks,
173
+ recurrence:{frequency:'weekly',timezone:'Asia/Tehran',slots:series[0].slots,occurrenceCount:expectedCount,completedCount:1},
174
+ offlineEditFields:['title'],javascriptErrors:errors,externalRuntimeOrigins:[],
175
+ unverified:['physical Android/iPhone/Safari','background OS alarms','managed-child private planner authorization','offline cold start','production deployment']},null,2));
176
+})().catch(async error => {
177
+ const message=String(error.message).replaceAll(fixture.password,'[fixture credential]');
178
+ console.error('FAIL '+stage+': '+message);
179
+ if(page) await page.screenshot({path:path.join(out,'failure-diagnostic.png')}).catch(()=>{});
180
+ if(page) fs.writeFileSync(path.join(out,'failure-semantics.json'),JSON.stringify(await page.locator('[role],[aria-label]').evaluateAll(es => es.map(e => ({role:e.getAttribute('role'),label:e.getAttribute('aria-label'),text:e.textContent}))),null,2));
181
+ fs.writeFileSync(path.join(out,'failure.json'),JSON.stringify({status:'FAILED_LOCAL_SYNTHETIC',stage,message,checks},null,2));
182
+ process.exitCode=1;
183
+}).finally(async()=>{if(browser)await browser.close();await db.end();});
docs/audits/evidence/weekly-planner-browser-2026-10-18.json
new
+87
@@ -0,0 +1,87 @@
1
+{
2
+ "status": "VERIFIED_LOCAL_SYNTHETIC_ONLY",
3
+ "sourceHead": "0bad011a0a37a43a4cc2d7ab69cf4f0bb0c00884",
4
+ "compiledMainSha256": "f0defa9ed20a7f2dc9b1c2f280caada6326574250d6687505da54de65f02e184",
5
+ "browser": "151.0.7922.173",
6
+ "tlsVerified": true,
7
+ "apiResponsesIntercepted": false,
8
+ "checks": [
9
+ {
10
+ "name": "verified HTTPS login to compiled Flutter with synthetic standard minor account",
11
+ "result": "PASS"
12
+ },
13
+ {
14
+ "name": "UI creates weekly school with different weekday hours; actual REST and PostgreSQL confirm private unique occurrences",
15
+ "result": "PASS"
16
+ },
17
+ {
18
+ "name": "ticking one occurrence leaves every other occurrence independently planned",
19
+ "result": "PASS"
20
+ },
21
+ {
22
+ "name": "page restart restores authenticated server-backed weekly record and completion",
23
+ "result": "PASS"
24
+ },
25
+ {
26
+ "name": "offline occurrence edit is durably pending while PostgreSQL remains unchanged",
27
+ "result": "PASS"
28
+ },
29
+ {
30
+ "name": "reconnect and subsequent restart retain one edited occurrence without duplicate generation",
31
+ "result": "PASS"
32
+ }
33
+ ],
34
+ "recurrence": {
35
+ "frequency": "weekly",
36
+ "timezone": "Asia/Tehran",
37
+ "slots": [
38
+ {
39
+ "end": "12:00",
40
+ "start": "08:00",
41
+ "weekday": 1
42
+ },
43
+ {
44
+ "end": "14:00",
45
+ "start": "10:00",
46
+ "weekday": 3
47
+ }
48
+ ],
49
+ "occurrenceCount": 18,
50
+ "completedCount": 1
51
+ },
52
+ "offlineEditFields": [
53
+ "title"
54
+ ],
55
+ "javascriptErrors": [],
56
+ "externalRuntimeOrigins": [],
57
+ "unverified": [
58
+ "physical Android/iPhone/Safari",
59
+ "background OS alarms",
60
+ "managed-child private planner authorization",
61
+ "offline cold start",
62
+ "production deployment"
63
+ ],
64
+ "testTool": {
65
+ "path": "apps/lifemate/tool/test_weekly_planner_browser.cjs",
66
+ "sha256": "c0682137b92c135f43c5395f1aaaeb78e496bb8270a2b6825f84a64dd2bb1f37"
67
+ },
68
+ "screenshots": [
69
+ {
70
+ "path": "docs/ux/weekly-planner-2026-10-18/LifeGuide-weekly-editor.png",
71
+ "sha256": "a1d2adb9273e1876bd471f0d8f1f6024be25b26ed814f9b911b6dd795496e626"
72
+ },
73
+ {
74
+ "path": "docs/ux/weekly-planner-2026-10-18/LifeGuide-weekly-home.png",
75
+ "sha256": "84ff8eded20d8408ec92036cca7498d9c50dcf1665c14b88d2c2e4fef4f5bf86"
76
+ },
77
+ {
78
+ "path": "docs/ux/weekly-planner-2026-10-18/LifeGuide-weekly-reopened.png",
79
+ "sha256": "95e8704dded3edbd1a83a848e1df2d531ea52bacd81973c103722038ef143f2b"
80
+ },
81
+ {
82
+ "path": "docs/ux/weekly-planner-2026-10-18/LifeGuide-weekly-schedule.png",
83
+ "sha256": "b67c4d1b5da56f0f56aaa65bc24f6abaddfec0abc968e6bc358c5391dd27c048"
84
+ }
85
+ ],
86
+ "syntheticAccountType": "standard legacy minor account; not managed-child education scope"
87
+}
docs/ux/weekly-planner-2026-10-18/LifeGuide-weekly-editor.png
Binary files /dev/null and b/docs/ux/weekly-planner-2026-10-18/LifeGuide-weekly-editor.png differ
docs/ux/weekly-planner-2026-10-18/LifeGuide-weekly-home.png
Binary files /dev/null and b/docs/ux/weekly-planner-2026-10-18/LifeGuide-weekly-home.png differ
docs/ux/weekly-planner-2026-10-18/LifeGuide-weekly-reopened.png
Binary files /dev/null and b/docs/ux/weekly-planner-2026-10-18/LifeGuide-weekly-reopened.png differ
docs/ux/weekly-planner-2026-10-18/LifeGuide-weekly-schedule.png
Binary files /dev/null and b/docs/ux/weekly-planner-2026-10-18/LifeGuide-weekly-schedule.png differ