Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: MeatSpace Life Calendar — mortality-aware time mapping

Adam Eivy886e4e751276
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 691de4c3f4..22b793aa35 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,6 +1,8 @@
# Unreleased Changes
## Added
+- MeatSpace Life Calendar tab — "4000 Weeks" mortality-aware time grid with weeks from birth to death, remaining Saturdays/Sundays/sleep/seasons stats, and customizable activity budgets (coffees, showers, workouts, etc.)
+- Life Calendar tile on MeatSpace Overview linking to full calendar view
## Changed
diff --git a/client/src/components/meatspace/constants.js b/client/src/components/meatspace/constants.js
index b837c0a371..18b06ce813 100644
--- a/client/src/components/meatspace/constants.js
+++ b/client/src/components/meatspace/constants.js
@@ -1,6 +1,7 @@
import {
Skull,
Beer,
+ Calendar,
Clock,
Dna,
Eye,
@@ -19,6 +20,7 @@ export const TABS = [
{ id: 'alcohol', label: 'Alcohol', icon: Beer },
{ id: 'blood', label: 'Blood', icon: HeartPulse },
{ id: 'body', label: 'Body', icon: Scale },
+ { id: 'calendar', label: 'Calendar', icon: Calendar },
{ id: 'eyes', label: 'Eyes', icon: Eye },
{ id: 'genome', label: 'Genome', icon: Dna },
{ id: 'health', label: 'Health', icon: Stethoscope },
diff --git a/client/src/components/meatspace/tabs/CalendarTab.jsx b/client/src/components/meatspace/tabs/CalendarTab.jsx
new file mode 100644
index 0000000000..5edcea5afe
--- /dev/null
+++ b/client/src/components/meatspace/tabs/CalendarTab.jsx
@@ -0,0 +1,367 @@
+import { useState, useEffect, useCallback, useMemo } from 'react';
+import {
+ Calendar, Coffee, Droplets, Utensils, Dumbbell, BookOpen, Scissors,
+ Cake, Plane, Plus, Trash2, Circle, Sun, Moon, TreePine, Snowflake,
+ Flower2, CloudSun
+} from 'lucide-react';
+import toast from 'react-hot-toast';
+import * as api from '../../../services/api';
+import BrailleSpinner from '../../BrailleSpinner';
+
+const ICON_MAP = {
+ coffee: Coffee, droplets: Droplets, utensils: Utensils, dumbbell: Dumbbell,
+ 'book-open': BookOpen, scissors: Scissors, cake: Cake, plane: Plane,
+ circle: Circle, sun: Sun, moon: Moon,
+};
+
+const CADENCE_LABELS = { day: '/day', week: '/week', month: '/month', year: '/year' };
+
+function IconForName({ name, size = 16, className }) {
+ const Comp = ICON_MAP[name] || Circle;
+ return <Comp size={size} className={className} />;
+}
+
+// === Life Grid ===
+
+function LifeGrid({ grid, stats }) {
+ const currentAge = Math.floor(stats.age.years);
+
+ // Decade labels
+ const decades = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100];
+
+ return (
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ <div className="flex items-center gap-2 mb-3">
+ <Calendar size={16} className="text-port-accent" />
+ <h3 className="text-sm font-medium text-white">Life in Weeks</h3>
+ <span className="text-xs text-gray-500 ml-auto">
+ Week {stats.age.weeks.toLocaleString()} of {stats.total.weeks.toLocaleString()}
+ </span>
+ </div>
+
+ {/* Legend */}
+ <div className="flex items-center gap-4 mb-3 text-xs text-gray-500">
+ <span className="flex items-center gap-1">
+ <span className="w-2 h-2 rounded-sm bg-gray-600" /> Spent
+ </span>
+ <span className="flex items-center gap-1">
+ <span className="w-2 h-2 rounded-sm bg-port-accent" /> Now
+ </span>
+ <span className="flex items-center gap-1">
+ <span className="w-2 h-2 rounded-sm bg-port-success/30" /> Remaining
+ </span>
+ </div>
+
+ {/* Grid */}
+ <div className="overflow-x-auto">
+ <div className="min-w-[600px]">
+ {grid.map((row) => (
+ <div key={row.age} className="flex items-center gap-px mb-px">
+ {/* Age label every 10 years */}
+ <span className={`w-6 text-right text-[9px] mr-1 shrink-0 ${
+ decades.includes(row.age) ? 'text-gray-400 font-medium' : 'text-transparent'
+ }`}>
+ {decades.includes(row.age) ? row.age : '.'}
+ </span>
+ {row.weeks.map((status, w) => (
+ <span
+ key={w}
+ className={`w-[9px] h-[9px] rounded-[1px] shrink-0 ${
+ status === 'c'
+ ? 'bg-port-accent shadow-[0_0_4px_rgba(59,130,246,0.5)]'
+ : status === 's'
+ ? row.age === currentAge ? 'bg-gray-500' : 'bg-gray-700'
+ : 'bg-port-success/20'
+ }`}
+ title={`Age ${row.age}, Week ${w + 1}`}
+ />
+ ))}
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+// === Stats Cards ===
+
+function StatCard({ icon: Icon, iconColor, label, value, sub }) {
+ return (
+ <div className="bg-port-card border border-port-border rounded-lg p-3">
+ <div className="flex items-center gap-2 mb-1">
+ <Icon size={14} className={iconColor} />
+ <span className="text-xs text-gray-400 uppercase tracking-wider">{label}</span>
+ </div>
+ <div className="text-xl font-bold text-white">{typeof value === 'number' ? value.toLocaleString() : value}</div>
+ {sub && <div className="text-xs text-gray-500 mt-0.5">{sub}</div>}
+ </div>
+ );
+}
+
+function TimeStats({ stats }) {
+ const r = stats.remaining;
+ return (
+ <div>
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-3">Time Remaining</h3>
+ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-2">
+ <StatCard icon={Sun} iconColor="text-yellow-400" label="Saturdays" value={r.saturdays} sub={`${Math.round(r.saturdays / 52)} years of Saturdays`} />
+ <StatCard icon={Sun} iconColor="text-orange-400" label="Sundays" value={r.sundays} sub={`${Math.round(r.sundays / 52)} years of Sundays`} />
+ <StatCard icon={CloudSun} iconColor="text-blue-400" label="Weekends" value={r.weekends} sub={`${Math.round(r.weekends * 2)} weekend days`} />
+ <StatCard icon={Moon} iconColor="text-indigo-400" label="Sleep" value={`${Math.round(r.sleepHours / 24 / 365.25)}y`} sub={`${r.sleepHours.toLocaleString()} hours`} />
+ <StatCard icon={Sun} iconColor="text-green-400" label="Awake Days" value={r.awakeDays} sub={`${Math.round(r.awakeDays / 365.25)} awake years`} />
+ <StatCard icon={Calendar} iconColor="text-purple-400" label="Months" value={r.months} />
+ <StatCard icon={Calendar} iconColor="text-teal-400" label="Weeks" value={r.weeks} />
+ <StatCard icon={Calendar} iconColor="text-port-accent" label="Days" value={r.days} />
+ <StatCard icon={Snowflake} iconColor="text-cyan-400" label="Winters" value={Math.floor(r.seasons / 4)} />
+ <StatCard icon={Flower2} iconColor="text-pink-400" label="Springs" value={Math.floor(r.seasons / 4)} />
+ <StatCard icon={TreePine} iconColor="text-green-400" label="Summers" value={Math.floor(r.seasons / 4)} />
+ <StatCard icon={Cake} iconColor="text-port-warning" label="Holidays" value={r.holidays} sub="Major holidays left" />
+ </div>
+ </div>
+ );
+}
+
+// === Activity Budgets ===
+
+function ActivityBudgets({ budgets, onRemove }) {
+ return (
+ <div>
+ <h3 className="text-sm font-medium text-gray-400 uppercase tracking-wider mb-3">Activity Budget</h3>
+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
+ {budgets.map((b, i) => (
+ <div key={i} className="bg-port-card border border-port-border rounded-lg p-3 flex items-center gap-3 group">
+ <IconForName name={b.icon} size={18} className="text-port-accent shrink-0" />
+ <div className="flex-1 min-w-0">
+ <div className="text-sm font-medium text-white">{b.name}</div>
+ <div className="text-xs text-gray-500">
+ {b.frequency}{CADENCE_LABELS[b.cadence]}
+ </div>
+ </div>
+ <div className="text-right">
+ <div className="text-lg font-bold text-white">{b.remaining.toLocaleString()}</div>
+ <div className="text-[10px] text-gray-500">remaining</div>
+ </div>
+ <button
+ onClick={() => onRemove(i)}
+ className="opacity-0 group-hover:opacity-100 transition-opacity text-gray-600 hover:text-port-error p-1"
+ title="Remove activity"
+ >
+ <Trash2 size={14} />
+ </button>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+// === Add Activity Form ===
+
+function AddActivityForm({ onAdd }) {
+ const [open, setOpen] = useState(false);
+ const [name, setName] = useState('');
+ const [cadence, setCadence] = useState('day');
+ const [frequency, setFrequency] = useState('1');
+ const [icon, setIcon] = useState('circle');
+
+ const handleSubmit = (e) => {
+ e.preventDefault();
+ if (!name.trim()) return;
+ onAdd({ name: name.trim(), cadence, frequency: parseFloat(frequency) || 1, icon });
+ setName('');
+ setFrequency('1');
+ setIcon('circle');
+ setOpen(false);
+ };
+
+ if (!open) {
+ return (
+ <button
+ onClick={() => setOpen(true)}
+ className="flex items-center gap-2 px-3 py-2 text-sm text-gray-400 hover:text-white bg-port-card border border-dashed border-port-border rounded-lg hover:border-port-accent/50 transition-colors"
+ >
+ <Plus size={16} />
+ Add Activity
+ </button>
+ );
+ }
+
+ const iconOptions = Object.keys(ICON_MAP);
+
+ return (
+ <form onSubmit={handleSubmit} className="bg-port-card border border-port-border rounded-lg p-4 space-y-3">
+ <div className="grid grid-cols-2 gap-3">
+ <div>
+ <label className="text-xs text-gray-400 mb-1 block">Name</label>
+ <input
+ type="text"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ placeholder="e.g. Coffees"
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-sm text-white focus:border-port-accent focus:outline-hidden"
+ autoFocus
+ />
+ </div>
+ <div>
+ <label className="text-xs text-gray-400 mb-1 block">Icon</label>
+ <div className="flex gap-1 flex-wrap">
+ {iconOptions.map(ic => (
+ <button
+ key={ic}
+ type="button"
+ onClick={() => setIcon(ic)}
+ className={`p-1.5 rounded ${icon === ic ? 'bg-port-accent/20 text-port-accent' : 'text-gray-500 hover:text-white'}`}
+ >
+ <IconForName name={ic} size={14} />
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ <div className="grid grid-cols-2 gap-3">
+ <div>
+ <label className="text-xs text-gray-400 mb-1 block">Frequency</label>
+ <input
+ type="number"
+ value={frequency}
+ onChange={(e) => setFrequency(e.target.value)}
+ min="0.01"
+ step="0.5"
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-sm text-white focus:border-port-accent focus:outline-hidden"
+ />
+ </div>
+ <div>
+ <label className="text-xs text-gray-400 mb-1 block">Cadence</label>
+ <select
+ value={cadence}
+ onChange={(e) => setCadence(e.target.value)}
+ className="w-full px-2 py-1.5 bg-port-bg border border-port-border rounded text-sm text-white focus:border-port-accent focus:outline-hidden"
+ >
+ <option value="day">Per Day</option>
+ <option value="week">Per Week</option>
+ <option value="month">Per Month</option>
+ <option value="year">Per Year</option>
+ </select>
+ </div>
+ </div>
+ <div className="flex gap-2">
+ <button type="submit" className="px-3 py-1.5 bg-port-accent text-white text-sm rounded hover:bg-port-accent/80 transition-colors">
+ Add
+ </button>
+ <button type="button" onClick={() => setOpen(false)} className="px-3 py-1.5 text-gray-400 text-sm hover:text-white transition-colors">
+ Cancel
+ </button>
+ </div>
+ </form>
+ );
+}
+
+// === Main CalendarTab ===
+
+export default function CalendarTab() {
+ const [data, setData] = useState(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState(null);
+
+ const fetchData = useCallback(async () => {
+ const result = await api.getLifeCalendar().catch(err => {
+ setError(err.message);
+ return null;
+ });
+ if (result) {
+ setData(result);
+ setError(null);
+ }
+ setLoading(false);
+ }, []);
+
+ useEffect(() => { fetchData(); }, [fetchData]);
+
+ const handleAddActivity = async (activity) => {
+ const result = await api.addActivity(activity).catch(() => null);
+ if (result) {
+ toast.success(`Added ${activity.name}`);
+ fetchData();
+ }
+ };
+
+ const handleRemoveActivity = async (index) => {
+ const name = data?.budgets?.[index]?.name || 'Activity';
+ const result = await api.removeActivity(index).catch(() => null);
+ if (result) {
+ toast.success(`Removed ${name}`);
+ fetchData();
+ }
+ };
+
+ if (loading) {
+ return (
+ <div className="flex items-center justify-center h-64">
+ <BrailleSpinner text="Loading life calendar" />
+ </div>
+ );
+ }
+
+ if (error || data?.error) {
+ return (
+ <div className="text-center py-12">
+ <Calendar size={48} className="text-gray-600 mx-auto mb-4" />
+ <p className="text-gray-400 mb-2">Life calendar unavailable</p>
+ <p className="text-sm text-gray-500">{error || data.error}</p>
+ </div>
+ );
+ }
+
+ const { stats, grid, budgets } = data;
+
+ // Header summary
+ const pctSpent = stats.age.weeks / stats.total.weeks * 100;
+ const pctColor = pctSpent < 50 ? 'text-port-accent' : pctSpent < 75 ? 'text-port-warning' : 'text-port-error';
+
+ return (
+ <div className="space-y-6">
+ {/* Summary bar */}
+ <div className="bg-port-card border border-port-border rounded-lg p-4">
+ <div className="flex flex-wrap items-center gap-6">
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wider">Age</div>
+ <div className="text-2xl font-bold text-white">{Math.floor(stats.age.years)}</div>
+ </div>
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wider">Weeks Lived</div>
+ <div className="text-2xl font-bold text-gray-400">{stats.age.weeks.toLocaleString()}</div>
+ </div>
+ <div>
+ <div className="text-xs text-gray-500 uppercase tracking-wider">Weeks Left</div>
+ <div className="text-2xl font-bold text-port-success">{stats.remaining.weeks.toLocaleString()}</div>
+ </div>
+ <div className="flex-1 min-w-[200px]">
+ <div className="flex justify-between text-xs text-gray-500 mb-1">
+ <span>Life Progress</span>
+ <span className={pctColor}>{pctSpent.toFixed(1)}%</span>
+ </div>
+ <div className="h-2 bg-port-bg rounded-full overflow-hidden">
+ <div
+ className={`h-full rounded-full transition-all ${
+ pctSpent < 50 ? 'bg-port-accent' : pctSpent < 75 ? 'bg-port-warning' : 'bg-port-error'
+ }`}
+ style={{ width: `${pctSpent}%` }}
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+
+ {/* Life Grid */}
+ <LifeGrid grid={grid} stats={stats} />
+
+ {/* Time remaining stats */}
+ <TimeStats stats={stats} />
+
+ {/* Activity budgets */}
+ <ActivityBudgets budgets={budgets} onRemove={handleRemoveActivity} />
+ <AddActivityForm onAdd={handleAddActivity} />
+ </div>
+ );
+}
diff --git a/client/src/components/meatspace/tabs/OverviewTab.jsx b/client/src/components/meatspace/tabs/OverviewTab.jsx
index 388b12eccf..37c2f0b666 100644
--- a/client/src/components/meatspace/tabs/OverviewTab.jsx
+++ b/client/src/components/meatspace/tabs/OverviewTab.jsx
@@ -1,6 +1,6 @@
import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
-import { Beer, Scale, HeartPulse, Dna, Eye, Dumbbell, Database, Rocket } from 'lucide-react';
+import { Beer, Scale, HeartPulse, Dna, Eye, Dumbbell, Database, Rocket, Calendar } from 'lucide-react';
import * as api from '../../../services/api';
import { useDeathClock } from '../../../hooks/useDeathClock';
import BrailleSpinner from '../../BrailleSpinner';
@@ -164,11 +164,12 @@ export default function OverviewTab() {
const [blood, setBlood] = useState(null);
const [epigenetic, setEpigenetic] = useState(null);
const [eyes, setEyes] = useState(null);
+ const [calendar, setCalendar] = useState(null);
const [loading, setLoading] = useState(true);
const navigate = useNavigate();
const fetchData = useCallback(async () => {
- const [overview, alc, bod, bld, epi, eye, hBody] = await Promise.all([
+ const [overview, alc, bod, bld, epi, eye, hBody, cal] = await Promise.all([
api.getMeatspaceOverview().catch(() => null),
api.getAlcoholSummary().catch(() => null),
api.getBodyHistory().catch(() => null),
@@ -176,6 +177,7 @@ export default function OverviewTab() {
api.getEpigeneticTests().catch(() => null),
api.getEyeExams().catch(() => null),
api.getLatestHealthMetrics(['body_mass', 'body_fat_percentage', 'lean_body_mass']).catch(() => null),
+ api.getLifeCalendar().catch(() => null),
]);
setData(overview);
setAlcohol(alc);
@@ -184,6 +186,7 @@ export default function OverviewTab() {
setBlood(bld);
setEpigenetic(epi);
setEyes(eye);
+ setCalendar(cal);
setLoading(false);
}, []);
@@ -330,6 +333,19 @@ export default function OverviewTab() {
{ label: 'Exercise', value: summary?.hasLifestyleData ? 'Set' : '—' },
]}
/>
+ {calendar?.stats && (
+ <HealthTile
+ icon={Calendar}
+ iconColor="text-port-accent"
+ label="Life Calendar"
+ onClick={() => navigate('/meatspace/calendar')}
+ metrics={[
+ { label: 'Saturdays left', value: calendar.stats.remaining.saturdays.toLocaleString() },
+ { label: 'Weeks left', value: calendar.stats.remaining.weeks.toLocaleString() },
+ { label: 'Awake days', value: calendar.stats.remaining.awakeDays.toLocaleString() },
+ ]}
+ />
+ )}
<HealthTile
icon={Database}
iconColor="text-gray-400"
diff --git a/client/src/pages/MeatSpace.jsx b/client/src/pages/MeatSpace.jsx
index 55b789e585..cd6573449e 100644
--- a/client/src/pages/MeatSpace.jsx
+++ b/client/src/pages/MeatSpace.jsx
@@ -8,6 +8,7 @@ import AgeTab from '../components/meatspace/tabs/AgeTab';
import AlcoholTab from '../components/meatspace/tabs/AlcoholTab';
import BloodTab from '../components/meatspace/tabs/BloodTab';
import BodyTab from '../components/meatspace/tabs/BodyTab';
+import CalendarTab from '../components/meatspace/tabs/CalendarTab';
import EyesTab from '../components/meatspace/tabs/EyesTab';
import GenomeTab from '../components/meatspace/tabs/GenomeTab';
import HealthTab from '../components/meatspace/tabs/HealthTab';
@@ -36,6 +37,8 @@ export default function MeatSpace() {
return <BloodTab />;
case 'body':
return <BodyTab />;
+ case 'calendar':
+ return <CalendarTab />;
case 'eyes':
return <EyesTab />;
case 'genome':
diff --git a/client/src/services/api.js b/client/src/services/api.js
index 76355d1868..9cfc86b2d9 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -1508,6 +1508,17 @@ export const scorePostLlmDrill = (type, drillData, responses, timeLimitMs, provi
body: JSON.stringify({ type, drillData, responses, timeLimitMs, ...(providerId && { providerId }), ...(model && { model }) })
});
+// Life Calendar
+export const getLifeCalendar = () => request('/meatspace/calendar');
+export const getActivities = () => request('/meatspace/activities');
+export const addActivity = (data) => request('/meatspace/activities', {
+ method: 'POST', body: JSON.stringify(data)
+});
+export const updateActivity = (index, data) => request(`/meatspace/activities/${index}`, {
+ method: 'PUT', body: JSON.stringify(data)
+});
+export const removeActivity = (index) => request(`/meatspace/activities/${index}`, { method: 'DELETE' });
+
// JIRA
export const getJiraInstances = () => request('/jira/instances');
export const getJiraProjects = (instanceId) => request(`/jira/instances/${instanceId}/projects`);
diff --git a/server/lib/meatspaceValidation.js b/server/lib/meatspaceValidation.js
index 430b2fdc71..1200bcec07 100644
--- a/server/lib/meatspaceValidation.js
+++ b/server/lib/meatspaceValidation.js
@@ -1,5 +1,18 @@
import { z } from 'zod';
+// =============================================================================
+// LIFE CALENDAR ACTIVITIES
+// =============================================================================
+
+export const activitySchema = z.object({
+ name: z.string().min(1).max(100),
+ cadence: z.enum(['day', 'week', 'month', 'year']),
+ frequency: z.number().min(0.01).max(1000),
+ icon: z.string().max(50).optional().default('circle'),
+});
+
+export const activityUpdateSchema = activitySchema.partial();
+
// =============================================================================
// MEATSPACE CONFIG & LIFESTYLE
// =============================================================================
diff --git a/server/routes/meatspace.js b/server/routes/meatspace.js
index a78d604d77..2dcd54ea11 100644
--- a/server/routes/meatspace.js
+++ b/server/routes/meatspace.js
@@ -13,6 +13,8 @@ import {
epigeneticTestSchema,
eyeExamSchema,
eyeExamUpdateSchema,
+ activitySchema,
+ activityUpdateSchema,
} from '../lib/meatspaceValidation.js';
import {
postSessionSubmitSchema,
@@ -26,6 +28,7 @@ import * as alcoholService from '../services/meatspaceAlcohol.js';
import * as healthService from '../services/meatspaceHealth.js';
import * as postService from '../services/meatspacePost.js';
import { generateLlmDrill, scoreLlmDrill } from '../services/meatspacePostLlm.js';
+import * as calendarService from '../services/meatspaceCalendar.js';
const router = Router();
@@ -435,4 +438,63 @@ router.post('/post/score-llm', asyncHandler(async (req, res) => {
res.json(result);
}));
+// ============================================================
+// Life Calendar
+// ============================================================
+
+/**
+ * GET /api/meatspace/calendar
+ * Full life calendar data: grid, stats, activity budgets.
+ */
+router.get('/calendar', asyncHandler(async (_req, res) => {
+ const data = await calendarService.getCalendarData();
+ res.json(data);
+}));
+
+/**
+ * GET /api/meatspace/activities
+ * List all custom activities (or defaults if none configured).
+ */
+router.get('/activities', asyncHandler(async (_req, res) => {
+ const activities = await calendarService.getActivities();
+ res.json(activities);
+}));
+
+/**
+ * POST /api/meatspace/activities
+ * Add a new activity.
+ */
+router.post('/activities', asyncHandler(async (req, res) => {
+ const data = validateRequest(activitySchema, req.body);
+ const activities = await calendarService.addActivity(data);
+ res.json(activities);
+}));
+
+/**
+ * PUT /api/meatspace/activities/:index
+ * Update an activity by index.
+ */
+router.put('/activities/:index', asyncHandler(async (req, res) => {
+ const index = parseInt(req.params.index, 10);
+ const data = validateRequest(activityUpdateSchema, req.body);
+ const activities = await calendarService.updateActivity(index, data);
+ if (!activities) {
+ throw new ServerError('Activity not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(activities);
+}));
+
+/**
+ * DELETE /api/meatspace/activities/:index
+ * Remove an activity by index.
+ */
+router.delete('/activities/:index', asyncHandler(async (req, res) => {
+ const index = parseInt(req.params.index, 10);
+ const activities = await calendarService.removeActivity(index);
+ if (!activities) {
+ throw new ServerError('Activity not found', { status: 404, code: 'NOT_FOUND' });
+ }
+ res.json(activities);
+}));
+
export default router;
diff --git a/server/services/meatspaceCalendar.js b/server/services/meatspaceCalendar.js
new file mode 100644
index 0000000000..7d32dfdd0d
--- /dev/null
+++ b/server/services/meatspaceCalendar.js
@@ -0,0 +1,277 @@
+/**
+ * MeatSpace Life Calendar Service
+ *
+ * "4000 Weeks" mortality-aware time mapping.
+ * Computes life grids, remaining time budgets, and activity estimates
+ * based on birth date and life expectancy.
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+import { PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';
+import { getDeathClock } from './meatspace.js';
+
+const MEATSPACE_DIR = PATHS.meatspace;
+const ACTIVITIES_FILE = join(MEATSPACE_DIR, 'activities.json');
+
+const MS_PER_DAY = 86400000;
+const MS_PER_WEEK = MS_PER_DAY * 7;
+
+// === Built-in time remaining stats ===
+
+/**
+ * Compute remaining counts of various time units and life events
+ */
+export function computeTimeStats(birthDate, deathDate, sleepHoursPerNight = 7.5) {
+ const now = new Date();
+ const death = new Date(deathDate);
+ const birth = new Date(birthDate);
+
+ if (death <= now) {
+ return { expired: true };
+ }
+
+ const msRemaining = death.getTime() - now.getTime();
+ const daysRemaining = msRemaining / MS_PER_DAY;
+ const weeksRemaining = msRemaining / MS_PER_WEEK;
+ const yearsRemaining = daysRemaining / 365.25;
+
+ // Count specific day-of-week remaining
+ const countDayOfWeek = (targetDay) => {
+ let count = 0;
+ const cursor = new Date(now);
+ // Advance to next target day
+ while (cursor.getDay() !== targetDay) {
+ cursor.setDate(cursor.getDate() + 1);
+ }
+ while (cursor <= death) {
+ count++;
+ cursor.setDate(cursor.getDate() + 7);
+ }
+ return count;
+ };
+
+ // Count seasons remaining (approximate by quarter)
+ const seasonsRemaining = Math.floor(yearsRemaining * 4);
+
+ // Count holidays remaining (approximate)
+ const holidaysPerYear = 11; // Major US holidays
+
+ // Sleep: remaining hours
+ const sleepHoursRemaining = Math.round(daysRemaining * sleepHoursPerNight);
+ const awakeDaysRemaining = Math.round(daysRemaining * (1 - sleepHoursPerNight / 24));
+
+ // Count how many of each month remain
+ const monthsRemaining = Math.round(yearsRemaining * 12);
+
+ // Years lived and total
+ const ageMs = now.getTime() - birth.getTime();
+ const ageDays = ageMs / MS_PER_DAY;
+ const ageWeeks = Math.floor(ageDays / 7);
+ const totalWeeks = Math.floor((death.getTime() - birth.getTime()) / MS_PER_WEEK);
+
+ return {
+ expired: false,
+ age: {
+ years: Math.round((ageDays / 365.25) * 100) / 100,
+ weeks: ageWeeks,
+ days: Math.floor(ageDays),
+ },
+ remaining: {
+ years: Math.round(yearsRemaining * 100) / 100,
+ months: monthsRemaining,
+ weeks: Math.floor(weeksRemaining),
+ days: Math.floor(daysRemaining),
+ saturdays: countDayOfWeek(6),
+ sundays: countDayOfWeek(0),
+ fridays: countDayOfWeek(5),
+ weekends: countDayOfWeek(6), // Same as saturdays (each weekend = 1 saturday)
+ seasons: seasonsRemaining,
+ holidays: Math.round(yearsRemaining * holidaysPerYear),
+ sleepHours: sleepHoursRemaining,
+ awakeDays: awakeDaysRemaining,
+ },
+ total: {
+ weeks: totalWeeks,
+ },
+ };
+}
+
+// === Life Grid (weeks from birth to death) ===
+
+/**
+ * Compute a compact life grid representation.
+ * Returns year rows, each with 52 week cells.
+ * Each cell: 'spent' | 'current' | 'remaining'
+ */
+export function computeLifeGrid(birthDate, deathDate) {
+ const birth = new Date(birthDate);
+ const death = new Date(deathDate);
+ const now = new Date();
+
+ const totalYears = Math.ceil((death.getTime() - birth.getTime()) / (365.25 * MS_PER_DAY));
+ const rows = [];
+
+ for (let y = 0; y < totalYears; y++) {
+ const yearStart = new Date(birth);
+ yearStart.setFullYear(birth.getFullYear() + y);
+ const yearAge = y;
+
+ const weeks = [];
+ for (let w = 0; w < 52; w++) {
+ const weekStart = new Date(yearStart.getTime() + w * MS_PER_WEEK);
+ const weekEnd = new Date(weekStart.getTime() + MS_PER_WEEK);
+
+ let status;
+ if (weekEnd <= now) {
+ status = 's'; // spent
+ } else if (weekStart <= now && now < weekEnd) {
+ status = 'c'; // current
+ } else if (weekStart > death) {
+ status = null; // beyond death date
+ } else {
+ status = 'r'; // remaining
+ }
+
+ if (status) weeks.push(status);
+ }
+
+ rows.push({ age: yearAge, weeks });
+ }
+
+ return rows;
+}
+
+// === Activity Budgets ===
+
+/**
+ * Compute remaining count for each activity based on cadence and time remaining
+ */
+export function computeActivityBudgets(deathDate, activities) {
+ const now = new Date();
+ const death = new Date(deathDate);
+
+ if (death <= now) return [];
+
+ const daysRemaining = (death.getTime() - now.getTime()) / MS_PER_DAY;
+
+ return activities.map(activity => {
+ const { name, cadence, frequency, icon } = activity;
+
+ let remaining;
+ switch (cadence) {
+ case 'day':
+ remaining = Math.floor(daysRemaining * frequency);
+ break;
+ case 'week':
+ remaining = Math.floor((daysRemaining / 7) * frequency);
+ break;
+ case 'month':
+ remaining = Math.floor((daysRemaining / 30.44) * frequency);
+ break;
+ case 'year':
+ remaining = Math.floor((daysRemaining / 365.25) * frequency);
+ break;
+ default:
+ remaining = 0;
+ }
+
+ return { name, cadence, frequency, icon, remaining };
+ });
+}
+
+// === File I/O ===
+
+async function loadActivities() {
+ return readJSONFile(ACTIVITIES_FILE, { activities: [] });
+}
+
+async function saveActivities(data) {
+ await ensureDir(MEATSPACE_DIR);
+ await writeFile(ACTIVITIES_FILE, JSON.stringify(data, null, 2));
+}
+
+// === Default Activities ===
+
+const DEFAULT_ACTIVITIES = [
+ { name: 'Coffees', cadence: 'day', frequency: 2, icon: 'coffee' },
+ { name: 'Showers', cadence: 'day', frequency: 1, icon: 'droplets' },
+ { name: 'Meals', cadence: 'day', frequency: 3, icon: 'utensils' },
+ { name: 'Workouts', cadence: 'week', frequency: 4, icon: 'dumbbell' },
+ { name: 'Books', cadence: 'month', frequency: 1, icon: 'book-open' },
+ { name: 'Haircuts', cadence: 'month', frequency: 1, icon: 'scissors' },
+ { name: 'Birthdays', cadence: 'year', frequency: 1, icon: 'cake' },
+ { name: 'Vacations', cadence: 'year', frequency: 2, icon: 'plane' },
+];
+
+// === Exported Service Functions ===
+
+export async function getCalendarData() {
+ const deathClock = await getDeathClock();
+ if (deathClock.error) {
+ return { error: deathClock.error };
+ }
+
+ const { birthDate, deathDate, lifeExpectancy } = deathClock;
+ const sleepHours = lifeExpectancy?.lifestyleAdjustment != null ? 7.5 : 7.5; // Could read from config
+
+ const stats = computeTimeStats(birthDate, deathDate, sleepHours);
+ const grid = computeLifeGrid(birthDate, deathDate);
+
+ // Load activities
+ const data = await loadActivities();
+ const activities = data.activities.length > 0 ? data.activities : DEFAULT_ACTIVITIES;
+ const budgets = computeActivityBudgets(deathDate, activities);
+
+ return {
+ birthDate,
+ deathDate,
+ lifeExpectancy: lifeExpectancy?.total,
+ stats,
+ grid,
+ budgets,
+ activitiesConfigured: data.activities.length > 0,
+ };
+}
+
+export async function getActivities() {
+ const data = await loadActivities();
+ return data.activities.length > 0 ? data.activities : DEFAULT_ACTIVITIES;
+}
+
+export async function addActivity(activity) {
+ const data = await loadActivities();
+ // If using defaults, seed with defaults first
+ if (data.activities.length === 0) {
+ data.activities = [...DEFAULT_ACTIVITIES];
+ }
+ data.activities.push(activity);
+ await saveActivities(data);
+ return data.activities;
+}
+
+export async function updateActivity(index, updates) {
+ const data = await loadActivities();
+ if (data.activities.length === 0) {
+ data.activities = [...DEFAULT_ACTIVITIES];
+ }
+ if (index < 0 || index >= data.activities.length) {
+ return null;
+ }
+ data.activities[index] = { ...data.activities[index], ...updates };
+ await saveActivities(data);
+ return data.activities;
+}
+
+export async function removeActivity(index) {
+ const data = await loadActivities();
+ if (data.activities.length === 0) {
+ data.activities = [...DEFAULT_ACTIVITIES];
+ }
+ if (index < 0 || index >= data.activities.length) {
+ return null;
+ }
+ data.activities.splice(index, 1);
+ await saveActivities(data);
+ return data.activities;
+}