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([issue-2150]): human activity store + timeline service + /timeline page

Adam Eivyf23a6994bd84
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index a43404b1cc..95a4e1e645 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,9 @@
# Unreleased Changes
+## Human Activity Tracking
+
+- **[issue-2150] Activity timeline** — a new `/timeline` page shows a unified, day-by-day view of your activity (emails sent/received and calendar events, with more sources coming), backed by a machine-local `human_activity_events` store that your existing message and calendar syncs populate automatically. Pick any day (deep-linkable via `/timeline/:date`), see an hourly activity histogram and per-source tallies, and browse the day's events. Only metadata and a short summary line are stored — full message bodies stay in their per-source caches — and the timeline is machine-local (never federated to peers), like Tribe.
+
## Songs
- **[issue-2109] The live vocal Tuner now locks onto the note you're singing instead of flickering.** Holding a steady note used to make the readout strobe — the note label flipped between neighbors, the needle lurched, and the display dropped to "—" on every breath or consonant. The tuner now holds a stable reading through brief dropouts (dimming while it coasts), only blanks after a real pause, keeps one note label while your pitch wanders up to ~60¢ around it, and re-locks promptly when you actually change notes — so a held note shows one label with a gently moving needle.
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 7c2547aae2..ef86af78c0 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -31,6 +31,7 @@ const FeatureAgentDetail = lazyWithReload(() => import('./pages/FeatureAgentDeta
const CalendarPage = lazyWithReload(() => import('./pages/Calendar'));
const Messages = lazyWithReload(() => import('./pages/Messages'));
const Tribe = lazyWithReload(() => import('./pages/Tribe'));
+const Timeline = lazyWithReload(() => import('./pages/Timeline'));
const Goals = lazyWithReload(() => import('./pages/Goals'));
const OpenClawPage = lazyWithReload(() => import('./pages/OpenClaw'));
const Submodules = lazyWithReload(() => import('./pages/Submodules'));
@@ -258,6 +259,8 @@ export default function App() {
<Route path="messages" element={<Navigate to="/messages/inbox" replace />} />
<Route path="messages/:tab" element={<Messages />} />
<Route path="tribe" element={<Tribe />} />
+ <Route path="timeline" element={<Timeline />} />
+ <Route path="timeline/:date" element={<Timeline />} />
<Route path="openclaw" element={<OpenClawPage />} />
<Route path="datadog" element={<Navigate to="/devtools/datadog" replace />} />
<Route path="jira" element={<Navigate to="/devtools/jira" replace />} />
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index 866423b445..d206cd9209 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -38,6 +38,7 @@ import {
GraduationCap,
Settings,
Users,
+ CalendarClock,
Upload,
SquareTerminal,
Globe,
@@ -152,6 +153,7 @@ const navItems = [
{ to: '/brain/notes', label: 'Notes', icon: FileText },
{ to: '/openclaw', label: 'OpenClaw', icon: MessagesSquare },
{ to: '/rapid-reader', label: 'Rapid Reader', icon: Zap },
+ { to: '/timeline', label: 'Timeline', icon: CalendarClock },
{ to: '/tribe', label: 'Tribe', icon: Users },
{ to: '/brain/trust', label: 'Trust', icon: Shield },
{ to: '/wiki/overview', label: 'Wiki', icon: BookOpen },
diff --git a/client/src/pages/Timeline.jsx b/client/src/pages/Timeline.jsx
new file mode 100644
index 0000000000..5b34f9929e
--- /dev/null
+++ b/client/src/pages/Timeline.jsx
@@ -0,0 +1,215 @@
+import { useState, useEffect, useMemo } from 'react';
+import { useParams, useNavigate } from 'react-router-dom';
+import {
+ CalendarClock, ChevronLeft, ChevronRight, Mail, MailOpen, Send,
+ CalendarDays, Music, Play, MessageSquare, Activity,
+} from 'lucide-react';
+import PageHeader from '../components/PageHeader';
+import * as api from '../services/api';
+import toast from '../components/ui/Toast';
+import { formatClockTime, formatDurationSec } from '../utils/formatters';
+
+// Local (browser-tz) YYYY-MM-DD for a Date — matches the server's local-day math
+// closely enough for defaulting the URL; the server is the source of truth for
+// which UTC instants fall in the day it returns.
+function localDateStr(d) {
+ const y = d.getFullYear();
+ const m = String(d.getMonth() + 1).padStart(2, '0');
+ const day = String(d.getDate()).padStart(2, '0');
+ return `${y}-${m}-${day}`;
+}
+
+function shiftDate(dateStr, days) {
+ const [y, m, d] = dateStr.split('-').map(Number);
+ const dt = new Date(y, m - 1, d);
+ dt.setDate(dt.getDate() + days);
+ return localDateStr(dt);
+}
+
+const SOURCE_ICON = {
+ gmail: Mail,
+ outlook: Mail,
+ teams: MessageSquare,
+ imap: Mail,
+ calendar: CalendarDays,
+ imessage: MessageSquare,
+ signal: MessageSquare,
+ spotify: Music,
+ youtube: Play,
+};
+
+function kindIcon(kind, source) {
+ if (kind === 'message.sent') return Send;
+ if (kind === 'message.received') return MailOpen;
+ if (kind === 'calendar.event') return CalendarDays;
+ return SOURCE_ICON[source] || Activity;
+}
+
+function KindBadge({ kind }) {
+ const label = kind === 'message.sent' ? 'Sent'
+ : kind === 'message.received' ? 'Received'
+ : kind === 'calendar.event' ? 'Event'
+ : kind;
+ return (
+ <span className="rounded bg-port-bg px-1.5 py-0.5 text-[10px] uppercase tracking-wide text-gray-400">
+ {label}
+ </span>
+ );
+}
+
+function Histogram({ histogram }) {
+ const max = useMemo(() => Math.max(1, ...histogram.map((h) => h.count)), [histogram]);
+ return (
+ <div className="rounded border border-port-border bg-port-card p-3">
+ <div className="mb-2 text-xs font-medium text-gray-400">Activity by hour</div>
+ <div className="flex items-end gap-[2px]" style={{ height: 64 }} role="img" aria-label="Hourly activity histogram">
+ {histogram.map((h) => (
+ <div key={h.hour} className="flex flex-1 flex-col items-center justify-end" title={`${h.hour}:00 — ${h.count} event(s)`}>
+ <div
+ className={`w-full rounded-t ${h.count ? 'bg-port-accent' : 'bg-port-border'}`}
+ style={{ height: `${Math.max(2, (h.count / max) * 56)}px` }}
+ />
+ </div>
+ ))}
+ </div>
+ <div className="mt-1 flex justify-between text-[10px] text-gray-500">
+ <span>12a</span><span>6a</span><span>12p</span><span>6p</span><span>11p</span>
+ </div>
+ </div>
+ );
+}
+
+function EventRow({ event }) {
+ const Icon = kindIcon(event.kind, event.source);
+ const when = new Date(event.happenedAt);
+ const participants = (event.participants || [])
+ .map((p) => p.name || p.email || p.phone)
+ .filter(Boolean)
+ .slice(0, 4)
+ .join(', ');
+ return (
+ <div className="flex gap-3 rounded border border-port-border bg-port-card p-3 min-w-0">
+ <div className="flex flex-col items-center pt-0.5">
+ <Icon size={16} className="text-port-accent" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="font-mono text-xs text-gray-500">{formatClockTime(when)}</span>
+ <KindBadge kind={event.kind} />
+ <span className="text-[10px] uppercase tracking-wide text-gray-500">{event.source}</span>
+ {Number.isFinite(event.durationS) && event.durationS > 0 && (
+ <span className="text-[10px] text-gray-500">{formatDurationSec(event.durationS)}</span>
+ )}
+ </div>
+ <div className="mt-1 truncate font-medium text-gray-100">{event.title || '(untitled)'}</div>
+ {event.summary && <div className="mt-0.5 truncate text-sm text-gray-400">{event.summary}</div>}
+ {participants && <div className="mt-0.5 truncate text-xs text-gray-500">{participants}</div>}
+ </div>
+ </div>
+ );
+}
+
+export default function Timeline() {
+ const { date: dateParam } = useParams();
+ const navigate = useNavigate();
+ const today = localDateStr(new Date());
+ const date = /^\d{4}-\d{2}-\d{2}$/.test(dateParam || '') ? dateParam : today;
+
+ const [day, setDay] = useState(null);
+ const [loading, setLoading] = useState(true);
+
+ useEffect(() => {
+ let active = true;
+ setLoading(true);
+ api.getTimelineDay({ date, silent: true })
+ .then((result) => { if (active) setDay(result); })
+ .catch((err) => { if (active) { setDay(null); toast.error(`Failed to load timeline: ${err.message}`); } })
+ .finally(() => { if (active) setLoading(false); });
+ return () => { active = false; };
+ }, [date]);
+
+ const goto = (target) => navigate(target === today ? '/timeline' : `/timeline/${target}`);
+
+ const events = day?.events || [];
+ const counts = day?.counts || { total: 0, bySource: {}, byKind: {} };
+ const histogram = day?.histogram || Array.from({ length: 24 }, (_, hour) => ({ hour, count: 0 }));
+
+ const dayLabel = useMemo(() => {
+ const [y, m, d] = date.split('-').map(Number);
+ return new Date(y, m - 1, d).toLocaleDateString([], { weekday: 'long', month: 'short', day: 'numeric', year: 'numeric' });
+ }, [date]);
+
+ return (
+ <div className="mx-auto flex max-w-4xl flex-col gap-4">
+ <PageHeader
+ icon={CalendarClock}
+ title="Timeline"
+ subtitle="Your unified activity across messages, calendar, and more."
+ />
+
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => goto(shiftDate(date, -1))}
+ className="rounded border border-port-border bg-port-card p-2 hover:border-port-accent"
+ aria-label="Previous day"
+ >
+ <ChevronLeft size={16} />
+ </button>
+ <input
+ type="date"
+ value={date}
+ max={today}
+ onChange={(e) => e.target.value && goto(e.target.value)}
+ className="rounded border border-port-border bg-port-card px-2 py-1.5 text-sm text-gray-100"
+ aria-label="Select day"
+ />
+ <button
+ type="button"
+ onClick={() => goto(shiftDate(date, 1))}
+ disabled={date >= today}
+ className="rounded border border-port-border bg-port-card p-2 hover:border-port-accent disabled:cursor-not-allowed disabled:opacity-40"
+ aria-label="Next day"
+ >
+ <ChevronRight size={16} />
+ </button>
+ {date !== today && (
+ <button
+ type="button"
+ onClick={() => goto(today)}
+ className="rounded border border-port-border bg-port-card px-3 py-1.5 text-sm hover:border-port-accent"
+ >
+ Today
+ </button>
+ )}
+ </div>
+ <div className="text-sm text-gray-400">{dayLabel}</div>
+ </div>
+
+ <Histogram histogram={histogram} />
+
+ <div className="flex flex-wrap gap-2 text-xs text-gray-400">
+ <span className="rounded bg-port-card px-2 py-1 border border-port-border">{counts.total} events</span>
+ {Object.entries(counts.bySource).map(([source, n]) => (
+ <span key={source} className="rounded bg-port-card px-2 py-1 border border-port-border">
+ {source}: {n}
+ </span>
+ ))}
+ </div>
+
+ {loading ? (
+ <div className="py-12 text-center text-gray-500">Loading…</div>
+ ) : events.length === 0 ? (
+ <div className="rounded border border-dashed border-port-border py-12 text-center text-gray-500">
+ No recorded activity on this day.
+ <div className="mt-1 text-xs">Activity populates as your message and calendar accounts sync.</div>
+ </div>
+ ) : (
+ <div className="flex flex-col gap-2 pb-6">
+ {events.map((event) => <EventRow key={event.id} event={event} />)}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/services/api.js b/client/src/services/api.js
index e62840c8fa..b517b6b6c6 100644
--- a/client/src/services/api.js
+++ b/client/src/services/api.js
@@ -34,6 +34,7 @@ export * from './apiGithub.js';
export * from './apiLoops.js';
export * from './apiMemory.js';
export * from './apiTribe.js';
+export * from './apiTimeline.js';
export * from './apiBrain.js';
export * from './apiNotes.js';
export * from './apiDigitalTwin.js';
diff --git a/client/src/services/apiTimeline.js b/client/src/services/apiTimeline.js
new file mode 100644
index 0000000000..f4087de4fd
--- /dev/null
+++ b/client/src/services/apiTimeline.js
@@ -0,0 +1,22 @@
+import { request } from './apiCore.js';
+
+// Human-activity timeline (#2150). Day view + filtered event list.
+
+export const getTimelineDay = (options = {}) => {
+ const params = new URLSearchParams();
+ if (options.date) params.set('date', options.date);
+ const qs = params.toString();
+ return request(`/timeline/day${qs ? `?${qs}` : ''}`, { silent: options.silent });
+};
+
+export const getTimelineEvents = (options = {}) => {
+ const params = new URLSearchParams();
+ if (options.from) params.set('from', options.from);
+ if (options.to) params.set('to', options.to);
+ if (options.source) params.set('source', options.source);
+ if (options.kind) params.set('kind', options.kind);
+ if (options.personId) params.set('personId', options.personId);
+ if (options.limit) params.set('limit', String(options.limit));
+ const qs = params.toString();
+ return request(`/timeline/events${qs ? `?${qs}` : ''}`, { silent: options.silent });
+};
diff --git a/scripts/migrations/160-human-activity-events-table.js b/scripts/migrations/160-human-activity-events-table.js
new file mode 100644
index 0000000000..c051ca4810
--- /dev/null
+++ b/scripts/migrations/160-human-activity-events-table.js
@@ -0,0 +1,26 @@
+/**
+ * Registration stub for the human_activity_events table (issue #2150).
+ *
+ * The actual DDL — `CREATE TABLE IF NOT EXISTS human_activity_events` plus its
+ * `idx_human_activity_dedupe` unique index and `idx_human_activity_happened`
+ * index — is idempotent and lives in `ensureSchema()` (`server/lib/db.js`) and
+ * the fresh-install seed (`server/scripts/init-db.sql`), both of which run at
+ * server boot AFTER the DB pool is up. The `scripts/migrations/` runner executes
+ * BEFORE the pool is initialized, so a DB-table create cannot live here — the
+ * same reason migrations 048–052 and 108 are boot-time + stub-registered.
+ *
+ * This stub exists so the new-table change is *registered the standard way*: it
+ * lands in `data/migrations.applied.json` so the migration ledger and `git log`
+ * show when the human_activity_events table was introduced. The table is
+ * additive (a brand-new, machine-local db-primary store), so there is no data
+ * backfill — the humanActivity service and the message/calendar sync hooks
+ * populate it lazily on the next sync.
+ *
+ * No-op + idempotent: nothing to do here.
+ */
+
+export default {
+ async up() {
+ console.log('🗓️ human_activity_events: table created idempotently by ensureSchema at boot; nothing to do in the file runner');
+ },
+};
diff --git a/server/index.js b/server/index.js
index d3b74a68ed..53d2e90bf7 100644
--- a/server/index.js
+++ b/server/index.js
@@ -47,6 +47,7 @@ import gsdRoutes from './routes/gsd.js';
import catalogRoutes from './routes/catalog.js';
import memoryRoutes from './routes/memory.js';
import tribeRoutes from './routes/tribe.js';
+import timelineRoutes from './routes/timeline.js';
import notificationsRoutes from './routes/notifications.js';
import standardizeRoutes from './routes/standardize.js';
import brainRoutes from './routes/brain.js';
@@ -470,6 +471,7 @@ app.use('/api/feeds', feedsRoutes);
app.use('/api/catalog', catalogRoutes);
app.use('/api/memory', memoryRoutes);
app.use('/api/tribe', tribeRoutes);
+app.use('/api/timeline', timelineRoutes);
app.use('/api/notifications', notificationsRoutes);
app.use('/api/standardize', standardizeRoutes);
app.use('/api/brain/import', brainImportRoutes);
diff --git a/server/lib/db.js b/server/lib/db.js
index 531a4c081a..4b5b35869d 100644
--- a/server/lib/db.js
+++ b/server/lib/db.js
@@ -406,6 +406,29 @@ async function ensureSchemaImpl() {
PRIMARY KEY (person_id, memory_id)
)`,
`CREATE INDEX IF NOT EXISTS idx_tribe_memory_links_memory ON tribe_memory_links (memory_id)`,
+ // Human activity timeline (#2150) — unified, machine-local event store fed by
+ // message/calendar syncs (later: iMessage, Spotify, YouTube, Signal). Stores
+ // metadata + a short summary only; full bodies stay in per-source caches, with
+ // metadata pointers (threadId/externalId) back to the source. Idempotent via the
+ // unique (source, dedupe_key) index + ON CONFLICT DO NOTHING. Machine-local like
+ // Tribe (ADR 2026-06-26) — excluded from peer sync, guarded in peerSync.test.js.
+ `CREATE TABLE IF NOT EXISTS human_activity_events (
+ id TEXT PRIMARY KEY,
+ source TEXT NOT NULL,
+ account_id TEXT,
+ kind TEXT NOT NULL,
+ happened_at TIMESTAMPTZ NOT NULL,
+ duration_s INTEGER,
+ title TEXT,
+ summary TEXT,
+ url TEXT,
+ participants JSONB DEFAULT '[]'::jsonb,
+ metadata JSONB DEFAULT '{}'::jsonb,
+ dedupe_key TEXT NOT NULL,
+ created_at TIMESTAMPTZ DEFAULT NOW()
+ )`,
+ `CREATE UNIQUE INDEX IF NOT EXISTS idx_human_activity_dedupe ON human_activity_events (source, dedupe_key)`,
+ `CREATE INDEX IF NOT EXISTS idx_human_activity_happened ON human_activity_events (happened_at)`,
];
for (const sql of upgrades) {
await pool.query(sql);
diff --git a/server/lib/navManifest.js b/server/lib/navManifest.js
index 784f63b72f..11c7d14e60 100644
--- a/server/lib/navManifest.js
+++ b/server/lib/navManifest.js
@@ -98,6 +98,7 @@ export const NAV_COMMANDS = [
{ id: 'nav.messages.config', path: '/messages/config', label: 'Config', section: 'Comms', aliases: ['messages-config', 'comms-config'], keywords: ['comms'] },
{ id: 'nav.messages.sync', path: '/messages/sync', label: 'Sync', section: 'Comms', aliases: ['messages-sync', 'comms-sync'], keywords: ['comms'] },
{ id: 'nav.openclaw', path: '/openclaw', label: 'OpenClaw', section: 'Brain', aliases: ['openclaw'] },
+ { id: 'nav.timeline', path: '/timeline', label: 'Timeline', section: 'Brain', aliases: ['activity-timeline', 'activity', 'my-day', 'life-log', 'life-timeline'], keywords: ['human activity', 'life log', 'timeline', 'messages', 'calendar', 'history', 'what did i do', 'daily'] },
{ id: 'nav.tribe', path: '/tribe', label: 'Tribe', section: 'Brain', aliases: ['tribe', 'relationships', 'relationship-manager', 'people'], keywords: ['dunbar', 'friends', 'family', 'network', 'social graph', 'care cadence'] },
{ id: 'nav.devtools.runs', path: '/devtools/runs', label: 'AI Runs', section: 'Dev Tools', aliases: ['ai-runs', 'devtools'] },
diff --git a/server/routes/timeline.js b/server/routes/timeline.js
new file mode 100644
index 0000000000..ace3507a29
--- /dev/null
+++ b/server/routes/timeline.js
@@ -0,0 +1,39 @@
+import { Router } from 'express';
+import { z } from 'zod';
+
+import { asyncHandler } from '../lib/errorHandler.js';
+import { validateRequest } from '../lib/validation.js';
+import * as humanActivity from '../services/humanActivity.js';
+
+const router = Router();
+
+const dayQuerySchema = z.object({
+ date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
+});
+
+const eventsQuerySchema = z.object({
+ from: z.string().datetime().optional(),
+ to: z.string().datetime().optional(),
+ source: z.string().max(64).optional(),
+ kind: z.string().max(64).optional(),
+ personId: z.string().max(200).optional(),
+ limit: z.coerce.number().int().min(1).max(2000).optional(),
+});
+
+// Day view — all activity on a local calendar day plus an hourly histogram and
+// source/kind tallies. `date` (YYYY-MM-DD) defaults to today in the user's tz;
+// the URL is the source of truth for the selected day on the /timeline page.
+router.get('/day', asyncHandler(async (req, res) => {
+ const { date } = validateRequest(dayQuerySchema, req.query);
+ const summary = await humanActivity.getDaySummary({ date });
+ res.json(summary);
+}));
+
+// Filtered raw event list (from/to/source/kind/personId). Newest first.
+router.get('/events', asyncHandler(async (req, res) => {
+ const filters = validateRequest(eventsQuerySchema, req.query);
+ const events = await humanActivity.listEvents(filters);
+ res.json({ events });
+}));
+
+export default router;
diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sql
index 30ca95a9ed..bb84aa1885 100644
--- a/server/scripts/init-db.sql
+++ b/server/scripts/init-db.sql
@@ -131,6 +131,29 @@ CREATE TABLE IF NOT EXISTS tribe_memory_links (
);
CREATE INDEX IF NOT EXISTS idx_tribe_memory_links_memory ON tribe_memory_links (memory_id);
+-- Human activity timeline (#2150) — unified, machine-local event store fed by
+-- message/calendar syncs (later: iMessage, Spotify, YouTube, Signal). Metadata +
+-- short summary only; full bodies stay in per-source caches. Idempotent via the
+-- unique (source, dedupe_key) index + ON CONFLICT DO NOTHING. Machine-local like
+-- Tribe (ADR 2026-06-26-tribe-and-universe-runs-local.md) — excluded from peer sync.
+CREATE TABLE IF NOT EXISTS human_activity_events (
+ id TEXT PRIMARY KEY,
+ source TEXT NOT NULL,
+ account_id TEXT,
+ kind TEXT NOT NULL,
+ happened_at TIMESTAMPTZ NOT NULL,
+ duration_s INTEGER,
+ title TEXT,
+ summary TEXT,
+ url TEXT,
+ participants JSONB DEFAULT '[]'::jsonb,
+ metadata JSONB DEFAULT '{}'::jsonb,
+ dedupe_key TEXT NOT NULL,
+ created_at TIMESTAMPTZ DEFAULT NOW()
+);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_human_activity_dedupe ON human_activity_events (source, dedupe_key);
+CREATE INDEX IF NOT EXISTS idx_human_activity_happened ON human_activity_events (happened_at);
+
-- Auto-update updated_at and sync_sequence on content/metadata changes.
-- Skips bump for access-stat-only updates (access_count, last_accessed)
-- to avoid sync noise from read operations.
diff --git a/server/services/calendarSync.js b/server/services/calendarSync.js
index b9c62ce762..d9c504c284 100644
--- a/server/services/calendarSync.js
+++ b/server/services/calendarSync.js
@@ -217,6 +217,11 @@ export async function syncAccount(accountId, io, options = {}) {
await logCalendarTouchpoints(accountId, newEvents).catch((err) =>
console.error(`🤝 Tribe auto-log failed for account ${accountId}: ${err.message}`));
+ // Populate the human-activity timeline (#2150) — secondary effect, must NOT
+ // fail the sync. Idempotent on (source, dedupe_key). Machine-local.
+ await recordCalendarActivity(account, newEvents).catch((err) =>
+ console.error(`🗓️ Activity ingest failed for account ${accountId}: ${err.message}`));
+
io?.emit('calendar:sync:completed', { accountId, newEvents: uniqueNew.length, pruned, status: providerStatus });
console.log(`📅 Sync complete for ${account.name}: ${uniqueNew.length} new, ${pruned} pruned, status=${providerStatus}`);
@@ -293,3 +298,14 @@ export async function logCalendarTouchpoints(accountId, events = []) {
}
return result;
}
+
+// Record synced calendar events into the machine-local human-activity timeline
+// (#2150). Only finished, non-declined/cancelled events count as activity.
+// Idempotent (dedupe on source + event id). humanActivity is imported
+// dynamically to keep this hook lazy (mirrors the tribe auto-log path).
+export async function recordCalendarActivity(account, events = []) {
+ const { calendarActivityCandidates, recordEvents } = await import('./humanActivity.js');
+ const candidates = calendarActivityCandidates(account, events);
+ if (candidates.length === 0) return { recorded: 0, skipped: 0 };
+ return recordEvents(candidates);
+}
diff --git a/server/services/humanActivity.db.test.js b/server/services/humanActivity.db.test.js
new file mode 100644
index 0000000000..16e4cc5c01
--- /dev/null
+++ b/server/services/humanActivity.db.test.js
@@ -0,0 +1,128 @@
+/**
+ * Postgres-backed tests for the human-activity timeline store (#2150):
+ * - recordEvents() — idempotent insert via ON CONFLICT (source, dedupe_key)
+ * - listEvents() — range / source / kind / personId filters
+ * - getDaySummary() — local-day window + hourly histogram + tallies
+ *
+ * `*.db.test.js` → runs ONLY via `npm run test:db` against `portos_test`, never
+ * the real `portos` DB (the db.js runner guard + the suite skip below enforce
+ * this). The DB is shared across worktrees, so every row created here uses a
+ * per-run nonce and is torn down in afterAll; assertions are relative to the
+ * rows this suite inserts.
+ */
+import { describe, it, expect, afterAll } from 'vitest';
+import { checkHealth, ensureSchema, close, query } from '../lib/db.js';
+import { recordEvents, listEvents, getDaySummary } from './humanActivity.js';
+
+let dbReady = false;
+let skipReason = '';
+{
+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));
+ if (!health.connected) {
+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;
+ } else {
+ await ensureSchema().catch(() => {});
+ dbReady = true;
+ }
+}
+if (!dbReady) console.log(`⏭️ humanActivity.db.test: skipping suite — ${skipReason || 'no database'}`);
+
+const nonce = `ha${Date.now()}`;
+const SOURCE = `test-${nonce}`;
+const PERSON = `person-${nonce}`;
+
+afterAll(async () => {
+ if (dbReady) {
+ await query('DELETE FROM human_activity_events WHERE source = $1', [SOURCE]).catch(() => {});
+ await close();
+ }
+});
+
+const mk = (over = {}) => ({
+ source: SOURCE,
+ kind: 'message.received',
+ happenedAt: '2026-07-04T15:00:00Z',
+ dedupeKey: `k-${Math.random().toString(36).slice(2)}`,
+ title: 'Test event',
+ ...over,
+});
+
+describe.skipIf(!dbReady)('humanActivity store (#2150)', () => {
+ it('records events and is idempotent on (source, dedupe_key)', async () => {
+ const cands = [
+ mk({ dedupeKey: 'dup-1', title: 'First' }),
+ mk({ dedupeKey: 'dup-2', title: 'Second' }),
+ ];
+ const first = await recordEvents(cands);
+ expect(first.recorded).toBe(2);
+
+ // Re-recording the exact same candidates is a no-op.
+ const second = await recordEvents(cands);
+ expect(second.recorded).toBe(0);
+ expect(second.skipped).toBe(2);
+
+ // A batch mixing a new + a duplicate records only the new one.
+ const mixed = await recordEvents([mk({ dedupeKey: 'dup-1' }), mk({ dedupeKey: 'dup-3' })]);
+ expect(mixed.recorded).toBe(1);
+ });
+
+ it('drops candidates that fail normalization (no double-count)', async () => {
+ const res = await recordEvents([mk({ dedupeKey: 'valid-1' }), { source: SOURCE /* missing kind/happenedAt/dedupeKey */ }]);
+ expect(res.recorded).toBe(1);
+ expect(res.skipped).toBe(1);
+ });
+
+ it('filters by source, kind, and time range', async () => {
+ await recordEvents([
+ mk({ dedupeKey: 'f-1', kind: 'message.sent', happenedAt: '2026-07-04T09:00:00Z' }),
+ mk({ dedupeKey: 'f-2', kind: 'calendar.event', happenedAt: '2026-07-04T18:00:00Z' }),
+ ]);
+ const bySource = await listEvents({ source: SOURCE, limit: 500 });
+ expect(bySource.every((e) => e.source === SOURCE)).toBe(true);
+
+ const byKind = await listEvents({ source: SOURCE, kind: 'calendar.event' });
+ expect(byKind.every((e) => e.kind === 'calendar.event')).toBe(true);
+ expect(byKind.some((e) => e.dedupeKey === 'f-2')).toBe(true);
+
+ const inRange = await listEvents({
+ source: SOURCE,
+ from: '2026-07-04T17:00:00Z',
+ to: '2026-07-04T19:00:00Z',
+ });
+ expect(inRange.some((e) => e.dedupeKey === 'f-2')).toBe(true);
+ expect(inRange.some((e) => e.dedupeKey === 'f-1')).toBe(false);
+ });
+
+ it('matches a participant by personId via JSONB containment', async () => {
+ await recordEvents([mk({
+ dedupeKey: 'p-1',
+ participants: [{ name: 'Pat', email: '[email protected]', personId: PERSON }],
+ })]);
+ const hits = await listEvents({ source: SOURCE, personId: PERSON });
+ expect(hits.some((e) => e.dedupeKey === 'p-1')).toBe(true);
+ const miss = await listEvents({ source: SOURCE, personId: `${PERSON}-nope` });
+ expect(miss.some((e) => e.dedupeKey === 'p-1')).toBe(false);
+ });
+
+ it('round-trips participants and metadata as JSON', async () => {
+ await recordEvents([mk({
+ dedupeKey: 'json-1',
+ participants: [{ email: '[email protected]' }],
+ metadata: { threadId: 't-9', externalId: 'x-9' },
+ })]);
+ const [row] = await listEvents({ source: SOURCE, kind: 'message.received', limit: 500 })
+ .then((rows) => rows.filter((r) => r.dedupeKey === 'json-1'));
+ expect(row.participants).toEqual([{ email: '[email protected]' }]);
+ expect(row.metadata).toEqual({ threadId: 't-9', externalId: 'x-9' });
+ });
+
+ it('getDaySummary returns events, a 24-slot histogram, and tallies', async () => {
+ // Use a source-scoped fetch to keep the assertion independent of other rows,
+ // then sanity-check the summary shape for the same day.
+ const summary = await getDaySummary({ date: '2026-07-04' });
+ expect(summary.date).toBe('2026-07-04');
+ expect(summary.histogram).toHaveLength(24);
+ expect(typeof summary.counts.total).toBe('number');
+ expect(summary.counts.bySource).toBeTruthy();
+ });
+});
diff --git a/server/services/humanActivity.js b/server/services/humanActivity.js
new file mode 100644
index 0000000000..eb0146cc21
--- /dev/null
+++ b/server/services/humanActivity.js
@@ -0,0 +1,353 @@
+/**
+ * Human Activity timeline (#2150) — unified, machine-local event store.
+ *
+ * All ingestion sources (message/calendar syncs today; iMessage, Spotify,
+ * YouTube, Signal in later phases) write normalized events into the
+ * `human_activity_events` Postgres table via `recordEvents()`. The store is:
+ *
+ * - **Idempotent.** Every event carries a stable `dedupeKey`; the unique
+ * `(source, dedupe_key)` index + `ON CONFLICT DO NOTHING` make re-syncs no-ops.
+ * Same contract as `tribe_touchpoints.dedupe_key`.
+ * - **Privacy-preserving.** Events store metadata + a SHORT summary line only —
+ * full message bodies stay in the per-source caches (`data/messages/cache/`,
+ * chat.db, …). `metadata` carries pointers (threadId / externalId / account) back
+ * to the source so a consumer can rehydrate the full body on demand.
+ * - **Machine-local.** Coupled to per-machine accounts and OS databases; NOT
+ * federated (ADR docs/decisions/2026-06-26-tribe-and-universe-runs-local.md,
+ * guarded in sharing/peerSync.test.js). Derived summaries federate via existing
+ * rails (Brain journals, digital-twin), not the raw events.
+ *
+ * Ingestion is LLM-free and deterministic; identity matching reuses the tribe
+ * email/handle index. No AI-provider calls happen here.
+ */
+import { v4 as uuidv4 } from '../lib/uuid.js';
+import { ensureSchema, query } from '../lib/db.js';
+import { getUserTimezone, getLocalParts, getUtcOffsetMs, todayInTimezone } from '../lib/timezone.js';
+
+// ---------------------------------------------------------------------------
+// Pure helpers (exported for unit tests — no DB, no side effects).
+// ---------------------------------------------------------------------------
+
+// Collapse whitespace and clamp to a short single line. Guards the privacy
+// contract: we keep a preview, never the full body.
+export function shortSummary(text, max = 160) {
+ if (!text) return '';
+ const line = String(text).replace(/\s+/g, ' ').trim();
+ if (line.length <= max) return line;
+ return `${line.slice(0, max - 1).trimEnd()}…`;
+}
+
+// A stable local-day key (YYYY-MM-DD) for a timestamp in the user's timezone.
+// Using the UTC day would split one local evening across two days whenever an
+// event straddles UTC midnight (common in the Americas).
+export function localDayKey(when, timezone) {
+ const d = new Date(when);
+ if (Number.isNaN(d.getTime())) return null;
+ const p = getLocalParts(d, timezone);
+ return `${p.year}-${String(p.month).padStart(2, '0')}-${String(p.day).padStart(2, '0')}`;
+}
+
+// UTC [start, end) instants that bound a local calendar day (YYYY-MM-DD) in the
+// given timezone. Offset is sampled at local midnight; a DST transition mid-day
+// shifts the far boundary by ≤1h, which is acceptable for day bucketing.
+export function localDayRangeUtc(dateStr, timezone) {
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(dateStr || '').trim());
+ if (!m) return null;
+ const [, y, mo, d] = m.map(Number);
+ const approxUtc = new Date(Date.UTC(y, mo - 1, d, 0, 0, 0));
+ const offset = getUtcOffsetMs(approxUtc, timezone);
+ const start = new Date(approxUtc.getTime() - offset);
+ const end = new Date(start.getTime() + 24 * 60 * 60 * 1000);
+ return { start, end };
+}
+
+// Normalize a participant to { name, email, phone, personId } — trimmed, empty
+// fields dropped. Accepts a bare email string or a { name, email, phone } object.
+export function normalizeParticipant(p) {
+ if (!p) return null;
+ const raw = typeof p === 'string' ? { email: p } : p;
+ const out = {};
+ if (raw.name) out.name = String(raw.name).trim();
+ if (raw.email) out.email = String(raw.email).trim().toLowerCase();
+ if (raw.phone) out.phone = String(raw.phone).trim();
+ if (raw.personId) out.personId = String(raw.personId);
+ return out.name || out.email || out.phone || out.personId ? out : null;
+}
+
+export function normalizeParticipants(list) {
+ if (!Array.isArray(list)) return [];
+ return list.map(normalizeParticipant).filter(Boolean);
+}
+
+// Normalize a raw ingestion candidate into the DB row shape, or null if it's
+// missing a required field (source / kind / happened_at / dedupeKey). A candidate
+// may supply its own id (stable across re-derivations) or get a fresh uuid.
+export function normalizeCandidate(candidate) {
+ if (!candidate) return null;
+ const source = String(candidate.source || '').trim();
+ const kind = String(candidate.kind || '').trim();
+ const dedupeKey = String(candidate.dedupeKey ?? candidate.dedupe_key ?? '').trim();
+ const when = candidate.happenedAt ?? candidate.happened_at;
+ const happenedAt = when ? new Date(when) : null;
+ if (!source || !kind || !dedupeKey || !happenedAt || Number.isNaN(happenedAt.getTime())) {
+ return null;
+ }
+ const durationRaw = candidate.durationS ?? candidate.duration_s;
+ const durationS = Number.isFinite(Number(durationRaw)) ? Math.round(Number(durationRaw)) : null;
+ return {
+ id: candidate.id || uuidv4(),
+ source,
+ accountId: candidate.accountId ?? candidate.account_id ?? null,
+ kind,
+ happenedAt: happenedAt.toISOString(),
+ durationS,
+ title: candidate.title ? shortSummary(candidate.title, 300) : null,
+ summary: candidate.summary ? shortSummary(candidate.summary) : null,
+ url: candidate.url || null,
+ participants: normalizeParticipants(candidate.participants),
+ metadata: candidate.metadata && typeof candidate.metadata === 'object' ? candidate.metadata : {},
+ dedupeKey,
+ };
+}
+
+// Bucket events into a 24-slot local-hour histogram: [{ hour, count }].
+export function hourlyHistogram(events, timezone) {
+ const counts = Array.from({ length: 24 }, (_, hour) => ({ hour, count: 0 }));
+ for (const ev of events || []) {
+ const d = new Date(ev.happenedAt ?? ev.happened_at);
+ if (Number.isNaN(d.getTime())) continue;
+ const { hour } = getLocalParts(d, timezone);
+ if (hour >= 0 && hour < 24) counts[hour].count += 1;
+ }
+ return counts;
+}
+
+// Tally events by source and by kind: { bySource: {…}, byKind: {…}, total }.
+export function summarizeCounts(events) {
+ const bySource = {};
+ const byKind = {};
+ for (const ev of events || []) {
+ const source = ev.source || 'unknown';
+ const kind = ev.kind || 'unknown';
+ bySource[source] = (bySource[source] || 0) + 1;
+ byKind[kind] = (byKind[kind] || 0) + 1;
+ }
+ return { bySource, byKind, total: (events || []).length };
+}
+
+// ---------------------------------------------------------------------------
+// Ingestion mappers (pure — turn source-specific records into candidates).
+// Kept here so the sync-hook glue in messageSync.js / calendarSync.js stays a
+// thin `.catch()`-guarded call, and so mapping is unit-testable without a DB.
+// ---------------------------------------------------------------------------
+
+function participantEmail(p) {
+ if (!p) return '';
+ return String((typeof p === 'string' ? p : p.email) || '').trim().toLowerCase();
+}
+
+// Map an account's cached messages to activity candidates. Direction (sent vs
+// received) is derived deterministically from the sender vs the account owner.
+export function messageActivityCandidates(account, messages = []) {
+ const selfEmail = String(account?.email || '').trim().toLowerCase();
+ const source = account?.type || 'message';
+ const accountId = account?.id || null;
+ const out = [];
+ for (const message of messages || []) {
+ const when = message?.date || message?.happenedAt;
+ if (!when) continue;
+ const externalId = message.externalId || message.id;
+ if (!externalId) continue;
+ const fromEmail = participantEmail(message.from);
+ const sent = Boolean(selfEmail) && fromEmail === selfEmail;
+ const participants = normalizeParticipants([
+ message.from,
+ ...(message.to || []),
+ ...(message.cc || []),
+ ]).filter((p) => !(p.email && p.email === selfEmail));
+ out.push({
+ source,
+ accountId,
+ kind: sent ? 'message.sent' : 'message.received',
+ happenedAt: when,
+ title: message.subject || '(no subject)',
+ summary: shortSummary(message.bodyText || message.snippet || ''),
+ participants,
+ dedupeKey: `msg:${accountId || 'x'}:${externalId}`,
+ metadata: {
+ threadId: message.threadId || null,
+ externalId,
+ channel: source,
+ },
+ });
+ }
+ return out;
+}
+
+// Map calendar events to activity candidates. Only events that have already
+// happened (end/start <= now) and weren't declined/cancelled count as activity,
+// mirroring the tribe touchpoint gate.
+export function calendarActivityCandidates(account, events = [], now = Date.now()) {
+ const accountId = account?.id || null;
+ const out = [];
+ for (const event of events || []) {
+ if (event?.isCancelled || event?.myStatus === 'declined') continue;
+ const startedAt = event.startTime || event.endTime;
+ if (!startedAt) continue;
+ const completedAt = event.endTime || event.startTime;
+ if (new Date(completedAt).getTime() > now) continue; // not finished yet
+ const eventKey = event.externalId || event.id;
+ if (!eventKey) continue;
+ const start = new Date(event.startTime).getTime();
+ const end = new Date(event.endTime).getTime();
+ const durationS = Number.isFinite(start) && Number.isFinite(end) && end > start
+ ? Math.round((end - start) / 1000)
+ : null;
+ out.push({
+ source: 'calendar',
+ accountId,
+ kind: 'calendar.event',
+ happenedAt: startedAt,
+ durationS,
+ title: event.title || '(untitled event)',
+ summary: shortSummary(event.location || event.description || ''),
+ participants: normalizeParticipants([event.organizer, ...(event.attendees || [])].filter(Boolean)),
+ dedupeKey: `cal:${accountId || 'x'}:${eventKey}`,
+ metadata: {
+ externalId: eventKey,
+ location: event.location || null,
+ startTime: event.startTime || null,
+ endTime: event.endTime || null,
+ subcalendarId: event.subcalendarId || null,
+ },
+ });
+ }
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// DB access.
+// ---------------------------------------------------------------------------
+
+let schemaReady = false;
+async function ensureReady() {
+ if (schemaReady) return;
+ await ensureSchema();
+ schemaReady = true;
+}
+
+function rowToEvent(row) {
+ return {
+ id: row.id,
+ source: row.source,
+ accountId: row.account_id,
+ kind: row.kind,
+ happenedAt: row.happened_at instanceof Date ? row.happened_at.toISOString() : row.happened_at,
+ durationS: row.duration_s,
+ title: row.title,
+ summary: row.summary,
+ url: row.url,
+ participants: row.participants || [],
+ metadata: row.metadata || {},
+ dedupeKey: row.dedupe_key,
+ createdAt: row.created_at instanceof Date ? row.created_at.toISOString() : row.created_at,
+ };
+}
+
+// Idempotently persist a batch of activity candidates. Returns
+// { recorded, skipped } where `recorded` is the count of newly-inserted rows and
+// `skipped` counts duplicates (already present for this source+dedupeKey) plus
+// any candidate that failed normalization.
+export async function recordEvents(candidates = []) {
+ const rows = (candidates || []).map(normalizeCandidate).filter(Boolean);
+ if (rows.length === 0) return { recorded: 0, skipped: (candidates || []).length };
+ await ensureReady();
+
+ // Chunk the multi-row insert so a large batch (the message hook passes the full
+ // capped cache each sync) can't exceed Postgres's 65535-param-per-statement
+ // limit — 12 params/row, so a 500-row chunk stays well under it.
+ const CHUNK = 500;
+ let recorded = 0;
+ for (let start = 0; start < rows.length; start += CHUNK) {
+ recorded += await insertActivityChunk(rows.slice(start, start + CHUNK));
+ }
+ const skipped = (candidates || []).length - recorded;
+ if (recorded > 0) {
+ console.log(`🗓️ Recorded ${recorded} activity event(s) (${skipped} skipped as duplicate/invalid)`);
+ }
+ return { recorded, skipped };
+}
+
+// Insert one chunk of normalized rows; returns the count actually inserted.
+// 12 bound params per row (created_at is a NOW() literal, not a param);
+// participants and metadata are JSON.stringify'd + ::jsonb-cast (node-pg would
+// otherwise coerce a JS array to a Postgres array literal and fail on jsonb).
+async function insertActivityChunk(rows) {
+ const paramsPerRow = 12;
+ const values = [];
+ const placeholders = rows.map((r, i) => {
+ const b = i * paramsPerRow;
+ values.push(
+ r.id, r.source, r.accountId, r.kind, r.happenedAt, r.durationS,
+ r.title, r.summary, r.url, JSON.stringify(r.participants),
+ JSON.stringify(r.metadata), r.dedupeKey,
+ );
+ return `($${b + 1}, $${b + 2}, $${b + 3}, $${b + 4}, $${b + 5}, $${b + 6}, $${b + 7}, $${b + 8}, $${b + 9}, $${b + 10}::jsonb, $${b + 11}::jsonb, $${b + 12}, NOW())`;
+ });
+ const result = await query(
+ `INSERT INTO human_activity_events
+ (id, source, account_id, kind, happened_at, duration_s, title, summary, url, participants, metadata, dedupe_key, created_at)
+ VALUES ${placeholders.join(', ')}
+ ON CONFLICT (source, dedupe_key) DO NOTHING
+ RETURNING id`,
+ values,
+ );
+ return result.rowCount || 0;
+}
+
+// Query events with optional filters. `from`/`to` are ISO timestamps (inclusive
+// lower, exclusive upper); `personId` matches a participant via the JSONB
+// containment operator. Newest first, capped by `limit` (default 500, max 2000).
+export async function listEvents({ from, to, source, kind, personId, limit } = {}) {
+ await ensureReady();
+ const clauses = [];
+ const params = [];
+ if (from) { params.push(new Date(from).toISOString()); clauses.push(`happened_at >= $${params.length}`); }
+ if (to) { params.push(new Date(to).toISOString()); clauses.push(`happened_at < $${params.length}`); }
+ if (source) { params.push(source); clauses.push(`source = $${params.length}`); }
+ if (kind) { params.push(kind); clauses.push(`kind = $${params.length}`); }
+ if (personId) {
+ params.push(JSON.stringify([{ personId: String(personId) }]));
+ clauses.push(`participants @> $${params.length}::jsonb`);
+ }
+ const cap = Math.min(Math.max(Number(limit) || 500, 1), 2000);
+ params.push(cap);
+ const where = clauses.length ? `WHERE ${clauses.join(' AND ')}` : '';
+ const result = await query(
+ `SELECT * FROM human_activity_events
+ ${where}
+ ORDER BY happened_at DESC
+ LIMIT $${params.length}`,
+ params,
+ );
+ return result.rows.map(rowToEvent);
+}
+
+// Day view: all events on a local calendar day plus an hourly histogram and
+// source/kind tallies. `date` defaults to today in the user's timezone.
+export async function getDaySummary({ date } = {}) {
+ const timezone = await getUserTimezone();
+ const day = /^\d{4}-\d{2}-\d{2}$/.test(String(date || '')) ? date : todayInTimezone(timezone);
+ const range = localDayRangeUtc(day, timezone);
+ if (!range) return { date: day, timezone, events: [], histogram: hourlyHistogram([], timezone), counts: summarizeCounts([]) };
+ const events = await listEvents({ from: range.start.toISOString(), to: range.end.toISOString(), limit: 2000 });
+ // listEvents returns newest-first; a day view reads better oldest-first.
+ const ordered = [...events].reverse();
+ return {
+ date: day,
+ timezone,
+ events: ordered,
+ histogram: hourlyHistogram(ordered, timezone),
+ counts: summarizeCounts(ordered),
+ };
+}
diff --git a/server/services/humanActivity.test.js b/server/services/humanActivity.test.js
new file mode 100644
index 0000000000..00f366650b
--- /dev/null
+++ b/server/services/humanActivity.test.js
@@ -0,0 +1,183 @@
+/**
+ * Pure-logic tests for the human-activity timeline (#2150). No DB — these cover
+ * the deterministic ingestion mappers, dedupe-key derivation, normalization, and
+ * the histogram/summary aggregates. The Postgres round-trip (recordEvents /
+ * listEvents / getDaySummary idempotency) is covered in humanActivity.db.test.js.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ shortSummary,
+ localDayKey,
+ localDayRangeUtc,
+ normalizeParticipant,
+ normalizeParticipants,
+ normalizeCandidate,
+ hourlyHistogram,
+ summarizeCounts,
+ messageActivityCandidates,
+ calendarActivityCandidates,
+} from './humanActivity.js';
+
+describe('shortSummary', () => {
+ it('collapses whitespace to a single line', () => {
+ expect(shortSummary('hello world\n\tfoo')).toBe('hello world foo');
+ });
+ it('clamps to max with an ellipsis and never returns the full body', () => {
+ const body = 'x'.repeat(500);
+ const out = shortSummary(body, 160);
+ expect(out.length).toBeLessThanOrEqual(160);
+ expect(out.endsWith('…')).toBe(true);
+ });
+ it('returns empty for falsy input', () => {
+ expect(shortSummary('')).toBe('');
+ expect(shortSummary(null)).toBe('');
+ });
+});
+
+describe('localDayKey / localDayRangeUtc', () => {
+ it('derives the local day key in a given timezone', () => {
+ // 2026-07-04T02:00:00Z is still 2026-07-03 in America/Los_Angeles (-07:00).
+ expect(localDayKey('2026-07-04T02:00:00Z', 'America/Los_Angeles')).toBe('2026-07-03');
+ // …and the same instant is already 2026-07-04 in UTC.
+ expect(localDayKey('2026-07-04T02:00:00Z', 'UTC')).toBe('2026-07-04');
+ });
+ it('returns a 24h UTC window bounding the local day', () => {
+ const range = localDayRangeUtc('2026-07-04', 'America/Los_Angeles');
+ expect(range).toBeTruthy();
+ // Local midnight PDT (-07:00) → 07:00Z.
+ expect(range.start.toISOString()).toBe('2026-07-04T07:00:00.000Z');
+ expect(range.end.getTime() - range.start.getTime()).toBe(24 * 60 * 60 * 1000);
+ });
+ it('rejects a malformed date string', () => {
+ expect(localDayRangeUtc('not-a-date', 'UTC')).toBeNull();
+ expect(localDayKey('not-a-date', 'UTC')).toBeNull();
+ });
+});
+
+describe('participant normalization', () => {
+ it('lowercases email, trims, drops empties', () => {
+ expect(normalizeParticipant(' [email protected] ')).toEqual({ email: '[email protected]' });
+ expect(normalizeParticipant({ name: ' Jane ', email: '[email protected]', phone: ' +1 555 ' }))
+ .toEqual({ name: 'Jane', email: '[email protected]', phone: '+1 555' });
+ expect(normalizeParticipant({})).toBeNull();
+ expect(normalizeParticipant(null)).toBeNull();
+ });
+ it('normalizes and filters a list', () => {
+ expect(normalizeParticipants(['[email protected]', {}, null, { name: 'X' }])).toEqual([
+ { email: '[email protected]' }, { name: 'X' },
+ ]);
+ expect(normalizeParticipants('nope')).toEqual([]);
+ });
+});
+
+describe('normalizeCandidate', () => {
+ const base = {
+ source: 'gmail', kind: 'message.received', happenedAt: '2026-07-04T12:00:00Z',
+ dedupeKey: 'msg:acct:ext1', title: 'Hi', summary: 'body preview',
+ };
+ it('produces a DB row shape with a generated id when none supplied', () => {
+ const row = normalizeCandidate(base);
+ expect(row.id).toBeTruthy();
+ expect(row.source).toBe('gmail');
+ expect(row.kind).toBe('message.received');
+ expect(row.happenedAt).toBe('2026-07-04T12:00:00.000Z');
+ expect(row.participants).toEqual([]);
+ expect(row.metadata).toEqual({});
+ expect(row.durationS).toBeNull();
+ });
+ it('preserves a supplied id and coerces duration to an int', () => {
+ const row = normalizeCandidate({ ...base, id: 'fixed-id', durationS: 90.7 });
+ expect(row.id).toBe('fixed-id');
+ expect(row.durationS).toBe(91);
+ });
+ it('returns null when a required field is missing or the date is invalid', () => {
+ expect(normalizeCandidate({ ...base, source: '' })).toBeNull();
+ expect(normalizeCandidate({ ...base, kind: '' })).toBeNull();
+ expect(normalizeCandidate({ ...base, dedupeKey: '' })).toBeNull();
+ expect(normalizeCandidate({ ...base, happenedAt: 'garbage' })).toBeNull();
+ expect(normalizeCandidate(null)).toBeNull();
+ });
+ it('accepts snake_case aliases from callers', () => {
+ const row = normalizeCandidate({
+ source: 'calendar', kind: 'calendar.event', happened_at: '2026-07-04T12:00:00Z',
+ dedupe_key: 'cal:a:1', account_id: 'acct-9', duration_s: 3600,
+ });
+ expect(row.accountId).toBe('acct-9');
+ expect(row.durationS).toBe(3600);
+ });
+});
+
+describe('hourlyHistogram / summarizeCounts', () => {
+ const events = [
+ { happenedAt: '2026-07-04T14:05:00Z', source: 'gmail', kind: 'message.received' },
+ { happenedAt: '2026-07-04T14:40:00Z', source: 'gmail', kind: 'message.sent' },
+ { happenedAt: '2026-07-04T22:00:00Z', source: 'calendar', kind: 'calendar.event' },
+ ];
+ it('buckets events into 24 local-hour slots', () => {
+ const hist = hourlyHistogram(events, 'UTC');
+ expect(hist).toHaveLength(24);
+ expect(hist[14].count).toBe(2);
+ expect(hist[22].count).toBe(1);
+ expect(hist[0].count).toBe(0);
+ });
+ it('tallies by source and kind', () => {
+ const counts = summarizeCounts(events);
+ expect(counts.total).toBe(3);
+ expect(counts.bySource).toEqual({ gmail: 2, calendar: 1 });
+ expect(counts.byKind).toEqual({ 'message.received': 1, 'message.sent': 1, 'calendar.event': 1 });
+ });
+});
+
+describe('messageActivityCandidates', () => {
+ const account = { id: 'acct-1', type: 'gmail', email: '[email protected]' };
+ it('marks sent vs received by comparing the sender to the account owner', () => {
+ const [received, sent] = messageActivityCandidates(account, [
+ { externalId: 'e1', date: '2026-07-04T10:00:00Z', from: '[email protected]', to: ['[email protected]'], subject: 'Hey' },
+ { externalId: 'e2', date: '2026-07-04T11:00:00Z', from: { email: '[email protected]' }, to: ['[email protected]'], subject: 'Re: Hey' },
+ ]);
+ expect(received.kind).toBe('message.received');
+ expect(sent.kind).toBe('message.sent');
+ });
+ it('excludes the account owner from participants and builds a stable dedupe key', () => {
+ const [c] = messageActivityCandidates(account, [
+ { externalId: 'e1', date: '2026-07-04T10:00:00Z', from: '[email protected]', to: ['[email protected]', '[email protected]'], subject: 'Hey', bodyText: 'the full body\nwith newlines' },
+ ]);
+ const emails = c.participants.map((p) => p.email);
+ expect(emails).toContain('[email protected]');
+ expect(emails).toContain('[email protected]');
+ expect(emails).not.toContain('[email protected]');
+ expect(c.dedupeKey).toBe('msg:acct-1:e1');
+ expect(c.metadata.externalId).toBe('e1');
+ // Privacy: summary is a collapsed preview, not the raw multi-line body.
+ expect(c.summary).toBe('the full body with newlines');
+ });
+ it('skips messages without a date or external id', () => {
+ expect(messageActivityCandidates(account, [{ subject: 'no date' }])).toEqual([]);
+ expect(messageActivityCandidates(account, [{ date: '2026-07-04T10:00:00Z' }])).toEqual([]);
+ });
+});
+
+describe('calendarActivityCandidates', () => {
+ const account = { id: 'cal-1', type: 'google-calendar' };
+ const now = new Date('2026-07-04T23:00:00Z').getTime();
+ it('records finished, non-declined events with a duration', () => {
+ const [c] = calendarActivityCandidates(account, [
+ {
+ externalId: 'ev1', title: 'Standup', location: 'Zoom',
+ startTime: '2026-07-04T09:00:00Z', endTime: '2026-07-04T09:30:00Z',
+ organizer: '[email protected]', attendees: ['[email protected]'],
+ },
+ ], now);
+ expect(c.source).toBe('calendar');
+ expect(c.kind).toBe('calendar.event');
+ expect(c.durationS).toBe(1800);
+ expect(c.dedupeKey).toBe('cal:cal-1:ev1');
+ expect(c.title).toBe('Standup');
+ });
+ it('skips cancelled, declined, and not-yet-finished events', () => {
+ expect(calendarActivityCandidates(account, [{ externalId: 'a', startTime: '2026-07-04T08:00:00Z', endTime: '2026-07-04T08:30:00Z', isCancelled: true }], now)).toEqual([]);
+ expect(calendarActivityCandidates(account, [{ externalId: 'b', startTime: '2026-07-04T08:00:00Z', endTime: '2026-07-04T08:30:00Z', myStatus: 'declined' }], now)).toEqual([]);
+ // ends in the future relative to `now`
+ expect(calendarActivityCandidates(account, [{ externalId: 'c', startTime: '2026-07-05T08:00:00Z', endTime: '2026-07-05T08:30:00Z' }], now)).toEqual([]);
+ });
+});
diff --git a/server/services/messageSync.js b/server/services/messageSync.js
index e9984a8085..6bcac2df84 100644
--- a/server/services/messageSync.js
+++ b/server/services/messageSync.js
@@ -195,6 +195,12 @@ export async function syncAccount(accountId, io, options = {}) {
await logMessageTouchpoints(account, cache.messages).catch((err) =>
console.error(`🤝 Tribe auto-log failed for account ${accountId}: ${err.message}`));
+ // Populate the human-activity timeline (#2150) — secondary effect, must NOT
+ // fail the sync. Idempotent on (source, dedupe_key), so re-scanning the full
+ // cache each sync is a no-op for already-recorded messages. Machine-local.
+ await recordMessageActivity(account, cache.messages).catch((err) =>
+ console.error(`🗓️ Activity ingest failed for account ${accountId}: ${err.message}`));
+
io?.emit('messages:sync:completed', { accountId, newMessages: uniqueNew.length, pruned, status: providerStatus });
if (providerStatus === 'success') {
io?.emit('messages:changed', {});
@@ -393,3 +399,15 @@ export async function logMessageTouchpoints(account, messages = []) {
}
return result;
}
+
+// Record synced messages into the machine-local human-activity timeline (#2150).
+// Deterministic + idempotent (dedupe on source + message externalId), so
+// re-scanning the full cache each sync is a no-op for already-recorded messages.
+// humanActivity is imported dynamically to keep this hook lazy (mirrors the tribe
+// auto-log path) and off the module graph for callers that never sync.
+export async function recordMessageActivity(account, messages = []) {
+ const { messageActivityCandidates, recordEvents } = await import('./humanActivity.js');
+ const candidates = messageActivityCandidates(account, messages);
+ if (candidates.length === 0) return { recorded: 0, skipped: 0 };
+ return recordEvents(candidates);
+}
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 4542d624ef..132d9caeef 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -3669,7 +3669,7 @@ describe('peerSync', () => {
}
});
- it('keeps the Tribe graph + universe render-runs intentionally OUT of the sync graph (#1724)', () => {
+ it('keeps the Tribe graph + universe render-runs + activity timeline intentionally OUT of the sync graph (#1724, #2150)', () => {
// ADR 2026-06-26: tribe_* and universe_runs are deliberately machine-local.
// - Tribe is relationship-graph data (mirrors the deliberate "memory_links
// are instance-local" policy in memorySync.js) and is coupled to
@@ -3677,14 +3677,17 @@ describe('peerSync', () => {
// - universe_runs is a regenerable render cache under a 200-row GLOBAL cap
// that two producers would mutually evict; the durable universe record
// already federates.
- // This guard pins that decision: federating either later is a conscious act
- // — wire the kind AND update this assertion + the ADR together.
- const localOnlyKinds = ['tribe', 'tribePerson', 'tribeTouchpoint', 'tribeMemoryLink', 'universeRun'];
+ // - human_activity_events (#2150) is coupled to per-machine accounts and OS
+ // databases; only DERIVED summaries (Brain journals, digital-twin) federate,
+ // never the raw events. Same machine-local boundary per the ADR.
+ // This guard pins that decision: federating any of them later is a conscious
+ // act — wire the kind AND update this assertion + the ADR together.
+ const localOnlyKinds = ['tribe', 'tribePerson', 'tribeTouchpoint', 'tribeMemoryLink', 'universeRun', 'humanActivityEvent'];
for (const kind of localOnlyKinds) {
expect(PEER_SUBSCRIBABLE_KINDS).not.toContain(kind);
expect(RECORD_KIND_SCHEMA_CATEGORIES[kind]).toBeUndefined();
}
- const localOnlyCategories = ['tribe', 'tribePeople', 'tribeTouchpoints', 'tribeMemoryLinks', 'universeRuns'];
+ const localOnlyCategories = ['tribe', 'tribePeople', 'tribeTouchpoints', 'tribeMemoryLinks', 'universeRuns', 'humanActivityEvents'];
for (const category of localOnlyCategories) {
expect(PORTOS_SCHEMA_VERSIONS[category]).toBeUndefined();
expect(NON_RECORD_SCHEMA_CATEGORIES.has(category)).toBe(false);
diff --git a/server/vitest.config.db.js b/server/vitest.config.db.js
index 87b4d25b71..d8ac0f0be2 100644
--- a/server/vitest.config.db.js
+++ b/server/vitest.config.db.js
@@ -11,6 +11,7 @@ export const DB_TEST_INCLUDE = [
'**/db.test.js',
'services/catalogDB.test.js',
'services/catalogDB.facets.db.test.js',
+ 'services/humanActivity.db.test.js',
'services/catalogCanonProjection.test.js',
'services/catalogRefResolver.test.js',
'services/creativeDirector/projectsDB.test.js',