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: voice-dictatable Daily Log in Brain (Obsidian mirror + CoS memory indexing) (#145)
[._.]/ Adam Eivy545eb3ea3be3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e50ede170d..abe4ebe186 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,6 +1,7 @@## Added-- **Voice CoS tool expansion — round two** — nine more hands-free tools registered in `server/services/voice/tools.js`, bringing the total to 14:+- **Daily Log — voice-dictatable diary in the Brain section** — new `Brain → Daily Log` tab at `/brain/daily-log` for free-form typed or dictated daily entries. One entry per date, stored in `data/brain/journals.json` with per-segment source metadata (`text` vs `voice`). Five voice tools land in the CoS: `daily_log_open` ("open my daily log" — navigates + optionally starts dictation), `daily_log_start_dictation` / `daily_log_stop_dictation`, `daily_log_append` (one-shot append without dictation mode), and `daily_log_read` (reads the entry verbatim via TTS). Dictation mode short-circuits the LLM at the server — every voice utterance appends straight to the log until the user says "stop dictation" — so the CoS stops talking back while you ramble. Tools can now emit client-side side effects (`voice:navigate`, `voice:dictation`); the Voice widget listens and routes the browser + surfaces a "Dictating to Daily Log" chip. Optional Obsidian mirror: each entry auto-writes to `<vault>/<folder>/<YYYY-MM-DD>.md` when a vault is configured in the tab's settings panel (reuses the existing Notes vault registry), picking up iCloud backup for free. Entries flow through `brainMemoryBridge.js` (new `journals` brain type, `daily-log` category) so the CoS memory system vector-embeds each day and agents can semantically search across the log history. New routes: `GET/PUT/DELETE /api/brain/daily-log/:date`, `POST /api/brain/daily-log/:date/append`, `GET/PUT /api/brain/daily-log/settings`, `POST /api/brain/daily-log/sync-obsidian`.+- **Voice CoS tool expansion — round two** — nine more hands-free tools registered in `server/services/voice/tools.js`, further expanding the Voice CoS toolset:- `brain_list_recent` — "Read me my last five captures"; returns the newest inbox entries with date + text.- `meatspace_log_weight` — "Log my weight at 180"; accepts `lb` (default) or `kg`, auto-converts to lb before persisting, defaults to today.- `goal_list` — "What are my goals?"; lists active goals ordered by urgency with horizon, category, and progress percent.diff --git a/client/src/components/brain/constants.js b/client/src/components/brain/constants.jsindex 231fe275d3..36a157e1ac 100644--- a/client/src/components/brain/constants.js+++ b/client/src/components/brain/constants.js@@ -1,8 +1,9 @@-import { MessageSquare, Database, Calendar, Rss, Shield, Users, FolderKanban, Lightbulb, ClipboardList, Settings, Link2, BookOpen, Network, FileText } from 'lucide-react';+import { MessageSquare, Database, Calendar, Rss, Shield, Users, FolderKanban, Lightbulb, ClipboardList, Settings, Link2, BookOpen, Network, FileText, NotebookPen } from 'lucide-react';// Main navigation tabsexport const TABS = [{ id: 'inbox', label: 'Inbox', icon: MessageSquare },+ { id: 'daily-log', label: 'Daily Log', icon: NotebookPen },{ id: 'links', label: 'Links', icon: Link2 },{ id: 'memory', label: 'Memory', icon: Database },{ id: 'notes', label: 'Notes', icon: FileText },diff --git a/client/src/components/brain/tabs/DailyLogTab.jsx b/client/src/components/brain/tabs/DailyLogTab.jsxnew file mode 100644index 0000000000..2b05617e4f--- /dev/null+++ b/client/src/components/brain/tabs/DailyLogTab.jsx@@ -0,0 +1,577 @@+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import {+ BookOpen, ChevronLeft, ChevronRight, Mic, MicOff, RefreshCw, Save, Volume2, Settings,+ Plus, Trash2, CloudUpload+} from 'lucide-react';+import * as api from '../../../services/api';+import { getNotesVaults } from '../../../services/apiNotes';+import toast from '../../ui/Toast';+import { onVoiceEvent, sendText, setDictation as setVoiceDictation } from '../../../services/voiceClient';++// Slim shape kept in the sidebar history list — full `content`/`segments`+// would accumulate as the log grows and the sidebar never renders them.+const toHistorySummary = (entry) => ({+ id: entry.id,+ date: entry.date,+ updatedAt: entry.updatedAt,+ obsidianPath: entry.obsidianPath || null,+ segmentCount: typeof entry.segmentCount === 'number'+ ? entry.segmentCount+ : (Array.isArray(entry.segments) ? entry.segments.length : 0),+});++const upsertHistory = (prev, entry) => {+ const summary = toHistorySummary(entry);+ const others = prev.filter((h) => h.date !== summary.date);+ return [summary, ...others].sort((a, b) => b.date.localeCompare(a.date));+};++// ISO YYYY-MM-DD fallback — browser local timezone. Used only as an initial+// value before the backend responds with its canonical "today" (which honors+// the user's configured timezone, so remote/VPN access doesn't desync the+// day). Replaced on mount via a GET /daily-log/today.+const localToday = () => {+ const d = new Date();+ 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}`;+};++const shiftDate = (iso, days) => {+ const [y, m, d] = iso.split('-').map(Number);+ const date = new Date(Date.UTC(y, m - 1, d));+ date.setUTCDate(date.getUTCDate() + days);+ return date.toISOString().slice(0, 10);+};++export default function DailyLogTab() {+ const [date, setDate] = useState(localToday());+ // 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 localToday() until fetched.+ const [serverToday, setServerToday] = useState(localToday());+ const [entry, setEntry] = useState(null);+ const [content, setContent] = useState('');+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [quickAppend, setQuickAppend] = useState('');+ const [appending, setAppending] = useState(false);+ const [history, setHistory] = useState([]);+ const [dictation, setDictation] = useState(false);+ const [showSettings, setShowSettings] = useState(false);+ const [settings, setSettings] = useState(null);+ const [vaults, setVaults] = useState([]);+ const [confirmDelete, setConfirmDelete] = useState(false);+ const [syncing, setSyncing] = useState(false);+ const editorRef = useRef(null);+ // Ref mirror of the dirty flag so the socket event handler can check it+ // without adding `content`/`entry` to the effect's dependency list+ // (which would re-subscribe on every keystroke).+ const dirtyRef = useRef(false);+ // Monotonic counter of outstanding loadEntry() calls so an older fetch+ // resolving after a newer one can't overwrite the entry state for the+ // wrong date (common when prev/next is mashed or the server-today fetch+ // lands after the user has already picked a different date).+ const loadRequestRef = useRef(0);+ // Tracks the dictation state the user just requested (null when idle).+ // Set by toggleDictation; consumed by the voice:dictation echo handler to+ // fire the success toast, or by the voice:error handler to revert and+ // surface a failure toast. Without this, clicking toggle while voice is+ // disabled would show an optimistic "Dictation on" that never actually+ // happened on the server.+ const pendingDictationRef = useRef(null);++ const dirty = content !== (entry?.content || '');+ dirtyRef.current = dirty;++ const loadEntry = useCallback(async (d, { silent = false } = {}) => {+ if (!silent) setLoading(true);+ const reqId = ++loadRequestRef.current;+ const res = await api.getDailyLog(d).catch(() => null);+ if (reqId !== loadRequestRef.current) return;+ const data = res?.entry || null;+ setEntry(data);+ setContent(data?.content || '');+ if (!silent) setLoading(false);+ }, []);++ const loadHistory = useCallback(async () => {+ const res = await api.listDailyLogs({ limit: 60 }).catch(() => null);+ setHistory(res?.records || []);+ }, []);++ const loadSettings = useCallback(async () => {+ const [s, v] = await Promise.all([+ api.getDailyLogSettings().catch(() => null),+ getNotesVaults().catch(() => []),+ ]);+ if (s) setSettings(s);+ setVaults(v || []);+ }, []);++ useEffect(() => { loadEntry(date); }, [date, loadEntry]);+ useEffect(() => { loadHistory(); loadSettings(); }, [loadHistory, loadSettings]);++ // Keep the server's dictation target date aligned with the UI while+ // dictation is active — otherwise navigating to an earlier day (prev/next+ // button, date picker) would still route new voice utterances into the+ // day that was active when the user toggled dictation on.+ useEffect(() => {+ if (dictation) setVoiceDictation(true, date);+ }, [date, dictation]);++ // Ask the server for its canonical "today" so a user in a different timezone+ // than the browser (remote/VPN access) doesn't open the tab on the wrong day.+ useEffect(() => {+ let cancelled = false;+ api.getDailyLog('today').then((res) => {+ if (cancelled || !res?.date) return;+ setServerToday(res.date);+ // If we initialized with a wrong local date, hop to the real one.+ if (date === localToday() && res.date !== date) setDate(res.date);+ }).catch(() => null);+ return () => { cancelled = true; };+ // Only on mount — we intentionally don't re-run when date changes.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ useEffect(() => {+ // Server sends only the delta ({date, text, segment, segmentCount,+ // updatedAt}) — patch local state to avoid repeatedly shipping the+ // full entry over the socket as the day grows.+ const onAppend = (payload) => {+ if (!payload?.date || typeof payload.text !== 'string') return;+ const { date: appendedDate, text: appendedText, segment, segmentCount, updatedAt } = payload;+ // Full-entry patch — used for the right-hand editor/preview where+ // `segments[]` and `content` must be present. Safe against either a+ // summary-only previous state or a full entry.+ const patchFullEntry = (prev) => {+ if (!prev || prev.date !== appendedDate) {+ return {+ date: appendedDate,+ content: appendedText,+ segments: segment ? [segment] : [],+ segmentCount: segmentCount ?? (segment ? 1 : 0),+ updatedAt: updatedAt || prev?.updatedAt,+ obsidianPath: prev?.obsidianPath || null,+ };+ }+ const nextContent = prev.content+ ? `${prev.content.replace(/\s+$/, '')}\n\n${appendedText}`+ : appendedText;+ const nextSegments = segment ? [...(prev.segments || []), segment] : (prev.segments || []);+ return {+ ...prev,+ content: nextContent,+ segments: nextSegments,+ segmentCount: segmentCount ?? nextSegments.length,+ updatedAt: updatedAt || prev.updatedAt,+ };+ };+ setHistory((prev) => {+ const existing = prev.find((h) => h.date === appendedDate);+ // Sidebar entries are summaries — only carry metadata, not content.+ // Patch just what the sidebar renders (segmentCount, updatedAt,+ // obsidianPath) to keep memory and renders cheap.+ const patched = existing+ ? { ...existing, segmentCount: segmentCount ?? (existing.segmentCount ?? 0) + 1, updatedAt: updatedAt || existing.updatedAt }+ : {+ date: appendedDate,+ segmentCount: segmentCount ?? 1,+ updatedAt: updatedAt || new Date().toISOString(),+ obsidianPath: null,+ };+ return upsertHistory(prev, patched);+ });+ if (appendedDate === date) {+ setEntry((prev) => patchFullEntry(prev));+ // Only sync the textarea when the user has no unsaved edits —+ // otherwise an incoming voice segment would clobber whatever they're+ // in the middle of typing. The entry state still updates so the+ // segment count badge reflects the append.+ if (!dirtyRef.current) {+ setContent((prevContent) => (prevContent+ ? `${prevContent.replace(/\s+$/, '')}\n\n${appendedText}`+ : appendedText));+ } else {+ toast('Voice segment appended while you were editing — save or refresh to see it.', { icon: '📝' });+ }+ }+ };+ const onDictation = (payload) => {+ const nextEnabled = !!payload?.enabled;+ setDictation((prev) => (prev === nextEnabled ? prev : nextEnabled));+ if (payload?.date && payload.date !== date) setDate(payload.date);+ // If this echo is the server's response to a user-initiated toggle,+ // confirm success with the appropriate toast. Voice-tool-initiated+ // changes (no pending ref set) are confirmed by the CoS reply, so+ // we stay quiet.+ const requested = pendingDictationRef.current;+ if (requested !== null && nextEnabled === requested) {+ pendingDictationRef.current = null;+ if (nextEnabled) {+ toast('Dictation on — speak your log. Say "stop dictation" to end.', { icon: '🎙️' });+ } else {+ toast('Dictation off.', { icon: '🔇' });+ }+ }+ };+ // A voice:error with stage='dictation' while a toggle is in flight+ // means the server rejected the change (most commonly: voice mode is+ // disabled). Revert the optimistic local state and surface a failure+ // toast. Unrelated voice:error stages (turn/text) are handled by the+ // VoiceWidget's own listener — don't clobber our pending dictation+ // state on those.+ const onVoiceError = (err) => {+ if (pendingDictationRef.current !== null && err?.stage === 'dictation') {+ pendingDictationRef.current = null;+ setDictation(false);+ toast.error('Voice mode is disabled — can\'t enter dictation. Enable it in Settings → Voice.');+ }+ };+ const offs = [+ onVoiceEvent('voice:dailyLog:appended', onAppend),+ onVoiceEvent('voice:dictation', onDictation),+ onVoiceEvent('voice:error', onVoiceError),+ ];+ return () => offs.forEach((off) => off());+ }, [date]);++ const applyEntry = (next) => {+ setEntry(next);+ setContent(next.content || '');+ setHistory((prev) => upsertHistory(prev, next));+ };++ const handleSave = async () => {+ setSaving(true);+ const res = await api.updateDailyLog(date, content).catch(() => null);+ setSaving(false);+ if (!res?.entry) {+ toast.error('Save failed');+ return;+ }+ applyEntry(res.entry);+ toast.success('Saved');+ };++ const handleAppend = async () => {+ const text = quickAppend.trim();+ if (!text) return;+ setAppending(true);+ const res = await api.appendDailyLog(date, text, 'text').catch(() => null);+ setAppending(false);+ if (!res?.entry) {+ toast.error('Append failed');+ return;+ }+ applyEntry(res.entry);+ setQuickAppend('');+ };++ const toggleDictation = () => {+ const next = !dictation;+ // Optimistic local flip for responsive UI; the success toast waits for+ // the server echo (voice:dictation) and a voice:error revert will undo+ // this if the server rejected the change (e.g. voice mode disabled).+ pendingDictationRef.current = next;+ setDictation(next);+ setVoiceDictation(next, date);+ };++ // Route the read-back through the voice assistant so its TTS pipeline fires+ // — the browser TTS APIs would skip the project's Kokoro/Piper voice.+ //+ // The socket's MAX_TEXT_LEN cap (4000 chars) would reject any reasonably+ // full log if we inlined the content, so for long entries we delegate to+ // the daily_log_read tool and let the LLM speak the server-returned body.+ // Short logs still get inlined so the model can't add commentary or+ // accidentally skip content by summarizing the tool result.+ const READ_BACK_INLINE_LIMIT = 3800; // leaves room for prompt scaffolding under MAX_TEXT_LEN+ const readBack = () => {+ const body = content.trim();+ if (!body) {+ toast('Daily log is empty.', { icon: '📖' });+ return;+ }+ if (body.length <= READ_BACK_INLINE_LIMIT) {+ sendText(`Read this back to me verbatim, exactly as written, with no commentary:\n\n${body}`);+ } else {+ sendText(`Use the daily_log_read tool for ${date} and speak the full returned content aloud verbatim — no summarization, no commentary, just read it exactly as written.`);+ }+ };++ const handleDelete = async () => {+ const ok = await api.deleteDailyLog(date).then(() => true, () => false);+ if (!ok) {+ toast.error('Delete failed');+ return;+ }+ toast.success('Deleted');+ setConfirmDelete(false);+ setEntry(null);+ setContent('');+ setHistory((prev) => prev.filter((h) => h.date !== date));+ };++ const handleSyncObsidian = async () => {+ setSyncing(true);+ const res = await api.syncDailyLogsToObsidian().catch(() => null);+ setSyncing(false);+ if (res) toast.success(`Synced ${res.synced} entries to Obsidian`);+ else toast.error('Sync failed');+ };++ const saveSettings = async (partial) => {+ const next = await api.updateDailyLogSettings(partial).catch(() => null);+ if (next) {+ setSettings(next);+ toast.success('Settings saved');+ }+ };++ const isToday = date === serverToday;+ const segmentCount = entry?.segments?.length ?? entry?.segmentCount ?? 0;++ const dateLabel = useMemo(() => {+ try {+ return new Date(`${date}T00:00:00`).toLocaleDateString(undefined, {+ weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'+ });+ } catch { return date; }+ }, [date]);++ return (+ <div className="flex h-full -m-4" style={{ height: 'calc(100vh - 180px)' }}>+ {/* Left: history + settings */}+ <div className="w-64 border-r border-port-border flex flex-col shrink-0">+ <div className="p-3 border-b border-port-border flex items-center gap-2">+ <BookOpen size={14} className="text-port-accent" />+ <span className="text-sm font-medium text-white">Daily Log</span>+ <button+ onClick={() => setShowSettings((s) => !s)}+ className="ml-auto p-1 rounded text-gray-400 hover:text-white hover:bg-port-card"+ title="Daily log settings"+ >+ <Settings size={14} />+ </button>+ </div>++ {showSettings && (+ <div className="p-3 border-b border-port-border space-y-3">+ <div>+ <label className="block text-xs text-gray-400 mb-1">Obsidian vault (mirror logs)</label>+ <select+ value={settings?.obsidianVaultId || ''}+ onChange={(e) => saveSettings({ obsidianVaultId: e.target.value || null })}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"+ >+ <option value="">None — PortOS only</option>+ {vaults.map((v) => (+ <option key={v.id} value={v.id}>{v.name}</option>+ ))}+ </select>+ </div>+ <div>+ <label className="block text-xs text-gray-400 mb-1">Folder inside vault</label>+ <input+ type="text"+ value={settings?.obsidianFolder || ''}+ onChange={(e) => setSettings((s) => ({ ...(s || {}), obsidianFolder: e.target.value }))}+ onBlur={(e) => saveSettings({ obsidianFolder: e.target.value })}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"+ placeholder="Daily Log"+ />+ </div>+ <label className="flex items-center gap-2 text-xs text-gray-400">+ <input+ type="checkbox"+ checked={!!settings?.autoSync}+ onChange={(e) => saveSettings({ autoSync: e.target.checked })}+ />+ Auto-mirror to Obsidian on every save+ </label>+ <button+ onClick={handleSyncObsidian}+ disabled={!settings?.obsidianVaultId || syncing}+ className="flex items-center gap-2 w-full px-3 py-1.5 rounded bg-port-card text-gray-300 text-xs hover:text-white hover:bg-port-border disabled:opacity-50"+ >+ <CloudUpload size={12} className={syncing ? 'animate-pulse' : ''} />+ Re-sync all entries now+ </button>+ <p className="text-[10px] text-gray-600">+ Entries embed into the Chief-of-Staff memory system automatically so agents can search+ across daily logs.+ </p>+ </div>+ )}++ <div className="flex-1 overflow-auto">+ {history.length === 0 ? (+ <div className="p-4 text-xs text-gray-500">No entries yet — start today.</div>+ ) : (+ <div className="divide-y divide-port-border/50">+ {history.map((h) => {+ const active = h.date === date;+ return (+ <button+ key={h.date}+ onClick={() => setDate(h.date)}+ className={`w-full text-left px-3 py-2 hover:bg-port-card/50 ${+ active ? 'bg-port-accent/10 border-l-2 border-port-accent' : ''+ }`}+ >+ <div className={`text-sm ${active ? 'text-white' : 'text-gray-300'}`}>{h.date}</div>+ <div className="text-xs text-gray-500 truncate">+ {(() => { const n = h.segmentCount ?? h.segments?.length ?? 0; return `${n} segment${n === 1 ? '' : 's'}`; })()}+ {h.obsidianPath ? ' · obsidian' : ''}+ </div>+ </button>+ );+ })}+ </div>+ )}+ </div>+ </div>++ {/* Right: editor */}+ <div className="flex-1 flex flex-col min-w-0">+ <div className="flex items-center gap-2 px-4 py-3 border-b border-port-border">+ <button+ onClick={() => setDate(shiftDate(date, -1))}+ className="p-1.5 rounded hover:bg-port-card text-gray-400 hover:text-white"+ title="Previous day"+ >+ <ChevronLeft size={16} />+ </button>+ <input+ type="date"+ value={date}+ onChange={(e) => setDate(e.target.value || serverToday)}+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-sm text-white"+ />+ <button+ onClick={() => setDate(shiftDate(date, 1))}+ disabled={date >= serverToday}+ className="p-1.5 rounded hover:bg-port-card text-gray-400 hover:text-white disabled:opacity-30"+ title="Next day"+ >+ <ChevronRight size={16} />+ </button>+ {!isToday && (+ <button+ onClick={() => setDate(serverToday)}+ className="px-2 py-1 rounded bg-port-card text-xs text-gray-300 hover:text-white"+ >+ Today+ </button>+ )}+ <div className="flex-1 min-w-0">+ <div className="text-white font-medium truncate">{dateLabel}</div>+ <div className="text-xs text-gray-500">+ {segmentCount} segment{segmentCount === 1 ? '' : 's'}+ {entry?.obsidianPath ? ` · ${entry.obsidianPath}` : ''}+ </div>+ </div>+ <button+ onClick={readBack}+ className="flex items-center gap-1 px-3 py-1.5 rounded bg-port-card text-gray-300 text-sm hover:text-white"+ title="Have the voice agent read this log back to you"+ >+ <Volume2 size={14} /> Read back+ </button>+ <button+ onClick={toggleDictation}+ className={`flex items-center gap-1 px-3 py-1.5 rounded text-sm ${+ dictation+ ? 'bg-port-accent text-white animate-pulse'+ : 'bg-port-card text-gray-300 hover:text-white'+ }`}+ title={dictation ? 'Stop voice dictation' : 'Start voice dictation (voice goes straight into this log)'}+ >+ {dictation ? <MicOff size={14} /> : <Mic size={14} />}+ {dictation ? 'Dictating' : 'Dictate'}+ </button>+ <button+ onClick={handleSave}+ disabled={saving || !dirty}+ className="flex items-center gap-1 px-3 py-1.5 rounded bg-port-accent text-white text-sm hover:bg-port-accent/80 disabled:opacity-50"+ >+ <Save size={14} />+ {saving ? 'Saving…' : 'Save'}+ </button>+ <button+ onClick={() => setConfirmDelete(true)}+ disabled={!entry}+ className="p-1.5 rounded hover:bg-port-card text-gray-400 hover:text-port-error disabled:opacity-30"+ title="Delete this entry"+ >+ <Trash2 size={14} />+ </button>+ </div>++ {dictation && (+ <div className="px-4 py-2 bg-port-accent/10 border-b border-port-accent/30 text-sm text-port-accent flex items-center gap-2">+ <Mic size={14} className="animate-pulse" />+ Dictation on — speak your log. Say <span className="font-mono">"stop dictation"</span> to end.+ The voice assistant is NOT replying — every utterance appends to this entry.+ </div>+ )}++ {confirmDelete && (+ <div className="px-4 py-2 bg-port-error/10 border-b border-port-error/30 flex items-center gap-3 text-sm">+ <span className="text-port-error">Delete the entry for {date} permanently?</span>+ <button onClick={handleDelete} className="px-2 py-1 rounded bg-port-error text-white text-xs">Delete</button>+ <button onClick={() => setConfirmDelete(false)} className="px-2 py-1 rounded bg-port-card text-gray-300 text-xs">Cancel</button>+ </div>+ )}++ {loading ? (+ <div className="flex items-center justify-center flex-1">+ <RefreshCw className="w-6 h-6 text-port-accent animate-spin" />+ </div>+ ) : (+ <>+ <textarea+ ref={editorRef}+ value={content}+ onChange={(e) => setContent(e.target.value)}+ placeholder={isToday+ ? "What's on your mind today? Type freely, append voice segments, or toggle dictation above…"+ : 'This day\'s entry is empty.'}+ className="flex-1 w-full p-4 bg-port-bg text-gray-200 text-sm resize-none focus:outline-none font-sans"+ spellCheck+ onKeyDown={(e) => {+ if ((e.metaKey || e.ctrlKey) && e.key === 's') {+ e.preventDefault();+ if (dirty) handleSave();+ }+ }}+ />+ <form+ onSubmit={(e) => { e.preventDefault(); handleAppend(); }}+ className="flex items-center gap-2 px-4 py-3 border-t border-port-border bg-port-card/30"+ >+ <Plus size={14} className="text-gray-500" />+ <input+ type="text"+ value={quickAppend}+ onChange={(e) => setQuickAppend(e.target.value)}+ placeholder="Quick append — adds a new paragraph to this day's log…"+ className="flex-1 bg-port-bg border border-port-border rounded px-3 py-1.5 text-sm text-white placeholder-gray-500"+ />+ <button+ type="submit"+ disabled={appending || !quickAppend.trim()}+ className="px-3 py-1.5 rounded bg-port-accent text-white text-sm disabled:opacity-50"+ >+ {appending ? '…' : 'Append'}+ </button>+ </form>+ </>+ )}+ </div>+ </div>+ );+}diff --git a/client/src/components/voice/VoiceWidget.jsx b/client/src/components/voice/VoiceWidget.jsxindex f91a39f746..4bc16cc38f 100644--- a/client/src/components/voice/VoiceWidget.jsx+++ b/client/src/components/voice/VoiceWidget.jsx@@ -1,5 +1,6 @@import { useState, useEffect, useRef, useCallback } from 'react';-import { Mic, MicOff, Brain, Volume2, Square, Trash2, ChevronDown, ChevronUp, Send, Infinity as InfinityIcon, X } from 'lucide-react';+import { useNavigate } from 'react-router-dom';+import { Mic, MicOff, Brain, Volume2, Square, Trash2, ChevronDown, ChevronUp, Send, Infinity as InfinityIcon, NotebookPen, X } from 'lucide-react';import {startCapture, stopCapture, interrupt, resetConversation, sendText, onVoiceEvent, isCapturing,startContinuous, stopContinuous, isContinuous, whenPlaybackDrained, getVadLevel,@@ -35,6 +36,7 @@ const warnIfQuiet = (peak) => {};export default function VoiceWidget() {+ const navigate = useNavigate();const [enabled, setEnabled] = useState(false);const [hotkey, setHotkey] = useState('Space');const [sttEngine, setSttEngine] = useState('whisper');@@ -45,6 +47,7 @@ export default function VoiceWidget() {const [draft, setDraft] = useState('');const [interimTranscript, setInterimTranscript] = useState('');const [expanded, setExpanded] = useState(false);+ const [dictationActive, setDictationActive] = useState(false);const [handsFree, setHandsFree] = useState(() => {if (typeof window === 'undefined') return true;const stored = window.localStorage.getItem(HANDS_FREE_KEY);@@ -136,9 +139,21 @@ export default function VoiceWidget() {toast.error(`Voice: ${d.message}`);setStage(restState());}),+ onVoiceEvent('voice:navigate', (d) => {+ if (d?.path && typeof d.path === 'string') navigate(d.path);+ }),+ onVoiceEvent('voice:dictation', (d) => {+ setDictationActive((prev) => (prev === !!d?.enabled ? prev : !!d?.enabled));+ }),+ onVoiceEvent('voice:dailyLog:appended', (d) => {+ if (d?.text) {+ const preview = d.text.length > 60 ? `${d.text.slice(0, 60)}…` : d.text;+ toast(`📓 +"${preview}"`);+ }+ }),];return () => offs.forEach((off) => off());- }, [enabled]);+ }, [enabled, navigate]);// Auto-scroll to bottom on new contentuseEffect(() => {@@ -361,6 +376,12 @@ export default function VoiceWidget() {<Send size={14} /></button></form>+ {dictationActive && (+ <div className="flex items-center gap-2 bg-port-accent/15 border border-port-accent/40 rounded-full px-3 py-1 text-xs text-port-accent shadow-lg">+ <NotebookPen size={12} className="animate-pulse" />+ Dictating to Daily Log — say "stop dictation" to end+ </div>+ )}<div className="flex items-center gap-2 bg-port-card/95 backdrop-blur border border-port-border rounded-full pl-3 pr-1 py-1 shadow-lg"><span className={`text-xs ${tone}`}>{label}</span>{!useWebSpeech && handsFree && isContinuous() && (diff --git a/client/src/pages/Brain.jsx b/client/src/pages/Brain.jsxindex c38d913649..5651c35691 100644--- a/client/src/pages/Brain.jsx+++ b/client/src/pages/Brain.jsx@@ -14,6 +14,7 @@ import DigestTab from '../components/brain/tabs/DigestTab';import FeedsTab from '../components/brain/tabs/FeedsTab';import TrustTab from '../components/brain/tabs/TrustTab';import NotesTab from '../components/brain/tabs/NotesTab';+import DailyLogTab from '../components/brain/tabs/DailyLogTab';import ConfigTab from '../components/brain/tabs/ConfigTab';export default function Brain() {@@ -55,6 +56,8 @@ export default function Brain() {return <MemoryTab onRefresh={fetchData} />;case 'notes':return <NotesTab onRefresh={fetchData} />;+ case 'daily-log':+ return <DailyLogTab />;case 'graph':return <BrainGraph />;case 'digest':diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.jsindex a4ea98794d..82ca660a1d 100644--- a/client/src/services/apiBrain.js+++ b/client/src/services/apiBrain.js@@ -159,3 +159,30 @@ export const getBrainGraph = () => request('/brain/graph');// Brain - Bridge Sync (brain data to CoS memory system)export const syncBrainData = () => request('/brain/bridge-sync', { method: 'POST' });++// Brain - Daily Log+export const listDailyLogs = (options = {}) => {+ const params = new URLSearchParams();+ if (options.limit) params.set('limit', options.limit);+ if (options.offset) params.set('offset', options.offset);+ return request(`/brain/daily-log?${params}`);+};+export const getDailyLog = (date = 'today') => request(`/brain/daily-log/${encodeURIComponent(date)}`);+export const appendDailyLog = (date, text, source = 'text') => request(+ `/brain/daily-log/${encodeURIComponent(date)}/append`,+ { method: 'POST', body: JSON.stringify({ text, source }) }+);+export const updateDailyLog = (date, content) => request(+ `/brain/daily-log/${encodeURIComponent(date)}`,+ { method: 'PUT', body: JSON.stringify({ content }) }+);+export const deleteDailyLog = (date) => request(+ `/brain/daily-log/${encodeURIComponent(date)}`,+ { method: 'DELETE' }+);+export const getDailyLogSettings = () => request('/brain/daily-log/settings');+export const updateDailyLogSettings = (settings) => request('/brain/daily-log/settings', {+ method: 'PUT',+ body: JSON.stringify(settings)+});+export const syncDailyLogsToObsidian = () => request('/brain/daily-log/sync-obsidian', { method: 'POST' });diff --git a/client/src/services/voiceClient.js b/client/src/services/voiceClient.jsindex 4b92c4ffa6..a1d16815c5 100644--- a/client/src/services/voiceClient.js+++ b/client/src/services/voiceClient.js@@ -219,11 +219,15 @@ export const stopCapture = async ({ submit = true } = {}) => {return { mimeType: 'audio/wav', size: wav.byteLength, sourceSize: blob.size, peak };};-export const sendText = (text) => {+export const sendText = (text, source = 'text') => {const trimmed = (text || '').trim();if (!trimmed) return;stopPlayback();- socket.emit('voice:text', { text: trimmed });+ socket.emit('voice:text', { text: trimmed, source });+};++export const setDictation = (enabled, date) => {+ socket.emit('voice:dictation:set', { enabled: !!enabled, date: date || null });};export const interrupt = () => {@@ -622,8 +626,9 @@ export const startWebSpeechCapture = ({ language, ...callbacks } = {}) => {callbacks.onFinal?.(final);// Any successful result resets the restart-failure counter.webSpeechRestartFailures = 0;- // Send as text — server pipeline skips STT and goes straight to LLM- sendText(final);+ // source='voice' so the server still treats this as a spoken utterance+ // for dictation-mode routing — the text path otherwise bypasses it.+ sendText(final, 'voice');}};diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex da485a557e..cf918b5629 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -399,3 +399,12 @@ const brainSyncChangeSchema = z.object({export const brainSyncPushSchema = z.object({changes: z.array(brainSyncChangeSchema).min(1).max(1000)});++// Daily log settings schema (PUT /api/brain/daily-log/settings body).+// Only these three keys are persisted — strict() rejects unknown keys so+// a typo or stray payload field can't corrupt the settings file.+export const dailyLogSettingsSchema = z.object({+ obsidianVaultId: z.string().nullable().optional(),+ obsidianFolder: z.string().optional(),+ autoSync: z.boolean().optional()+}).strict();diff --git a/server/routes/brain.js b/server/routes/brain.jsindex e080d8b235..6ae4ebf20a 100644--- a/server/routes/brain.js+++ b/server/routes/brain.js@@ -31,13 +31,15 @@ import {linkUpdateInputSchema,linksQuerySchema,brainSyncQuerySchema,- brainSyncPushSchema+ brainSyncPushSchema,+ dailyLogSettingsSchema} from '../lib/brainValidation.js';import * as githubCloner from '../services/githubCloner.js';import { getBrainGraphData } from '../services/brainGraph.js';import { syncAllBrainData } from '../services/brainMemoryBridge.js';import * as brainSyncLog from '../services/brainSyncLog.js';import * as brainSync from '../services/brainSync.js';+import * as journal from '../services/brainJournal.js';const router = Router();@@ -767,4 +769,119 @@ router.post('/sync', asyncHandler(async (req, res) => {res.json(result);}));+// =============================================================================+// DAILY LOG+// =============================================================================++// Resolve the :date route param: either 'today' → current local date, or a+// real ISO YYYY-MM-DD calendar day. Delegates to journal.isIsoDate so the+// date rules stay in one place (service layer) and can't drift between+// routes and internal callers.+const resolveJournalDate = async (date) => {+ if (!date || date === 'today') return journal.getToday();+ if (!journal.isIsoDate(date)) {+ throw new ServerError('Invalid date. Expected "today" or YYYY-MM-DD.', {+ status: 400,+ code: 'BAD_REQUEST',+ });+ }+ return date;+};++/**+ * GET /api/brain/daily-log+ * List daily log entries (most recent first)+ */+router.get('/daily-log', asyncHandler(async (req, res) => {+ // Clamp pagination: negative or zero limit / negative offset would slice+ // unpredictably (or from the end of the array). Match the convention used+ // by other paginated brain routes.+ const parsedLimit = parseInt(req.query.limit, 10);+ const parsedOffset = parseInt(req.query.offset, 10);+ const limit = Math.min(Math.max(Number.isNaN(parsedLimit) ? 50 : parsedLimit, 1), 200);+ const offset = Math.max(Number.isNaN(parsedOffset) ? 0 : parsedOffset, 0);+ // Opt-in to full entries; default is slim summaries (date + segmentCount ++ // obsidianPath) so the sidebar doesn't pull every day's content on load.+ const includeContent = req.query.includeContent === '1' || req.query.includeContent === 'true';+ const result = await journal.listJournals({ limit, offset, includeContent });+ res.json(result);+}));++/**+ * GET /api/brain/daily-log/settings+ * Get daily log configuration (obsidian vault/folder, auto-sync)+ */+router.get('/daily-log/settings', asyncHandler(async (req, res) => {+ const settings = await journal.getSettings();+ res.json(settings);+}));++/**+ * PUT /api/brain/daily-log/settings+ */+router.put('/daily-log/settings', asyncHandler(async (req, res) => {+ const data = validateRequest(dailyLogSettingsSchema, req.body || {});+ const next = await journal.updateSettings(data);+ res.json(next);+}));++/**+ * POST /api/brain/daily-log/sync-obsidian+ * Re-mirror every existing entry into the currently-configured Obsidian vault.+ */+router.post('/daily-log/sync-obsidian', asyncHandler(async (req, res) => {+ const stats = await journal.resyncAllToObsidian();+ res.json(stats);+}));++/**+ * GET /api/brain/daily-log/:date (accepts 'today')+ */+router.get('/daily-log/:date', asyncHandler(async (req, res) => {+ const date = await resolveJournalDate(req.params.date);+ const entry = await journal.getJournal(date);+ res.json({ date, entry });+}));++/**+ * POST /api/brain/daily-log/:date/append — append a text segment+ */+router.post('/daily-log/:date/append', asyncHandler(async (req, res) => {+ const date = await resolveJournalDate(req.params.date);+ const { text, source } = req.body || {};+ // Trim-check here too so a whitespace-only payload doesn't no-op all the+ // way through appendJournal() and still return a 200 — clients would read+ // that as a successful append.+ if (typeof text !== 'string' || text.trim().length === 0) {+ throw new ServerError('text is required', { status: 400, code: 'BAD_REQUEST' });+ }+ const entry = await journal.appendJournal(date, text, { source });+ res.json({ date, entry });+}));++/**+ * PUT /api/brain/daily-log/:date — full content replace+ */+router.put('/daily-log/:date', asyncHandler(async (req, res) => {+ const date = await resolveJournalDate(req.params.date);+ const { content } = req.body || {};+ if (typeof content !== 'string') {+ throw new ServerError('content is required', { status: 400, code: 'BAD_REQUEST' });+ }+ const entry = await journal.setJournalContent(date, content);+ res.json({ date, entry });+}));++/**+ * DELETE /api/brain/daily-log/:date+ */+router.delete('/daily-log/:date', asyncHandler(async (req, res) => {+ const date = await resolveJournalDate(req.params.date);+ const deleted = await journal.deleteJournal(date);+ if (!deleted) {+ throw new ServerError('Journal not found', { status: 404, code: 'NOT_FOUND' });+ }+ res.status(204).send();+}));+export default router;diff --git a/server/routes/brain.test.js b/server/routes/brain.test.jsindex 9ad4b60e27..6c7c93301f 100644--- a/server/routes/brain.test.js+++ b/server/routes/brain.test.js@@ -76,12 +76,37 @@ vi.mock('../services/brainSync.js', () => ({applyRemoteChanges: vi.fn()}));+// Mock the brain journal service+vi.mock('../services/brainJournal.js', () => ({+ listJournals: vi.fn(),+ getJournal: vi.fn(),+ appendJournal: vi.fn(),+ setJournalContent: vi.fn(),+ deleteJournal: vi.fn(),+ getSettings: vi.fn(),+ updateSettings: vi.fn(),+ resyncAllToObsidian: vi.fn(),+ getToday: vi.fn(() => Promise.resolve('2026-04-17')),+ resolveDate: vi.fn((d) => Promise.resolve(d && /^\d{4}-\d{2}-\d{2}$/.test(d) ? d : '2026-04-17')),+ isIsoDate: vi.fn((date) => {+ if (typeof date !== 'string') return false;+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date);+ if (!match) return false;+ const [, y, m, d] = match.map((v, i) => (i === 0 ? v : Number(v)));+ const parsed = new Date(Date.UTC(y, m - 1, d));+ return parsed.getUTCFullYear() === y+ && parsed.getUTCMonth() === m - 1+ && parsed.getUTCDate() === d;+ })+}));+// Import mocked modulesimport * as brainService from '../services/brain.js';import { getBrainGraphData } from '../services/brainGraph.js';import { syncAllBrainData } from '../services/brainMemoryBridge.js';import { getChangesSince } from '../services/brainSyncLog.js';import { applyRemoteChanges } from '../services/brainSync.js';+import * as journal from '../services/brainJournal.js';describe('Brain Routes', () => {let app;@@ -1016,4 +1041,140 @@ describe('Brain Routes', () => {expect(response.status).toBe(400);});});++ // ===========================================================================+ // DAILY LOG+ // ===========================================================================++ describe('GET /api/brain/daily-log', () => {+ it('lists entries', async () => {+ journal.listJournals.mockResolvedValue({+ records: [{ id: 'j1', date: '2026-04-17', content: 'hi', segments: [] }],+ total: 1,+ });+ const res = await request(app).get('/api/brain/daily-log');+ expect(res.status).toBe(200);+ expect(res.body.total).toBe(1);+ expect(res.body.records[0].date).toBe('2026-04-17');+ });+ });++ describe('GET /api/brain/daily-log/:date', () => {+ it('resolves "today" to current local date', async () => {+ journal.getJournal.mockResolvedValue({ id: 'j1', date: '2026-04-17', content: 'x', segments: [] });+ const res = await request(app).get('/api/brain/daily-log/today');+ expect(res.status).toBe(200);+ expect(res.body.date).toBe('2026-04-17');+ expect(journal.getJournal).toHaveBeenCalledWith('2026-04-17');+ });++ it('returns null entry for unknown date', async () => {+ journal.getJournal.mockResolvedValue(null);+ const res = await request(app).get('/api/brain/daily-log/2020-01-01');+ expect(res.status).toBe(200);+ expect(res.body.entry).toBeNull();+ });+ });++ describe('POST /api/brain/daily-log/:date/append', () => {+ it('appends text', async () => {+ journal.appendJournal.mockResolvedValue({+ id: 'j1', date: '2026-04-17', content: 'hello', segments: [{ text: 'hello' }]+ });+ const res = await request(app)+ .post('/api/brain/daily-log/today/append')+ .send({ text: 'hello', source: 'voice' });+ expect(res.status).toBe(200);+ expect(journal.appendJournal).toHaveBeenCalledWith('2026-04-17', 'hello', { source: 'voice' });+ });++ it('rejects empty text', async () => {+ const res = await request(app)+ .post('/api/brain/daily-log/today/append')+ .send({});+ expect(res.status).toBe(400);+ });+ });++ describe('PUT /api/brain/daily-log/:date', () => {+ it('replaces content', async () => {+ journal.setJournalContent.mockResolvedValue({ id: 'j1', date: '2026-04-17', content: 'replaced', segments: [] });+ const res = await request(app)+ .put('/api/brain/daily-log/today')+ .send({ content: 'replaced' });+ expect(res.status).toBe(200);+ expect(res.body.entry.content).toBe('replaced');+ });+ });++ describe('daily-log settings', () => {+ it('reads settings', async () => {+ journal.getSettings.mockResolvedValue({ obsidianVaultId: null, obsidianFolder: 'Daily Log', autoSync: true });+ const res = await request(app).get('/api/brain/daily-log/settings');+ expect(res.status).toBe(200);+ expect(res.body.obsidianFolder).toBe('Daily Log');+ });++ it('updates settings', async () => {+ journal.updateSettings.mockResolvedValue({ obsidianVaultId: 'v1', obsidianFolder: 'Diary', autoSync: true });+ const res = await request(app)+ .put('/api/brain/daily-log/settings')+ .send({ obsidianVaultId: 'v1', obsidianFolder: 'Diary' });+ expect(res.status).toBe(200);+ expect(res.body.obsidianVaultId).toBe('v1');+ });+ });++ describe('DELETE /api/brain/daily-log/:date', () => {+ it('deletes the entry for a valid date', async () => {+ journal.deleteJournal.mockResolvedValue(true);+ const res = await request(app).delete('/api/brain/daily-log/2026-04-17');+ expect(res.status).toBe(204);+ expect(journal.deleteJournal).toHaveBeenCalledWith('2026-04-17');+ });++ it('returns 404 when the entry is not found', async () => {+ journal.deleteJournal.mockResolvedValue(false);+ const res = await request(app).delete('/api/brain/daily-log/2026-04-17');+ expect(res.status).toBe(404);+ });+ });++ describe('POST /api/brain/daily-log/sync-obsidian', () => {+ it('returns bulk sync stats', async () => {+ journal.resyncAllToObsidian.mockResolvedValue({ synced: 3, skipped: 1 });+ const res = await request(app).post('/api/brain/daily-log/sync-obsidian');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ synced: 3, skipped: 1 });+ });+ });++ describe('invalid date handling', () => {+ // Previously any non-'today' string fell back to journal.resolveDate()+ // which defaulted invalid input to today, so PUT /daily-log/not-a-date+ // silently overwrote today's entry. Reject malformed dates with 400.+ it('rejects malformed dates with 400 on GET', async () => {+ const res = await request(app).get('/api/brain/daily-log/not-a-date');+ expect(res.status).toBe(400);+ });++ it('rejects malformed dates with 400 on PUT', async () => {+ const res = await request(app)+ .put('/api/brain/daily-log/2026-13-40')+ .send({ content: 'x' });+ expect(res.status).toBe(400);+ expect(journal.setJournalContent).not.toHaveBeenCalled();+ });++ it('rejects malformed dates with 400 on DELETE', async () => {+ const res = await request(app).delete('/api/brain/daily-log/bogus');+ expect(res.status).toBe(400);+ expect(journal.deleteJournal).not.toHaveBeenCalled();+ });++ it('rejects impossible calendar days (2026-02-30)', async () => {+ const res = await request(app).get('/api/brain/daily-log/2026-02-30');+ expect(res.status).toBe(400);+ });+ });});diff --git a/server/services/brainJournal.js b/server/services/brainJournal.jsnew file mode 100644index 0000000000..c549c81145--- /dev/null+++ b/server/services/brainJournal.js@@ -0,0 +1,359 @@+/**+ * Daily Log (Journal) Service+ *+ * Single-entry-per-date diary store. Supports:+ * - Free-form typed or dictated content per calendar date+ * - Append-style segments from voice dictation+ * - Mirroring to an optional Obsidian vault (so Apple Notes / iCloud backups+ * pick up the file) — configured via brain meta (obsidianVaultId, obsidianFolder)+ * - Emission of brainEvents so brainMemoryBridge can vector-embed each day+ *+ * Storage files:+ * data/brain/journals.json — { records: { 'YYYY-MM-DD': entry } }+ * data/brain/journal-settings.json — { obsidianVaultId, obsidianFolder, autoSync }+ */++import { writeFile } from 'fs/promises';+import { existsSync } from 'fs';+import { join } from 'path';+import { v4 as uuidv4 } from '../lib/uuid.js';+import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';+import { createMutex } from '../lib/asyncMutex.js';+import { brainEvents, now } from './brainStorage.js';+import * as obsidian from './obsidian.js';+import { getUserTimezone, todayInTimezone } from '../lib/timezone.js';++const JOURNALS_FILE = join(PATHS.brain, 'journals.json');+const SETTINGS_FILE = join(PATHS.brain, 'journal-settings.json');++const DEFAULT_SETTINGS = {+ obsidianVaultId: null,+ obsidianFolder: 'Daily Log',+ autoSync: true,+};++// ─── Settings ──────────────────────────────────────────────────────────────++export async function getSettings() {+ await ensureDir(PATHS.brain);+ const loaded = await readJSONFile(SETTINGS_FILE, null);+ return loaded ? { ...DEFAULT_SETTINGS, ...loaded } : { ...DEFAULT_SETTINGS };+}++export async function updateSettings(partial) {+ const current = await getSettings();+ const next = { ...current, ...partial };+ await writeFile(SETTINGS_FILE, JSON.stringify(next, null, 2));+ return next;+}++// ─── Store ─────────────────────────────────────────────────────────────────++// Serialize every load→mutate→save of journals.json so a fire-and-forget+// Obsidian path-persist can't interleave with an appendJournal() and clobber+// newer segments. PortOS is single-user, but dictation bursts schedule+// overlapping async tasks (appendJournal → fire-and-forget syncToObsidian →+// persistObsidianPath) that all want to rewrite the same file. This mutex+// guarantees at most one read-modify-write runs at a time.+const storeMutex = createMutex();++async function loadStore() {+ await ensureDir(PATHS.brain);+ return readJSONFile(JOURNALS_FILE, { records: {} });+}++async function saveStore(store) {+ await ensureDir(PATHS.brain);+ await writeFile(JOURNALS_FILE, JSON.stringify(store, null, 2));+}++// Accept YYYY-MM-DD only, and require a real calendar day so we can't create+// store keys like '2026-02-30' that don't sort meaningfully or round-trip.+export const isIsoDate = (date) => {+ if (typeof date !== 'string') return false;+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(date);+ if (!match) return false;+ const [, y, m, d] = match.map((v, i) => (i === 0 ? v : Number(v)));+ const parsed = new Date(Date.UTC(y, m - 1, d));+ return parsed.getUTCFullYear() === y+ && parsed.getUTCMonth() === m - 1+ && parsed.getUTCDate() === d;+};++export async function resolveDate(date) {+ return isIsoDate(date) ? date : getToday();+}++export async function getToday() {+ return todayInTimezone(await getUserTimezone());+}++// ─── Reads ─────────────────────────────────────────────────────────────────++// Sidebar/history views only need lightweight metadata — full `content` and+// `segments` would balloon the response as the log grows. Callers that want+// the full entry should use getJournal(date) or pass includeContent=true.+function toJournalSummary(entry) {+ return {+ id: entry.id,+ date: entry.date,+ createdAt: entry.createdAt,+ updatedAt: entry.updatedAt,+ obsidianPath: entry.obsidianPath,+ obsidianVaultId: entry.obsidianVaultId || null,+ segmentCount: Array.isArray(entry.segments) ? entry.segments.length : 0,+ };+}++export async function listJournals({ limit = 50, offset = 0, includeContent = false } = {}) {+ const store = await loadStore();+ const records = Object.values(store.records || {});+ records.sort((a, b) => (b.date || '').localeCompare(a.date || ''));+ const total = records.length;+ const page = records.slice(offset, offset + limit);+ return {+ records: includeContent ? page : page.map(toJournalSummary),+ total,+ };+}++export async function getJournal(date) {+ if (!isIsoDate(date)) return null;+ const store = await loadStore();+ return store.records?.[date] || null;+}++// ─── Writes ────────────────────────────────────────────────────────────────++function ensureEntry(store, date) {+ if (!store.records) store.records = {};+ if (store.records[date]) return store.records[date];+ const entry = {+ id: uuidv4(),+ date,+ content: '',+ segments: [],+ createdAt: now(),+ updatedAt: now(),+ obsidianPath: null,+ obsidianVaultId: null,+ };+ store.records[date] = entry;+ return entry;+}++// Fire-and-forget: Obsidian lives on iCloud and writes can stall for hundreds+// of ms; callers shouldn't wait on it. The sync path persists any discovered+// obsidianPath itself via persistObsidianPath() — callers must not assume+// this async work mutates the `entry` they passed in or that a later+// saveStore() in their flow will pick up the path.+function scheduleObsidianSync(entry) {+ syncToObsidian(entry).catch((err) => console.error(`📓 Obsidian sync failed: ${err.message}`));+}++export async function setJournalContent(date, content) {+ if (!isIsoDate(date)) throw new Error(`invalid date: ${date}`);+ const { entry, records } = await storeMutex(async () => {+ const store = await loadStore();+ const entryLocal = ensureEntry(store, date);+ const clean = content || '';+ entryLocal.content = clean;+ // Full replace invalidates the old segment history: the user rewrote the+ // whole day, so segment metadata (counts, per-line sources, timestamps)+ // would otherwise drift from what's actually stored in `content`. Collapse+ // to a single 'edit' segment that represents the rewrite.+ entryLocal.segments = clean+ ? [{ text: clean, at: now(), source: 'edit' }]+ : [];+ entryLocal.updatedAt = now();+ await saveStore(store);+ return { entry: entryLocal, records: store.records };+ });+ scheduleObsidianSync(entry);+ brainEvents.emit('journals:changed', { records });+ // Per-entry event so downstream syncers (memory bridge) can update the+ // single affected day without iterating the whole store.+ brainEvents.emit('journals:upserted', { entry });+ return entry;+}++// Segment source metadata is persisted on disk, so reject unknown or+// non-string values at the service boundary rather than trusting the caller+// (HTTP body, socket payload). Unknown sources fall back to 'text'.+const SEGMENT_SOURCES = new Set(['text', 'voice', 'edit']);+const normalizeSource = (source) => (SEGMENT_SOURCES.has(source) ? source : 'text');++/**+ * Append a text segment (typed or dictated) to the given date's entry.+ * Preserves segment metadata (source, timestamp) so the entry can be+ * re-played later with provenance.+ */+export async function appendJournal(date, text, { source = 'text' } = {}) {+ if (!isIsoDate(date)) throw new Error(`invalid date: ${date}`);+ const clean = (text || '').trim();+ if (!clean) return null;+ const segmentSource = normalizeSource(source);++ const { entry, segment, records } = await storeMutex(async () => {+ const store = await loadStore();+ const entryLocal = ensureEntry(store, date);+ const segmentLocal = { text: clean, at: now(), source: segmentSource };+ entryLocal.segments.push(segmentLocal);+ entryLocal.content = entryLocal.content+ ? `${entryLocal.content.trimEnd()}\n\n${clean}`+ : clean;+ entryLocal.updatedAt = now();+ await saveStore(store);+ return { entry: entryLocal, segment: segmentLocal, records: store.records };+ });+ scheduleObsidianSync(entry);+ brainEvents.emit('journals:changed', { records });+ brainEvents.emit('journals:appended', { entry, segment });+ // Per-entry event so the memory bridge re-embeds only this day, not all+ // of them. (Keep journals:appended separate — it carries the single new+ // segment for UI live-updates, which is a different consumer.)+ brainEvents.emit('journals:upserted', { entry });+ return entry;+}++export async function deleteJournal(date) {+ if (!isIsoDate(date)) return false;+ const result = await storeMutex(async () => {+ const store = await loadStore();+ if (!store.records?.[date]) return null;+ const entryLocal = store.records[date];+ delete store.records[date];+ await saveStore(store);+ return { entry: entryLocal, records: store.records };+ });+ if (!result) return false;+ const { entry, records } = result;+ if (entry.obsidianPath) {+ await removeFromObsidian(entry).catch((err) => console.error(`📓 Obsidian delete failed: ${err.message}`));+ }+ brainEvents.emit('journals:changed', { records });+ // Explicit deletion signal so memory bridges / integrations can archive+ // the corresponding vector entry — the changed event alone doesn't tell+ // the bridge which record vanished.+ brainEvents.emit('journals:deleted', { date, entry });+ return true;+}++// ─── Obsidian mirror ───────────────────────────────────────────────────────++function buildMarkdown(entry) {+ const lines = [+ '---',+ `date: ${entry.date}`,+ `tags: [daily-log, portos]`,+ '---',+ '',+ `# Daily Log — ${entry.date}`,+ '',+ entry.content || '',+ '',+ ];+ return lines.join('\n');+}++function buildObsidianNotePath(settings, date) {+ const folder = (settings.obsidianFolder || '').replace(/^\/+|\/+$/g, '');+ const filename = `${date}.md`;+ return folder ? `${folder}/${filename}` : filename;+}++/**+ * Write the entry's markdown to the configured Obsidian vault. If the file+ * doesn't exist yet, create it; otherwise update. Records the path on the+ * entry so delete can unlink it later.+ *+ * `force: true` bypasses the autoSync check — used by the manual "Re-sync+ * all entries now" action so users who turn off auto-sync can still trigger+ * a one-shot backfill.+ */+export async function syncToObsidian(entry, { force = false } = {}) {+ const settings = await getSettings();+ if (!settings.obsidianVaultId) return null;+ if (!force && !settings.autoSync) return null;++ const vault = await obsidian.getVaultById(settings.obsidianVaultId);+ if (!vault || !existsSync(vault.path)) return null;++ const vaultId = settings.obsidianVaultId;+ const notePath = buildObsidianNotePath(settings, entry.date);+ const markdown = buildMarkdown(entry);++ // createNote errors when the file exists; try update first then create.+ const update = await obsidian.updateNote(vaultId, notePath, markdown);+ if (update?.error === 'NOTE_NOT_FOUND') {+ const created = await obsidian.createNote(vaultId, notePath, markdown);+ if (created?.error) return null;+ await persistObsidianLocation(entry.date, notePath, vaultId);+ return notePath;+ }+ if (update?.error) return null;+ // Persist whenever the path OR the vault changes — a folder rename or+ // a vault swap in Settings both need to update the store so a later+ // deleteJournal() unlinks the right file in the right vault.+ if (entry.obsidianPath !== notePath || entry.obsidianVaultId !== vaultId) {+ await persistObsidianLocation(entry.date, notePath, vaultId);+ }+ return notePath;+}++// Record the note location (path + vault) on the store entry whenever it+// changes. Serialized via storeMutex so a fire-and-forget Obsidian persist+// can't clobber concurrent appendJournal writes.+async function persistObsidianLocation(date, notePath, vaultId) {+ return storeMutex(async () => {+ const store = await loadStore();+ const entry = store.records?.[date];+ if (!entry) return;+ if (entry.obsidianPath !== notePath || entry.obsidianVaultId !== vaultId) {+ entry.obsidianPath = notePath;+ entry.obsidianVaultId = vaultId;+ await saveStore(store);+ }+ });+}++// Refuse to delete if the entry's recorded vault doesn't match the currently+// configured vault — the same relative path in a different vault points at an+// unrelated note, and silently nuking it would be data loss.+async function removeFromObsidian(entry) {+ const settings = await getSettings();+ if (!settings.obsidianVaultId || !entry.obsidianPath) return false;+ if (entry.obsidianVaultId && entry.obsidianVaultId !== settings.obsidianVaultId) {+ console.warn(+ `📓 Skipping Obsidian delete for ${entry.date}: entry was mirrored to vault ` ++ `${entry.obsidianVaultId} but current vault is ${settings.obsidianVaultId}. ` ++ `Clean up the stale note manually if needed.`+ );+ return false;+ }+ const result = await obsidian.deleteNote(settings.obsidianVaultId, entry.obsidianPath);+ return result === true;+}++/**+ * Rewrite every existing daily-log entry to the currently-configured Obsidian+ * vault. Used when the user first points the daily log at a vault or changes+ * which vault it targets.+ */+export async function resyncAllToObsidian() {+ const settings = await getSettings();+ if (!settings.obsidianVaultId) return { synced: 0, skipped: 0 };++ const { records } = await listJournals({ limit: 10000, includeContent: true });+ let synced = 0;+ let skipped = 0;+ for (const entry of records) {+ // force:true so this bulk resync still writes even when the user has+ // turned off the per-write autoSync — they explicitly clicked "Re-sync+ // all entries now", which is the manual-sync escape hatch.+ const path = await syncToObsidian(entry, { force: true }).catch(() => null);+ if (path) synced += 1;+ else skipped += 1;+ }+ return { synced, skipped };+}diff --git a/server/services/brainJournal.test.js b/server/services/brainJournal.test.jsnew file mode 100644index 0000000000..f80a416537--- /dev/null+++ b/server/services/brainJournal.test.js@@ -0,0 +1,225 @@+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import { mkdirSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++// vi.hoisted lets us share this constant with the hoisted vi.mock factory.+const { TEMP_ROOT } = vi.hoisted(() => {+ const { mkdtempSync } = require('fs');+ const { tmpdir } = require('os');+ const { join } = require('path');+ return { TEMP_ROOT: mkdtempSync(join(tmpdir(), 'journal-')) };+});++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return {+ ...actual,+ PATHS: { ...actual.PATHS, brain: TEMP_ROOT },+ };+});++vi.mock('../lib/timezone.js', () => ({+ getUserTimezone: () => Promise.resolve('UTC'),+ todayInTimezone: () => '2026-04-17',+}));++vi.mock('./obsidian.js', () => ({+ getVaultById: vi.fn(),+ updateNote: vi.fn(),+ createNote: vi.fn(),+ deleteNote: vi.fn(),+}));++vi.mock('./brainStorage.js', () => ({+ brainEvents: { emit: vi.fn() },+ now: () => '2026-04-17T12:00:00.000Z',+}));++import * as journal from './brainJournal.js';+import { brainEvents } from './brainStorage.js';+import * as obsidian from './obsidian.js';++afterAll(() => {+ rmSync(TEMP_ROOT, { recursive: true, force: true });+});++describe('brainJournal', () => {+ beforeEach(() => {+ // Fresh scratch state per test — rm then recreate the same dir so the+ // vi.mock of PATHS.brain still points at it. (mkdtempSync with a concrete+ // path silently creates sibling dirs, orphaning our mocked path.)+ rmSync(TEMP_ROOT, { recursive: true, force: true });+ mkdirSync(TEMP_ROOT, { recursive: true });+ vi.clearAllMocks();+ });++ describe('getToday', () => {+ it('returns the user timezone today', async () => {+ expect(await journal.getToday()).toBe('2026-04-17');+ });+ });++ describe('getJournal / listJournals', () => {+ it('returns null for missing dates', async () => {+ expect(await journal.getJournal('2026-01-01')).toBeNull();+ });++ it('rejects malformed dates in getJournal', async () => {+ expect(await journal.getJournal('not-a-date')).toBeNull();+ });++ it('lists empty initially', async () => {+ const { records, total } = await journal.listJournals();+ expect(total).toBe(0);+ expect(records).toEqual([]);+ });++ it('default listJournals returns slim summaries (no content/segments)', async () => {+ await journal.appendJournal('2026-04-17', 'day one body', { source: 'voice' });+ const { records } = await journal.listJournals();+ expect(records).toHaveLength(1);+ const [entry] = records;+ expect(entry).toHaveProperty('segmentCount', 1);+ expect(entry).toHaveProperty('date', '2026-04-17');+ expect(entry).not.toHaveProperty('content');+ expect(entry).not.toHaveProperty('segments');+ });++ it('includeContent: true returns full entries', async () => {+ await journal.appendJournal('2026-04-17', 'day one body');+ const { records } = await journal.listJournals({ includeContent: true });+ expect(records[0].content).toBe('day one body');+ expect(records[0].segments).toHaveLength(1);+ });+ });++ describe('appendJournal', () => {+ it('creates an entry on first append and joins subsequent segments with blank lines', async () => {+ const first = await journal.appendJournal('2026-04-17', 'line one', { source: 'voice' });+ expect(first.content).toBe('line one');+ expect(first.segments).toHaveLength(1);+ expect(first.segments[0].source).toBe('voice');++ const second = await journal.appendJournal('2026-04-17', 'line two');+ expect(second.content).toBe('line one\n\nline two');+ expect(second.segments).toHaveLength(2);+ });++ it('emits journals:changed, journals:appended, and journals:upserted', async () => {+ await journal.appendJournal('2026-04-17', 'hello');+ const eventNames = brainEvents.emit.mock.calls.map((c) => c[0]);+ expect(eventNames).toContain('journals:changed');+ expect(eventNames).toContain('journals:appended');+ // journals:upserted is the per-entry event the memory bridge listens+ // on — must fire for every append so a single day's embedding gets+ // refreshed without re-embedding every other day in the store.+ expect(eventNames).toContain('journals:upserted');+ });++ it('ignores empty/whitespace text', async () => {+ const res = await journal.appendJournal('2026-04-17', ' ');+ expect(res).toBeNull();+ });++ it('rejects invalid dates', async () => {+ await expect(journal.appendJournal('not-a-date', 'hi')).rejects.toThrow(/invalid date/);+ });+ });++ describe('setJournalContent', () => {+ it('replaces the full content and collapses segments', async () => {+ await journal.appendJournal('2026-04-17', 'old one');+ await journal.appendJournal('2026-04-17', 'old two');+ const replaced = await journal.setJournalContent('2026-04-17', 'brand new');+ expect(replaced.content).toBe('brand new');+ // Full replace invalidates prior segment history — collapse to a single+ // 'edit' segment that matches the current content.+ expect(replaced.segments).toHaveLength(1);+ expect(replaced.segments[0].source).toBe('edit');+ expect(replaced.segments[0].text).toBe('brand new');+ });++ it('clears segments when content is emptied', async () => {+ await journal.appendJournal('2026-04-17', 'old');+ const cleared = await journal.setJournalContent('2026-04-17', '');+ expect(cleared.content).toBe('');+ expect(cleared.segments).toEqual([]);+ });+ });++ describe('Obsidian mirror', () => {+ it('skips sync when autoSync is false', async () => {+ await journal.updateSettings({ obsidianVaultId: 'v1', autoSync: false });+ await journal.appendJournal('2026-04-17', 'hi');+ expect(obsidian.updateNote).not.toHaveBeenCalled();+ expect(obsidian.createNote).not.toHaveBeenCalled();+ });++ it('honors force:true even when autoSync is false (manual resync path)', async () => {+ obsidian.getVaultById.mockResolvedValue({ id: 'v1', path: '/' });+ obsidian.updateNote.mockResolvedValueOnce({ path: 'Daily Log/2026-04-17.md' });++ await journal.updateSettings({ obsidianVaultId: 'v1', autoSync: false, obsidianFolder: 'Daily Log' });+ // Regular syncToObsidian() still no-ops without force.+ await journal.syncToObsidian({ id: 'j1', date: '2026-04-17', content: 'hi', segments: [] });+ expect(obsidian.updateNote).not.toHaveBeenCalled();++ // force bypasses autoSync so the manual "Re-sync all" action works.+ await journal.syncToObsidian(+ { id: 'j1', date: '2026-04-17', content: 'hi', segments: [] },+ { force: true },+ );+ expect(obsidian.updateNote).toHaveBeenCalled();+ });++ // Test syncToObsidian() directly rather than going through+ // appendJournal()'s fire-and-forget scheduleObsidianSync() — the+ // background promise isn't awaited, so assertions against mocked+ // obsidian calls would otherwise race with the test runner.+ it('creates an obsidian note on first sync and updates on later syncs', async () => {+ obsidian.getVaultById.mockResolvedValue({ id: 'v1', path: '/' });+ obsidian.updateNote.mockResolvedValueOnce({ error: 'NOTE_NOT_FOUND' });+ obsidian.createNote.mockResolvedValueOnce({ path: 'Daily Log/2026-04-17.md' });+ obsidian.updateNote.mockResolvedValueOnce({ path: 'Daily Log/2026-04-17.md' });++ await journal.updateSettings({ obsidianVaultId: 'v1', autoSync: true, obsidianFolder: 'Daily Log' });+ const entry = { id: 'j1', date: '2026-04-17', content: 'first', segments: [] };+ await journal.syncToObsidian(entry);+ await journal.syncToObsidian({ ...entry, content: 'first\n\nsecond' });++ expect(obsidian.createNote).toHaveBeenCalledTimes(1);+ const [vaultIdArg, pathArg, markdownArg] = obsidian.createNote.mock.calls[0];+ expect(vaultIdArg).toBe('v1');+ expect(pathArg).toBe('Daily Log/2026-04-17.md');+ expect(markdownArg).toContain('# Daily Log — 2026-04-17');+ expect(markdownArg).toContain('first');++ // Second sync updates, not creates+ expect(obsidian.updateNote).toHaveBeenCalled();+ });++ it('refuses to delete notes from a different vault than the one the entry was mirrored to', async () => {+ obsidian.getVaultById.mockResolvedValue({ id: 'v1', path: '/' });+ obsidian.updateNote.mockResolvedValueOnce({ error: 'NOTE_NOT_FOUND' });+ obsidian.createNote.mockResolvedValueOnce({ path: 'Daily Log/2026-04-17.md' });++ // Mirror a note to vault v1.+ await journal.updateSettings({ obsidianVaultId: 'v1', autoSync: true, obsidianFolder: 'Daily Log' });+ await journal.appendJournal('2026-04-17', 'content');+ await journal.syncToObsidian({+ id: 'j1', date: '2026-04-17', content: 'content', segments: [], obsidianPath: null, obsidianVaultId: null,+ });++ // User changes their configured vault to v2. deleteJournal() should not+ // delete the v1 note (which could collide with an unrelated v2 note at+ // the same relative path).+ await journal.updateSettings({ obsidianVaultId: 'v2' });+ obsidian.deleteNote.mockClear();++ await journal.deleteJournal('2026-04-17');++ expect(obsidian.deleteNote).not.toHaveBeenCalled();+ });+ });+});diff --git a/server/services/brainMemoryBridge.js b/server/services/brainMemoryBridge.jsindex 3e8ba134c5..fcf6d26551 100644--- a/server/services/brainMemoryBridge.js+++ b/server/services/brainMemoryBridge.js@@ -17,6 +17,7 @@ import * as brainStorage from './brainStorage.js';import * as memory from './memoryBackend.js';import * as embeddings from './memoryEmbeddings.js';import { ensureDir, PATHS } from '../lib/fileUtils.js';+import { listJournals } from './brainJournal.js';const BRIDGE_MAP_PATH = join(PATHS.brain, 'memory-bridge-map.json');@@ -28,7 +29,8 @@ const TYPE_MAP = {admin: { type: 'fact', category: 'admin' },memories: { type: 'observation', category: 'personal' },digests: { type: 'context', category: 'digest' },- reviews: { type: 'context', category: 'review' }+ reviews: { type: 'context', category: 'review' },+ journals: { type: 'observation', category: 'daily-log' }};// ─── Bridge Map ─────────────────────────────────────────────────────────────@@ -121,6 +123,12 @@ function composeReviewContent(r) {return parts.join('\n');}+function composeDailyLogContent(r) {+ const parts = [`Daily Log — ${r.date}`];+ if (r.content) parts.push(r.content);+ return parts.join('\n');+}+export const CONTENT_COMPOSERS = {people: composePeopleContent,projects: composeProjectContent,@@ -128,7 +136,8 @@ export const CONTENT_COMPOSERS = {admin: composeAdminContent,memories: composeJournalContent,digests: composeDigestContent,- reviews: composeReviewContent+ reviews: composeReviewContent,+ journals: composeDailyLogContent};// ─── Core Mapping ───────────────────────────────────────────────────────────@@ -234,6 +243,35 @@ export async function syncAllBrainData({ dryRun = false } = {}) {}}+ // Daily log entries — one memory per day, initial/backfill import only;+ // already-mapped records are skipped by this bulk sync. Content updates+ // and deletions flow through the 'journals:upserted' / 'journals:deleted'+ // event handlers instead (see initBridge).+ {+ const { records: journals } = await listJournals({ limit: 10000, includeContent: true });+ for (const record of journals) {+ const key = bridgeKey('journals', record.id);+ // Already-mapped days are skipped in both real and dry-run modes so+ // dry-run stats match actual-run stats (rather than claiming to+ // re-sync every day every time).+ if (map[key]) {+ stats.skipped += 1;+ continue;+ }+ if (dryRun) {+ console.log(`🧠🔗 [dry-run] Would sync journals/${record.date}`);+ stats.synced += 1;+ continue;+ }+ const memoryId = await syncBrainRecord('journals', record).catch((err) => {+ console.error(`❌ Failed to sync journals/${record.date}: ${err.message}`);+ stats.errors += 1;+ return null;+ });+ if (memoryId) stats.synced += 1;+ }+ }+// JSONL stores (digests, reviews)const jsonlTypes = ['digests', 'reviews'];for (const type of jsonlTypes) {@@ -311,5 +349,39 @@ export function initBridge() {brainEvents.on('digests:added', (record) => handleJsonlAdded('digests', record));brainEvents.on('reviews:added', (record) => handleJsonlAdded('reviews', record));+ // Daily log — per-entry events so a single append doesn't re-embed every+ // day of the user's history. (An earlier version listened for the+ // store-wide 'journals:changed' event, which would trigger O(totalDays)+ // embedding calls per dictation segment and saturate the embedding+ // backend.) appendJournal/setJournalContent fire 'journals:upserted' with+ // the single affected entry; deleteJournal fires 'journals:deleted'.+ brainEvents.on('journals:upserted', ({ entry }) => handleJournalUpserted(entry));+ // handleJournalDeleted is async and awaits loadBridgeMap(); wrap the call+ // in a .catch so a rejection becomes a logged error instead of an+ // unhandled-rejection warning (or a process crash under strict modes).+ brainEvents.on('journals:deleted', ({ entry }) => {+ handleJournalDeleted(entry).catch((err) => {+ console.error(`❌ Brain bridge delete sync failed for journals/${entry?.id}: ${err.message}`);+ });+ });+console.log('🧠🔗 Brain→Memory bridge initialized');}++function handleJournalUpserted(entry) {+ if (!entry?.id) return;+ syncBrainRecord('journals', entry).catch((err) => {+ console.error(`❌ Brain bridge sync failed for journals/${entry.id}: ${err.message}`);+ });+}++async function handleJournalDeleted(entry) {+ if (!entry?.id) return;+ const map = await loadBridgeMap();+ const key = bridgeKey('journals', entry.id);+ const memoryId = map[key];+ if (!memoryId) return;+ memory.updateMemory(memoryId, { status: 'archived' }).catch((err) => {+ console.error(`❌ Brain bridge archive failed for journals/${entry.id}: ${err.message}`);+ });+}diff --git a/server/services/voice/pipeline.js b/server/services/voice/pipeline.jsindex 52ee21d6fb..85f80646cd 100644--- a/server/services/voice/pipeline.js+++ b/server/services/voice/pipeline.js@@ -11,6 +11,7 @@ import { synthesize } from './tts.js';import { streamChat } from './llm.js';import { getVoiceConfig } from './config.js';import { getToolSpecs, dispatchTool } from './tools.js';+import { appendJournal, getToday } from '../brainJournal.js';const buildSystemPrompt = (cfg) => {if (!cfg.llm.usePersonality) return cfg.llm.systemPrompt;@@ -68,7 +69,11 @@ export const splitSentences = (buffer) => {// [LAUGHTER], [INAUDIBLE]. Treat those as empty so we don't waste an LLM turn.export const isNonSpeechMarker = (text) => /^\s*\[[A-Z_ ]+\]\s*$/i.test(text);-export const runTurn = async ({ audio, text, mimeType, history = [], emit, signal }) => {+// Recognize spoken phrases that should end dictation without going through the+// LLM. Intentionally narrow — "I'm done writing" shouldn't match.+const STOP_DICTATION_RE = /^(stop|end|exit|cancel|pause)\s+(dictation|dictating|logging|recording)[\.\!\s]*$/i;++export const runTurn = async ({ audio, text, mimeType, source, history = [], emit, signal, state }) => {const cfg = await getVoiceConfig();if (signal?.aborted) return { transcript: '', reply: '' };@@ -82,7 +87,18 @@ export const runTurn = async ({ audio, text, mimeType, history = [], emit, signauserText = isNonSpeechMarker(stt.text) ? '' : stt.text;emit('voice:transcript', { text: userText, latencyMs: stt.latencyMs });} else {- emit('voice:transcript', { text: userText, latencyMs: 0, source: 'text' });+ // VoiceWidget treats transcripts with source !== 'text' as server-STT+ // output and appends them to the chat log. Web Speech already appended+ // the user's words locally on onFinal, so reclassifying this echo as+ // 'voice' would duplicate the message. Keep `source` stable and expose+ // the caller's routing hint separately so dictation/Origin-aware code+ // can still distinguish typed vs spoken without breaking chat history.+ emit('voice:transcript', {+ text: userText,+ latencyMs: 0,+ source: 'text',+ inputSource: source || 'text',+ });}if (!userText) {@@ -92,6 +108,68 @@ export const runTurn = async ({ audio, text, mimeType, history = [], emit, signa}if (signal?.aborted) return { transcript: userText, reply: '' };+ // Dictation mode short-circuits the LLM: the user's speech goes straight+ // into the daily-log entry unless they say the stop phrase, which ends+ // dictation and falls through to a normal confirmation turn.+ //+ // Only applies to spoken input. Typed input (the "Read back" button,+ // assistant-issued sendText, manual typing) bypasses dictation so the+ // user can still drive the app while dictation is live. Web Speech mode+ // hands transcripts over as voice:text with source='voice', so we honor+ // that hint in addition to the no-text case.+ const isSpokenInput = !text || source === 'voice';+ if (isSpokenInput && state?.dictation?.enabled) {+ const trimmed = userText.trim();+ // STT can return whitespace-only transcripts (Whisper on silent audio,+ // trailing partials). Don't fire a bogus append event with { entry: null };+ // just go idle and wait for the next utterance.+ if (!trimmed) {+ emit('voice:idle', { reason: 'empty-transcript' });+ return { transcript: userText, reply: '' };+ }+ if (STOP_DICTATION_RE.test(trimmed)) {+ state.dictation = { enabled: false, date: null };+ emit('voice:dictation', { enabled: false });+ const reply = 'Dictation off.';+ const { wav, latencyMs } = await synthesize(reply, { signal });+ // Report the real synth latency so the client's TTS timing stats+ // reflect actual work, not a hardcoded zero.+ if (!signal?.aborted) emit('voice:tts:audio', { sentence: reply, wav, latencyMs });+ emit('voice:llm:delta', { delta: reply });+ emit('voice:llm:done', { text: reply });+ emit('voice:idle', { reason: 'turn-complete' });+ return { transcript: userText, reply };+ }+ // Defensive: dictation can be enabled without a date (e.g. UI toggle+ // without a date, or tool side-effect missing one). Default to today so+ // we never throw here and kill the user's dictation turn.+ let date = state.dictation.date;+ if (!date) {+ date = await getToday();+ state.dictation.date = date;+ console.warn(`🎙️ dictation missing date; defaulting to ${date}`);+ emit('voice:dictation', { enabled: true, date });+ }+ const entry = await appendJournal(date, trimmed, { source: 'voice' });+ // Ship only the delta (new segment + metadata) rather than the full+ // entry. `entry.content` and `entry.segments` grow over the day, so+ // emitting the whole record per utterance would push socket payload+ // size and serialization cost toward O(n²) during long dictation+ // sessions. The client patches local state from these fields.+ const segments = Array.isArray(entry?.segments) ? entry.segments : [];+ const segment = segments.length ? segments[segments.length - 1] : null;+ emit('voice:dailyLog:appended', {+ date,+ text: trimmed,+ segment,+ segmentCount: segments.length,+ updatedAt: entry?.updatedAt,+ });+ console.log(`🎙️ dictation → journal[${date}] +${trimmed.length} chars`);+ emit('voice:idle', { reason: 'dictation-appended' });+ return { transcript: userText, reply: '' };+ }+const messages = [{ role: 'system', content: buildSystemPrompt(cfg) },...history,@@ -183,14 +261,32 @@ export const runTurn = async ({ audio, text, mimeType, history = [], emit, signaconst t0 = Date.now();let result;let args = {};+ const ctx = { sideEffects: [] };try {args = tc.function.arguments ? JSON.parse(tc.function.arguments) : {};- result = await dispatchTool(tc.function.name, args);+ result = await dispatchTool(tc.function.name, args, ctx);toolRuns.push({ name: tc.function.name, ok: true, ms: Date.now() - t0 });} catch (err) {result = { ok: false, error: err.message };toolRuns.push({ name: tc.function.name, ok: false, ms: Date.now() - t0, error: err.message });}+ // Apply server-side side-effects (dictation state) and forward+ // client-facing side-effects (navigation) over the socket.+ for (const fx of ctx.sideEffects) {+ if (fx.type === 'dictation' && state) {+ // When disabling dictation, clear the date so it can't leak to the+ // UI or be picked up by the next enable. A stale date is worse than+ // null — it can cause surprising "jumped back to April 17" behavior.+ const enabled = !!fx.enabled;+ state.dictation = {+ enabled,+ date: enabled ? (fx.date || state.dictation?.date || null) : null,+ };+ emit('voice:dictation', { enabled: state.dictation.enabled, date: state.dictation.date });+ } else if (fx.type === 'navigate') {+ emit('voice:navigate', { path: fx.path });+ }+ }emit('voice:tool', { name: tc.function.name, args, result });messages.push({role: 'tool',@@ -205,12 +301,12 @@ export const runTurn = async ({ audio, text, mimeType, history = [], emit, signaconst totalMs = Date.now() - turnStart;const ttsTotal = ttsTimings.reduce((a, b) => a + b, 0);- const source = text ? 'text' : 'voice';+ const inputKind = text ? 'text' : 'voice';const toolSummary = toolRuns.length? ` · tools=${toolRuns.map((r) => `${r.name}(${r.ok ? `${r.ms}ms` : 'err'})`).join(',')}`: '';console.log(- `🎙️ ${source} turn ${totalMs}ms — ` ++ `🎙️ ${inputKind} turn ${totalMs}ms — ` +`stt=${sttLatencyMs}ms · ` +`llm[${lastLlm?.model}] ttft=${firstLlm?.ttfbMs ?? '—'}ms total=${lastLlm?.totalMs}ms · ` +`tts=${ttsTotal}ms (${ttsTimings.length} sentences)` +diff --git a/server/services/voice/tools.js b/server/services/voice/tools.jsindex cab6189949..48ffc718a5 100644--- a/server/services/voice/tools.js+++ b/server/services/voice/tools.js@@ -10,6 +10,9 @@ import { getGoals, updateGoalProgress, addProgressEntry } from '../identity.js';import { listProcesses, restartApp } from '../pm2.js';import { getItems, getFeeds } from '../feeds.js';import { getUserTimezone, todayInTimezone, getLocalParts } from '../../lib/timezone.js';+import * as journal from '../brainJournal.js';++const DAILY_LOG_PATH = '/brain/daily-log';// Shorthand presets for voice logging. A user saying "I had a beer" should// not need to recite oz + ABV — these defaults match typical US servings.@@ -498,6 +501,120 @@ const TOOLS = [},},+ {+ name: 'daily_log_open',+ description:+ 'Open the Daily Log page in the UI and optionally start voice dictation mode. Use when the user says "open my daily log", "take me to my daily log", "go to daily log", "I want to dictate my daily log", "start my daily log". Set startDictation=true when the user wants to speak entries (explicit dictation verbs: "dictate", "record", "start logging"). The tool navigates the browser to the Daily Log page; the confirmation spoken back to the user should be one short sentence.',+ parameters: {+ type: 'object',+ properties: {+ startDictation: {+ type: 'boolean',+ description: 'Immediately enter dictation mode where subsequent speech is appended to the log verbatim instead of sent to you as conversation.',+ },+ },+ },+ execute: async ({ startDictation = false } = {}, ctx = {}) => {+ const date = await journal.getToday();+ const entry = await journal.getJournal(date);+ ctx.sideEffects?.push({ type: 'navigate', path: DAILY_LOG_PATH });+ if (startDictation) {+ ctx.sideEffects?.push({ type: 'dictation', enabled: true, date });+ }+ const existingLen = entry?.content?.length || 0;+ const parts = [`Opened daily log for ${date}`];+ if (startDictation) parts.push('Dictation mode on — everything you say now will be added to today\'s log. Say "stop dictation" when done.');+ else if (existingLen) parts.push(`(${entry.segments?.length || 1} segment${entry.segments?.length === 1 ? '' : 's'} so far).`);+ else parts.push('(empty so far).');+ return { ok: true, date, dictation: !!startDictation, summary: parts.join(' ') };+ },+ },++ {+ name: 'daily_log_start_dictation',+ description:+ 'Begin voice dictation into the Daily Log: subsequent user speech is transcribed and appended verbatim to today\'s log until they say stop. Use when the user says "start dictation", "record my log", "begin logging", "dictate this", "I want to start talking into my daily log". After calling, do not comment further — just confirm briefly.',+ parameters: {+ type: 'object',+ properties: {+ date: { type: 'string', description: 'Target date YYYY-MM-DD; defaults to today.' },+ },+ },+ execute: async ({ date } = {}, ctx = {}) => {+ const target = await journal.resolveDate(date);+ ctx.sideEffects?.push({ type: 'navigate', path: DAILY_LOG_PATH });+ ctx.sideEffects?.push({ type: 'dictation', enabled: true, date: target });+ return { ok: true, date: target, summary: `Dictation on for ${target}. Everything you say will be added to the log. Say "stop dictation" when finished.` };+ },+ },++ {+ name: 'daily_log_stop_dictation',+ description:+ 'End voice dictation and return to normal conversation mode. Only useful if dictation is currently active. Use when the user says "stop dictation", "end dictation", "I\'m done", "exit dictation mode".',+ parameters: { type: 'object', properties: {} },+ execute: async (_args, ctx = {}) => {+ ctx.sideEffects?.push({ type: 'dictation', enabled: false });+ return { ok: true, summary: 'Dictation off.' };+ },+ },++ {+ name: 'daily_log_append',+ description:+ 'Append a text segment to a Daily Log entry (does NOT enter dictation mode — one-shot). Use when the user says "add to my daily log: X", "write in my daily log that X", "note in today\'s log: X". Exact text goes in; do not summarize.',+ parameters: {+ type: 'object',+ properties: {+ text: { type: 'string', description: 'The exact text to append, in the user\'s words.' },+ date: { type: 'string', description: 'YYYY-MM-DD; defaults to today.' },+ },+ required: ['text'],+ },+ execute: async ({ text, date }) => {+ if (!text || !text.trim()) throw new Error('text is required');+ const target = await journal.resolveDate(date);+ const entry = await journal.appendJournal(target, text.trim(), { source: 'voice' });+ return {+ ok: true,+ date: target,+ segments: entry.segments.length,+ summary: `Added to daily log for ${target}.`,+ };+ },+ },++ {+ name: 'daily_log_read',+ description:+ 'Read back the full content of a Daily Log entry aloud. Use when the user says "read me my daily log", "what did I write today?", "play back yesterday\'s log". Defaults to today. Returns content so the LLM can read it verbatim — do NOT summarize, speak the content as-is.',+ parameters: {+ type: 'object',+ properties: {+ date: { type: 'string', description: 'YYYY-MM-DD; defaults to today.' },+ },+ },+ execute: async ({ date } = {}, ctx = {}) => {+ const target = await journal.resolveDate(date);+ ctx.sideEffects?.push({ type: 'navigate', path: DAILY_LOG_PATH });+ const entry = await journal.getJournal(target);+ if (!entry || !entry.content?.trim()) {+ return { ok: true, date: target, empty: true, summary: `Daily log for ${target} is empty.` };+ }+ // Keep `summary` short — tool results are JSON-stringified into the+ // LLM message history, and duplicating the full content here would+ // double the token cost of every subsequent turn for no benefit.+ // Content is returned once in `content`.+ return {+ ok: true,+ date: target,+ content: entry.content,+ segments: entry.segments?.length || 0,+ summary: `Daily log for ${target} (${entry.segments?.length || 0} segments).`,+ };+ },+ },+{name: 'time_now',description:@@ -527,8 +644,8 @@ export const getToolSpecs = () => TOOLS.map((t) => ({function: { name: t.name, description: t.description, parameters: t.parameters },}));-export const dispatchTool = async (name, args) => {+export const dispatchTool = async (name, args, ctx) => {const tool = TOOLS.find((t) => t.name === name);if (!tool) throw new Error(`Unknown tool: ${name}`);- return tool.execute(args || {});+ return tool.execute(args || {}, ctx || { sideEffects: [] });};diff --git a/server/sockets/voice.js b/server/sockets/voice.jsindex 160a033b03..632c011e4b 100644--- a/server/sockets/voice.js+++ b/server/sockets/voice.js@@ -1,10 +1,13 @@// Per-socket voice handlers.// Inbound: voice:turn | voice:text | voice:interrupt | voice:reset+// | voice:dictation:set// Outbound: voice:transcript | voice:llm:delta | voice:llm:done | voice:tts:audio-// | voice:tool | voice:error | voice:idle+// | voice:tool | voice:dictation | voice:navigate+// | voice:dailyLog:appended | voice:error | voice:idleimport { runTurn } from '../services/voice/pipeline.js';import { getVoiceConfig } from '../services/voice/config.js';+import { isIsoDate } from '../services/brainJournal.js';// Cap by messages (each user utterance + assistant reply is ~2). 24 → ~12 turns.const HISTORY_MESSAGES = 24;@@ -25,6 +28,7 @@ export const registerVoiceHandlers = (socket) => {const state = {history: [],ctrl: null,+ dictation: { enabled: false, date: null },};const pushHistory = (role, content) => {@@ -35,7 +39,7 @@ export const registerVoiceHandlers = (socket) => {}};- const runTurnWithState = async ({ audio, mimeType, text, errorStage }) => {+ const runTurnWithState = async ({ audio, mimeType, text, source, errorStage }) => {state.ctrl?.abort();state.ctrl = new AbortController();const { signal } = state.ctrl;@@ -47,14 +51,19 @@ export const registerVoiceHandlers = (socket) => {try {const { transcript, reply } = await runTurn({- audio, mimeType, text, history: state.history, emit, signal,+ audio, mimeType, text, source, history: state.history, emit, signal, state,});// Don't persist transcript/reply when the turn was aborted or superseded// by a newer turn — the user interrupted, and that output shouldn't// re-enter context on the next turn.if (signal.aborted || state.ctrl?.signal !== signal) return;- pushHistory('user', transcript);- pushHistory('assistant', reply);+ // Skip history push while dictating — the transcripts aren't part of+ // the conversation with the CoS, just raw journal content. An exception:+ // the stop-dictation reply IS a normal assistant turn, push both sides.+ if (!state.dictation.enabled || reply) {+ pushHistory('user', transcript);+ pushHistory('assistant', reply);+ }} catch (err) {if (signal.aborted) return;console.error(`🎙️ ${errorStage} failed: ${err.message}`);@@ -106,7 +115,7 @@ export const registerVoiceHandlers = (socket) => {socket.on('voice:text', async (payload = {}) => {if (!(await ensureEnabled('text'))) return;- const raw = payload.text;+ const raw = payload?.text;if (typeof raw !== 'string' && typeof raw !== 'number') {socket.emit('voice:error', { stage: 'text', message: 'text is required' });return;@@ -120,7 +129,7 @@ export const registerVoiceHandlers = (socket) => {socket.emit('voice:error', { stage: 'text', message: `text too long (${text.length} > ${MAX_TEXT_LEN} chars)` });return;}- await runTurnWithState({ text, errorStage: 'text' });+ await runTurnWithState({ text, source: payload?.source, errorStage: 'text' });});socket.on('voice:interrupt', () => {@@ -131,9 +140,38 @@ export const registerVoiceHandlers = (socket) => {socket.on('voice:reset', () => {state.ctrl?.abort();state.history = [];+ state.dictation = { enabled: false, date: null };+ socket.emit('voice:dictation', { enabled: false });socket.emit('voice:idle', { reason: 'reset' });});+ // Explicit UI control — user toggled dictation from the Daily Log page.+ // Validate the date to prevent malformed values from flowing into+ // appendJournal(), which would throw and break the dictation turn. Fall+ // back to the existing state date (or null to let the pipeline default to+ // today) rather than storing garbage. Read the payload defensively — a+ // client emitting `null` or a primitive would otherwise crash the+ // destructure before our validation runs.+ //+ // Gated on the same voice.enabled toggle as voice:turn / voice:text: if+ // voice is disabled, turning dictation *on* would leave the UI in a+ // dictating state while subsequent voice turns would be rejected. Force+ // dictation off and surface the error instead. Disabling is always+ // allowed — it's a clean-up path that can run regardless of config.+ socket.on('voice:dictation:set', async (payload) => {+ const { enabled, date } = payload && typeof payload === 'object' ? payload : {};+ if (enabled && !(await ensureEnabled('dictation'))) {+ // Ensure UI and server agree that dictation is off after a blocked+ // enable, otherwise the UI can silently drift into "dictating" state.+ state.dictation = { enabled: false, date: null };+ socket.emit('voice:dictation', { enabled: false });+ return;+ }+ const normalizedDate = isIsoDate(date) ? date : (state.dictation.date || null);+ state.dictation = { enabled: !!enabled, date: enabled ? normalizedDate : null };+ socket.emit('voice:dictation', { enabled: state.dictation.enabled, date: state.dictation.date });+ });+socket.on('disconnect', () => {state.ctrl?.abort();});