diff --git a/package.json b/package.json
index 170ec09..76a926d 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "life-os",
- "version": "1.19.0",
+ "version": "1.20.0",
"private": true,
"type": "module",
"scripts": {
diff --git a/public/addons.js b/public/addons.js
index ca1019b..2ba43db 100644
--- a/public/addons.js
+++ b/public/addons.js
@@ -3,7 +3,7 @@
const DRAFT_KEY = 'lifeos_today_draft_v1';
const localDay = () => { const d = new Date(); return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`; };
const escapeHtml = value => String(value || '').replace(/[&<>]/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[char]));
- const APP_VERSION = '1.19.0';
+ const APP_VERSION = '1.20.0';
window.LifeOSVersion = APP_VERSION;
const appIds = ['today', 'timeline', 'museum', 'insights', 'profile', 'tasks', 'calendar', 'system', 'browser', 'terminal', 'database'];
const t = (key, values) => LifeI18n.t(key, values);
diff --git a/public/backup.js b/public/backup.js
new file mode 100644
index 0000000..bc17dad
--- /dev/null
+++ b/public/backup.js
@@ -0,0 +1,96 @@
+/* Portable Life OS backup format. Schema v3 carries every device-local app record. */
+(() => {
+ const BACKUP_SCHEMA = 3;
+ const SAFETY_KEY = 'lifeos_restore_safety_v1';
+ const excluded = /^(lifeos_(?:cloud_|precloud_|sync_conflict_|storage_mode_|local_cache_revision_|restore_safety_))/;
+ const portableKey = key => typeof key === 'string' && key.startsWith('lifeos_') && !excluded.test(key);
+ const records = () => Object.fromEntries(
+ Array.from({ length: localStorage.length }, (_, index) => localStorage.key(index))
+ .filter(portableKey)
+ .sort()
+ .map(key => [key, localStorage.getItem(key)])
+ );
+ const canonical = value => JSON.stringify(Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b))));
+ const sha256 = async value => {
+ const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(value));
+ return Array.from(new Uint8Array(bytes), byte => byte.toString(16).padStart(2, '0')).join('');
+ };
+ const json = (key, fallback) => { try { return JSON.parse(localStorage.getItem(key) || 'null') ?? fallback; } catch { return fallback; } };
+ const safeDay = () => new Date().toISOString().slice(0, 10);
+
+ async function createBackup() {
+ const stored = records();
+ return {
+ app: 'Life OS',
+ version: window.LifeOSVersion || '1.20.0',
+ schemaVersion: BACKUP_SCHEMA,
+ exportedAt: new Date().toISOString(),
+ profile: json('lifeos_profile', {}),
+ memories: json('lifeos_memories', []),
+ museum: json('lifeos_museum', []),
+ settings: json('lifeos_settings', {}),
+ system: json('lifeos_system', { schemaVersion: 2 }),
+ desktopLayout: json('lifeos_window_layout_v1', null),
+ widgetLayout: json('lifeos_widget_layout_v1', null),
+ records: stored,
+ recordCount: Object.keys(stored).length,
+ checksum: { algorithm: 'SHA-256', value: await sha256(canonical(stored)) }
+ };
+ }
+
+ function download(data, filename) {
+ const url = URL.createObjectURL(new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' }));
+ const link = document.createElement('a');
+ link.href = url; link.download = filename; link.click();
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
+ }
+
+ async function valid(data) {
+ if (!data || data.app !== 'Life OS' || ![1, 2, 3].includes(data.schemaVersion) || !Array.isArray(data.memories) || !Array.isArray(data.museum)) return false;
+ if (data.schemaVersion < BACKUP_SCHEMA) return true;
+ if (!data.records || Array.isArray(data.records) || typeof data.records !== 'object') return false;
+ const entries = Object.entries(data.records);
+ if (entries.some(([key, value]) => !portableKey(key) || typeof value !== 'string')) return false;
+ if (data.recordCount !== entries.length || data.checksum?.algorithm !== 'SHA-256' || !/^[a-f0-9]{64}$/.test(data.checksum?.value || '')) return false;
+ return (await sha256(canonical(data.records))) === data.checksum.value;
+ }
+
+ window.exportData = async () => {
+ const state = settings(); state.lastBackup = new Date().toISOString(); save('lifeos_settings', state);
+ download(await createBackup(), `life-os-backup-${safeDay()}.json`);
+ window.renderAll?.(); window.toast?.('feedback.backup');
+ };
+
+ window.readImport = async input => {
+ const file = input.files?.[0];
+ input.value = '';
+ if (!file || file.size > 32 * 1024 * 1024) return window.toast?.('feedback.invalid');
+ try {
+ const data = JSON.parse(await file.text());
+ if (!(await valid(data))) throw new Error('invalid backup');
+ importData = data;
+ window.importPreview();
+ } catch {
+ window.toast?.('feedback.invalid');
+ }
+ };
+
+ const previousApplyImport = window.applyImport;
+ window.applyImport = async mode => {
+ const data = importData;
+ if (mode !== 'replace' || data?.schemaVersion !== BACKUP_SCHEMA) return previousApplyImport(mode);
+ const safety = await createBackup();
+ localStorage.setItem(SAFETY_KEY, JSON.stringify(safety));
+ download(safety, `life-os-before-restore-${safeDay()}.json`);
+ for (const key of Array.from({ length: localStorage.length }, (_, index) => localStorage.key(index)).filter(portableKey)) localStorage.removeItem(key);
+ for (const [key, value] of Object.entries(data.records)) localStorage.setItem(key, value);
+ document.querySelector('#modal').innerHTML = '';
+ window.toast?.('feedback.restoring');
+ setTimeout(() => {
+ window.renderIcons?.(); window.renderAll?.(); window.applyLanguage?.(); window.applyDesktopPreferences?.();
+ window.LifeOSLocalDB?.refresh?.(); window.toast?.('feedback.restored');
+ }, 500);
+ };
+
+ window.LifeOSBackup = { schemaVersion: BACKUP_SCHEMA, create: createBackup, validate: valid, portableKey };
+})();
diff --git a/public/index.html b/public/index.html
index 56e1f34..0119caf 100644
--- a/public/index.html
+++ b/public/index.html
@@ -23,6 +23,6 @@ function museumApp(c){let a=museum(),ms=mems();c.innerHTML=`
m.date===d.toISOString().slice(0,10))){s++;d.setDate(d.getDate()-1)}return s}function longest(a){let ds=a.map(x=>x.date).sort(),best=0,run=0,last='';ds.forEach(d=>{run=last&&((new Date(d)-new Date(last))/864e5===1)?run+1:1;best=Math.max(best,run);last=d});return best}function insights(c){let a=mems(),last=a.filter(m=>(Date.now()-new Date(m.date+'T12:00:00'))<2592e6),cnt={clear:0,light:0,cloudy:0,rain:0,storm:0};last.forEach(x=>cnt[x.mood]++);let avg=a.length?(a.reduce((s,x)=>s+x.energy,0)/a.length).toFixed(1):'—',days={};a.forEach(x=>{let d=new Date(x.date+'T12:00:00').toLocaleDateString('en-US',{weekday:'long'});days[d]=(days[d]||0)+1});let active=Object.entries(days).sort((x,y)=>y[1]-x[1])[0]?.[0]||'—';c.innerHTML=`
LAST 30 DAYS
Insights, quietly. WEATHER
${Object.entries(cnt).map(([k,v])=>`${cap(k)} ${v} DAYS
`).join('')}AVERAGE ENERGY
${avg} / 5
${a.slice(0,10).reverse().map(x=>` `).join('')||'No entries yet '}
CURRENT STREAK
${streak(a)} DAYS
Longest streak: ${longest(a)} days
`}
function profileApp(c){let p=profile(),a=mems(),common=Object.entries(a.reduce((o,m)=>(o[m.mood]=(o[m.mood]||0)+1,o),{})).sort((x,y)=>y[1]-x[1])[0]?.[0]||'—',avg=a.length?(a.reduce((x,m)=>x+m.energy,0)/a.length).toFixed(1):'—',started=Math.max(1,Math.floor((Date.now()-new Date(p.startDate))/864e5));c.innerHTML=`
SYSTEM PROFILE
${p.name?esc(p.name)+' · ':''}LIFE OS ONLINE ${started} DAYS ONLINE
${a.length} MEMORIES
${museum().length} MUSEUM ITEMS
${streak(a)} CURRENT STREAK
${longest(a)} LONGEST STREAK
${cap(common)} COMMON WEATHER
PERSONAL SYSTEM
Display Name
Birthday (optional)
Life OS Start Date
Personal Motto
SAVE PROFILE AVERAGE ENERGY ${avg} / 5
`}function saveProfile(){save('lifeos_profile',{name:pname.value,birthday:pbday.value,startDate:pstart.value||day(),motto:pmotto.value});renderAll();toast('PROFILE SAVED')}
function today(c){let m=mems().find(x=>x.date===day());if(todayDraft===null){selectedMood=m?.mood||'cloudy';selectedEnergy=m?.energy||3}let f=m||filmFor(selectedMood,selectedEnergy),text=todayDraft===null?(m?.text||''):todayDraft,cWeek=new Date().toLocaleDateString(LifeI18n.locale(),{weekday:'long'}).toUpperCase();c.innerHTML=`
${cWeek}
${fmtDate(day()).replace(/^[^,]+, /,'')} ${i18n('How was your day?')}
${i18n(m?'UPDATE MEMORY':'ARCHIVE TODAY')}
${i18n("TODAY'S WEATHER")}
${['clear','light','cloudy','rain','storm'].map(x=>`${moodName(x)} `).join('')}
${i18n('ENERGY LEVEL')}
${[1,2,3,4,5].map(x=>`${x} `).join('')}
${i18n("TODAY'S FILM")}
${f.filmTitle}
${f.filmSubtitle}
“${f.filmLine}”
`}function rerenderToday(){let old=document.querySelector('#entry');todayDraft=old?old.value:todayDraft||'';window.today(document.querySelector('#content-today'));let entry=document.querySelector('#entry');entry?.focus();entry?.setSelectionRange(entry.value.length,entry.value.length)}
-function systemApp(c){let s=settings(),bytes=new Blob([JSON.stringify({mems:mems(),museum:museum(),profile:profile()})]).size;let rec=s.lastBackup&&(Date.now()-new Date(s.lastBackup)>12096e5);c.innerHTML=`
SYSTEM SETTINGS
System, local and yours. APPEARANCE
${['dark','light','auto'].map(x=>`${x.toUpperCase()} `).join('')}
STORAGE
Local Storage ${mems().length} memories · ${museum().length} museum items · Approx. ${Math.ceil(bytes/1024)} KB
DATA STORAGE
Your data is stored locally in this browser. Create regular backups to prevent data loss.
${s.lastBackup?'LAST BACKUP · '+fmtDate(s.lastBackup.slice(0,10)):'LAST BACKUP · NEVER'} ${rec?'BACKUP RECOMMENDED ':''}
VERSION
Life OS Version ${window.LifeOSVersion||'1.18.1'} · Schema v2
`}function theme(x){let s=settings();s.theme=x;save('lifeos_settings',s);init();renderAll()}function exportData(){let data={app:'Life OS',version:window.LifeOSVersion||'1.18.1',schemaVersion:1,exportedAt:new Date().toISOString(),profile:profile(),memories:mems(),museum:museum(),settings:settings()};let a=document.createElement('a');a.href=URL.createObjectURL(new Blob([JSON.stringify(data,null,2)],{type:'application/json'}));a.download='life-os-backup-'+day()+'.json';a.click();let s=settings();s.lastBackup=new Date().toISOString();save('lifeos_settings',s);renderAll();toast('BACKUP CREATED')}function readImport(el){let f=el.files[0];if(!f)return;let r=new FileReader;r.onload=()=>{try{let d=JSON.parse(r.result);if(d.app!=='Life OS'||![1,2].includes(d.schemaVersion)||!Array.isArray(d.memories)||!Array.isArray(d.museum))throw 0;importData=d;importPreview()}catch{toast('INVALID BACKUP FILE')}};r.readAsText(f)}function importPreview(){let d=importData;modal.innerHTML=`
LIFE OS BACKUP
Ready to restore Exported: ${fmtDate(d.exportedAt.slice(0,10))} Memories: ${d.memories.length} Museum Items: ${d.museum.length}
MERGE REPLACE ALL DATA CANCEL
`}function replaceConfirm(){modal.innerHTML=`
FINAL CONFIRMATION
Replace all Life OS data? This will replace all current Life OS data.
REPLACE DATA CANCEL
`}function applyImport(mode){let d=importData;if(mode==='replace'){save('lifeos_memories',d.memories);save('lifeos_museum',d.museum);save('lifeos_profile',d.profile||{});save('lifeos_settings',d.settings||{})}else{let a=mems(), ids=new Set(a.map(x=>x.id)),dates=new Set(a.map(x=>x.date));save('lifeos_memories',[...a,...d.memories.filter(x=>!ids.has(x.id)&&!dates.has(x.date))]);let mu=museum(),mi=new Set(mu.map(x=>x.id));save('lifeos_museum',[...mu,...d.museum.filter(x=>!mi.has(x.id))])}modal.innerHTML='';toast('RESTORING SYSTEM...');setTimeout(()=>{renderAll();toast('SYSTEM RESTORED')},500)}function resetConfirm(){modal.innerHTML=`
RESET LIFE OS
Reset all local data? Export a backup first if you want to keep it.
RESET DATA CANCEL
`}function toast(t){let x=document.createElement('div');x.className='toast';x.textContent=t;document.body.append(x);setTimeout(()=>x.remove(),2000)}
+function systemApp(c){let s=settings(),bytes=new Blob([JSON.stringify({mems:mems(),museum:museum(),profile:profile()})]).size;let rec=s.lastBackup&&(Date.now()-new Date(s.lastBackup)>12096e5);c.innerHTML=`
SYSTEM SETTINGS
System, local and yours. APPEARANCE
${['dark','light','auto'].map(x=>`${x.toUpperCase()} `).join('')}
STORAGE
Local Storage ${mems().length} memories · ${museum().length} museum items · Approx. ${Math.ceil(bytes/1024)} KB
DATA STORAGE
Your data is stored locally in this browser. Create regular backups to prevent data loss.
${s.lastBackup?'LAST BACKUP · '+fmtDate(s.lastBackup.slice(0,10)):'LAST BACKUP · NEVER'} ${rec?'BACKUP RECOMMENDED ':''}
VERSION
Life OS Version ${window.LifeOSVersion||'1.18.1'} · Schema v2
`}function theme(x){let s=settings();s.theme=x;save('lifeos_settings',s);init();renderAll()}function exportData(){let data={app:'Life OS',version:window.LifeOSVersion||'1.18.1',schemaVersion:1,exportedAt:new Date().toISOString(),profile:profile(),memories:mems(),museum:museum(),settings:settings()};let a=document.createElement('a');a.href=URL.createObjectURL(new Blob([JSON.stringify(data,null,2)],{type:'application/json'}));a.download='life-os-backup-'+day()+'.json';a.click();let s=settings();s.lastBackup=new Date().toISOString();save('lifeos_settings',s);renderAll();toast('BACKUP CREATED')}function readImport(el){let f=el.files[0];if(!f)return;let r=new FileReader;r.onload=()=>{try{let d=JSON.parse(r.result);if(d.app!=='Life OS'||![1,2,3].includes(d.schemaVersion)||!Array.isArray(d.memories)||!Array.isArray(d.museum))throw 0;importData=d;importPreview()}catch{toast('INVALID BACKUP FILE')}};r.readAsText(f)}function importPreview(){let d=importData;modal.innerHTML=`
LIFE OS BACKUP
Ready to restore Exported: ${fmtDate(d.exportedAt.slice(0,10))} Memories: ${d.memories.length} Museum Items: ${d.museum.length}
MERGE REPLACE ALL DATA CANCEL
`}function replaceConfirm(){modal.innerHTML=`
FINAL CONFIRMATION
Replace all Life OS data? This will replace all current Life OS data.
REPLACE DATA CANCEL
`}function applyImport(mode){let d=importData;if(mode==='replace'){save('lifeos_memories',d.memories);save('lifeos_museum',d.museum);save('lifeos_profile',d.profile||{});save('lifeos_settings',d.settings||{})}else{let a=mems(), ids=new Set(a.map(x=>x.id)),dates=new Set(a.map(x=>x.date));save('lifeos_memories',[...a,...d.memories.filter(x=>!ids.has(x.id)&&!dates.has(x.date))]);let mu=museum(),mi=new Set(mu.map(x=>x.id));save('lifeos_museum',[...mu,...d.museum.filter(x=>!mi.has(x.id))])}modal.innerHTML='';toast('RESTORING SYSTEM...');setTimeout(()=>{renderAll();toast('SYSTEM RESTORED')},500)}function resetConfirm(){modal.innerHTML=`
RESET LIFE OS
Reset all local data? Export a backup first if you want to keep it.
RESET DATA CANCEL
`}function toast(t){let x=document.createElement('div');x.className='toast';x.textContent=t;document.body.append(x);setTimeout(()=>x.remove(),2000)}
window.renderIcons=renderIcons;window.renderAll=renderAll;window.toast=toast;
-