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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(on-this-day-dashboard-widget): surface past-year Brain captures on the dashboard
[._.]/ Adam Eivy3ed604a0ed0c
diff --git a/PLAN.md b/PLAN.mdindex 5dbe3b0e56..0a0f710052 100644--- a/PLAN.md+++ b/PLAN.md@@ -1,3 +1,4 @@# PLAN- [x] [today-agenda-dashboard-widget] Today's Agenda dashboard widget — glanceable list of today's remaining calendar events (new `GET /api/calendar/agenda` with a timezone-correct day window, gated on a connected calendar account, seeded into the Everything and Morning Review layouts)+- [x] [on-this-day-dashboard-widget] On This Day dashboard widget — resurfaces Brain journal entries, memories, and ideas written on today's date in past years (new `GET /api/brain/on-this-day` with timezone-correct date matching, journal rows deep-link into the Daily Log via a new `?date=` param, seeded into the Everything and Morning Review layouts)diff --git a/client/src/components/brain/tabs/DailyLogTab.jsx b/client/src/components/brain/tabs/DailyLogTab.jsxindex ee3fd0f95d..34d112e545 100644--- a/client/src/components/brain/tabs/DailyLogTab.jsx+++ b/client/src/components/brain/tabs/DailyLogTab.jsx@@ -1,4 +1,5 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useSearchParams } from 'react-router';import {BookOpen, ChevronLeft, ChevronRight, Mic, MicOff, Save, Volume2, Settings,Plus, Trash2, CloudUpload, Menu, X, Sparkles} from 'lucide-react';import * as api from '../../../services/api';@@ -76,8 +77,16 @@ export const mergeMissingVoiceSegments = (localContent, serverEntry) => {// whatever is still dirty if we exhaust the budget mid-burst.const STALE_JOURNAL_MAX_ATTEMPTS = 3;+const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;+export default function DailyLogTab() {- const [date, setDate] = useState(localDateKey());+ const [searchParams, setSearchParams] = useSearchParams();+ // Deep-linkable date (?date=YYYY-MM-DD) — the On This Day widget and shared+ // links open a specific past day; without the param the tab opens on today.+ const [date, setDate] = useState(() => {+ const param = searchParams.get('date');+ return param && ISO_DATE_RE.test(param) ? param : localDateKey();+ });// Backend today — resolved via GET /daily-log/today on mount so the// "Today" button, disabled-forward-nav check, and isToday chip all match// the server's timezone. Falls back to localDateKey() until fetched.@@ -169,6 +178,18 @@ export default function DailyLogTab() {}, []);useEffect(() => { loadEntry(date); }, [date, loadEntry]);++ // Reflect non-today dates back into ?date= so the open day stays shareable+ // and reload-safe. Replace, not push — prev/next taps shouldn't pile up+ // history entries.+ useEffect(() => {+ setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ if (date === serverToday) next.delete('date');+ else next.set('date', date);+ return next;+ }, { replace: true });+ }, [date, serverToday, setSearchParams]);useEffect(() => { loadHistory(); loadSettings(); }, [loadHistory, loadSettings]);// Keep the server's dictation target date aligned with the UI whilediff --git a/client/src/components/brain/tabs/DailyLogTab.test.jsx b/client/src/components/brain/tabs/DailyLogTab.test.jsxindex d041f749ef..34894ed7db 100644--- a/client/src/components/brain/tabs/DailyLogTab.test.jsx+++ b/client/src/components/brain/tabs/DailyLogTab.test.jsx@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { render, screen, fireEvent, act, within } from '@testing-library/react';+import { MemoryRouter } from 'react-router';import { __resetVisibilityEventForTests } from '../../../hooks/useVisibilityEvent';// ── Mock toast ────────────────────────────────────────────────────────────────@@ -62,7 +63,8 @@ const entryFor = (date, content) => ({let store;const renderTab = async () => {- const result = render(<DailyLogTab />);+ // Router context is required for the ?date= deep-link search param.+ const result = render(<MemoryRouter><DailyLogTab /></MemoryRouter>);// Flush the mount fetches (entry + server-today + history + settings).await act(async () => { await vi.advanceTimersByTimeAsync(0); });return result;diff --git a/client/src/components/dashboard/builtins/OnThisDayWidget.jsx b/client/src/components/dashboard/builtins/OnThisDayWidget.jsxnew file mode 100644index 0000000000..c16a01fc35--- /dev/null+++ b/client/src/components/dashboard/builtins/OnThisDayWidget.jsx@@ -0,0 +1,67 @@+import { Link } from 'react-router';+import { History, Lightbulb, BookOpen, NotebookPen } from 'lucide-react';++// "On this day" memory lane — journal entries, memories, and ideas written on+// this calendar date in previous years. Reads the shared `brainOnThisDay`+// slice of dashboardState (populated from GET /api/brain/on-this-day — the+// server owns the timezone-correct date key, so this never re-derives it).+// Gated off until there is at least one past-year item to show, so a young+// install reserves no grid cell.+const ROW_META = {+ journal: { icon: NotebookPen, label: 'Daily Log', link: (item) => `/brain/daily-log?date=${item.date}` },+ memory: { icon: BookOpen, label: 'Memory', link: () => '/brain/memory' },+ idea: { icon: Lightbulb, label: 'Idea', link: () => '/brain/ideas' },+};++const yearsAgoLabel = (yearsAgo) => (yearsAgo === 1 ? '1 year ago' : `${yearsAgo} years ago`);++export default function OnThisDayWidget({ dashboardState }) {+ const data = dashboardState?.brainOnThisDay;+ if (!data) return null;++ const items = Array.isArray(data.items) ? data.items : [];+ const total = data.total ?? items.length;++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-4 h-full">+ <div className="flex items-center gap-2 mb-3">+ <History size={16} className="text-gray-500" />+ <h3 className="text-sm font-semibold text-white">On This Day</h3>+ </div>++ {items.length === 0 ? (+ <div className="text-xs text-gray-500">No captures from this day in past years.</div>+ ) : (+ <>+ <ul className="space-y-2">+ {items.map((item) => {+ const meta = ROW_META[item.type] || ROW_META.memory;+ const Icon = meta.icon;+ return (+ <li key={`${item.type}:${item.id}`}>+ <Link to={meta.link(item)} className="group flex items-start gap-2 text-xs">+ <Icon size={14} className="shrink-0 mt-0.5 text-gray-500" />+ <span className="min-w-0">+ <span className="block text-gray-500">+ {yearsAgoLabel(item.yearsAgo)} · {meta.label}+ </span>+ <span className="block truncate text-gray-300 group-hover:text-white" title={item.title || item.snippet}>+ {item.title || item.snippet}+ </span>+ {item.title && item.snippet && (+ <span className="block truncate text-gray-500">{item.snippet}</span>+ )}+ </span>+ </Link>+ </li>+ );+ })}+ </ul>+ {total > items.length && (+ <div className="text-xs text-gray-500 mt-2">+{total - items.length} more</div>+ )}+ </>+ )}+ </div>+ );+}diff --git a/client/src/components/dashboard/builtins/OnThisDayWidget.test.jsx b/client/src/components/dashboard/builtins/OnThisDayWidget.test.jsxnew file mode 100644index 0000000000..3b6496772f--- /dev/null+++ b/client/src/components/dashboard/builtins/OnThisDayWidget.test.jsx@@ -0,0 +1,55 @@+import { describe, it, expect } from 'vitest';+import { render, screen } from '@testing-library/react';+import { MemoryRouter } from 'react-router';+import OnThisDayWidget from './OnThisDayWidget';++const renderWidget = (brainOnThisDay) =>+ render(+ <MemoryRouter>+ <OnThisDayWidget dashboardState={{ brainOnThisDay }} />+ </MemoryRouter>+ );++describe('OnThisDayWidget', () => {+ it('renders nothing when the data is absent (fetch failed / no data)', () => {+ const { container } = renderWidget(null);+ expect(container.firstChild).toBeNull();+ });++ it('shows the empty state when nothing matched today', () => {+ renderWidget({ date: '2026-09-01', timezone: 'UTC', total: 0, items: [] });+ expect(screen.getByText(/No captures from this day/)).toBeTruthy();+ });++ it('deep-links each row by type — journals to their exact past date', () => {+ renderWidget({+ date: '2026-09-01',+ timezone: 'UTC',+ total: 3,+ items: [+ { type: 'journal', id: '2025-09-01', date: '2025-09-01', yearsAgo: 1, title: null, snippet: 'shipped the thing' },+ { type: 'memory', id: 'm1', date: '2024-09-01', yearsAgo: 2, title: 'Trip planning', snippet: 'packed bags' },+ { type: 'idea', id: 'i1', date: '2023-09-01', yearsAgo: 3, title: 'Spark', snippet: 'the pitch' },+ ],+ });++ const hrefs = screen.getAllByRole('link').map((a) => a.getAttribute('href'));+ expect(hrefs).toEqual(['/brain/daily-log?date=2025-09-01', '/brain/memory', '/brain/ideas']);+ expect(screen.getByText('1 year ago · Daily Log')).toBeTruthy();+ expect(screen.getByText('2 years ago · Memory')).toBeTruthy();+ expect(screen.getByText('shipped the thing')).toBeTruthy();+ expect(screen.getByText('Trip planning')).toBeTruthy();+ });++ it('surfaces the overflow count when the server truncated the list', () => {+ renderWidget({+ date: '2026-09-01',+ timezone: 'UTC',+ total: 12,+ items: [+ { type: 'journal', id: '2025-09-01', date: '2025-09-01', yearsAgo: 1, title: null, snippet: 'one' },+ ],+ });+ expect(screen.getByText('+11 more')).toBeTruthy();+ });+});diff --git a/client/src/components/dashboard/widgetRegistry.jsx b/client/src/components/dashboard/widgetRegistry.jsxindex 17dce3c9a0..223b983ff7 100644--- a/client/src/components/dashboard/widgetRegistry.jsx+++ b/client/src/components/dashboard/widgetRegistry.jsx@@ -28,6 +28,7 @@ const MeatSpaceStreakWidget = lazyWithReload(() => import('./builtins/MeatSpaceSconst AutoFixMetricsWidget = lazyWithReload(() => import('./builtins/AutoFixMetricsWidget'));const DailyDriverWidget = lazyWithReload(() => import('./builtins/DailyDriverWidget'));const TodayAgendaWidget = lazyWithReload(() => import('./builtins/TodayAgendaWidget'));+const OnThisDayWidget = lazyWithReload(() => import('./builtins/OnThisDayWidget'));const ActiveProcessingWidget = lazyWithReload(() => import('./ActiveProcessingWidget'));const DailyActionsWidget = lazyWithReload(() => import('../DailyActionsWidget'));@@ -73,6 +74,7 @@ export const WIDGETS = [{ id: 'feeds', label: 'Feeds Digest', Component: FeedsWidget, width: 'quarter', defaultH: 4, gate: (s) => (s.feeds?.totalFeeds ?? 0) > 0 },{ id: 'meatspace-streak', label: 'Health Logging Streak', Component: MeatSpaceStreakWidget, width: 'third', defaultH: 4, gate: (s) => (s.meatspaceLogging?.totalLogged ?? 0) > 0 },{ id: 'today-agenda', label: 'Today\'s Agenda', Component: TodayAgendaWidget, width: 'third', defaultH: 4, gate: (s) => (s.calendarAgenda?.accountCount ?? 0) > 0 },+ { id: 'on-this-day', label: 'On This Day', Component: OnThisDayWidget, width: 'third', defaultH: 4, gate: (s) => (s.brainOnThisDay?.total ?? 0) > 0 },{ id: 'autofix-metrics', label: 'Auto-Fix Telemetry', Component: AutoFixMetricsWidget, width: 'quarter', defaultH: 5 },{ id: 'active-processing', label: 'Active Processing', Component: ActiveProcessingWidget, width: 'half', defaultH: 5 },];diff --git a/client/src/pages/Dashboard.jsx b/client/src/pages/Dashboard.jsxindex 5dc4e6ee2d..bc39cd32a0 100644--- a/client/src/pages/Dashboard.jsx+++ b/client/src/pages/Dashboard.jsx@@ -29,6 +29,7 @@ export default function Dashboard() {const [feeds, setFeeds] = useState(null);const [meatspaceLogging, setMeatspaceLogging] = useState(null);const [calendarAgenda, setCalendarAgenda] = useState(null);+ const [brainOnThisDay, setBrainOnThisDay] = useState(null);const [dailyDriver, setDailyDriver] = useState(null);const [dailyActions, setDailyActions] = useState(null);const [loading, setLoading] = useState(true);@@ -114,6 +115,7 @@ export default function Dashboard() {api.getFeedStats({ silent: true }).catch(() => null).then(setFeeds),api.getMeatspaceLoggingStats({ silent: true }).catch(() => null).then(setMeatspaceLogging),api.getCalendarAgenda({ silent: true }).catch(() => null).then(setCalendarAgenda),+ api.getBrainOnThisDay({ silent: true }).catch(() => null).then(setBrainOnThisDay),// GET records the first-visit-of-day signal (issue #2666); a failure just// hides the Daily Driver card via its gate. No LLM calls here.api.getDailyDriverState().catch(() => null).then(setDailyDriver),@@ -239,8 +241,8 @@ export default function Dashboard() {}), [activeApps]);const dashboardState = useMemo(- () => ({ apps: appList, appsLoading, sortedApps, activeApps, appStats, health, usage, tribeCare, feeds, meatspaceLogging, calendarAgenda, dailyDriver, dailyActions, instanceFeatures, refetch: fetchData, refetchHealth: refreshHealth }),- [appList, appsLoading, sortedApps, activeApps, appStats, health, usage, tribeCare, feeds, meatspaceLogging, calendarAgenda, dailyDriver, dailyActions, instanceFeatures, fetchData, refreshHealth]+ () => ({ apps: appList, appsLoading, sortedApps, activeApps, appStats, health, usage, tribeCare, feeds, meatspaceLogging, calendarAgenda, brainOnThisDay, dailyDriver, dailyActions, instanceFeatures, refetch: fetchData, refetchHealth: refreshHealth }),+ [appList, appsLoading, sortedApps, activeApps, appStats, health, usage, tribeCare, feeds, meatspaceLogging, calendarAgenda, brainOnThisDay, dailyDriver, dailyActions, instanceFeatures, fetchData, refreshHealth]);// Falls back to a local minimal layout only AFTER the initial fetch hasdiff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.jsindex bc8305410f..c1a044ada9 100644--- a/client/src/services/apiBrain.js+++ b/client/src/services/apiBrain.js@@ -321,6 +321,9 @@ export const getEmbeddingsStatus = () => request('/brain/embeddings/status');export const syncBrainData = ({ refresh = false, onlyMissing = false } = {}, options = {}) =>request('/brain/bridge-sync', { method: 'POST', body: JSON.stringify({ refresh, onlyMissing }), ...options });+// Brain - On This Day (dashboard widget: past-year journals/memories/ideas)+export const getBrainOnThisDay = (options = {}) => request('/brain/on-this-day', options);+// Brain - Daily Logexport const listDailyLogs = (options = {}) => {const params = new URLSearchParams();diff --git a/scripts/migrations/329-seed-on-this-day-widget.js b/scripts/migrations/329-seed-on-this-day-widget.jsnew file mode 100644index 0000000000..bc33992a2b--- /dev/null+++ b/scripts/migrations/329-seed-on-this-day-widget.js@@ -0,0 +1,46 @@+/**+ * Seed the On This Day brain widget into the built-in Everything and Morning+ * Review layouts. The widget is gated on having past-year Brain captures for+ * today's date, so installs without history see no change. Custom/user layouts+ * are intentionally untouched: the layout editor is the user's source of truth+ * for those.+ */++import { readLayoutsDoc, writeLayoutsDoc } from './_lib.js';++const LABEL = 'migration 329';+const TARGET_LAYOUTS = new Set(['default', 'morning-review']);+const WIDGET_ID = 'on-this-day';++function applyToLayout(layout) {+ if (!layout || !TARGET_LAYOUTS.has(layout.id) || !Array.isArray(layout.widgets)) return false;+ const hasWidget = layout.widgets.includes(WIDGET_ID);+ const hasGridEntry = Array.isArray(layout.grid) && layout.grid.some((item) => item?.id === WIDGET_ID);+ if (hasWidget && hasGridEntry) return false;++ if (!hasWidget) layout.widgets = [...layout.widgets, WIDGET_ID];+ if (!hasGridEntry) {+ // Append at the end of the packing sequence — the widget is gated, so a+ // trailing cell that gates off leaves only harmless trailing space.+ const grid = Array.isArray(layout.grid) ? layout.grid : [];+ const maxOrder = grid.reduce((max, item) => Math.max(max, Number.isFinite(item?.order) ? item.order : -1), -1);+ layout.grid = [...grid, { id: WIDGET_ID, x: 0, w: 4, order: maxOrder + 1, h: 4 }];+ }+ return true;+}++export default {+ async up({ rootDir }) {+ const result = await readLayoutsDoc({ rootDir, label: LABEL });+ if (!result.ok) return { updated: 0, reason: result.reason };+ const { doc, path } = result;+ let updated = 0;+ for (const layout of doc.layouts) {+ if (applyToLayout(layout)) updated += 1;+ }+ if (updated === 0) return { updated: 0, reason: 'already-applied' };+ await writeLayoutsDoc(path, doc);+ console.log(`🗓️ ${LABEL}: seeded On This Day widget in ${updated} built-in dashboard layout(s).`);+ return { updated };+ },+};diff --git a/scripts/migrations/329-seed-on-this-day-widget.test.js b/scripts/migrations/329-seed-on-this-day-widget.test.jsnew file mode 100644index 0000000000..c7479cac9a--- /dev/null+++ b/scripts/migrations/329-seed-on-this-day-widget.test.js@@ -0,0 +1,67 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import migration from './329-seed-on-this-day-widget.js';++const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);+const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));++describe('migration 329 — seed On This Day dashboard widget', () => {+ let rootDir;+ let layoutsPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-329-'));+ mkdirSync(join(rootDir, 'data'), { recursive: true });+ layoutsPath = join(rootDir, 'data', 'dashboard-layouts.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('does nothing on a fresh install with no persisted layouts', async () => {+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'no-state' });+ });++ it('appends the widget after the existing grid and skips custom layouts', async () => {+ writeJson(layoutsPath, {+ activeLayoutId: 'default',+ layouts: [+ {+ id: 'default', name: 'Everything', builtIn: true,+ widgets: ['quick-brain', 'today-agenda'],+ grid: [+ { id: 'quick-brain', x: 0, w: 3, order: 0, h: 2 },+ { id: 'today-agenda', x: 0, w: 4, order: 1, h: 4 },+ ],+ },+ {+ id: 'custom', name: 'Mine', builtIn: false,+ widgets: ['quick-brain'], grid: [{ id: 'quick-brain', x: 0, w: 12, order: 0, h: 2 }],+ },+ ],+ });++ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });+ const after = readJson(layoutsPath);+ const seeded = after.layouts.find((layout) => layout.id === 'default');+ expect(seeded.widgets).toEqual(['quick-brain', 'today-agenda', 'on-this-day']);+ expect(seeded.grid.at(-1)).toEqual({ id: 'on-this-day', x: 0, w: 4, order: 2, h: 4 });+ expect(after.layouts.find((layout) => layout.id === 'custom').widgets).toEqual(['quick-brain']);+ });++ it('is idempotent once the widget is present', async () => {+ writeJson(layoutsPath, {+ activeLayoutId: 'default',+ layouts: [+ {+ id: 'default', name: 'Everything', builtIn: true,+ widgets: ['on-this-day'],+ grid: [{ id: 'on-this-day', x: 0, w: 4, order: 0, h: 4 }],+ },+ ],+ });++ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });+ });+});diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex ef15e95d66..2493d0edca 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -2867,6 +2867,17 @@}]},+ {+ "method": "GET",+ "path": "/api/brain/on-this-day",+ "mountPath": "/api/brain",+ "sources": [+ {+ "source": "server/routes/brainOnThisDay.js",+ "line": 14+ }+ ]+ },{"method": "GET","path": "/api/brain/people",@@ -23831,8 +23842,8 @@],"stats": {"mounts": 147,- "operations": 2150,- "declarations": 2153,- "sourceFiles": 228+ "operations": 2151,+ "declarations": 2154,+ "sourceFiles": 229}}diff --git a/server/routes/brain.js b/server/routes/brain.jsindex 5229684031..e9cc1e8ecc 100644--- a/server/routes/brain.js+++ b/server/routes/brain.js@@ -15,6 +15,7 @@ import linkRoutes from './brainLinks.js';import graphRoutes from './brainGraph.js';import syncRoutes from './brainSync.js';import dailyLogRoutes from './brainDailyLog.js';+import onThisDayRoutes from './brainOnThisDay.js';import songbookRoutes from './brainSongbook.js';import youtubeRoutes from './brainYoutube.js';import ideaLoomRoutes from './brainIdeaLoom.js';@@ -31,6 +32,7 @@ router.use(linkRoutes);router.use(graphRoutes);router.use(syncRoutes);router.use(dailyLogRoutes);+router.use(onThisDayRoutes);router.use('/songbook', songbookRoutes);router.use('/youtube', youtubeRoutes);diff --git a/server/routes/brainOnThisDay.js b/server/routes/brainOnThisDay.jsnew file mode 100644index 0000000000..ef343bbd3d--- /dev/null+++ b/server/routes/brainOnThisDay.js@@ -0,0 +1,19 @@+/**+ * On This Day route — past-year journal entries and Brain captures for the+ * dashboard widget. The server owns the timezone-correct date key (same+ * contract as /api/calendar/agenda).+ */++import { Router } from 'express';+import { getOnThisDay } from '../services/brainOnThisDay.js';+import { asyncHandler } from '../lib/errorHandler.js';+import { parsePagination } from '../lib/validation.js';++const router = Router();++router.get('/on-this-day', asyncHandler(async (req, res) => {+ const { limit } = parsePagination(req.query, { defaultLimit: 8, maxLimit: 20 });+ res.json(await getOnThisDay({ limit }));+}));++export default router;diff --git a/server/routes/brainOnThisDay.test.js b/server/routes/brainOnThisDay.test.jsnew file mode 100644index 0000000000..ee80212c4d--- /dev/null+++ b/server/routes/brainOnThisDay.test.js@@ -0,0 +1,37 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import onThisDayRoutes from './brainOnThisDay.js';++vi.mock('../services/brainOnThisDay.js', () => ({+ getOnThisDay: vi.fn(),+}));++import { getOnThisDay } from '../services/brainOnThisDay.js';++const app = express();+app.use('/api/brain', onThisDayRoutes);++describe('GET /api/brain/on-this-day', () => {+ beforeEach(() => vi.clearAllMocks());++ it('returns the service payload with the default limit', async () => {+ const payload = { date: '2026-09-01', timezone: 'UTC', total: 1, items: [{ type: 'journal', id: '2025-09-01', date: '2025-09-01', yearsAgo: 1, title: null, snippet: 'a year ago' }] };+ getOnThisDay.mockResolvedValue(payload);++ const response = await request(app).get('/api/brain/on-this-day');++ expect(response.status).toBe(200);+ expect(response.body).toEqual(payload);+ expect(getOnThisDay).toHaveBeenCalledWith({ limit: 8 });+ });++ it('clamps the limit query param to the route maximum', async () => {+ getOnThisDay.mockResolvedValue({ date: '2026-09-01', timezone: 'UTC', total: 0, items: [] });++ const response = await request(app).get('/api/brain/on-this-day?limit=500');++ expect(response.status).toBe(200);+ expect(getOnThisDay).toHaveBeenCalledWith({ limit: 20 });+ });+});diff --git a/server/services/brainOnThisDay.js b/server/services/brainOnThisDay.jsnew file mode 100644index 0000000000..2900bca860--- /dev/null+++ b/server/services/brainOnThisDay.js@@ -0,0 +1,99 @@+/**+ * On This Day — resurface Brain journal entries, memories, and ideas written+ * on this calendar date in previous years. Machine-local read for the+ * dashboard widget; nothing here rides federation.+ *+ * The server owns the timezone-correct date key (same contract as+ * /api/calendar/agenda): journals are already keyed by local date, and+ * created-at timestamps are converted through the user's configured timezone+ * so a late-night capture lands on the day the user experienced.+ */++import * as brainStorage from './brainStorage.js';+import { getUserTimezone } from './userTimezone.js';+import { todayInTimezone } from '../lib/timezone.js';++const SNIPPET_MAX = 160;++// Rows within the same year group in narrative order: the day's journal first,+// then captured memories, then ideas.+const TYPE_RANK = { journal: 0, memory: 1, idea: 2 };++/**+ * Collapse a markdown-ish body to one line of preview text.+ */+export function snippetOf(text, max = SNIPPET_MAX) {+ if (typeof text !== 'string') return '';+ const flat = text+ .replace(/```[\s\S]*?```/g, ' ')+ .replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')+ .replace(/^[#>\-*\s]+/gm, ' ')+ .replace(/\s+/g, ' ')+ .trim();+ if (flat.length <= max) return flat;+ return `${flat.slice(0, max - 1).trimEnd()}…`;+}++const yearOf = (isoDate) => Number(isoDate.slice(0, 4));++/**+ * Pure collector: match records to today's month-day in prior years.+ * `today` is the local YYYY-MM-DD; `timezone` converts record timestamps to+ * local dates. Exported for tests.+ */+export function collectOnThisDay({ today, timezone, journals = [], ideas = [], memories = [] }) {+ const monthDay = today.slice(5);+ const currentYear = yearOf(today);+ const items = [];++ // A record counts when its local date shares today's MM-DD in a PRIOR year.+ const priorYearLocalDate = (stamp) => {+ const at = Date.parse(stamp ?? '');+ if (!Number.isFinite(at)) return null;+ const localDate = todayInTimezone(timezone, new Date(at));+ if (localDate.slice(5) !== monthDay || yearOf(localDate) >= currentYear) return null;+ return localDate;+ };++ for (const journal of journals) {+ if (typeof journal?.date !== 'string' || !journal.date.endsWith(`-${monthDay}`)) continue;+ const year = yearOf(journal.date);+ if (!Number.isInteger(year) || year >= currentYear) continue;+ const snippet = snippetOf(journal.content);+ if (!snippet) continue;+ items.push({ type: 'journal', id: journal.date, date: journal.date, yearsAgo: currentYear - year, title: null, snippet });+ }++ for (const memory of memories) {+ // Imported memories carry the original capture time in sourceCreatedAt.+ const date = priorYearLocalDate(memory?.sourceCreatedAt || memory?.createdAt);+ if (!date || !memory.title) continue;+ items.push({ type: 'memory', id: memory.id, date, yearsAgo: currentYear - yearOf(date), title: memory.title, snippet: snippetOf(memory.content) });+ }++ for (const idea of ideas) {+ const date = priorYearLocalDate(idea?.createdAt);+ if (!date || !idea.title) continue;+ items.push({ type: 'idea', id: idea.id, date, yearsAgo: currentYear - yearOf(date), title: idea.title, snippet: snippetOf(idea.oneLiner) });+ }++ return items.sort((a, b) => a.yearsAgo - b.yearsAgo+ || TYPE_RANK[a.type] - TYPE_RANK[b.type]+ || (a.title || '').localeCompare(b.title || ''));+}++/**+ * The dashboard widget's read: today's lookbacks across journals, memories,+ * and ideas, capped at `limit` rows (total reports the uncapped match count).+ */+export async function getOnThisDay({ limit = 8 } = {}) {+ const timezone = await getUserTimezone();+ const today = todayInTimezone(timezone);+ const [journals, ideas, memories] = await Promise.all([+ brainStorage.getAll('journals'),+ brainStorage.getAll('ideas'),+ brainStorage.getAll('memories'),+ ]);+ const items = collectOnThisDay({ today, timezone, journals, ideas, memories });+ return { date: today, timezone, total: items.length, items: items.slice(0, limit) };+}diff --git a/server/services/brainOnThisDay.test.js b/server/services/brainOnThisDay.test.jsnew file mode 100644index 0000000000..3bd435c2d5--- /dev/null+++ b/server/services/brainOnThisDay.test.js@@ -0,0 +1,92 @@+import { describe, it, expect } from 'vitest';+import { collectOnThisDay, snippetOf } from './brainOnThisDay.js';++const TZ = 'America/Los_Angeles';+const TODAY = '2026-09-01';++describe('snippetOf', () => {+ it('flattens markdown chrome and collapses whitespace', () => {+ expect(snippetOf('# Heading\n\n- did a [thing](https://example.com)\n> quote')).toBe('Heading did a thing quote');+ });++ it('drops fenced code blocks and truncates with an ellipsis', () => {+ const long = `intro ${'word '.repeat(60)}`;+ expect(snippetOf('```js\nsecret()\n```\nafter')).toBe('after');+ const out = snippetOf(long, 40);+ expect(out.length).toBeLessThanOrEqual(40);+ expect(out.endsWith('…')).toBe(true);+ });++ it('returns empty for non-strings and whitespace-only bodies', () => {+ expect(snippetOf(null)).toBe('');+ expect(snippetOf(' \n ')).toBe('');+ });+});++describe('collectOnThisDay', () => {+ it('matches journals by month-day in prior years only', () => {+ const items = collectOnThisDay({+ today: TODAY,+ timezone: TZ,+ journals: [+ { date: '2024-09-01', content: 'two years back' },+ { date: '2025-09-01', content: 'one year back' },+ { date: '2026-09-01', content: 'today itself' },+ { date: '2025-08-31', content: 'wrong day' },+ { date: '2025-09-01', content: ' ' },+ ],+ });+ expect(items.map((i) => [i.type, i.date, i.yearsAgo])).toEqual([+ ['journal', '2025-09-01', 1],+ ['journal', '2024-09-01', 2],+ ]);+ });++ it('converts memory/idea timestamps through the user timezone', () => {+ // 2025-09-02T04:30Z is still Sep 1 in Los Angeles — it must match.+ // 2025-09-01T04:30Z is Aug 31 local — it must not.+ const items = collectOnThisDay({+ today: TODAY,+ timezone: TZ,+ memories: [+ { id: 'm1', title: 'Late night', content: 'body', createdAt: '2025-09-02T04:30:00.000Z' },+ { id: 'm2', title: 'Wrong local day', content: 'body', createdAt: '2025-09-01T04:30:00.000Z' },+ ],+ ideas: [+ { id: 'i1', title: 'Spark', oneLiner: 'the pitch', createdAt: '2024-09-01T18:00:00.000Z' },+ ],+ });+ expect(items.map((i) => [i.type, i.id, i.yearsAgo])).toEqual([+ ['memory', 'm1', 1],+ ['idea', 'i1', 2],+ ]);+ expect(items[0].date).toBe('2025-09-01');+ });++ it('prefers sourceCreatedAt for imported memories and skips unparseable stamps', () => {+ const items = collectOnThisDay({+ today: TODAY,+ timezone: TZ,+ memories: [+ // createdAt is the import time (today); sourceCreatedAt is the real capture.+ { id: 'm1', title: 'Imported', sourceCreatedAt: '2023-09-01T20:00:00.000Z', createdAt: '2026-08-30T00:00:00.000Z' },+ { id: 'm2', title: 'Broken stamp', createdAt: 'not-a-date' },+ { id: 'm3', createdAt: '2023-09-01T20:00:00.000Z' },+ ],+ });+ expect(items).toEqual([+ { type: 'memory', id: 'm1', date: '2023-09-01', yearsAgo: 3, title: 'Imported', snippet: '' },+ ]);+ });++ it('sorts most recent year first, journal before memory before idea within a year', () => {+ const items = collectOnThisDay({+ today: TODAY,+ timezone: TZ,+ journals: [{ date: '2025-09-01', content: 'journal' }],+ ideas: [{ id: 'i1', title: 'Idea', oneLiner: 'x', createdAt: '2025-09-01T18:00:00.000Z' }],+ memories: [{ id: 'm1', title: 'Memory', createdAt: '2025-09-01T18:00:00.000Z' }],+ });+ expect(items.map((i) => i.type)).toEqual(['journal', 'memory', 'idea']);+ });+});diff --git a/server/services/dashboardLayouts.js b/server/services/dashboardLayouts.jsindex e64dfc2603..68906617ae 100644--- a/server/services/dashboardLayouts.js+++ b/server/services/dashboardLayouts.js@@ -111,7 +111,7 @@ const DEFAULT_LAYOUTS = ['apps','cos', 'goal-progress', 'upcoming-tasks','proactive-alerts', 'review-hub', 'while-away', 'system-health', 'active-processing', 'network-exposure', 'backup', 'death-clock', 'quick-stats', 'decision-log',- 'hourly-activity', 'tribe-care', 'feeds', 'today-agenda',+ 'hourly-activity', 'tribe-care', 'feeds', 'today-agenda', 'on-this-day',],// Above-the-fold capture row stretches to h=5 so the Quick Task card// can show its expanded options (worktree/PR/simplify/etc.) without@@ -151,6 +151,8 @@ const DEFAULT_LAYOUTS = [{ id: 'feeds', x: 8, w: 3, order: 20, h: 4 },// Gated on a connected calendar account — hidden until one exists.{ id: 'today-agenda', x: 0, w: 4, order: 21, h: 4 },+ // Gated on having past-year Brain captures for today's date.+ { id: 'on-this-day', x: 4, w: 4, order: 22, h: 4 },],},{@@ -172,7 +174,7 @@ const DEFAULT_LAYOUTS = [id: 'morning-review',name: 'Morning Review',builtIn: true,- widgets: ['proactive-alerts', 'upcoming-tasks', 'review-hub', 'goal-progress', 'death-clock', 'daily-driver', 'today-agenda'],+ widgets: ['proactive-alerts', 'upcoming-tasks', 'review-hub', 'goal-progress', 'death-clock', 'daily-driver', 'today-agenda', 'on-this-day'],// Scan-and-act morning ritual — the classic scan quadrants above the fold.// Tasks list takes the tall center column (the actionable hot zone); alerts// top-left grab attention first; death-clock top-right for mortality framing;@@ -192,6 +194,9 @@ const DEFAULT_LAYOUTS = [// Gated on a connected calendar account — sequenced last (like the// gated tribe-care/feeds widgets) so its absence leaves only trailing space.{ id: 'today-agenda', x: 0, w: 4, order: 6, h: 4 },+ // Gated on having past-year Brain captures for today's date — same+ // trailing-space contract as the other gated widgets.+ { id: 'on-this-day', x: 4, w: 4, order: 7, h: 4 },],},{