Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix([issue-2681]): derive POST daily status from the user's timezone, not UTC

[._.]/ Adam Eivy91c2d68b213b
diff --git a/client/src/components/dashboard/builtins/DailyDriverWidget.jsx b/client/src/components/dashboard/builtins/DailyDriverWidget.jsx
index 2aefabb8fb..e9b8373433 100644
--- a/client/src/components/dashboard/builtins/DailyDriverWidget.jsx
+++ b/client/src/components/dashboard/builtins/DailyDriverWidget.jsx
@@ -79,9 +79,8 @@ export default function DailyDriverWidget({ dashboardState }) {
// `completedToday`/`streak` come straight from getPostStats — the same source
// the standalone DailyPostWidget uses — so the driver's POST row always agrees
- // with it. (getPostStats derives "today" from the server's UTC day, a
- // subsystem-wide property of meatspacePost, not this widget; a timezone-aware
- // POST day boundary is a separate POST-service change, out of scope here.)
+ // with it. getPostStats derives "today" from the user's configured timezone
+ // (issue #2681), matching the Daily Driver's own tz-correct day boundary.
const completedToday = !!post?.completedToday;
const streak = post?.currentStreak ?? 0;
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index caff6ad21b..2f1120ac71 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -25,13 +25,27 @@ import { applySessionToMemoryItems, getMemoryItems, getDueMemoryItems, isStatMas
import { applySessionToReviewSchedule, getDueReviews, getRetentionReport } from './meatspacePostReview.js';
import { getAllTrainingEntries } from './meatspacePostTraining.js';
import { getMorseProgress, MAX_KOCH_LEVEL } from './meatspacePostMorse.js';
-import { computePostStreaks, computeUnifiedStreak, ymdToUTC } from '../lib/postStreak.js';
+import { computePostStreaks, computeUnifiedStreak, ymdToUTC, ymdShift } from '../lib/postStreak.js';
+import { getUserTimezone, todayInTimezone } from '../lib/timezone.js';
// Re-export the shared streak helper so existing importers of
// `computePostStreaks` from this module keep working after it moved to
// server/lib/postStreak.js (single implementation — see that file).
export { computePostStreaks };
+// Today's `YYYY-MM-DD` in the USER's configured timezone (not the server's UTC
+// day). The process runs `TZ=UTC`, so a bare `new Date().toISOString()` day
+// derivation misfiles POSTs around the local/UTC midnight boundary — a scored
+// session completed the previous local evening reads as "done today," or a
+// just-completed local-day session reads as incomplete (issue #2681). Both the
+// session `date` stamp (write side) and the `completedToday`/`todayScore`/streak
+// derivations (read side) key off this so they agree on the user's local day,
+// mirroring the Daily Driver's tz-correct first-visit/handled markers (#2666).
+async function localToday() {
+ const tz = await getUserTimezone();
+ return todayInTimezone(tz);
+}
+
const MEATSPACE_DIR = PATHS.meatspace;
const SESSIONS_FILE = join(MEATSPACE_DIR, 'post-sessions.json');
const CONFIG_FILE = join(MEATSPACE_DIR, 'post-config.json');
@@ -205,6 +219,10 @@ export async function submitPostSession(sessionData) {
const config = await getPostConfig();
const data = await loadSessions();
const now = new Date().toISOString();
+ // Stamp the session's day in the user's local timezone, so `completedToday`
+ // and the day-keyed streak/stats math classify it by the local day the user
+ // actually completed it — not the server's UTC day (issue #2681).
+ const todayLocal = await localToday();
// Strip client-provided score/correct — plus every separated metric field
// (issue #2094) — and recompute server-side. Stripping up front means the
@@ -275,7 +293,7 @@ export async function submitPostSession(sessionData) {
// crosses midnight (or just arrives later) must not move the session to a
// new date, which would corrupt history ordering and streak math. Only a
// fresh insert stamps "now".
- date: existing?.date ?? now.split('T')[0],
+ date: existing?.date ?? todayLocal,
startedAt: existing?.startedAt ?? now,
completedAt: now,
durationMs: rescoredTasks.reduce((sum, t) => sum + (t.totalMs || 0), 0),
@@ -574,14 +592,15 @@ export function deriveTaskAvgResponseMs(task) {
* a scored session or a training-log entry (Morse / memory practice). Computed
* over ALL history, independent of any stats window.
*/
-export async function getUnifiedActivityStreak(todayStr = new Date().toISOString().split('T')[0]) {
+export async function getUnifiedActivityStreak(todayStr) {
+ const day = todayStr ?? await localToday();
const [sessions, training] = await Promise.all([getPostSessions(), getAllTrainingEntries()]);
- return computeUnifiedStreak(sessions, training, todayStr);
+ return computeUnifiedStreak(sessions, training, day);
}
export async function getPostStats(days = 30) {
const sessions = await getPostSessions();
- const todayStr = new Date().toISOString().split('T')[0];
+ const todayStr = await localToday();
// Streaks are computed over ALL history, independent of the stats window, and
// over BOTH scored sessions and the training log so the launcher/dashboard
// streak matches the Morse trainer and the Progress page (issue #2091).
@@ -599,9 +618,9 @@ export async function getPostStats(days = 30) {
};
let recent = sessions;
if (days > 0) {
- const cutoff = new Date();
- cutoff.setDate(cutoff.getDate() - days);
- const cutoffStr = cutoff.toISOString().split('T')[0];
+ // Window the stats relative to the user's local today (day-string math via
+ // UTC midnight, DST-safe) so the cutoff matches the tz-correct session dates.
+ const cutoffStr = ymdShift(todayStr, -days);
recent = sessions.filter(s => s.date >= cutoffStr);
}
@@ -715,7 +734,7 @@ function finalizeMetricSeries(map) {
* fallback for legacy sessions.
*/
export async function getPostProgress({ days = 90 } = {}) {
- const todayStr = new Date().toISOString().split('T')[0];
+ const todayStr = await localToday();
const window = Number.isFinite(days) && days > 0 ? Math.min(days, 365) : 0;
const allSessions = await getPostSessions();
diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.js
index 533053db25..ae6deb285b 100644
--- a/server/services/meatspacePost.test.js
+++ b/server/services/meatspacePost.test.js
@@ -1,4 +1,4 @@
-import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
// Mock file I/O so submitPostSession tests stay pure. Shared by meatspacePost.js
// AND meatspacePostMemory.js (imported transitively for advanceScheduleFromSession) —
@@ -13,6 +13,16 @@ vi.mock('../lib/fileUtils.js', () => ({
readJSONFile: vi.fn((path, defaultValue) => Promise.resolve(defaultValue)),
}));
+// getUserTimezone (via ../lib/timezone.js) reads getSettings() to derive the
+// user's local day (issue #2681). Mock settings so the day-boundary is
+// controllable. Default `{}` = no configured timezone, so getUserTimezone falls
+// back to the process timezone (the suite runs TZ=UTC) and every existing
+// UTC-today assertion holds unchanged; tz-specific tests set settingsState.current.
+const settingsState = vi.hoisted(() => ({ current: {} }));
+vi.mock('../services/settings.js', () => ({
+ getSettings: () => Promise.resolve(settingsState.current),
+}));
+
import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';
import {
generateDoublingChain,
@@ -1289,6 +1299,86 @@ describe('getPostStats — byModule averaging, days window cutoff, empty-window
});
});
+// =============================================================================
+// getPostStats / submitPostSession — timezone-correct day boundary (issue #2681)
+//
+// The server process runs TZ=UTC, so a bare `new Date().toISOString()` day
+// derivation misfiles POSTs around the local/UTC midnight boundary. These tests
+// pin `now` to an instant where the UTC day and the user's LOCAL day DIFFER, and
+// prove `completedToday`/`todayScore`/the session `date` stamp all key off the
+// user's configured timezone — not the server's UTC day. Each case would fail
+// under the old UTC-day logic (asserted by contrasting the UTC-day session).
+// =============================================================================
+
+describe('getPostStats / submitPostSession — timezone-correct day boundary (issue #2681)', () => {
+ beforeEach(() => { vi.clearAllMocks(); });
+ afterEach(() => { vi.useRealTimers(); settingsState.current = {}; });
+
+ function mockSessions(sessions) {
+ readJSONFile.mockImplementation((path, defaultValue) => {
+ if (String(path).includes('post-sessions')) return Promise.resolve({ sessions });
+ return Promise.resolve(defaultValue);
+ });
+ }
+
+ // Freeze the clock at a UTC instant and set the user's timezone.
+ function freezeAt(utcIso, timezone) {
+ settingsState.current = { timezone };
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(utcIso));
+ }
+
+ it('completedToday reads TRUE for a session on the local day even when UTC has already rolled to the next day (America/Los_Angeles)', async () => {
+ // 2026-07-16T05:00Z = 2026-07-15 22:00 PDT — UTC day July 16, LA day July 15.
+ freezeAt('2026-07-16T05:00:00Z', 'America/Los_Angeles');
+ mockSessions([
+ { date: '2026-07-15', score: 88, tasks: [{ module: 'mental-math', type: 'doubling-chain', score: 88 }] },
+ ]);
+ const stats = await getPostStats(30);
+ // Old UTC logic derived today='2026-07-16' → would have read completedToday=false.
+ expect(stats.completedToday).toBe(true);
+ expect(stats.todayScore).toBe(88);
+ expect(stats.currentStreak).toBe(1);
+ });
+
+ it('completedToday reads FALSE for a session stamped on the UTC day but belonging to the PREVIOUS local evening (America/Los_Angeles)', async () => {
+ // Same instant: UTC day July 16, LA day July 15. A session dated '2026-07-16'
+ // (the UTC day) is NOT the user's local today, so it must not read as done.
+ freezeAt('2026-07-16T05:00:00Z', 'America/Los_Angeles');
+ mockSessions([
+ { date: '2026-07-16', score: 88, tasks: [{ module: 'mental-math', type: 'doubling-chain', score: 88 }] },
+ ]);
+ const stats = await getPostStats(30);
+ // Old UTC logic derived today='2026-07-16' → would have wrongly read TRUE.
+ expect(stats.completedToday).toBe(false);
+ expect(stats.todayScore).toBeNull();
+ });
+
+ it('completedToday reads TRUE for a session on the local day when the local day is AHEAD of UTC (Asia/Tokyo)', async () => {
+ // 2026-07-15T20:00Z = 2026-07-16 05:00 JST — UTC day July 15, Tokyo day July 16.
+ freezeAt('2026-07-15T20:00:00Z', 'Asia/Tokyo');
+ mockSessions([
+ { date: '2026-07-16', score: 72, tasks: [{ module: 'mental-math', type: 'doubling-chain', score: 72 }] },
+ ]);
+ const stats = await getPostStats(30);
+ // Old UTC logic derived today='2026-07-15' → would have read completedToday=false.
+ expect(stats.completedToday).toBe(true);
+ expect(stats.todayScore).toBe(72);
+ });
+
+ it('submitPostSession stamps a new session date in the user local timezone, not the server UTC day', async () => {
+ // UTC day July 16 / LA day July 15 — a freshly submitted session must be
+ // dated by the user's local day so completedToday later agrees with it.
+ freezeAt('2026-07-16T05:00:00Z', 'America/Los_Angeles');
+ mockSessions([]);
+ const session = await submitPostSession({
+ modules: ['mental-math'],
+ tasks: [{ module: 'mental-math', type: 'doubling-chain', questions: [] }],
+ });
+ expect(session.date).toBe('2026-07-15');
+ });
+});
+
// =============================================================================
// resolveDrillConfig / getAdaptivePreview — adaptive integration across ALL
// math drill types (issue #2102 gap 3). The pure `adaptDrillConfig` policy is
diff --git a/server/services/meatspacePostProgress.test.js b/server/services/meatspacePostProgress.test.js
index 6b8756350f..b86c178743 100644
--- a/server/services/meatspacePostProgress.test.js
+++ b/server/services/meatspacePostProgress.test.js
@@ -18,6 +18,14 @@ vi.mock('../lib/fileUtils.js', () => ({
}),
}));
+// getUserTimezone (via ../lib/timezone.js) reads getSettings() for the local-day
+// boundary (issue #2681). Mock it to no configured tz so getUserTimezone falls
+// back to the process timezone (TZ=UTC in tests) — matching these tests' UTC-today
+// assumptions.
+vi.mock('../services/settings.js', () => ({
+ getSettings: () => Promise.resolve({}),
+}));
+
import { getPostProgress, getPostStats, getUnifiedActivityStreak } from './meatspacePost.js';
import { getTrainingStats } from './meatspacePostTraining.js';
import { postProgressQuerySchema } from '../lib/postValidation.js';
diff --git a/server/services/meatspacePostRecommendations.test.js b/server/services/meatspacePostRecommendations.test.js
index f89797122a..de5df2651d 100644
--- a/server/services/meatspacePostRecommendations.test.js
+++ b/server/services/meatspacePostRecommendations.test.js
@@ -23,6 +23,13 @@ vi.mock('../lib/fileUtils.js', () => ({
}),
}));
+// getPostStats (via getPostRecommendations) derives the local day through
+// getUserTimezone → getSettings (issue #2681). Mock it to no configured tz so
+// the day boundary falls back to the process timezone (TZ=UTC in tests).
+vi.mock('../services/settings.js', () => ({
+ getSettings: () => Promise.resolve({}),
+}));
+
import {
composePostRecommendations,
weakestSkillFromStats,
diff --git a/server/services/meatspacePostTraining.test.js b/server/services/meatspacePostTraining.test.js
index f03c29df8a..a702b408b7 100644
--- a/server/services/meatspacePostTraining.test.js
+++ b/server/services/meatspacePostTraining.test.js
@@ -11,6 +11,13 @@ tryReadFile: vi.fn().mockResolvedValue(null),
readJSONFile: vi.fn().mockResolvedValue({ entries: [] }),
}));
+// getUnifiedActivityStreak (via meatspacePost.js) derives the local day through
+// getUserTimezone → getSettings (issue #2681). Mock it to no configured tz so
+// the day boundary falls back to the process timezone (TZ=UTC in tests).
+vi.mock('../services/settings.js', () => ({
+ getSettings: () => Promise.resolve({}),
+}));
+
import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';
import {
submitTrainingEntry,