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: daily-log auto-drafts from activity digest (#2155)
Adam Eivyfdb973f372ef
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex aebb7f6a7e..1302df3ab8 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,7 @@# Unreleased Changes+- **[issue-2155] Daily-log auto-drafts from the activity timeline (Human Activity Tracking Phase 6).** An evening scheduled job drafts a "what actually happened today" section into that day's Brain daily log — the first federated output of the activity timeline. `server/services/activityDigest.js` summarizes a day's `human_activity_events` (conversations grouped with sent/received tallies, meetings with attendee names, media consumed — tribe-person names resolved from participants + the tribe registry) into a deterministic structured bullet list. That list is useful on its own AND is the template fed to an LLM: when the user has configured a provider/model, an opt-in narrative is generated on top of the bullets; otherwise the structured summary ships with **zero provider calls**. Per the AI policy the feature is silent until enabled — a dedicated scheduler (`activityDigestScheduler.js`, patterned on `brainScheduler.js` with an evening time-of-day trigger + missed-day catch-up, started from `server/index.js`, NOT `taskSchedule.js`) no-ops entirely when disabled and never fires a cold-bootstrap LLM call. The draft is spliced into the journal as a clearly-marked, marker-delimited section via a new `brainJournal.upsertAutoSection()` (rides `brainStorage.upsertWithId` so it federates + re-embeds through `brainMemoryBridge`); user-typed/dictated content and segment history are never touched, and a re-run replaces only the auto section (stable HTML-comment markers via the pure, unit-tested `server/lib/markedSection.js`). A "Draft" button on the Daily Log tab runs it on demand (direct user action — names the provider, no extra consent modal), and the tab's settings drawer gains the enable toggle + provider/model/run-time config. (`server/services/activityDigest.js`, `server/services/activityDigestScheduler.js`, `server/services/brainJournal.js`, `server/lib/markedSection.js`, `server/lib/brainValidation.js`, `server/routes/brainDailyLog.js`, `client/src/components/brain/tabs/DailyLogTab.jsx`, `client/src/services/apiBrain.js`)+## CoS Agents- **branch-reconcile now reaps ABANDONED `/claim` worktrees instead of parking on them forever.** When a `/claim` (or `/do:next`) agent finishes WITHOUT committing, it leaves a `claim/issue-N` branch that's just a bare pointer at an already-merged commit plus a lingering worktree. branch-reconcile classified these as `MERGED` but its cleanup unconditionally protected any `claim-*` worktree as a live human session (`worktree-human-claim`) — so it skipped them every run and parked with the misleading *"nothing in-flight (cleaned 0)"*, and the stale branches/worktrees accumulated indefinitely (this is exactly what left `claim/issue-1933` + `claim/issue-1938` stuck locally). The protection is now age-gated: a claim worktree is reaped only when it's **merged AND clean AND older than `STALE_CLAIM_IDLE_MS` (7 days)** — a trio that's only ever true for an abandoned claim, since a claim with real work in progress is never merged+clean (uncommitted edits → dirty → WIP; committed work → not an ancestor of default → not MERGED). Because a merged+clean worktree has nothing beyond the default branch and nothing uncommitted, the reap loses no recoverable work, and re-running `/claim` recreates it — so the window is set very conservatively (a full week) to preserve even a *paused* human session returned-to within days; unknown-age worktrees fail safe toward not-deleting, and branch-reconcile's daily recheck reaps a genuinely-leaked worktree once it finally crosses the threshold. The park log also now names any merged branches held back by a protection guard (`, N merged branch(es) held back (worktree-human-claim, …)`) so a lingering worktree is a visible breadcrumb instead of an invisible "cleaned 0". Worktree age is read from the worktree root's mtime (set at `git worktree add`, unmoved by deep-file edits) in `gatherBranchState` and threaded into the pure `worktreeProtectionReason` gate. (`server/services/branchReconcile.js`, `server/services/cosTaskGenerator.js`)diff --git a/client/src/components/brain/tabs/DailyLogTab.jsx b/client/src/components/brain/tabs/DailyLogTab.jsxindex 188f115826..5304273e55 100644--- a/client/src/components/brain/tabs/DailyLogTab.jsx+++ b/client/src/components/brain/tabs/DailyLogTab.jsx@@ -1,6 +1,6 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import {BookOpen, ChevronLeft, ChevronRight, Mic, MicOff, Save, Volume2, Settings,- Plus, Trash2, CloudUpload, Menu, X} from 'lucide-react';+ Plus, Trash2, CloudUpload, Menu, X, Sparkles} from 'lucide-react';import * as api from '../../../services/api';import { getNotesVaults } from '../../../services/apiNotes';import toast from '../../ui/Toast';@@ -63,6 +63,10 @@ export default function DailyLogTab() {const [showSettings, setShowSettings] = useState(false);const [settings, setSettings] = useState(null);const [vaults, setVaults] = useState([]);+ // Activity-digest (auto-draft) config + provider list for the picker (#2155).+ const [digestSettings, setDigestSettings] = useState(null);+ const [providers, setProviders] = useState([]);+ const [drafting, setDrafting] = useState(false);const [confirmDelete, setConfirmDelete] = useState(false);const [syncing, setSyncing] = useState(false);const [historyOpen, setHistoryOpen] = useState(false);@@ -104,12 +108,16 @@ export default function DailyLogTab() {}, []);const loadSettings = useCallback(async () => {- const [s, v] = await Promise.all([+ const [s, v, d, p] = await Promise.all([api.getDailyLogSettings().catch(() => null),getNotesVaults().catch(() => []),+ api.getActivityDigestSettings().catch(() => null),+ api.getProviders({ silent: true }).catch(() => null),]);if (s) setSettings(s);setVaults(v || []);+ if (d) setDigestSettings(d);+ setProviders(p?.providers || (Array.isArray(p) ? p : []));}, []);useEffect(() => { loadEntry(date); }, [date, loadEntry]);@@ -332,6 +340,44 @@ export default function DailyLogTab() {}};+ const saveDigestSettings = async (partial) => {+ // Optimistic local merge so the control reflects the change immediately;+ // the server response is authoritative and replaces it on success.+ setDigestSettings((prev) => ({ ...(prev || {}), ...partial }));+ const next = await api.updateActivityDigestSettings(partial).catch(() => null);+ if (next) {+ setDigestSettings(next);+ toast.success('Digest settings saved');+ }+ };++ const handleDraft = async () => {+ // The draft splices its section into the SERVER's persisted entry, so+ // unsaved edits in the textarea would be clobbered by the returned content.+ // Make the user save (or discard) first rather than silently losing them.+ if (dirty) {+ toast('Save or discard your edits before drafting.', { icon: '📝' });+ return;+ }+ setDrafting(true);+ const res = await api.draftActivityDigest(date).catch(() => null);+ setDrafting(false);+ if (!res) {+ toast.error('Draft failed');+ return;+ }+ if (res.entry) applyEntry(res.entry);+ if (res.drafted) {+ toast.success(res.usedLlm ? 'Drafted with AI narrative' : 'Drafted from your timeline');+ } else {+ toast('No tracked activity for this day yet.', { icon: '🗓️' });+ }+ };++ // The provider whose id is currently configured — used to name it in the UI+ // (AI policy: the surface that can trigger LLM work must name the provider).+ const digestProvider = providers.find((p) => p.id === digestSettings?.provider) || null;+const isToday = date === serverToday;const segmentCount = entry?.segments?.length ?? entry?.segmentCount ?? 0;@@ -420,6 +466,68 @@ export default function DailyLogTab() {Entries embed into the Chief-of-Staff memory system automatically so agents can searchacross daily logs.</p>++ <div className="pt-3 border-t border-port-border space-y-3">+ <div className="flex items-center gap-2">+ <Sparkles size={13} className="text-port-accent" />+ <span className="text-xs font-medium text-white">Activity Digest auto-drafts</span>+ </div>+ <p className="text-[10px] text-gray-600">+ Summarizes each day's activity timeline (conversations, meetings, media) into a+ clearly-marked section of that day's log. Your typed and dictated text is never+ changed. Runs only when enabled below.+ </p>+ <label htmlFor="digest-enabled" className="flex items-center gap-2 text-xs text-gray-400">+ <input+ id="digest-enabled"+ type="checkbox"+ checked={!!digestSettings?.enabled}+ onChange={(e) => saveDigestSettings({ enabled: e.target.checked })}+ />+ Enable the scheduled evening draft+ </label>+ <FormField label="AI provider (optional — narrative summary)" labelClassName="block text-xs text-gray-400 mb-1">+ <select+ id="digest-provider"+ value={digestSettings?.provider || ''}+ onChange={(e) => saveDigestSettings({ provider: 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 — structured summary only (no AI)</option>+ {providers.map((p) => (+ <option key={p.id} value={p.id}>{p.name || p.id}</option>+ ))}+ </select>+ </FormField>+ {digestProvider && (+ <FormField label="Model (optional)" labelClassName="block text-xs text-gray-400 mb-1">+ <input+ id="digest-model"+ type="text"+ value={digestSettings?.model || ''}+ onChange={(e) => setDigestSettings((s) => ({ ...(s || {}), model: e.target.value }))}+ onBlur={(e) => saveDigestSettings({ model: e.target.value || null })}+ className="w-full bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"+ placeholder={digestProvider.defaultModel || 'provider default'}+ />+ </FormField>+ )}+ <FormField label="Evening run time" labelClassName="block text-xs text-gray-400 mb-1">+ <input+ id="digest-runtime"+ type="time"+ value={digestSettings?.runTime || '21:00'}+ onChange={(e) => setDigestSettings((s) => ({ ...(s || {}), runTime: e.target.value }))}+ onBlur={(e) => e.target.value && saveDigestSettings({ runTime: e.target.value })}+ className="bg-port-bg border border-port-border rounded px-2 py-1.5 text-sm text-white"+ />+ </FormField>+ <p className="text-[10px] text-gray-600">+ {digestProvider+ ? `Scheduled drafts will call ${digestProvider.name || digestProvider.id}. Use the Draft button in the toolbar to run it now.`+ : 'No AI provider selected — drafts are a deterministic structured summary with zero AI calls.'}+ </p>+ </div></div>)}@@ -498,6 +606,18 @@ export default function DailyLogTab() {{entry?.obsidianPath ? ` · ${entry.obsidianPath}` : ''}</div></div>+ <button+ onClick={handleDraft}+ disabled={drafting}+ className="flex items-center gap-1 px-3 min-h-[40px] rounded bg-port-card text-gray-300 text-sm hover:text-white disabled:opacity-50"+ title={digestProvider+ ? `Draft an activity-digest section for this day using ${digestProvider.name || digestProvider.id}`+ : 'Draft an activity-digest section for this day (structured summary — no AI provider)'}+ aria-label="Draft activity digest"+ >+ <Sparkles size={14} className={drafting ? 'animate-pulse' : ''} />+ <span className="hidden sm:inline">{drafting ? 'Drafting…' : 'Draft'}</span>+ </button><buttononClick={readBack}className="flex items-center gap-1 px-3 min-h-[40px] rounded bg-port-card text-gray-300 text-sm hover:text-white"diff --git a/client/src/services/apiBrain.js b/client/src/services/apiBrain.jsindex 6ac7640de2..9c49bc78b5 100644--- a/client/src/services/apiBrain.js+++ b/client/src/services/apiBrain.js@@ -295,3 +295,14 @@ export const updateDailyLogSettings = (settings) => request('/brain/daily-log/sebody: JSON.stringify(settings)});export const syncDailyLogsToObsidian = () => request('/brain/daily-log/sync-obsidian', { method: 'POST' });++// Brain - Daily Log - Activity Digest (auto-drafts, #2155)+export const getActivityDigestSettings = () => request('/brain/daily-log/digest-settings');+export const updateActivityDigestSettings = (settings) => request('/brain/daily-log/digest-settings', {+ method: 'PUT',+ body: JSON.stringify(settings)+});+export const draftActivityDigest = (date = 'today') => request(+ `/brain/daily-log/${encodeURIComponent(date)}/draft`,+ { method: 'POST' }+);diff --git a/server/index.js b/server/index.jsindex 76bbbc10c7..6564ffc201 100644--- a/server/index.js+++ b/server/index.js@@ -179,6 +179,7 @@ import { startUpdateScheduler, clearStaleUpdateInProgress, processUpdateMarker }import { captureBootCommit } from './services/installState.js';import { restoreLoops } from './services/loops.js';import { startBrainScheduler } from './services/brainScheduler.js';+import { startActivityDigestScheduler } from './services/activityDigestScheduler.js';import { recoverStuckClassifications } from './services/brain.js';import { recoverStuckAnalyses } from './services/writersRoom/evaluator.js';import { recoverStuckAutoRuns } from './services/pipeline/autoRunner.js';@@ -585,6 +586,10 @@ recoverStuckAutoRuns().catch(err => console.error(`❌ Pipeline auto-run recoverrecoverStuckAutopilots().catch(err => console.error(`❌ Pipeline autopilot recovery failed: ${err.message}`));// Initialize brain scheduler for daily digests and weekly reviewsstartBrainScheduler();+// Initialize activity-digest scheduler — OFF by default; drafts daily-log+// auto-summaries from the Human Activity timeline only when the user enables it+// (Settings → Daily Log → Activity Digest). Silent + no LLM calls until then.+startActivityDigestScheduler();// Initialize brain→memory bridge (mirrors brain data into CoS memory for semantic search)initBrainMemoryBridge();// Load any on-disk POST drill cache into memory. Does NOT trigger LLM calls —diff --git a/server/lib/README.md b/server/lib/README.mdindex 979da22d84..98a1f7e0d4 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -255,6 +255,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `errorHandler.js` | `ServerError` + `asyncHandler` middleware. || `lwwTimestamp.js` | Last-writer-wins timestamp comparison for cross-instance sync merges. `parseTsMs(s)` (Date.parse → epoch ms or null), `compareNewerWins(candidate, incumbent)` (true iff candidate strictly newer; unparseable-loses, tie → incumbent — used to decide remote-overwrites-local), `compareEarlierWins(a, b)` (−1/0/1 earliest-wins tiebreak; unparseable-loses). Single source of the LWW polarity shared by `mergeMediaCollectionsFromSync` / `mergeAuthorsFromSync` etc. || `mapWithConcurrency.js` | Generic bounded-concurrency async mapper that preserves input order while capping in-flight work. |+| `markedSection.js` | Marker-delimited section replacement (pure). `buildMarkers(id)` → `{ start, end }` HTML-comment marker pair; `replaceMarkedSection(content, body, markers)` splices/replaces/removes an auto-generated region without touching surrounding user content (idempotent); `extractMarkedSection` / `hasMarkedSection` read it back. Powers the daily-log activity-digest auto-drafts (#2155) via `brainJournal.upsertAutoSection()`. || `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). || `openapiSpec.js` | `buildOpenApiSpec(settings, { baseUrl, version })` — builds an OpenAPI 3.1 document for the currently-exposed public APIs from `apiRegistry`, reusing route Zod schemas via `z.toJSONSchema`. Exposed+`requireAuth` operations get a `security` requirement; passwordless ones don't. Served by `routes/apiDocs.js`. || `shellQuote.js` | `shellQuote(value)` — POSIX single-quote escaping for values interpolated into shell command strings (display command lines, copy-paste blocks in agent prompts). Bare-safe tokens pass through; everything else is single-quoted. Canonical escaper — don't hand-roll. |diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex 16d6bf5e23..884d5d8e4b 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -528,3 +528,16 @@ export const dailyLogSettingsSchema = z.object({obsidianFolder: z.string().optional(),autoSync: z.boolean().optional()}).strict();++// Activity-digest (daily-log auto-drafts, #2155) settings. Managed fields+// (lastRunDate/lastRunAt) are server-owned and intentionally NOT accepted here —+// the service strips anything but these client-settable keys. Empty-string+// provider/model (UI "None" sentinel) coerces to null so the non-LLM path runs.+const emptyToNull = (v) => (v === '' ? null : v);+export const activityDigestSettingsSchema = z.object({+ enabled: z.boolean().optional(),+ provider: z.preprocess(emptyToNull, z.string().nullable().optional()),+ model: z.preprocess(emptyToNull, z.string().nullable().optional()),+ runTime: z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, 'Expected HH:MM (24h)').optional(),+ catchUpDays: z.number().int().min(0).max(30).optional()+}).strict();diff --git a/server/lib/index.js b/server/lib/index.jsindex f227b5c2f1..40af3b53a1 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -225,6 +225,7 @@ export * from './domainBudgets.js';export * from './errorHandler.js';export * from './lwwTimestamp.js';export * from './mapWithConcurrency.js';+export * from './markedSection.js';export * from './objects.js';export * from './openapiSpec.js';export * from './shellQuote.js';diff --git a/server/lib/markedSection.js b/server/lib/markedSection.jsnew file mode 100644index 0000000000..f984016e07--- /dev/null+++ b/server/lib/markedSection.js@@ -0,0 +1,92 @@+/**+ * Marker-delimited section replacement (pure, no I/O).+ *+ * Lets an automated writer own a clearly-delimited region inside a larger+ * user-authored document (e.g. the auto-generated activity-digest section inside+ * a Brain daily-log entry, #2155) without ever touching the surrounding+ * hand-written content. Re-runs replace ONLY the region between the stable+ * start/end markers; everything else is preserved byte-for-byte.+ *+ * Consumers: `server/services/activityDigest.js` builds the section body,+ * `brainJournal.upsertAutoSection()` splices it in.+ */++// Build a matched start/end marker pair for a stable section id. HTML-comment+// syntax so the markers render invisibly in Markdown / Obsidian previews and+// never collide with user prose.+export function buildMarkers(id) {+ const safe = String(id || 'section').trim() || 'section';+ return {+ start: `<!-- portos:${safe}:start -->`,+ end: `<!-- portos:${safe}:end -->`,+ };+}++// Escape a literal string for embedding inside a RegExp.+function escapeRegExp(s) {+ return String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+}++// Match the full marker region plus any leading blank line(s) the writer added+// so a replace/remove doesn't accumulate (or leave) widening gaps. Non-greedy+// body so two regions can't be swallowed as one.+function regionRegExp({ start, end }) {+ return new RegExp(`(?:\\n{1,2})?${escapeRegExp(start)}[\\s\\S]*?${escapeRegExp(end)}`);+}++// True when `content` already carries a well-formed (start … end) region.+export function hasMarkedSection(content, { start, end }) {+ if (typeof content !== 'string' || !content) return false;+ const si = content.indexOf(start);+ if (si === -1) return false;+ return content.indexOf(end, si + start.length) !== -1;+}++// Extract the trimmed body BETWEEN the markers, or null when absent. Markers+// themselves are stripped.+export function extractMarkedSection(content, { start, end }) {+ if (typeof content !== 'string') return null;+ const si = content.indexOf(start);+ if (si === -1) return null;+ const bodyStart = si + start.length;+ const ei = content.indexOf(end, bodyStart);+ if (ei === -1) return null;+ return content.slice(bodyStart, ei).trim();+}++/**+ * Replace (or insert, or remove) the marker-delimited section in `content`.+ *+ * - `body` non-empty → the region is (re)written to `${start}\n${body}\n${end}`.+ * An existing region is replaced in place (surrounding content + position+ * preserved); otherwise the block is appended after the existing content,+ * separated by a blank line.+ * - `body` empty/null → any existing region (and its leading blank line) is+ * removed; content with no region is returned untouched.+ *+ * Idempotent: replacing a region with the same body yields byte-identical+ * output, and markers never nest or duplicate.+ */+export function replaceMarkedSection(content, body, markers) {+ const base = typeof content === 'string' ? content : '';+ const trimmedBody = typeof body === 'string' ? body.trim() : '';+ const regionRe = regionRegExp(markers);++ if (!trimmedBody) {+ // Remove an existing region; collapse the resulting trailing whitespace so+ // the document doesn't end on a growing run of blank lines.+ return base.replace(regionRe, '').replace(/\s+$/, '');+ }++ const block = `${markers.start}\n${trimmedBody}\n${markers.end}`;++ if (regionRe.test(base)) {+ // Replace in place. Re-attach the blank-line separator the regex consumed so+ // the block stays visually detached from the content above; strip any+ // leading newlines left when the region was at the very top of the document.+ return base.replace(regionRe, `\n\n${block}`).replace(/^\n+/, '');+ }++ const head = base.replace(/\s+$/, '');+ return head ? `${head}\n\n${block}` : block;+}diff --git a/server/lib/markedSection.test.js b/server/lib/markedSection.test.jsnew file mode 100644index 0000000000..5df33fb48e--- /dev/null+++ b/server/lib/markedSection.test.js@@ -0,0 +1,103 @@+import { describe, it, expect } from 'vitest';+import {+ buildMarkers,+ replaceMarkedSection,+ extractMarkedSection,+ hasMarkedSection,+} from './markedSection.js';++const M = buildMarkers('activity-digest');++describe('buildMarkers', () => {+ it('produces a matched HTML-comment start/end pair from a stable id', () => {+ expect(M.start).toBe('<!-- portos:activity-digest:start -->');+ expect(M.end).toBe('<!-- portos:activity-digest:end -->');+ });++ it('falls back to a default id for empty/blank input', () => {+ expect(buildMarkers('').start).toBe('<!-- portos:section:start -->');+ expect(buildMarkers(' ').start).toBe('<!-- portos:section:start -->');+ });+});++describe('replaceMarkedSection', () => {+ it('inserts a section after existing user content, separated by a blank line', () => {+ const out = replaceMarkedSection('My hand-written notes.', 'AUTO BODY', M);+ expect(out).toBe(`My hand-written notes.\n\n${M.start}\nAUTO BODY\n${M.end}`);+ });++ it('inserts into empty content with no leading whitespace', () => {+ const out = replaceMarkedSection('', 'AUTO BODY', M);+ expect(out).toBe(`${M.start}\nAUTO BODY\n${M.end}`);+ });++ it('replaces ONLY the marked region and preserves surrounding user content', () => {+ const first = replaceMarkedSection('User text above.', 'FIRST', M);+ const second = replaceMarkedSection(`${first}\n\nUser text added below.`, 'SECOND', M);+ // The user text on both sides survives; only the body changed.+ expect(second).toContain('User text above.');+ expect(second).toContain('User text added below.');+ expect(second).toContain('SECOND');+ expect(second).not.toContain('FIRST');+ // Exactly one region.+ expect(second.match(new RegExp(M.start, 'g'))).toHaveLength(1);+ expect(second.match(new RegExp(M.end, 'g'))).toHaveLength(1);+ });++ it('is idempotent — replacing with the same body yields identical output', () => {+ const once = replaceMarkedSection('Notes.', 'SAME BODY', M);+ const twice = replaceMarkedSection(once, 'SAME BODY', M);+ expect(twice).toBe(once);+ });++ it('does not accumulate blank lines across repeated re-drafts', () => {+ let content = 'Notes.';+ for (let i = 0; i < 5; i++) content = replaceMarkedSection(content, `body ${i}`, M);+ expect(content).toBe(`Notes.\n\n${M.start}\nbody 4\n${M.end}`);+ });++ it('trims the body before embedding it', () => {+ const out = replaceMarkedSection('', ' padded body \n', M);+ expect(out).toBe(`${M.start}\npadded body\n${M.end}`);+ });++ it('removes the region (and its leading blank line) when body is empty', () => {+ const withSection = replaceMarkedSection('Kept notes.', 'AUTO', M);+ const removed = replaceMarkedSection(withSection, '', M);+ expect(removed).toBe('Kept notes.');+ expect(hasMarkedSection(removed, M)).toBe(false);+ });++ it('returns content untouched when removing a section that is not present', () => {+ expect(replaceMarkedSection('Just notes.', '', M)).toBe('Just notes.');+ });++ it('does not swallow content between two different regions (non-greedy)', () => {+ const other = buildMarkers('other');+ let content = replaceMarkedSection('top', 'A', M);+ content = replaceMarkedSection(content, 'B', other);+ // Replacing M again must leave the `other` region intact.+ const out = replaceMarkedSection(content, 'A2', M);+ expect(out).toContain('A2');+ expect(extractMarkedSection(out, other)).toBe('B');+ });+});++describe('extractMarkedSection / hasMarkedSection', () => {+ it('round-trips the body', () => {+ const content = replaceMarkedSection('notes', 'the body', M);+ expect(hasMarkedSection(content, M)).toBe(true);+ expect(extractMarkedSection(content, M)).toBe('the body');+ });++ it('reports absence for content without markers', () => {+ expect(hasMarkedSection('plain text', M)).toBe(false);+ expect(extractMarkedSection('plain text', M)).toBeNull();+ });++ it('treats a start marker with no end as absent', () => {+ const broken = `notes\n${M.start}\ndangling`;+ expect(hasMarkedSection(broken, M)).toBe(false);+ expect(extractMarkedSection(broken, M)).toBeNull();+ });+});diff --git a/server/routes/brainDailyLog.js b/server/routes/brainDailyLog.jsindex a046af7fe6..2e95cd65ce 100644--- a/server/routes/brainDailyLog.js+++ b/server/routes/brainDailyLog.js@@ -7,8 +7,9 @@import { Router } from 'express';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';-import { dailyLogSettingsSchema } from '../lib/brainValidation.js';+import { dailyLogSettingsSchema, activityDigestSettingsSchema } from '../lib/brainValidation.js';import * as journal from '../services/brainJournal.js';+import * as activityDigest from '../services/activityDigest.js';const router = Router();@@ -73,6 +74,25 @@ router.post('/daily-log/sync-obsidian', asyncHandler(async (req, res) => {res.json(stats);}));+/**+ * GET /api/brain/daily-log/digest-settings+ * Activity-digest (auto-draft) configuration. Registered BEFORE /:date so the+ * literal path isn't captured by the date param.+ */+router.get('/daily-log/digest-settings', asyncHandler(async (req, res) => {+ const settings = await activityDigest.getSettings();+ res.json(settings);+}));++/**+ * PUT /api/brain/daily-log/digest-settings+ */+router.put('/daily-log/digest-settings', asyncHandler(async (req, res) => {+ const data = validateRequest(activityDigestSettingsSchema, req.body || {});+ const next = await activityDigest.updateSettings(data);+ res.json(next);+}));+/*** GET /api/brain/daily-log/:date (accepts 'today')*/@@ -98,6 +118,19 @@ router.post('/daily-log/:date/append', asyncHandler(async (req, res) => {res.json({ date, entry });}));+/**+ * POST /api/brain/daily-log/:date/draft — manual "draft today now".+ * Direct user action, so it runs regardless of the scheduler's enabled flag and+ * doesn't advance the scheduler cursor. Uses the configured provider/model when+ * one is set (LLM narrative), else the non-LLM structured summary.+ */+router.post('/daily-log/:date/draft', asyncHandler(async (req, res) => {+ const date = await resolveJournalDate(req.params.date);+ const result = await activityDigest.runDigestForDate(date);+ const entry = await journal.getJournal(date);+ res.json({ ...result, entry });+}));+/*** PUT /api/brain/daily-log/:date — full content replace*/diff --git a/server/services/activityDigest.js b/server/services/activityDigest.jsnew file mode 100644index 0000000000..4e736783a5--- /dev/null+++ b/server/services/activityDigest.js@@ -0,0 +1,336 @@+/**+ * Activity Digest — daily-log auto-drafts (Human Activity Tracking Phase 6, #2155).+ *+ * Summarizes a day's Human Activity timeline (conversations, meetings, media+ * consumed — with tribe-person names resolved) into a compact draft, then+ * splices it as a clearly-marked auto-generated section into that day's Brain+ * daily-log entry (via brainJournal.upsertAutoSection → federates + re-embeds).+ *+ * Two modes:+ * 1. Non-LLM (always available, zero provider calls). `formatActivityDigest`+ * renders a deterministic structured bullet list — useful on its own AND+ * the template fed to the LLM.+ * 2. LLM narrative (opt-in). Only when a provider is configured in settings —+ * the config UI names the provider/model. See "AI Provider Usage Policy" in+ * CLAUDE.md: the feature is silent until the user enables it, and the+ * scheduled run is a sanctioned automation the user set up.+ *+ * The scheduler lives in activityDigestScheduler.js; the manual "draft today+ * now" button hits POST /brain/daily-log/:date/draft (a direct user action).+ */++import { join } from 'path';+import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';+import { buildMarkers } from '../lib/markedSection.js';+import { getUserTimezone } from '../lib/timezone.js';+import { getDaySummary } from './humanActivity.js';+import * as journal from './brainJournal.js';+import { getPerson } from './tribe.js';+import { getProviderById } from './providers.js';+import { runPromptThroughProvider } from '../lib/promptRunner.js';++const SETTINGS_FILE = join(PATHS.brain, 'activity-digest-settings.json');++// Stable marker pair — a re-run replaces ONLY this region in the journal entry.+export const DIGEST_MARKERS = buildMarkers('activity-digest');++const DEFAULT_SETTINGS = {+ // Scheduler opt-in. When false the feature is entirely silent — no scheduled+ // runs, no provider calls (the manual "draft now" button still works).+ enabled: false,+ // LLM provider/model for the narrative. null → non-LLM bullets only (zero+ // provider calls). The config UI names whichever provider/model is set here.+ provider: null,+ model: null,+ // Evening local time (HH:MM, user's timezone) the scheduled draft runs.+ runTime: '21:00',+ // How many prior days a missed-run catch-up will backfill (0 = today only).+ catchUpDays: 3,+ // Managed server-side — the last day successfully drafted + when.+ lastRunDate: null,+ lastRunAt: null,+};++// Keys the client may write via PUT — managed fields (lastRun*) are stripped.+const CLIENT_SETTABLE = ['enabled', 'provider', 'model', 'runTime', 'catchUpDays'];++// ─── Settings ────────────────────────────────────────────────────────────────++export async function getSettings() {+ await ensureDir(PATHS.brain);+ const loaded = await readJSONFile(SETTINGS_FILE, null);+ return loaded ? { ...DEFAULT_SETTINGS, ...loaded } : { ...DEFAULT_SETTINGS };+}++// Persist a partial update. Only client-settable keys are honored from+// `partial`; `internal` carries server-managed fields (lastRunDate/lastRunAt).+export async function updateSettings(partial = {}, internal = {}) {+ const current = await getSettings();+ const next = { ...current };+ for (const key of CLIENT_SETTABLE) {+ if (partial[key] !== undefined) next[key] = partial[key];+ }+ if (internal.lastRunDate !== undefined) next.lastRunDate = internal.lastRunDate;+ if (internal.lastRunAt !== undefined) next.lastRunAt = internal.lastRunAt;+ await atomicWrite(SETTINGS_FILE, next);+ return next;+}++// ─── Pure helpers (exported for unit tests — no I/O) ─────────────────────────++const CONVERSATION_KINDS = new Set(['message.sent', 'message.received']);+const MEETING_KINDS = new Set(['calendar.event']);+const MEDIA_KINDS = new Set(['media.listen', 'media.watch']);++const isoRe = /^\d{4}-\d{2}-\d{2}$/;+const isIso = (d) => typeof d === 'string' && isoRe.test(d);++// Shift a YYYY-MM-DD string by N days (UTC math — the string is a calendar day,+// not an instant, so DST doesn't apply). Returns YYYY-MM-DD.+export function shiftIso(date, days) {+ const [y, m, d] = date.split('-').map(Number);+ const dt = new Date(Date.UTC(y, m - 1, d));+ dt.setUTCDate(dt.getUTCDate() + days);+ return dt.toISOString().slice(0, 10);+}++/**+ * Which calendar days are due for a draft, given the last-drafted day and the+ * catch-up window. Returns an ascending list of YYYY-MM-DD (always includes+ * `today` when it hasn't been drafted yet — the scheduler decides today's+ * time-of-day gate separately). Pure + timezone-agnostic (operates on the+ * already-resolved local `today`).+ *+ * - never run → [today - catchUpDays … today]+ * - last run == today → [] (nothing due; re-draft is idempotent)+ * - last run == earlier → [max(lastRun+1, today-catchUpDays) … today]+ */+export function computeCatchUpDates(settings, today) {+ if (!isIso(today)) return [];+ const catchUpDays = Number.isFinite(settings?.catchUpDays)+ ? Math.max(0, Math.floor(settings.catchUpDays))+ : 0;+ const earliest = shiftIso(today, -catchUpDays);+ let cursor;+ if (isIso(settings?.lastRunDate)) {+ const dayAfterLast = shiftIso(settings.lastRunDate, 1);+ cursor = dayAfterLast > earliest ? dayAfterLast : earliest;+ } else {+ cursor = earliest;+ }+ const dates = [];+ // `cursor > today` guards against a lastRunDate in the future (clock skew).+ while (cursor <= today && dates.length <= catchUpDays + 1) {+ dates.push(cursor);+ cursor = shiftIso(cursor, 1);+ }+ return dates;+}++// Resolve a participant to a display name, preferring an explicit name, then a+// tribe-resolved name (nameByPersonId), then email/phone. Returns null when the+// participant has nothing usable.+function resolveParticipantName(p, nameByPersonId) {+ if (!p) return null;+ if (p.name) return p.name;+ if (p.personId && nameByPersonId[p.personId]) return nameByPersonId[p.personId];+ return p.email || p.phone || null;+}++// Unique, order-preserving list of participant display names across events.+function collectNames(events, nameByPersonId) {+ const seen = new Set();+ const names = [];+ for (const ev of events) {+ for (const p of ev.participants || []) {+ const name = resolveParticipantName(p, nameByPersonId);+ if (name && !seen.has(name)) {+ seen.add(name);+ names.push(name);+ }+ }+ }+ return names;+}++const joinNames = (names, max = 8) => (+ names.length <= max+ ? names.join(', ')+ : `${names.slice(0, max).join(', ')} +${names.length - max} more`+);++/**+ * Render a day's activity into a deterministic Markdown bullet summary — the+ * non-LLM fallback mode AND the template fed to the LLM. Returns null when the+ * day has no tracked events (so callers skip writing an empty section).+ *+ * @param {object} daySummary — shape from humanActivity.getDaySummary()+ * @param {object} [opts]+ * @param {Record<string,string>} [opts.nameByPersonId] — personId → tribe name+ */+export function formatActivityDigest(daySummary, { nameByPersonId = {} } = {}) {+ const events = Array.isArray(daySummary?.events) ? daySummary.events : [];+ if (events.length === 0) return null;++ const conversations = events.filter((e) => CONVERSATION_KINDS.has(e.kind));+ const meetings = events.filter((e) => MEETING_KINDS.has(e.kind));+ const media = events.filter((e) => MEDIA_KINDS.has(e.kind));++ const lines = [];++ if (conversations.length) {+ const sent = conversations.filter((e) => e.kind === 'message.sent').length;+ const received = conversations.length - sent;+ const names = collectNames(conversations, nameByPersonId);+ const withWhom = names.length ? ` with ${joinNames(names)}` : '';+ lines.push(`**Conversations** — ${conversations.length} message${conversations.length === 1 ? '' : 's'} (${sent} sent, ${received} received)${withWhom}`);+ }++ if (meetings.length) {+ lines.push(`**Meetings** — ${meetings.length}`);+ for (const ev of meetings) {+ const names = collectNames([ev], nameByPersonId);+ const withWhom = names.length ? ` (with ${joinNames(names, 5)})` : '';+ lines.push(`- ${ev.title || '(untitled event)'}${withWhom}`);+ }+ }++ if (media.length) {+ lines.push(`**Media** — ${media.length}`);+ for (const ev of media) {+ const verb = ev.kind === 'media.watch' ? 'Watched' : 'Listened';+ const detail = ev.summary ? ` — ${ev.summary}` : '';+ lines.push(`- ${verb}: ${ev.title || '(untitled)'}${detail}`);+ }+ }++ // Anything that isn't a known category still counts as activity — summarize a+ // tail count so the draft never silently drops events.+ const known = conversations.length + meetings.length + media.length;+ const other = events.length - known;+ if (other > 0) {+ lines.push(`**Other activity** — ${other} event${other === 1 ? '' : 's'}`);+ }++ return lines.join('\n');+}++// Wrap the section body with a visible header (rendered inside the markers). The+// header names the mode so the user can tell an LLM draft from raw bullets.+function buildSectionBody(date, body, { usedLlm }) {+ const badge = usedLlm ? 'AI-drafted' : 'auto-summary';+ return `### 🗓️ Activity Digest — ${date}\n_${badge} from your activity timeline. Edits above this line are preserved; this section is regenerated on each draft._\n\n${body}`;+}++// Build the LLM prompt from the non-LLM bullet template.+function buildNarrativePrompt(template, date) {+ return [+ 'You are writing a brief first-person journal entry summarizing my day, based ONLY on the structured activity summary below.',+ 'Write 2–4 short sentences in past tense, first person ("I ..."). Be factual — do not invent people, events, or details not present in the summary. Do not add a heading or a preamble.',+ '',+ `Date: ${date}`,+ '',+ 'Structured activity summary:',+ template,+ ].join('\n');+}++// ─── Orchestration ───────────────────────────────────────────────────────────++// Build a personId → display-name map by resolving tribe people for the+// personIds present in the day's events. Best-effort: a lookup failure just+// leaves that id unresolved (formatter falls back to name/email/phone).+async function buildNameMap(events) {+ const ids = new Set();+ for (const ev of events) {+ for (const p of ev.participants || []) {+ // Only resolve ids we actually need — a participant that already carries a+ // name doesn't need a tribe round-trip.+ if (p?.personId && !p?.name) ids.add(p.personId);+ }+ }+ const map = {};+ for (const id of ids) {+ const person = await getPerson(id).catch(() => null);+ if (person?.name) map[id] = person.name;+ }+ return map;+}++// Generate the LLM narrative from the bullet template. Returns null on any+// failure (caller falls back to the non-LLM bullets). Never throws — runs on+// the scheduler path too.+async function generateNarrative(template, date, settings) {+ const provider = await getProviderById(settings.provider).catch(() => null);+ if (!provider || !provider.enabled) return null;+ const model = settings.model || provider.defaultModel;+ // Headless classification-style run — append headlessArgs so a CLI provider+ // doesn't persist a session transcript for the draft.+ const providerForCall = provider.headlessArgs?.length+ ? { ...provider, args: [...(provider.args || []), ...provider.headlessArgs] }+ : provider;+ const result = await runPromptThroughProvider({+ provider: providerForCall,+ prompt: buildNarrativePrompt(template, date),+ source: 'activity-digest',+ model,+ }).catch((err) => {+ console.error(`🗓️ Activity digest LLM narrative failed for ${date}: ${err.message}`);+ return null;+ });+ const text = (result?.text || '').trim();+ return text || null;+}++/**+ * Draft (or re-draft) the activity digest for one calendar day and splice it+ * into that day's Brain daily-log entry. Idempotent — re-runs replace only the+ * marked auto section, never user content.+ *+ * @param {string} date — YYYY-MM-DD+ * @param {object} [opts]+ * @param {boolean} [opts.recordRun=false] — stamp settings.lastRun* on success+ * (the scheduler sets this; manual drafts don't move the scheduler cursor).+ * @returns {Promise<{ date, drafted: boolean, usedLlm: boolean, reason?: string }>}+ */+export async function runDigestForDate(date, { recordRun = false } = {}) {+ if (!journal.isIsoDate(date)) throw new Error(`invalid date: ${date}`);+ const started = Date.now();+ const settings = await getSettings();+ const daySummary = await getDaySummary({ date });+ const events = daySummary?.events || [];++ const template = formatActivityDigest(daySummary, {+ nameByPersonId: await buildNameMap(events),+ });++ if (!template) {+ console.log(`🗓️ Activity digest ${date}: no tracked activity — nothing to draft`);+ // Clear a stale auto section from a previous draft if the day is now empty.+ await journal.upsertAutoSection(date, '', DIGEST_MARKERS);+ if (recordRun) await stampRun(date);+ return { date, drafted: false, usedLlm: false, reason: 'no-activity' };+ }++ let sectionBody = template;+ let usedLlm = false;+ if (settings.provider) {+ const narrative = await generateNarrative(template, date, settings);+ if (narrative) {+ // Prose narrative on top; keep the structured bullets beneath it for+ // provenance / at-a-glance scanning.+ sectionBody = `${narrative}\n\n${template}`;+ usedLlm = true;+ }+ }++ await journal.upsertAutoSection(date, buildSectionBody(date, sectionBody, { usedLlm }), DIGEST_MARKERS);+ if (recordRun) await stampRun(date);+ console.log(`🗓️ Activity digest drafted ${date} (${events.length} event(s), ${usedLlm ? 'LLM' : 'non-LLM'}) in ${Date.now() - started}ms`);+ return { date, drafted: true, usedLlm };+}++// Advance the scheduler cursor to the drafted day.+async function stampRun(date) {+ await updateSettings({}, { lastRunDate: date, lastRunAt: new Date().toISOString() });+}diff --git a/server/services/activityDigest.test.js b/server/services/activityDigest.test.jsnew file mode 100644index 0000000000..b276bd2403--- /dev/null+++ b/server/services/activityDigest.test.js@@ -0,0 +1,127 @@+import { describe, it, expect } from 'vitest';+import {+ formatActivityDigest,+ computeCatchUpDates,+ shiftIso,+} from './activityDigest.js';++const ev = (kind, over = {}) => ({+ kind,+ title: over.title ?? null,+ summary: over.summary ?? null,+ participants: over.participants ?? [],+ ...over,+});++describe('formatActivityDigest (non-LLM formatter)', () => {+ it('returns null for a day with no tracked events', () => {+ expect(formatActivityDigest({ events: [] })).toBeNull();+ expect(formatActivityDigest({})).toBeNull();+ expect(formatActivityDigest(null)).toBeNull();+ });++ it('groups conversations with a sent/received tally and resolved names', () => {+ const summary = {+ events: [+ ev('message.sent', { participants: [{ name: 'Alice Smith' }] }),+ ev('message.received', { participants: [{ name: 'Alice Smith' }] }),+ ev('message.received', { participants: [{ email: '[email protected]' }] }),+ ],+ };+ const out = formatActivityDigest(summary);+ expect(out).toContain('**Conversations** — 3 messages (1 sent, 2 received)');+ expect(out).toContain('Alice Smith');+ expect(out).toContain('[email protected]');+ // Names are de-duplicated (Alice appears in two events but once in the line).+ expect(out.match(/Alice Smith/g)).toHaveLength(1);+ });++ it('resolves a tribe personId to a name via nameByPersonId', () => {+ const summary = {+ events: [ev('message.sent', { participants: [{ personId: 'p1' }] })],+ };+ const out = formatActivityDigest(summary, { nameByPersonId: { p1: 'Carol Jones' } });+ expect(out).toContain('Carol Jones');+ });++ it('lists meetings with attendee names', () => {+ const summary = {+ events: [+ ev('calendar.event', { title: 'Standup', participants: [{ name: 'Alice' }, { name: 'Bob' }] }),+ ],+ };+ const out = formatActivityDigest(summary);+ expect(out).toContain('**Meetings** — 1');+ expect(out).toContain('- Standup (with Alice, Bob)');+ });++ it('lists media with a watch/listen verb and detail', () => {+ const summary = {+ events: [+ ev('media.watch', { title: 'Some Video' }),+ ev('media.listen', { title: 'A Song', summary: 'The Band' }),+ ],+ };+ const out = formatActivityDigest(summary);+ expect(out).toContain('**Media** — 2');+ expect(out).toContain('- Watched: Some Video');+ expect(out).toContain('- Listened: A Song — The Band');+ });++ it('counts uncategorized events under Other activity (never drops events)', () => {+ const summary = { events: [ev('mystery.kind'), ev('another.kind')] };+ const out = formatActivityDigest(summary);+ expect(out).toContain('**Other activity** — 2 events');+ });+});++describe('shiftIso', () => {+ it('shifts calendar days across month/year boundaries', () => {+ expect(shiftIso('2026-07-08', 1)).toBe('2026-07-09');+ expect(shiftIso('2026-07-08', -1)).toBe('2026-07-07');+ expect(shiftIso('2026-07-31', 1)).toBe('2026-08-01');+ expect(shiftIso('2026-01-01', -1)).toBe('2025-12-31');+ });+});++describe('computeCatchUpDates (catch-up window logic)', () => {+ const TODAY = '2026-07-08';++ it('drafts only today when the last run was yesterday', () => {+ const dates = computeCatchUpDates({ lastRunDate: '2026-07-07', catchUpDays: 3 }, TODAY);+ expect(dates).toEqual([TODAY]);+ });++ it('returns nothing when already drafted today', () => {+ expect(computeCatchUpDates({ lastRunDate: TODAY, catchUpDays: 3 }, TODAY)).toEqual([]);+ });++ it('backfills the gap since the last run, capped by catchUpDays', () => {+ // last run 10 days ago, window of 3 → today-3 … today (4 days).+ const dates = computeCatchUpDates({ lastRunDate: '2026-06-28', catchUpDays: 3 }, TODAY);+ expect(dates).toEqual(['2026-07-05', '2026-07-06', '2026-07-07', '2026-07-08']);+ });++ it('backfills only up to the last-run day when the gap is inside the window', () => {+ const dates = computeCatchUpDates({ lastRunDate: '2026-07-06', catchUpDays: 5 }, TODAY);+ expect(dates).toEqual(['2026-07-07', '2026-07-08']);+ });++ it('first run (never drafted) backfills the full catch-up window plus today', () => {+ expect(computeCatchUpDates({ lastRunDate: null, catchUpDays: 2 }, TODAY)).toEqual([+ '2026-07-06', '2026-07-07', '2026-07-08',+ ]);+ });++ it('first run with catchUpDays 0 drafts today only', () => {+ expect(computeCatchUpDates({ lastRunDate: null, catchUpDays: 0 }, TODAY)).toEqual([TODAY]);+ });++ it('ignores a future lastRunDate (clock skew) without over-drafting', () => {+ expect(computeCatchUpDates({ lastRunDate: '2026-07-20', catchUpDays: 3 }, TODAY)).toEqual([]);+ });++ it('returns [] for an invalid today', () => {+ expect(computeCatchUpDates({ lastRunDate: null, catchUpDays: 3 }, 'nonsense')).toEqual([]);+ });+});diff --git a/server/services/activityDigestScheduler.js b/server/services/activityDigestScheduler.jsnew file mode 100644index 0000000000..87e3f1c842--- /dev/null+++ b/server/services/activityDigestScheduler.js@@ -0,0 +1,109 @@+/**+ * Activity Digest Scheduler (#2155)+ *+ * Dedicated scheduler for the daily-log auto-drafts — patterned on+ * brainScheduler.js (time-of-day trigger + missed-day catch-up), NOT+ * taskSchedule.js (that's the CoS agent system).+ *+ * OFF by default: only runs when the user has enabled it in Settings →+ * Daily Log → Activity Digest (`enabled: true`). This is a sanctioned+ * scheduled automation per CLAUDE.md's AI policy — the user opted in and the+ * config UI names the provider/model. Until then it is entirely silent (no+ * provider calls, no journal writes). The `enabled` flag + provider/model are+ * re-read every tick so toggling them takes effect without a restart.+ *+ * Timing model:+ * - Past days that were missed (server off, feature just enabled) are drafted+ * immediately on the next tick — their day is already complete.+ * - TODAY's draft waits until the configured evening `runTime`.+ */++import { getLocalParts, getUserTimezone, parseHHMM, todayInTimezone } from '../lib/timezone.js';+import { getSettings, computeCatchUpDates, runDigestForDate } from './activityDigest.js';++let schedulerInterval = null;+let running = false;+let lastFailure = null;+const CHECK_INTERVAL_MS = 60000; // Check every minute+const FAILURE_COOLDOWN_MS = 30 * 60 * 1000; // 30 min cooldown after a failure++// True when the current local time (user's timezone) is at/after the configured+// runTime — the gate for drafting TODAY.+function isPastRunTime(runTime, parts) {+ const runMinutes = parseHHMM(runTime); // minutes-from-midnight, or null+ if (runMinutes === null) return false;+ const nowMinutes = parts.hour * 60 + parts.minute;+ return nowMinutes >= runMinutes;+}++function isInCooldown(now) {+ return lastFailure ? (now - lastFailure) < FAILURE_COOLDOWN_MS : false;+}++/**+ * Decide which dates to draft on this tick (pure given its inputs). Past days+ * (before `today`) run regardless of time-of-day; `today` only runs once the+ * runTime has passed.+ */+export function selectDueDates(settings, today, parts) {+ const due = computeCatchUpDates(settings, today);+ const past = due.filter((d) => d < today);+ const includeToday = due.includes(today) && isPastRunTime(settings.runTime, parts);+ return includeToday ? [...past, today] : past;+}++async function checkSchedule() {+ const settings = await getSettings();+ if (!settings.enabled) return;++ const now = Date.now();+ if (running || isInCooldown(now)) return;++ const timezone = await getUserTimezone();+ const parts = getLocalParts(new Date(now), timezone);+ const today = todayInTimezone(timezone);+ const dueDates = selectDueDates(settings, today, parts);+ if (dueDates.length === 0) return;++ running = true;+ console.log(`🗓️ Activity digest scheduler: drafting ${dueDates.length} day(s): ${dueDates.join(', ')}`);+ try {+ for (const date of dueDates) {+ // recordRun advances the scheduler cursor (lastRunDate) after each day so+ // a crash mid-catch-up resumes instead of re-drafting from the start.+ await runDigestForDate(date, { recordRun: true });+ }+ } catch (err) {+ lastFailure = Date.now();+ console.error(`🗓️ Activity digest scheduler run failed: ${err.message} (retry in 30min)`);+ } finally {+ running = false;+ }+}++/**+ * Start the activity-digest scheduler. Registers the interval unconditionally+ * (like brainScheduler); each tick no-ops when the feature is disabled, so a+ * user enabling it later doesn't need a restart.+ */+export function startActivityDigestScheduler() {+ if (schedulerInterval) {+ console.log('🗓️ Activity digest scheduler: already running');+ return;+ }+ console.log('🗓️ Activity digest scheduler: starting');+ // Initial check — wrapped so an early throw can't crash boot (runs outside+ // the request lifecycle).+ checkSchedule().catch((err) => console.error(`🗓️ Activity digest scheduler initial check failed: ${err.message}`));+ schedulerInterval = setInterval(() => {+ checkSchedule().catch((err) => console.error(`🗓️ Activity digest scheduler check failed: ${err.message}`));+ }, CHECK_INTERVAL_MS);+}++export function stopActivityDigestScheduler() {+ if (schedulerInterval) {+ clearInterval(schedulerInterval);+ schedulerInterval = null;+ console.log('🗓️ Activity digest scheduler: stopped');+ }+}diff --git a/server/services/activityDigestScheduler.test.js b/server/services/activityDigestScheduler.test.jsnew file mode 100644index 0000000000..198ecb70e8--- /dev/null+++ b/server/services/activityDigestScheduler.test.js@@ -0,0 +1,34 @@+import { describe, it, expect } from 'vitest';+import { selectDueDates } from './activityDigestScheduler.js';++const TODAY = '2026-07-08';+const parts = (hour, minute = 0) => ({ hour, minute });++describe('selectDueDates (scheduler time gating)', () => {+ const settings = (over = {}) => ({ runTime: '21:00', catchUpDays: 3, lastRunDate: '2026-07-07', ...over });++ it('does not draft today before the configured runTime', () => {+ // Last run yesterday → only today is due, but it is 15:00 (< 21:00).+ expect(selectDueDates(settings(), TODAY, parts(15))).toEqual([]);+ });++ it('drafts today once the runTime has passed', () => {+ expect(selectDueDates(settings(), TODAY, parts(21, 0))).toEqual([TODAY]);+ expect(selectDueDates(settings(), TODAY, parts(22, 30))).toEqual([TODAY]);+ });++ it('drafts past missed days immediately regardless of time-of-day', () => {+ // Server was off for days; it is only 09:00, but the completed past days run now.+ const dates = selectDueDates(settings({ lastRunDate: '2026-07-04' }), TODAY, parts(9));+ expect(dates).toEqual(['2026-07-05', '2026-07-06', '2026-07-07']); // today excluded (before 21:00)+ });++ it('includes today alongside past days once runTime passes', () => {+ const dates = selectDueDates(settings({ lastRunDate: '2026-07-04' }), TODAY, parts(21, 30));+ expect(dates).toEqual(['2026-07-05', '2026-07-06', '2026-07-07', '2026-07-08']);+ });++ it('returns nothing when already drafted today', () => {+ expect(selectDueDates(settings({ lastRunDate: TODAY }), TODAY, parts(23))).toEqual([]);+ });+});diff --git a/server/services/brainJournal.js b/server/services/brainJournal.jsindex 0d512b4632..5dc601f1c5 100644--- a/server/services/brainJournal.js+++ b/server/services/brainJournal.js@@ -26,6 +26,7 @@ import { existsSync } from 'fs';import { join } from 'path';import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';+import { replaceMarkedSection } from '../lib/markedSection.js';import * as brainStorage from './brainStorage.js';import { brainEvents, now } from './brainStorage.js';import * as obsidian from './obsidian.js';@@ -303,6 +304,39 @@ export async function appendJournal(date, text, { source = 'text' } = {}) {return entry;}+/**+ * Splice an auto-generated, marker-delimited section into a day's entry WITHOUT+ * disturbing user-authored content or segment history. Unlike setJournalContent+ * (which collapses segments on a full rewrite), this preserves `segments` — it+ * only rewrites the region between the markers (see server/lib/markedSection.js),+ * so a re-run replaces just the auto section and typed/dictated text stays+ * primary. Passing an empty `body` removes the section.+ *+ * Rides the same brainStorage.upsertWithId path as every other journal write+ * (via putEntry), so the edit federates + re-embeds through brainMemoryBridge.+ * Returns the updated entry, or null when there was nothing to write (no+ * existing entry AND an empty section, or an idempotent no-op re-run).+ */+export async function upsertAutoSection(date, body, markers) {+ if (!isIsoDate(date)) throw new Error(`invalid date: ${date}`);+ const entry = await storeMutex(async () => {+ const existing = await getEntry(date);+ const base = existing || newEntry(date);+ const nextContent = replaceMarkedSection(base.content || '', body, markers);+ // Idempotent re-run against an unchanged day: skip the write, sync-log+ // append, and Obsidian round-trip entirely.+ if (existing && nextContent === (base.content || '')) return existing;+ // Nothing to persist: no prior entry and the draft produced no section.+ if (!existing && !nextContent.trim()) return null;+ return putEntry(date, { ...base, content: nextContent });+ });+ if (!entry) return null;+ scheduleObsidianSync(entry);+ brainEvents.emit('journals:changed', { records: await rawRecords() });+ brainEvents.emit('journals:upserted', { entry });+ return entry;+}+export async function deleteJournal(date) {if (!isIsoDate(date)) return false;const entry = await storeMutex(async () => {