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
fix(issue-2015): timezone refresh, missed-slot catch-up, centralize POST reminder reschedule
Adam Eivy36898680de83
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex b340c38e53..a428dd48eb 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -34,6 +34,7 @@- **[issue-2009] Hardened the N-Back / Digit Span / Stroop cognitive drills against silent scoring regressions.** The result-assembly logic that turns your answers into the `questions[]` payload the server rescores from (N-Back's off-by-one-prone target lookup, Digit Span's forward-vs-backward comparison, Stroop's ink-vs-word grading) is now covered by focused unit tests, matching the test coverage the other POST drill runners already had. No behavior change. (`client/src/components/meatspace/post/PostCognitiveDrillRunner.jsx`, Closes #2009)- **[issue-2010] Memory drills inside a POST session now count as a review.** Practicing a memory item (Sequence or Element Flash) as part of a scored POST session previously updated your score but never touched that item's spaced-repetition schedule — so it stayed on "Due Today" even right after you'd just reviewed it, which only the dedicated Memory Builder practice screen would clear. A POST-session memory drill now advances the item's schedule the same way MemoryBuilder practice does (a strong session pushes the next review out; a miss-heavy one resets it to due-now), so "Due Today" and the review streak stay accurate no matter which screen you practiced from. (`server/services/meatspacePost.js`, `server/services/meatspacePostMemory.js`, `client/src/hooks/usePostSession.js`, Closes #2010)- **[issue-2006] Three more Cognitive drills — Schulte Table, Mental Rotation, and Reaction Time.** Rounds out the Cognitive domain from #1993 with the three follow-up exercises: **Schulte Table** (scan a shuffled numbered grid and tap 1, 2, 3... in order — visual attention and scan speed), **Mental Rotation** (pick which of four shapes is the reference shape rotated, not mirrored — spatial reasoning), and **Reaction Time** (simple or choice reaction-time baseline, with a false-start penalty for jumping the gun). All three are configurable, playable in Test and Train modes, scored, and saved to your training history alongside the rest of POST — with zero AI provider calls, same as the rest of the Cognitive domain.+- **[issue-2015] The daily POST reminder now follows timezone changes and catches up after a restart.** Three follow-ups to #1994's reminder: changing your timezone elsewhere in Settings now reschedules the reminder to the new local time automatically, instead of it silently keeping the old offset until you next touch POST's own config; if the server was down (or mid-restart) when today's reminder was due, it now fires as soon as the server is back up rather than staying silent until tomorrow; and it's protected against sending a duplicate nudge if that catch-up and the normal daily tick ever land on the same day. No user-facing config changes. (`server/services/meatspacePostReminder.js`, `server/services/meatspacePost.js`, Closes #2015)## Media Generationdiff --git a/server/index.js b/server/index.jsindex 1f7f49f410..c1f55b52bf 100644--- a/server/index.js+++ b/server/index.js@@ -582,7 +582,10 @@ initBrainMemoryBridge();initDrillCache().catch(err => console.error(`❌ POST drill cache init failed: ${err.message}`));// Register the optional daily POST reminder (opt-in, off by default) if the// user has enabled it — deterministic cron nudge, no LLM calls.-registerPostReminderSchedule().catch(err => console.error(`❌ POST reminder init failed: ${err.message}`));+// catchUpMissedSlot: true so a reminder whose slot elapsed while the server+// was down (or during a redeploy) still fires once we're back up, instead of+// silently waiting for tomorrow's tick (#2015).+registerPostReminderSchedule({ catchUpMissedSlot: true }).catch(err => console.error(`❌ POST reminder init failed: ${err.message}`));// Initialize backup scheduler for daily data backupsstartBackupScheduler().catch(err => console.error(`❌ Backup scheduler init failed: ${err.message}`));// Initialize CyberCity snapshot scheduler — records periodic city-state framesdiff --git a/server/routes/meatspacePostRoutes.js b/server/routes/meatspacePostRoutes.jsindex 8daa91bcac..f5d9b5d362 100644--- a/server/routes/meatspacePostRoutes.js+++ b/server/routes/meatspacePostRoutes.js@@ -27,7 +27,11 @@ import * as memoryService from '../services/meatspacePostMemory.js';import { generateLlmDrill, scoreLlmDrill } from '../services/meatspacePostLlm.js';import { getCachedDrill, triggerReplenish, getCacheStats, requestCacheFill } from '../services/meatspacePostDrillCache.js';import * as trainingService from '../services/meatspacePostTraining.js';-import { registerPostReminderSchedule } from '../services/meatspacePostReminder.js';+// meatspacePostReminder.js is not imported here — updatePostConfig() itself+// reschedules the daily reminder (via meatspacePost.js's postConfigEvents) so+// any current or future caller gets that behavior for free (#2015). Loaded+// once at boot from server/index.js, which is enough to attach its listener+// for the lifetime of the process.const router = Router();@@ -50,15 +54,13 @@ router.get('/post/config', asyncHandler(async (req, res) => {*/router.put('/post/config', asyncHandler(async (req, res) => {const data = validateRequest(postConfigUpdateSchema, req.body);+ // updatePostConfig() reschedules the daily reminder itself (via its+ // postConfigEvents emitter, subscribed in meatspacePostReminder.js) whenever+ // `data.reminder` is part of the patch — see meatspacePost.js. That+ // reschedule runs fire-and-forget and swallows its own errors, so a+ // rescheduling failure (e.g. timezone settings unreadable) can never+ // surface as a save error here.const config = await postService.updatePostConfig(data);- // Reschedule the daily reminder immediately (no restart needed) whenever- // its enabled/time fields change — see meatspacePostReminder.js. The config- // write above already succeeded, so a rescheduling failure (e.g. timezone- // settings unreadable) must not surface as a save error to the client —- // log and swallow it, mirroring the boot-time registration's own handling.- if (data.reminder) {- await registerPostReminderSchedule().catch(err => console.error(`❌ POST reminder reschedule failed: ${err.message}`));- }res.json(config);}));diff --git a/server/routes/meatspacePostRoutes.reminder.test.js b/server/routes/meatspacePostRoutes.reminder.test.jsindex 7c81ebd5ba..2fdc39f562 100644--- a/server/routes/meatspacePostRoutes.reminder.test.js+++ b/server/routes/meatspacePostRoutes.reminder.test.js@@ -2,25 +2,22 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import express from 'express';import { request } from '../lib/testHelper.js';-// Scoped to PUT /post/config's reminder-rescheduling wiring — only the two-// services that route touches (postService.updatePostConfig and-// meatspacePostReminder.registerPostReminderSchedule) are mocked. Mirrors the-// scoping rationale in meatspacePostRoutes.drillCache.test.js.+// PUT /post/config no longer wires the reminder reschedule itself (#2015) —+// that now lives centrally inside meatspacePost.js's updatePostConfig(), via+// its postConfigEvents emitter, so any current or future caller of+// updatePostConfig gets the reschedule for free. See:+// - server/services/meatspacePost.test.js for updatePostConfig emitting+// postConfigEvents on every save.+// - server/services/meatspacePostReminder.test.js for the subscription+// that reschedules when the `reminder` slice is part of the patch.+// This file is now a lean smoke test for the route itself: it validates the+// body, delegates to postService.updatePostConfig, and returns the result.vi.mock('../services/meatspacePost.js', () => ({getPostConfig: vi.fn(),updatePostConfig: vi.fn(),}));-vi.mock('../services/meatspacePostReminder.js', () => ({- // Real implementation is async (always returns a Promise) — the route- // chains `.catch()` onto the call, so the mock must resolve rather than- // return `undefined` synchronously (clearAllMocks in beforeEach clears call- // history, not the configured resolution, so this default is safe to set once).- registerPostReminderSchedule: vi.fn().mockResolvedValue(undefined),-}));-import * as postService from '../services/meatspacePost.js';-import { registerPostReminderSchedule } from '../services/meatspacePostReminder.js';import { errorMiddleware } from '../lib/errorHandler.js';import meatspacePostRoutes from './meatspacePostRoutes.js';@@ -32,7 +29,7 @@ function makeApp() {return app;}-describe('PUT /api/meatspace/post/config — reminder rescheduling', () => {+describe('PUT /api/meatspace/post/config', () => {let app;beforeEach(() => {app = makeApp();@@ -40,31 +37,20 @@ describe('PUT /api/meatspace/post/config — reminder rescheduling', () => {postService.updatePostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });});- it('reschedules the reminder when the payload includes a reminder block', async () => {+ it('delegates to postService.updatePostConfig and returns the saved config', async () => {const r = await request(app).put('/api/meatspace/post/config').send({ reminder: { enabled: true, time: '09:00' } });expect(r.status).toBe(200);- expect(registerPostReminderSchedule).toHaveBeenCalledTimes(1);+ expect(postService.updatePostConfig).toHaveBeenCalledWith({ reminder: { enabled: true, time: '09:00' } });+ expect(r.body).toEqual({ reminder: { enabled: true, time: '09:00' } });});- it('does not touch the reminder schedule when the payload has no reminder key', async () => {+ it('accepts a payload with no reminder key', async () => {const r = await request(app).put('/api/meatspace/post/config').send({ adaptive: { enabled: true } });expect(r.status).toBe(200);- expect(registerPostReminderSchedule).not.toHaveBeenCalled();- });-- // Regression: a rescheduling failure must not mask a config write that- // already succeeded — the client shouldn't be told "save failed" when the- // new value was in fact persisted.- it('still returns the saved config with a 200 when rescheduling itself throws', async () => {- registerPostReminderSchedule.mockRejectedValueOnce(new Error('timezone settings unreadable'));- const r = await request(app)- .put('/api/meatspace/post/config')- .send({ reminder: { enabled: true, time: '09:00' } });- expect(r.status).toBe(200);- expect(r.body).toEqual({ reminder: { enabled: true, time: '09:00' } });+ expect(postService.updatePostConfig).toHaveBeenCalledWith({ adaptive: { enabled: true } });});});diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.jsindex 30d9ae8ee8..537cfb788a 100644--- a/server/services/meatspacePost.js+++ b/server/services/meatspacePost.js@@ -7,6 +7,7 @@import { join } from 'path';import { randomUUID } from 'crypto';+import { EventEmitter } from 'events';import { atomicWrite, PATHS, ensureDir, readJSONFile } from '../lib/fileUtils.js';import { deepMerge, isPlainObject } from '../lib/objects.js';import { LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, POST_SUPPORTED_MEMORY_TYPES } from '../lib/postValidation.js';@@ -18,6 +19,15 @@ const MEATSPACE_DIR = PATHS.meatspace;const SESSIONS_FILE = join(MEATSPACE_DIR, 'post-sessions.json');const CONFIG_FILE = join(MEATSPACE_DIR, 'post-config.json');+// Tiny pub/sub (mirrors settingsEvents in server/services/settings.js) so+// features that react to a specific config slice — e.g. meatspacePostReminder.js+// rescheduling its cron when `reminder` changes — can subscribe without+// meatspacePost.js importing back into them (which would create a service+// cycle). This is what makes updatePostConfig() the single place ANY current+// or future caller gets slice-specific side effects "for free", instead of+// each route handler having to remember to bolt one on (#2015).+export const postConfigEvents = new EventEmitter();+const DEFAULT_CONFIG = {mentalMath: {enabled: true,@@ -92,6 +102,11 @@ export async function updatePostConfig(updates) {await ensureMeatspaceDir();await atomicWrite(CONFIG_FILE, merged);console.log(`🧪 POST config updated`);+ // Emit AFTER the write succeeds so a subscriber (reminder rescheduler, etc.)+ // never reacts to a config change that didn't actually persist. `updates` is+ // included (not just `merged`) so subscribers can gate on which slice was+ // touched rather than re-evaluating on every unrelated save.+ postConfigEvents.emit('post-config:updated', { config: merged, updates });return merged;}diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.jsindex c0477d19eb..a0e94d019f 100644--- a/server/services/meatspacePost.test.js+++ b/server/services/meatspacePost.test.js@@ -24,6 +24,8 @@ import {computeExpectedFromPrompt,computePostStreaks,submitPostSession,+ updatePostConfig,+ postConfigEvents,} from './meatspacePost.js';// =============================================================================@@ -541,3 +543,59 @@ describe('submitPostSession — memory drill schedule advance', () => {expect(memoryWrite).toBeUndefined();});});++// =============================================================================+// UPDATE CONFIG — postConfigEvents (issue #2015)+//+// updatePostConfig() emits `post-config:updated` on its own EventEmitter+// (postConfigEvents) after every successful write, carrying both the merged+// config and the raw `updates` patch. meatspacePostReminder.js subscribes to+// this to reschedule the daily reminder — this is what centralizes+// reschedule-on-save so ANY caller of updatePostConfig gets it for free,+// instead of each route handler having to remember to bolt one on.+// =============================================================================++describe('updatePostConfig — postConfigEvents', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ readJSONFile.mockImplementation((path, defaultValue) => Promise.resolve(defaultValue));+ atomicWrite.mockResolvedValue(undefined);+ });++ it('emits post-config:updated with the merged config and the raw updates patch', async () => {+ const handler = vi.fn();+ postConfigEvents.once('post-config:updated', handler);++ const merged = await updatePostConfig({ reminder: { enabled: true, time: '09:00' } });++ expect(handler).toHaveBeenCalledTimes(1);+ expect(handler.mock.calls[0][0]).toEqual({+ config: merged,+ updates: { reminder: { enabled: true, time: '09:00' } },+ });+ expect(merged.reminder).toEqual({ enabled: true, time: '09:00' });+ });++ it('still emits for updates unrelated to the reminder — subscribers decide what to react to', async () => {+ const handler = vi.fn();+ postConfigEvents.once('post-config:updated', handler);++ await updatePostConfig({ adaptive: { enabled: true } });++ expect(handler).toHaveBeenCalledTimes(1);+ expect(handler.mock.calls[0][0].updates).toEqual({ adaptive: { enabled: true } });+ });++ it('only emits after the config write has persisted, not before', async () => {+ let writeResolved = false;+ atomicWrite.mockImplementationOnce(async () => { writeResolved = true; });+ const handler = vi.fn(() => {+ expect(writeResolved).toBe(true);+ });+ postConfigEvents.once('post-config:updated', handler);++ await updatePostConfig({ adaptive: { enabled: true } });++ expect(handler).toHaveBeenCalledTimes(1);+ });+});diff --git a/server/services/meatspacePostReminder.js b/server/services/meatspacePostReminder.jsindex 5f24223304..e895a3a4ba 100644--- a/server/services/meatspacePostReminder.js+++ b/server/services/meatspacePostReminder.js@@ -11,20 +11,32 @@* Mirrors backupScheduler.js's daily-cron registration pattern via* eventScheduler.js, but — unlike backupScheduler's fixed-at-registration cron* expression — the time-of-day is user-editable at runtime:- * registerPostReminderSchedule() is called both at server boot and again after- * every `PUT /post/config`, so a changed time or enabled flag takes effect on- * the next tick without a restart (same idea as cosJobScheduler.js's- * `registerSingleJobSchedule`, simplified since a daily HH:MM nudge doesn't- * need that module's weekday/interval-fallback machinery).+ * registerPostReminderSchedule() is called at server boot, whenever+ * updatePostConfig() saves a `reminder` change (via meatspacePost.js's+ * postConfigEvents — see below), and whenever the user's global timezone+ * changes (via settings.js's settingsEvents) — so a changed time, enabled+ * flag, or timezone all take effect on the next tick without a restart (same+ * idea as cosJobScheduler.js's `registerSingleJobSchedule`, simplified since+ * a daily HH:MM nudge doesn't need that module's weekday/interval-fallback+ * machinery). The boot-time call additionally checks for a missed slot+ * (mirrors taskSchedule.js's `parseCronToPrevRun` catch-up) so a reminder+ * whose slot elapsed while the server was down still fires once it's back up.*/-import { schedule, cancel } from './eventScheduler.js';+import { schedule, cancel, parseCronToPrevRun } from './eventScheduler.js';import { getUserTimezone, getLocalParts, todayInTimezone, HHMM_STRICT_RE } from '../lib/timezone.js';-import { getPostConfig, getPostSessions } from './meatspacePost.js';-import { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';+import { getPostConfig, getPostSessions, postConfigEvents } from './meatspacePost.js';+import { addNotification, getNotifications, NOTIFICATION_TYPES, PRIORITY_LEVELS } from './notifications.js';+import { settingsEvents } from './settings.js';export const POST_REMINDER_EVENT_ID = 'post-daily-reminder';+// Timezone actually applied to the current cron registration — tracked so a+// global settings save that doesn't touch the timezone (most of them) skips+// a redundant reschedule + log line (see settingsEvents subscription below).+// Reset to null whenever the reminder is disabled/unregistered.+let lastAppliedTimezone = null;+/*** Convert an "HH:MM" time-of-day into a daily cron expression ("M H * * *").* Pure — exported for unit testing. Returns null for a malformed/missing time@@ -36,6 +48,19 @@ export function reminderTimeToCron(time) {return `${minute} ${hour} * * *`;}+/**+ * True if a UTC timestamp falls on the given "YYYY-MM-DD" LOCAL calendar day+ * (in `timezone`). Shared by both the "did today's session complete" and+ * "did a reminder already go out today" checks below — both need the same+ * UTC-timestamp-to-local-day comparison, just against a different collection.+ */+function isOnLocalDay(timestamp, timezone, dayStr) {+ if (!timestamp) return false;+ const parts = getLocalParts(new Date(timestamp), timezone);+ const localDate = `${parts.year}-${String(parts.month).padStart(2, '0')}-${String(parts.day).padStart(2, '0')}`;+ return localDate === dayStr;+}+/*** Fire the reminder notification if — and only if — today's POST is still* incomplete. Re-reads config at fire time (mirrors backupScheduler's@@ -64,17 +89,24 @@ export async function firePostReminderIfIncomplete() {const timezone = await getUserTimezone();const todayStr = todayInTimezone(timezone);const sessions = await getPostSessions();- const completedToday = sessions.some(s => {- if (!s?.startedAt) return false;- const parts = getLocalParts(new Date(s.startedAt), timezone);- const localDate = `${parts.year}-${String(parts.month).padStart(2, '0')}-${String(parts.day).padStart(2, '0')}`;- return localDate === todayStr;- });+ const completedToday = sessions.some(s => isOnLocalDay(s?.startedAt, timezone, todayStr));if (completedToday) {console.log(`🔔 POST reminder: today's session already complete — no nudge`);return;}+ // De-dupe against a notification already sent today. Without this, the+ // missed-slot catch-up (registerPostReminderSchedule, run on every server+ // restart) would re-nag if the server restarts again later the same day+ // after the normal cron tick already fired — "still incomplete" alone+ // isn't enough to guarantee this run is the first one today.+ const existing = await getNotifications({ type: NOTIFICATION_TYPES.DAILY_POST_REMINDER });+ const alreadyNotifiedToday = existing.some(n => isOnLocalDay(n?.timestamp, timezone, todayStr));+ if (alreadyNotifiedToday) {+ console.log(`🔔 POST reminder: already notified today — skipping duplicate`);+ return;+ }+await addNotification({type: NOTIFICATION_TYPES.DAILY_POST_REMINDER,title: "Today's POST is still open",@@ -85,18 +117,50 @@ export async function firePostReminderIfIncomplete() {console.log(`🔔 POST reminder: nudge sent (today's session incomplete)`);}+/**+ * If today's cron slot has already elapsed (the server was down or just+ * booted after the scheduled minute), fire the reminder immediately instead+ * of waiting for tomorrow's tick. Mirrors taskSchedule.js's+ * `parseCronToPrevRun`-based catch-up: bound the lookback to ONE cron period+ * (the occurrence before the most recent one) so this only ever replays+ * "today's" missed slot, never a backlog. `firePostReminderIfIncomplete`+ * itself is idempotent (completedToday + already-notified-today guards), so+ * calling it here is safe even when nothing was actually missed.+ */+async function catchUpMissedSlot(cron, timezone) {+ const now = Date.now();+ const prevRun = parseCronToPrevRun(cron, new Date(now), timezone);+ if (!prevRun) return;++ const prevRunMs = prevRun.getTime();+ const beforePrev = parseCronToPrevRun(cron, new Date(prevRunMs - 60_000), timezone);+ const lookbackBound = beforePrev ? beforePrev.getTime() : 0;++ if (prevRunMs > lookbackBound && prevRunMs <= now) {+ console.log(`🔔 POST reminder: missed slot detected (${prevRun.toISOString()}) — catching up now`);+ await firePostReminderIfIncomplete();+ }+}+/*** Register (or cancel) the daily reminder cron job from the current POST* config. Safe to call repeatedly — `schedule()` replaces any existing* registration under the same id, so calling this again after a settings* change reschedules immediately.+ *+ * @param {Object} [options]+ * @param {boolean} [options.catchUpMissedSlot] - Check for and fire a slot+ * that already elapsed (server-restart recovery). Only the boot-time+ * registration in server/index.js sets this — reschedules triggered by a+ * config/timezone save should NOT replay a slot the user didn't miss.*/-export async function registerPostReminderSchedule() {+export async function registerPostReminderSchedule({ catchUpMissedSlot: shouldCatchUp = false } = {}) {const config = await getPostConfig();const { enabled, time } = config.reminder || {};if (!enabled) {cancel(POST_REMINDER_EVENT_ID);+ lastAppliedTimezone = null;return;}@@ -104,10 +168,12 @@ export async function registerPostReminderSchedule() {if (!cron) {console.error(`❌ POST reminder: invalid time "${time}" — not scheduling`);cancel(POST_REMINDER_EVENT_ID);+ lastAppliedTimezone = null;return;}const timezone = await getUserTimezone();+ lastAppliedTimezone = timezone;schedule({id: POST_REMINDER_EVENT_ID,type: 'cron',@@ -117,11 +183,50 @@ export async function registerPostReminderSchedule() {metadata: { source: 'meatspacePostReminder' }});console.log(`🔔 POST reminder: registered daily at ${time} (${timezone})`);++ if (shouldCatchUp) {+ await catchUpMissedSlot(cron, timezone);+ }+}++/**+ * Refresh the cron's timezone when the user's global timezone setting+ * changes elsewhere (Settings page, not this feature's own config) — without+ * this, the reminder keeps firing at the OLD offset until the next unrelated+ * POST-config save happens to reschedule it. Fired on every `settings:updated`+ * event but only actually reschedules (and logs) when the effective timezone+ * changed, so tweaking an unrelated setting doesn't spam a reschedule.+ */+async function refreshTimezoneIfChanged() {+ const config = await getPostConfig();+ if (config.reminder?.enabled !== true) return; // nothing scheduled to refresh++ const timezone = await getUserTimezone();+ if (timezone === lastAppliedTimezone) return;++ console.log(`🔔 POST reminder: timezone changed (${lastAppliedTimezone || 'unset'} → ${timezone}) — rescheduling`);+ await registerPostReminderSchedule();}+settingsEvents.on('settings:updated', () => {+ refreshTimezoneIfChanged().catch(err => console.error(`❌ POST reminder timezone refresh failed: ${err.message}`));+});++// Centralizes reschedule-on-save inside updatePostConfig() (via its+// postConfigEvents emitter) rather than bolting it onto one route handler —+// any current or future caller of updatePostConfig gets the reschedule for+// free (#2015). Gated on the `reminder` slice actually being part of the+// patch so unrelated config saves (drill settings, adaptive toggle, etc.)+// don't trigger a redundant reschedule + log line.+postConfigEvents.on('post-config:updated', ({ updates }) => {+ if (!updates?.reminder) return;+ registerPostReminderSchedule().catch(err => console.error(`❌ POST reminder reschedule failed: ${err.message}`));+});+/*** Cancel the reminder schedule outright (explicit teardown / test cleanup).*/export function stopPostReminderSchedule() {cancel(POST_REMINDER_EVENT_ID);+ lastAppliedTimezone = null;}diff --git a/server/services/meatspacePostReminder.test.js b/server/services/meatspacePostReminder.test.jsindex 27e5bcb431..f9a1600d04 100644--- a/server/services/meatspacePostReminder.test.js+++ b/server/services/meatspacePostReminder.test.js@@ -2,15 +2,38 @@* Tests for meatspacePostReminder — the opt-in (default OFF) daily reminder* for POST sessions. Covers: the pure HH:MM -> cron conversion, that the* scheduler only registers when enabled, that it reschedules (not- * double-registers) on repeated calls, and that the fired handler only sends- * a notification when today's session is genuinely incomplete.+ * double-registers) on repeated calls, that the fired handler only sends a+ * notification when today's session is genuinely incomplete AND it hasn't+ * already notified today, the missed-slot catch-up on server restart, the+ * timezone-change refresh via settingsEvents, and the centralized+ * reschedule-on-save via meatspacePost.js's postConfigEvents (#2015).*/-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++// Minimal EventEmitter stubs so `<emitter>.on(...)` at module-load time works+// and tests can `.emit(...)` to drive the subscription paths directly —+// mirrors sharing/annotationIdentity.test.js's settingsEvents stub.+const settingsEventEmitter = vi.hoisted(() => {+ const listeners = {};+ return {+ on(event, fn) { (listeners[event] ||= []).push(fn); },+ emit(event, ...args) { (listeners[event] || []).forEach(fn => fn(...args)); },+ };+});++const postConfigEventEmitter = vi.hoisted(() => {+ const listeners = {};+ return {+ on(event, fn) { (listeners[event] ||= []).push(fn); },+ emit(event, ...args) { (listeners[event] || []).forEach(fn => fn(...args)); },+ };+});vi.mock('./eventScheduler.js', () => ({schedule: vi.fn(),- cancel: vi.fn()+ cancel: vi.fn(),+ parseCronToPrevRun: vi.fn()}));vi.mock('../lib/timezone.js', () => ({@@ -22,19 +45,25 @@ vi.mock('../lib/timezone.js', () => ({vi.mock('./meatspacePost.js', () => ({getPostConfig: vi.fn(),- getPostSessions: vi.fn()+ getPostSessions: vi.fn(),+ postConfigEvents: postConfigEventEmitter}));vi.mock('./notifications.js', () => ({addNotification: vi.fn().mockResolvedValue({ id: 'n1' }),+ getNotifications: vi.fn().mockResolvedValue([]),NOTIFICATION_TYPES: { DAILY_POST_REMINDER: 'daily_post_reminder' },PRIORITY_LEVELS: { LOW: 'low' }}));-import { schedule, cancel } from './eventScheduler.js';+vi.mock('./settings.js', () => ({+ settingsEvents: settingsEventEmitter+}));++import { schedule, cancel, parseCronToPrevRun } from './eventScheduler.js';import { getUserTimezone, getLocalParts, todayInTimezone } from '../lib/timezone.js';import { getPostConfig, getPostSessions } from './meatspacePost.js';-import { addNotification } from './notifications.js';+import { addNotification, getNotifications } from './notifications.js';import {reminderTimeToCron,registerPostReminderSchedule,@@ -62,6 +91,8 @@ describe('reminderTimeToCron', () => {describe('registerPostReminderSchedule', () => {beforeEach(() => {vi.clearAllMocks();+ getUserTimezone.mockResolvedValue('UTC');+ parseCronToPrevRun.mockReturnValue(null);});it('cancels the schedule and does not register when disabled (default off)', async () => {@@ -105,6 +136,138 @@ describe('registerPostReminderSchedule', () => {expect(schedule).toHaveBeenCalledTimes(2);expect(schedule.mock.calls[1][0]).toMatchObject({ id: POST_REMINDER_EVENT_ID, cron: '30 18 * * *' });});++ it('does not check for a missed slot unless catchUpMissedSlot is requested', async () => {+ getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });+ await registerPostReminderSchedule();+ expect(parseCronToPrevRun).not.toHaveBeenCalled();+ expect(getPostSessions).not.toHaveBeenCalled();+ });++ // Missed-slot catch-up (finding 2): mirrors taskSchedule.js's+ // parseCronToPrevRun-based recovery — a slot that already elapsed while+ // the server was down fires immediately instead of waiting for tomorrow.+ describe('catchUpMissedSlot: true (boot-time recovery)', () => {+ // Pin the clock so "prevRunMs <= now" comparisons in catchUpMissedSlot+ // are deterministic regardless of what time of day the suite runs.+ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-07-01T12:00:00.000Z'));+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it('fires the reminder immediately when the most recent cron slot already elapsed today', async () => {+ getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });+ getPostSessions.mockResolvedValue([]);+ todayInTimezone.mockReturnValue('2026-07-01');+ const missedSlot = new Date('2026-07-01T09:00:00.000Z');+ const dayBefore = new Date('2026-06-30T09:00:00.000Z');+ parseCronToPrevRun.mockReturnValueOnce(missedSlot).mockReturnValueOnce(dayBefore);++ await registerPostReminderSchedule({ catchUpMissedSlot: true });++ expect(addNotification).toHaveBeenCalledTimes(1);+ });++ it('does not fire when there is no elapsed occurrence within the lookback bound', async () => {+ getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });+ parseCronToPrevRun.mockReturnValue(null);++ await registerPostReminderSchedule({ catchUpMissedSlot: true });++ expect(addNotification).not.toHaveBeenCalled();+ expect(getPostSessions).not.toHaveBeenCalled();+ });++ it('is idempotent — firePostReminderIfIncomplete still skips when today is already complete', async () => {+ getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });+ todayInTimezone.mockReturnValue('2026-07-01');+ getPostSessions.mockResolvedValue([{ startedAt: '2026-07-01T15:00:00.000Z' }]);+ getLocalParts.mockReturnValue({ year: 2026, month: 7, day: 1 });+ const missedSlot = new Date('2026-07-01T09:00:00.000Z');+ const dayBefore = new Date('2026-06-30T09:00:00.000Z');+ parseCronToPrevRun.mockReturnValueOnce(missedSlot).mockReturnValueOnce(dayBefore);++ await registerPostReminderSchedule({ catchUpMissedSlot: true });++ expect(addNotification).not.toHaveBeenCalled();+ });+ });++ // Timezone refresh (finding 1): a global timezone change elsewhere (not+ // through POST config) must reschedule the cron at the new offset.+ describe('timezone refresh via settingsEvents', () => {+ it('reschedules when the global timezone changes', async () => {+ getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });+ getUserTimezone.mockResolvedValue('UTC');+ await registerPostReminderSchedule();+ expect(schedule).toHaveBeenCalledTimes(1);++ getUserTimezone.mockResolvedValue('America/Los_Angeles');+ settingsEventEmitter.emit('settings:updated', { timezone: 'America/Los_Angeles' });++ await vi.waitFor(() => {+ expect(schedule).toHaveBeenCalledTimes(2);+ });+ expect(schedule.mock.calls[1][0]).toMatchObject({ timezone: 'America/Los_Angeles' });+ });++ it('does not reschedule when the effective timezone is unchanged', async () => {+ getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });+ getUserTimezone.mockResolvedValue('UTC');+ await registerPostReminderSchedule();+ expect(schedule).toHaveBeenCalledTimes(1);++ settingsEventEmitter.emit('settings:updated', { timezone: 'UTC' });+ // Flush any pending microtasks from the (no-op) listener before asserting.+ await Promise.resolve();+ await Promise.resolve();++ expect(schedule).toHaveBeenCalledTimes(1);+ });++ it('does not reschedule when the reminder is disabled', async () => {+ getPostConfig.mockResolvedValue({ reminder: { enabled: false, time: '09:00' } });+ settingsEventEmitter.emit('settings:updated', { timezone: 'America/Los_Angeles' });+ await Promise.resolve();+ await Promise.resolve();++ expect(schedule).not.toHaveBeenCalled();+ });+ });++ // Centralized reschedule-on-save (finding 3): meatspacePost.js's+ // updatePostConfig() emits postConfigEvents on every save; this module+ // reschedules whenever the `reminder` slice was part of the patch,+ // regardless of which caller invoked updatePostConfig.+ describe('reschedule via meatspacePost.js postConfigEvents', () => {+ it('reschedules when the saved patch includes a reminder block', async () => {+ getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });++ postConfigEventEmitter.emit('post-config:updated', {+ config: { reminder: { enabled: true, time: '09:00' } },+ updates: { reminder: { enabled: true, time: '09:00' } }+ });++ await vi.waitFor(() => {+ expect(schedule).toHaveBeenCalledTimes(1);+ });+ });++ it('does not reschedule when the saved patch has no reminder key', async () => {+ postConfigEventEmitter.emit('post-config:updated', {+ config: { adaptive: { enabled: true } },+ updates: { adaptive: { enabled: true } }+ });+ await Promise.resolve();+ await Promise.resolve();++ expect(schedule).not.toHaveBeenCalled();+ expect(getPostConfig).not.toHaveBeenCalled();+ });+ });});describe('stopPostReminderSchedule', () => {@@ -119,6 +282,7 @@ describe('firePostReminderIfIncomplete', () => {beforeEach(() => {vi.clearAllMocks();getPostSessions.mockResolvedValue([]);+ getNotifications.mockResolvedValue([]);getUserTimezone.mockResolvedValue('UTC');todayInTimezone.mockReturnValue('2026-07-01');// Default: getLocalParts on any session's startedAt resolves to "today" —@@ -177,6 +341,31 @@ describe('firePostReminderIfIncomplete', () => {expect(getPostSessions).not.toHaveBeenCalled();});+ // De-dupe guard backing the missed-slot catch-up: a second evaluation of+ // the same local day (e.g. catch-up re-running after the normal cron tick+ // already fired earlier) must not send a second notification.+ it('does not nag again if a reminder notification already exists for today', async () => {+ getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });+ getPostSessions.mockResolvedValue([]);+ getNotifications.mockResolvedValue([{ timestamp: '2026-07-01T09:00:05.000Z' }]);+ getLocalParts.mockReturnValue({ year: 2026, month: 7, day: 1 });++ await firePostReminderIfIncomplete();++ expect(addNotification).not.toHaveBeenCalled();+ });++ it('nags when the only existing reminder notification is from a different local day', async () => {+ getPostConfig.mockResolvedValue({ reminder: { enabled: true, time: '09:00' } });+ getPostSessions.mockResolvedValue([]);+ getNotifications.mockResolvedValue([{ timestamp: '2026-06-30T09:00:05.000Z' }]);+ getLocalParts.mockReturnValue({ year: 2026, month: 6, day: 30 }); // yesterday++ await firePostReminderIfIncomplete();++ expect(addNotification).toHaveBeenCalledTimes(1);+ });+// Regression (finding 1 + its follow-up): the reminder cron fires on the// user's LOCAL wall-clock time, so "is today done" must be evaluated in// that same local calendar day. Sessions are day-bucketed server-side via