-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
6263 lines (5533 loc) · 250 KB
/
Copy pathapp.js
File metadata and controls
6263 lines (5533 loc) · 250 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// === GOOGLE OAUTH & DRIVE CONFIGURATION ===
const GOOGLE_CLIENT_ID = "936086701935-l8rpp157i9lcm3fka67et9ntgeurbruh.apps.googleusercontent.com";
let _googleTokenClient = null;
let _googleAccessToken = null;
let _googleTokenExpiry = 0;
let _driveFileId = null; // cached Drive file ID for ethos_state.json
// === STATE ===
function escapeHtml(s) {
if (typeof s !== 'string') return s;
return s.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function load(k,d){try{const v=localStorage.getItem(k);return v?JSON.parse(v):d;}catch{return d;}}
function save(k,v){try{localStorage.setItem(k,JSON.stringify(v));}catch{}}
let S = load('mathInit_state', {
routines: DEFAULT_ROUTINES,
ethosGroups: JSON.parse(JSON.stringify(ETHOS_GROUPS)),
papers: DEFAULT_PAPERS,
skills: {}, xp: 0, xpToday: 0, streak: 0,
totalHours: 0, weekHours: 0,
todayNote: '', paperNote: '',
logs: [], contrib: [], lastDate: '', theme: 'default',
weekOffset: 0, history: {}, activeDate: new Date().toDateString(),
activeGroupFilter: 'all',
swimHistory: [],
waterLogs: {},
weightLogs: [],
trilumaStartDate: '2026-01-01',
todayOnlyToggle: true,
swimFilter: 'all',
swimSearchQuery: '',
authEmail: '',
authUsername: '',
lastUpdated: 0,
everSynced: false
});
function sanitizeStateArrays(state) {
if (!state) return;
const ensureArray = (val) => {
if (!val) return [];
if (Array.isArray(val)) return val;
if (typeof val === 'object') {
return Object.keys(val)
.sort((a, b) => parseInt(a) - parseInt(b))
.map(k => val[k]);
}
return [];
};
state.logs = ensureArray(state.logs);
state.contrib = ensureArray(state.contrib);
state.swimHistory = ensureArray(state.swimHistory);
state.weightLogs = ensureArray(state.weightLogs);
state.reminders = ensureArray(state.reminders);
state.oracleHistory = ensureArray(state.oracleHistory);
state.papers = ensureArray(state.papers);
if (state.routines) {
state.routines = ensureArray(state.routines);
state.routines.forEach(r => {
if (r) r.ethe = ensureArray(r.ethe);
});
}
// Safeguards for empty objects stripped by Firebase
state.history = state.history || {};
state.skills = state.skills || {};
state.unlockedAchievements = state.unlockedAchievements || {};
state.notificationSettings = state.notificationSettings || { enabled: false, sound: 'cyber_pulse', volume: 0.6 };
}
sanitizeStateArrays(S);
let _syncSafe = false;
let _syncRetryTimer = null;
let _syncRetryDelay = 2000;
function hasUserHistory(state) {
if (!state) return false;
if (state.history) {
for (let k in state.history) {
const rec = state.history[k] || {};
if (Object.values(rec).some(v => v === true)) return true;
}
}
const swims = state.swimHistory || [];
const hasRealSwims = swims.some(s => s && s.status === 'Swam' && s.sessions && s.sessions.length > 0);
if (hasRealSwims) return true;
if (state.waterLogs) {
for (let k in state.waterLogs) {
if (state.waterLogs[k] > 0 && (typeof DEFAULT_WATER_LOGS === 'undefined' || !DEFAULT_WATER_LOGS[k])) return true;
}
}
if (state.weightLogs && state.weightLogs.length > 1) return true;
return false;
}
function localIsUntrustedFresh(state) {
if (state.everSynced === true) return false;
const ls = getStateStats(state);
return (ls.pushCount === 0) || (ls.etheCount === 0) || (!hasUserHistory(state) && (state.xp || 0) === 0);
}
function normalizeDateKey(k) {
if (!k) return k;
if (/^[A-Z][a-z]{2} [A-Z][a-z]{2} \d{2} \d{4}$/.test(k)) return k;
if (/^\d{4}-\d{2}-\d{2}$/.test(k)) {
const [y, m, d] = k.split('-').map(Number);
return new Date(y, m - 1, d).toDateString();
}
const d = new Date(k);
return isNaN(d.getTime()) ? k : d.toDateString();
}
function scheduleSyncRetry(fn) {
if (_syncRetryTimer) clearTimeout(_syncRetryTimer);
_syncRetryTimer = setTimeout(() => {
_syncRetryTimer = null;
_syncRetryDelay = Math.min(_syncRetryDelay * 2, 60000);
fn();
}, _syncRetryDelay);
}
function setSyncStatus(text) {
const el = document.getElementById('auth-sync-status');
if (el) el.textContent = text;
}
function applyMigrations(state) {
// Old key migration
if (!state.routines && localStorage.getItem('mathInit')) {
const old = load('mathInit', null);
if (old) { state = old; localStorage.removeItem('mathInit'); }
}
// groups -> routines, habits -> ethe
if (state.groups && !state.routines) {
state.routines = state.groups.map(g => {
const r = Object.assign({}, g);
if (r.habits) { r.ethe = r.habits; delete r.habits; }
if (!r.ethe) r.ethe = [];
r.ethe.forEach(e => { if (!e.groupId) e.groupId = 'math'; });
return r;
});
delete state.groups;
}
if (state.habits && !state.routines) { state.routines = DEFAULT_ROUTINES; delete state.habits; }
if (state.routines) {
state.routines.forEach(r => {
if (r.habits && !r.ethe) { r.ethe = r.habits; delete r.habits; }
if (!r.ethe) r.ethe = [];
r.ethe.forEach(e => { if (!e.groupId) e.groupId = 'math'; });
});
}
// id 303 rename
if (state.routines) {
state.routines.forEach(r => (r.ethe || []).forEach(e => {
if (Number(e.id) === 303 && (e.name === 'Cardio / aerobic conditioning' || e.name === 'Swimming')) {
e.name = 'Swimming session (90 min)';
}
}));
}
// Defensive defaults
if (!state.ethosGroups) state.ethosGroups = JSON.parse(JSON.stringify(ETHOS_GROUPS));
if (state.weekOffset === undefined) state.weekOffset = 0;
if (!state.history) state.history = {};
if (!state.activeDate) state.activeDate = new Date().toDateString();
if (!state.activeGroupFilter) state.activeGroupFilter = 'all';
if (!state.skills) state.skills = {};
SKILLS.forEach(s => { if (state.skills[s.key] === undefined) state.skills[s.key] = 0; });
if (!state.focusStats) state.focusStats = { sessions: 0, totalMins: 0, maxSessionMins: 0 };
if (!state.unlockedAchievements) state.unlockedAchievements = {};
if (state.everSynced === undefined) state.everSynced = false;
// v2 lifestyle — DE-FANGED: never reset a real/returning user.
if (!state.v2LifestyleLoaded) {
if (state.everSynced === true || (state.pushCount || 0) > 0 || (state.xp || 0) > 0) {
state.v2LifestyleLoaded = true; // mark migrated, do NOT reset
} else {
// genuinely first-run, empty device: it is safe to seed structure (not fake history)
state.routines = state.routines && state.routines.length ? state.routines : DEFAULT_ROUTINES;
state.ethosGroups = JSON.parse(JSON.stringify(ETHOS_GROUPS));
state.papers = state.papers && state.papers.length ? state.papers : DEFAULT_PAPERS;
state.v2LifestyleLoaded = true;
}
}
if (!state.v22WaterSeeded) { state.v22WaterSeeded = true; } // do NOT inject fake water on a synced user
// history key normalization (merge, not overwrite)
if (!state.historyKeysMigrated) {
const newHistory = {};
Object.keys(state.history || {}).forEach(key => {
const nk = normalizeDateKey(key);
if (!newHistory[nk]) newHistory[nk] = {};
const rec = state.history[key] || {};
Object.keys(rec).forEach(id => { if (rec[id] === true) newHistory[nk][id] = true; else if (newHistory[nk][id] !== true) newHistory[nk][id] = !!rec[id]; });
});
state.history = newHistory;
state.historyKeysMigrated = true;
}
return state;
}
S = applyMigrations(S);
// v2.3.0 migrations
if (S.crtEnabled === undefined) S.crtEnabled = false;
if (!S.cmdHistory) S.cmdHistory = [];
var historyIdx = -1;
// v2.4.0 migrations
if (!S.ethosViewMode) S.ethosViewMode = 'groups';
if (!S.protocolCollapsed) S.protocolCollapsed = {};
// Cloud Sync migrations
if (S.authEmail === undefined) S.authEmail = '';
if (S.authUsername === undefined) S.authUsername = '';
if (S.lastUpdated === undefined) S.lastUpdated = 0;
if (S.pushCount === undefined) S.pushCount = 0;
if (S.customSyncProxy === undefined) S.customSyncProxy = '';
if (S.customSyncKey === undefined) S.customSyncKey = '';
// PWA & Reminders migrations
if (!S.reminders) S.reminders = [];
if (!S.notificationSettings) S.notificationSettings = { enabled: false, sound: 'cyber_chime', volume: 0.5 };
// Oracle AI Conversational Engine migrations
if (S.geminiKey === undefined) S.geminiKey = '';
if (!S.oracleHistory) S.oracleHistory = [];
// ECRE Session Memory migrations
if (!S.ecreMemory) S.ecreMemory = {
lastObservations: [], // Last 7 observations
namedPatterns: [], // Explicitly named patterns
openQuestions: [], // Diagnostic questions posed: { question, answer, date, sessionAsked }
userPromises: [], // Promises made by user: { promise, date, targetGroup, fulfilled }
sessionCount: 0,
patternViolationActive: false
};
S.ecreMemory.sessionCount = (S.ecreMemory.sessionCount || 0) + 1;
ss(true);
let TODAY = new Date().toDateString();
function checkDailyReset(skipFirebase = false) {
const currentToday = new Date().toDateString();
if (S.lastDate !== currentToday) {
if (S.lastDate) {
S.history[S.lastDate] = {};
S.routines.forEach(r => r.ethe.forEach(e => { S.history[S.lastDate][e.id] = e.done; }));
}
S.routines.forEach(r => r.ethe.forEach(e => { if(!e.isWater) e.done = false; }));
S.xpToday = 0; S.lastDate = currentToday; S.activeDate = currentToday;
ss(skipFirebase);
} else {
S.routines.forEach(r => r.ethe.forEach(e => {
if(!e.isWater) {
e.done = S.history[normalizeDateKey(S.activeDate)] ? !!S.history[normalizeDateKey(S.activeDate)][e.id] : (S.activeDate === TODAY ? e.done : false);
}
}));
}
}
function updateTodayDate() {
const currentToday = new Date().toDateString();
if (TODAY !== currentToday) {
TODAY = currentToday;
checkDailyReset(false);
render();
addLog('info', `system clock: new day detected (${TODAY}). rolled over lifestyle parameters.`);
}
}
setInterval(updateTodayDate, 30000);
function getNetworkErrorTip(err) {
const isNetworkErr = (err && (err.message && err.message.toLowerCase().includes('network')));
if (isNetworkErr) {
return '<div style="margin-top: 8px; padding: 10px; background: rgba(255, 68, 68, 0.08); border: 1px solid rgba(255, 68, 68, 0.3); border-radius: 4px; font-size: 11px; line-height: 1.4; color: var(--text);">' +
'<strong style="color:var(--red);">[NETWORK BLOCK DETECTED]</strong><br>' +
'// Connection to Google Identity / Drive servers (googleapis.com) was blocked.<br>' +
'<b>Probable Causes & Solutions:</b><br>' +
' 1. <b>Ad Blockers / Privacy Shields:</b> Extensions like uBlock Origin, Privacy Badger, or Brave Shields often block googleapis.com. Disable them temporarily for this app.<br>' +
' 2. <b>DNS Blockers:</b> Using custom DNS (AdGuard DNS, NextDNS, Pi-hole)? They might block googleapis.com. Try using standard DNS (e.g. 1.1.1.1 or 8.8.8.8) or cellular hotspot.<br>' +
' 3. <b>Firewall / VPN:</b> A VPN or custom firewall rules might be filtering network traffic.<br>' +
' 4. <b>Inspection:</b> Press F12 to open Developer Tools, click the "Console" or "Network" tab, and look for red failed connection logs to identify the exact blocked host.' +
'</div>';
}
return '';
}
let _bootSyncLocked = true; // Prevent ss() from bumping lastUpdated during boot pull
function unlockBootSync() {
_bootSyncLocked = false;
}
function ss(skipFirebase = false) {
if (!skipFirebase && !_bootSyncLocked) {
S.lastUpdated = Date.now();
}
save('mathInit_state', S);
if (!skipFirebase && !_bootSyncLocked && _syncSafe && _googleAccessToken) {
queueDriveSyncPush();
}
}
let _syncPushTimer = null;
function queueDriveSyncPush() {
if (!_syncSafe) return;
if (_syncPushTimer) clearTimeout(_syncPushTimer);
_syncPushTimer = setTimeout(function () {
_syncPushTimer = null;
driveSyncPush();
}, 1200);
}
function getStateStats(state) {
var routines = Array.isArray(state && state.routines) ? state.routines : [];
var etheCount = 0;
routines.forEach(function(r) {
if (r && Array.isArray(r.ethe)) etheCount += r.ethe.length;
});
return {
pushCount: (state && state.pushCount) || 0,
xp: (state && state.xp) || 0,
etheCount: etheCount,
size: state ? JSON.stringify(state).length : 0
};
}
function backupLocalStateBeforeCloudReplace(reason) {
try {
var stamp = new Date().toISOString().replace(/[:.]/g, '-');
localStorage.setItem('mathInit_state_backup_' + stamp, JSON.stringify({
reason: reason || 'cloud_replace',
savedAt: Date.now(),
state: S
}));
} catch (e) {
console.warn('[Sync] Could not save pre-replace local backup:', e);
}
}
// === GOOGLE DRIVE CLOUD SYNC CORE ===
function getValidToken() {
if (!_googleAccessToken) {
return Promise.reject(new Error("No access token available. Please sign in."));
}
if (Date.now() < _googleTokenExpiry) {
return Promise.resolve(_googleAccessToken);
}
// Token expired or close to expiry, request a new one
return new Promise((resolve, reject) => {
if (!_googleTokenClient) {
reject(new Error("Google Identity Services not initialized."));
return;
}
const originalCallback = _googleTokenClient.callback;
_googleTokenClient.callback = (tokenResponse) => {
_googleTokenClient.callback = originalCallback;
if (tokenResponse.error) {
reject(new Error("Failed to refresh token: " + tokenResponse.error));
return;
}
_googleAccessToken = tokenResponse.access_token;
_googleTokenExpiry = Date.now() + (parseInt(tokenResponse.expires_in) || 3600) * 1000 - 60000;
localStorage.setItem('google_access_token', _googleAccessToken);
localStorage.setItem('google_token_expiry', _googleTokenExpiry);
resolve(_googleAccessToken);
};
_googleTokenClient.requestAccessToken({ prompt: '' });
});
}
function getSyncPathReport() {
const uid = currentUser ? currentUser.uid : '<not-authenticated>';
return {
uid: uid,
path: 'GOOGLE DRIVE APPDATA',
url: _driveFileId ? `files/${_driveFileId}` : 'ethos_state.json',
clientKeyLength: 0,
auth: _googleAccessToken ? 'Google OAuth2 Token' : 'unauthenticated'
};
}
function driveFindStateFile(token) {
if (_driveFileId) return Promise.resolve(_driveFileId);
return fetch("https://www.googleapis.com/drive/v3/files?spaces=appDataFolder&q=name='ethos_state.json'", {
headers: { 'Authorization': `Bearer ${token}` }
})
.then(res => {
if (res.status === 401) {
handleLogout();
throw new Error("Unauthorized");
}
if (!res.ok) throw new Error("Drive search failed: " + res.statusText);
return res.json();
})
.then(data => {
if (data.files && data.files.length > 0) {
_driveFileId = data.files[0].id;
return _driveFileId;
}
return null;
});
}
function driveReadState(token, fileId) {
return fetch(`https://www.googleapis.com/drive/v3/files/${fileId}?alt=media`, {
headers: { 'Authorization': `Bearer ${token}` }
})
.then(res => {
if (res.status === 401) {
handleLogout();
throw new Error("Unauthorized");
}
if (res.status === 404) return null;
if (!res.ok) throw new Error("Drive read failed: " + res.statusText);
return res.json();
});
}
function driveWriteState(token, statePayload) {
return driveFindStateFile(token).then(fileId => {
if (fileId) {
return fetch(`https://www.googleapis.com/upload/drive/v3/files/${fileId}?uploadType=media`, {
method: 'PATCH',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(statePayload)
})
.then(res => {
if (res.status === 401) {
handleLogout();
throw new Error("Unauthorized");
}
if (!res.ok) throw new Error("Drive patch failed: " + res.statusText);
return res.json();
});
} else {
return fetch(`https://www.googleapis.com/drive/v3/files`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'ethos_state.json',
parents: ['appDataFolder']
})
})
.then(res => {
if (res.status === 401) {
handleLogout();
throw new Error("Unauthorized");
}
if (!res.ok) throw new Error("Drive create failed: " + res.statusText);
return res.json();
})
.then(meta => {
_driveFileId = meta.id;
return fetch(`https://www.googleapis.com/upload/drive/v3/files/${_driveFileId}?uploadType=media`, {
method: 'PATCH',
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(statePayload)
});
})
.then(res => {
if (res.status === 401) {
handleLogout();
throw new Error("Unauthorized");
}
if (!res.ok) throw new Error("Drive write failed: " + res.statusText);
return res.json();
});
}
});
}
function driveSyncPush(callback) {
if (!_syncSafe) { if (callback) callback(false, 'sync not ready'); return; }
if (currentUser && currentUser.uid === 'demo-session') {
if (callback) callback(true, 'demo_session_no_push');
return;
}
getValidToken().then(token => {
S.pushCount = (S.pushCount || 0) + 1;
const syncableState = Object.assign({}, S);
delete syncableState.cmdHistory;
setSyncStatus('Status: pushing to Drive...');
return driveWriteState(token, {
state: syncableState,
lastUpdated: S.lastUpdated,
pushCount: S.pushCount
})
.then(data => {
_syncRetryDelay = 2000;
const payloadStr = JSON.stringify({ state: syncableState, lastUpdated: S.lastUpdated, pushCount: S.pushCount });
const sizeKb = (payloadStr.length / 1024).toFixed(1) + 'kb';
addLog('info', 'Cloud sync: Pushed newer local state to Drive. [' + sizeKb + ']');
setSyncStatus('Status: synced (' + new Date(S.lastUpdated).toLocaleTimeString() + ')');
if (callback) callback(true, 'pushed');
});
})
.catch(err => {
console.warn('[Sync] Drive push failed:', err.message);
setSyncStatus('Status: sync unavailable — retrying…');
scheduleSyncRetry(() => { driveSyncPush(); });
if (callback) callback(false, err);
});
}
function driveSyncPull(callback, forcePull = false) {
if (currentUser && currentUser.uid === 'demo-session') {
if (callback) callback(true, 'demo_session_no_pull');
return;
}
getValidToken().then(token => {
setSyncStatus('Status: pulling from Drive...');
return driveFindStateFile(token).then(fileId => {
if (!fileId) {
applyCloudState(null, forcePull, callback);
return;
}
return driveReadState(token, fileId).then(payload => {
_syncRetryDelay = 2000;
if (payload) {
const payloadStr = JSON.stringify(payload);
const sizeKb = (payloadStr.length / 1024).toFixed(1) + 'kb';
addLog('info', 'Cloud sync: Pulled state from Drive. [' + sizeKb + ']');
let val = null;
if (payload.state) {
val = { state: payload.state, lastUpdated: payload.lastUpdated, pushCount: payload.pushCount };
}
applyCloudState(val, forcePull, callback);
} else {
applyCloudState(null, forcePull, callback);
}
});
});
})
.catch(err => {
console.warn('[Sync] Drive pull failed:', err.message);
setSyncStatus('Status: sync unavailable — retrying…');
scheduleSyncRetry(() => { driveSyncPull(callback, forcePull); });
if (callback) callback(false, err);
});
}
// === ROBUST CLOUD PULL ENGINE ===
// Applies cloud state to the local app. Shared by both WebSocket and REST paths.
function applyCloudState(val, forcePull, callback) {
const statusEl = document.getElementById('auth-sync-status');
if (val && val.state) {
const cloudTime = val.lastUpdated || val.state.lastUpdated || 0;
const cloudPushCount = val.pushCount || val.state.pushCount || 0;
const localTime = S.lastUpdated || 0;
const localPushCount = S.pushCount || 0;
const cloudIsNewer = cloudTime > localTime || (cloudTime === localTime && cloudPushCount > localPushCount);
const localIsNewer = localTime > cloudTime || (localTime === cloudTime && localPushCount > cloudPushCount);
if (forcePull || cloudIsNewer || localIsUntrustedFresh(S)) {
backupLocalStateBeforeCloudReplace(forcePull ? 'force_pull' : 'cloud_newer_or_fresh');
S = mergeState(S, val.state);
sanitizeStateArrays(S);
S = applyMigrations(S);
S.everSynced = true;
_syncSafe = true;
checkDailyReset(true);
addLog('info', 'Cloud sync: Pulled state from Drive.');
ss(true);
render();
if (statusEl) statusEl.textContent = 'Status: synced (pulled Drive state)';
unlockBootSync();
// If the merge captured genuine local edits, converge once.
_syncSafe = true; queueDriveSyncPush();
if (callback) callback(true, 'pulled');
return;
} else if (localIsNewer) {
S.everSynced = true;
_syncSafe = true;
addLog('info', 'Cloud sync: Pushed newer local state to Drive.');
driveSyncPush();
if (statusEl) statusEl.textContent = 'Status: synced (pushed newer state)';
unlockBootSync();
if (callback) callback(true, 'pushed');
return;
} else {
S.everSynced = true;
_syncSafe = true;
if (statusEl) statusEl.textContent = 'Status: synced (up to date)';
unlockBootSync();
if (callback) callback(true, 'synced');
return;
}
}
// No cloud data (exists:false / null).
if (localIsUntrustedFresh(S)) {
if (statusEl) statusEl.textContent = 'Status: no Drive data yet (not overwriting)';
S = applyMigrations(S);
S.everSynced = true;
_syncSafe = true;
checkDailyReset(true);
addLog('info', 'Cloud sync: Initialized Drive backup with local state.');
unlockBootSync();
driveSyncPush(); // create the user's initial cloud record from (empty) defaults
if (callback) callback(true, 'initialized_empty');
return;
}
// Returning device with real local data, cloud empty: legitimate first upload.
S.everSynced = true;
_syncSafe = true;
checkDailyReset(true);
addLog('info', 'Cloud sync: Initialized Drive backup with local state.');
driveSyncPush();
if (statusEl) statusEl.textContent = 'Status: synced (created Drive backup)';
unlockBootSync();
if (callback) callback(true, 'pushed_initial');
}
function mergeState(local, cloud) {
if (!cloud) return local;
if (!local) return cloud;
const out = JSON.parse(JSON.stringify(cloud)); // start from cloud
// 1) Device-local-only fields: always keep local.
const LOCAL_ONLY = ['authEmail','authUsername','cmdHistory','geminiKey',
'customSyncProxy','customSyncKey','crtEnabled','everSynced',
'activeGroupFilter','ethosViewMode','protocolCollapsed','todayOnlyToggle',
'swimFilter','swimSearchQuery','weekOffset','activeDate','theme'];
LOCAL_ONLY.forEach(k => { if (local[k] !== undefined) out[k] = local[k]; });
// 2) Date-keyed maps: history (true-wins), waterLogs (max), normalized keys.
out.history = mergeHistory(local.history, cloud.history);
out.waterLogs = mergeWaterLogs(local.waterLogs, cloud.waterLogs);
// 3) Date-keyed arrays: swimHistory, weightLogs (union by normalized date).
out.swimHistory = mergeByDate(local.swimHistory, cloud.swimHistory, function (a, b) {
const aN = (a.sessions || []).length, bN = (b.sessions || []).length;
return aN >= bN ? a : b;
});
out.weightLogs = mergeByDate(local.weightLogs, cloud.weightLogs, function (a, b) { return b; });
// 4) Achievements: union, keep earliest date.
out.unlockedAchievements = Object.assign({}, cloud.unlockedAchievements || {}, local.unlockedAchievements || {});
// 5) ecreMemory: union arrays, max sessionCount.
out.ecreMemory = mergeEcre(local.ecreMemory, cloud.ecreMemory);
// 6) papers: union by id, status furthest-along wins.
out.papers = mergePapers(local.papers, cloud.papers);
// 7) Monotonic scalars: take newer-lastUpdated side (TODO: append-only event log).
const cloudNewer = (cloud.lastUpdated || 0) >= (local.lastUpdated || 0);
const src = cloudNewer ? cloud : local;
['xp','xpToday','totalHours','weekHours','streak','pushCount','lastUpdated'].forEach(k => {
if (src[k] !== undefined) out[k] = src[k];
});
out.focusStats = src.focusStats || cloud.focusStats || local.focusStats || { sessions:0, totalMins:0, maxSessionMins:0 };
// 8) routines: union ethe by id; reconcile today's done from merged history below in app boot.
out.routines = mergeRoutines(local.routines, cloud.routines);
// 9) logs: union by timestamp/date/message to prevent sync feedback wipes
out.logs = mergeLogs(local.logs, cloud.logs);
return out;
}
function mergeHistory(a, b) {
const out = {};
const add = (src) => {
Object.keys(src || {}).forEach(rawDate => {
const date = normalizeDateKey(rawDate);
if (!out[date]) out[date] = {};
const rec = src[rawDate] || {};
Object.keys(rec).forEach(id => { if (rec[id] === true) out[date][id] = true; else if (out[date][id] !== true) out[date][id] = !!rec[id]; });
});
};
add(a); add(b);
return out;
}
function mergeWaterLogs(a, b) {
const out = {};
const add = (src) => {
Object.keys(src || {}).forEach(rawDate => {
const date = normalizeDateKey(rawDate);
const v = parseFloat(src[rawDate]) || 0;
out[date] = Math.max(out[date] || 0, v);
});
};
add(a); add(b);
return out;
}
function mergeByDate(a, b, pick) {
const map = {};
(a || []).forEach(e => { if (e && e.date) map[normalizeDateKey(e.date)] = Object.assign({}, e, { date: normalizeDateKey(e.date) }); });
(b || []).forEach(e => {
if (!e || !e.date) return;
const key = normalizeDateKey(e.date);
const norm = Object.assign({}, e, { date: key });
map[key] = map[key] ? pick(map[key], norm) : norm;
});
return Object.keys(map).sort((x, y) => new Date(x) - new Date(y)).map(k => map[k]);
}
function mergeEcre(a, b) {
a = a || {}; b = b || {};
const unionArr = (x, y) => {
const seen = new Set(); const out = [];
[...(x||[]), ...(y||[])].forEach(item => {
const key = JSON.stringify(item);
if (!seen.has(key)) { seen.add(key); out.push(item); }
});
return out;
};
return {
lastObservations: unionArr(a.lastObservations, b.lastObservations),
namedPatterns: unionArr(a.namedPatterns, b.namedPatterns),
openQuestions: unionArr(a.openQuestions, b.openQuestions),
userPromises: unionArr(a.userPromises, b.userPromises),
sessionCount: Math.max(a.sessionCount || 0, b.sessionCount || 0),
patternViolationActive: !!(a.patternViolationActive || b.patternViolationActive),
};
}
function mergePapers(a, b) {
const rank = { queued: 0, reading: 1, done: 2 };
const map = {};
(a || []).forEach(p => { if (p) map[p.id] = p; });
(b || []).forEach(p => {
if (!p) return;
const ex = map[p.id];
if (!ex) map[p.id] = p;
else map[p.id] = (rank[p.status] || 0) >= (rank[ex.status] || 0) ? p : ex;
});
return Object.values(map);
}
function mergeRoutines(localR, cloudR) {
// Prefer cloud routine structure; union ethe by id; for today's working `done`,
// take true-wins so a completion on either device sticks.
const base = JSON.parse(JSON.stringify(cloudR || localR || []));
const localById = {};
(localR || []).forEach(r => (r.ethe || []).forEach(e => { localById[e.id] = e; }));
base.forEach(r => {
(r.ethe || []).forEach(e => {
const le = localById[e.id];
if (le) {
e.done = !!(e.done || le.done);
e.streak = Math.max(e.streak || 0, le.streak || 0);
}
});
});
return base;
}
function mergeLogs(a, b) {
const seen = new Set();
const out = [];
const add = (src) => {
(src || []).forEach(item => {
if (!item || !item.ts || !item.date || !item.msg) return;
const key = item.ts + '|' + item.date + '|' + item.msg;
if (!seen.has(key)) {
seen.add(key);
out.push(item);
}
});
};
add(a); add(b);
return out.sort((x, y) => {
const tX = new Date(x.date + ' ' + x.ts).getTime() || 0;
const tY = new Date(y.date + ' ' + y.ts).getTime() || 0;
return tX - tY;
}).slice(-200);
}
function renderSyncPanel() {
const usernameEl = document.getElementById('auth-profile-username');
const emailEl = document.getElementById('auth-profile-email');
const statusEl = document.getElementById('auth-sync-status');
if (usernameEl) {
usernameEl.textContent = S.authUsername ? '@' + S.authUsername : (S.authEmail ? '@' + S.authEmail.split('@')[0] : 'unknown');
}
if (emailEl) {
emailEl.textContent = S.authEmail ? '(' + S.authEmail + ')' : '';
}
if (statusEl && !S.authEmail) {
statusEl.textContent = 'Status: unauthenticated';
}
}
function handleLogout() {
addLog('info', 'Deauthorizing current terminal session...');
const clearSessionAndReload = () => {
S.authEmail = '';
S.authUsername = '';
_googleAccessToken = null;
_googleTokenExpiry = 0;
_driveFileId = null;
localStorage.removeItem('google_access_token');
localStorage.removeItem('google_token_expiry');
localStorage.removeItem('google_user_profile');
save('mathInit_state', S);
window.location.reload();
};
if (currentUser && currentUser.uid === 'demo-session') {
clearSessionAndReload();
return;
}
if (_googleAccessToken) {
try {
google.accounts.oauth2.revoke(_googleAccessToken, () => {
clearSessionAndReload();
});
return;
} catch (e) {
console.warn("Revoke failed, clearing local session anyway:", e);
}
}
clearSessionAndReload();
}
// === DESTRUCTIVE MIGRATIONS (v2Lifestyle, v22Water, historyKeys) ===
// DEFERRED: These now run inside runDestructiveMigrations(), called by
// unlockBootSync() AFTER the cloud pull completes. This prevents a fresh
// device from seeding defaults, out-timestamping the cloud, and pushing
// blank state that overwrites real data from device 1.
// See runDestructiveMigrations() definition near unlockBootSync().
// === BOOT & AUTH GATEWAY CONTROL ===
let bootFinished = false;
let authStateFetched = false;
let currentUser = null;
function tryDismissBoot() {
if (!bootFinished || !authStateFetched) return;
const bootEl = document.getElementById('boot');
if (currentUser) {
if (bootEl) {
bootEl.classList.add('done');
setTimeout(() => bootEl.remove(), 600);
}
try {
init();
} catch (e) {
console.error("Downstream initialization failed, but boot transition succeeded:", e);
}
} else {
const authGate = document.getElementById('auth-gate');
if (authGate) {
authGate.style.display = 'block';
}
}
}
// Start boot timer
setTimeout(() => {
bootFinished = true;
tryDismissBoot();
}, document.getElementById('boot') ? 2200 : 0);
// Double-tap 't' to fast boot into terminal if authenticated
let lastTKeyPress = 0;
document.addEventListener('keydown', function(e) {
if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.isContentEditable) {
return;
}
if (e.key.toLowerCase() === 't') {
const now = Date.now();
if (now - lastTKeyPress < 500) {
if (_googleAccessToken || (currentUser && currentUser.uid === 'demo-session')) {
bootFinished = true;
authStateFetched = true;
// Remove boot gate immediately
const bootEl = document.getElementById('boot');
if (bootEl) {
bootEl.classList.add('done');
bootEl.remove();
}
try {
init();
} catch (err) {
console.error("Downstream init failed during fast boot:", err);
}
// Launch interactive terminal instantly
const terminalEl = document.getElementById('interactive-terminal');
if (terminalEl) {
terminalEl.classList.add('open');
const tvInput = document.getElementById('tv-input');
if (tvInput) tvInput.focus();
const outInner = document.getElementById('tv-output-inner');
if (outInner && outInner.innerHTML === '') {
var welcomeLogo =
'<div style="font-family: monospace; white-space: pre; line-height: 1.4; color: var(--text-dim);">' +
' ███████╗████████╗██╗ ██╗ ██████╗ ███████╗\n' +
' ██╔════╝╚══██╔══╝██║ ██║██╔═══██╗██╔════╝\n' +
' █████╗ ██║ ███████║██║ ██║███████╗\n' +
' ██╔══╝ ██║ ██╔══██║██║ ██║╚════██║\n' +
' ███████╗ ██║ ██║ ██║╚██████╔╝███████║\n' +
' ╚══════╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝\n' +
'</div>' +
'<div style="margin-top: 8px;">' + ('ethos.init v2.4.0 interactive mode. type "help" for commands.') + '</div>';
printTermTyped(welcomeLogo, 'sys');
}
}
}
}
lastTKeyPress = now;
}
});
// === INIT ===
let initCalled = false;
function init() {
if (initCalled) return;
initCalled = true;
if (S.theme && S.theme !== 'default') document.documentElement.setAttribute('data-theme', S.theme);
// CRT overlay init
var crtEl = document.getElementById('crt-screen-effect');
if (crtEl) { if (S.crtEnabled) crtEl.classList.add('crt-active'); else crtEl.classList.remove('crt-active'); }
initTabs(); initButtons(); render(); startClock(); startFlowerAnimation();
// v2.4.0 PWA & Reminders Init
initPWANotifications();
startReminderTicker();
// ECRE Waveform and diagnostics boot
if (typeof initCoherenceWave === 'function') initCoherenceWave();
if (typeof printECREDiagnosticBoot === 'function') printECREDiagnosticBoot();
// Global Ctrl+Alt+C shortcut for CRT toggle
document.addEventListener('keydown', function(e) {
if (e.ctrlKey && e.altKey && e.key.toLowerCase() === 'c') {
e.preventDefault();
toggleCRT();
}
});
}
// === INTERACTIVE TERMINAL AUTH PORTAL ===
function initAuthGate() {
const googleBtn = document.getElementById('auth-google-btn');
const demoBtn = document.getElementById('auth-demo-btn');
const errorDisplay = document.getElementById('auth-error-display');
if (googleBtn) {
googleBtn.onclick = () => {
if (!_googleTokenClient) {
showAuthError("Google Identity Services is still loading. Please wait.");
return;
}
if (errorDisplay) errorDisplay.style.display = 'none';
_googleTokenClient.requestAccessToken();
};
}
if (demoBtn) {
demoBtn.onclick = () => {
currentUser = { uid: 'demo-session', displayName: 'demo', email: 'demo@ethos.io' };
authStateFetched = true;
if (typeof seedDemoData === 'function') {
seedDemoData();
} else {
S.authEmail = 'demo@ethos.io';
S.authUsername = 'demo';