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: anchor POST day reads to request instant (#4211)

[._.]/ Adam Eivy7e081cc95241
diff --git a/server/services/meatspacePost.js b/server/services/meatspacePost.js
index dfbbddc140..8f28e028de 100644
--- a/server/services/meatspacePost.js
+++ b/server/services/meatspacePost.js
@@ -645,9 +645,10 @@ export function deriveTaskAvgResponseMs(task) {
}
export async function getPostStats(days = 30) {
+ const atDate = new Date();
const sessions = await getPostSessions();
const timezone = await getUserTimezone();
- const todayStr = todayInTimezone(timezone);
+ const todayStr = todayInTimezone(timezone, atDate);
// 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).
@@ -784,8 +785,9 @@ function finalizeMetricSeries(map) {
* fallback for legacy sessions.
*/
export async function getPostProgress({ days = 90 } = {}) {
+ const atDate = new Date();
const timezone = await getUserTimezone();
- const todayStr = todayInTimezone(timezone);
+ const todayStr = todayInTimezone(timezone, atDate);
const window = Number.isFinite(days) && days > 0 ? Math.min(days, 365) : 0;
const allSessions = await getPostSessions();
@@ -1298,6 +1300,7 @@ export function isRecDrillRunnable(config, module, type, memoryItemId = null) {
* config can actually run.
*/
export async function getPostRecommendations({ limit = RECOMMENDATION_LIMIT } = {}) {
+ const atDate = new Date();
const [dueMemoryItems, dueReviews, stats, mulProgress, powersProgress, cogProgress, morse, sessions, config, training, timezone] = await Promise.all([
getDueMemoryItems(),
getDueReviews(new Date(), Infinity),
@@ -1311,7 +1314,7 @@ export async function getPostRecommendations({ limit = RECOMMENDATION_LIMIT } =
getAllTrainingEntries(),
getUserTimezone(),
]);
- const todayStr = todayInTimezone(timezone);
+ const todayStr = todayInTimezone(timezone, atDate);
// Weakest skill — drop it unless the drill is currently runnable; a memory
// weak-skill deep-links to its own tab rather than a composed session.
@@ -1564,12 +1567,13 @@ async function getAdaptiveSignal(type) {
* @returns {Promise<{stats: Record<number, {samples,accuracy,avgResponseMs}>, floorLevel: number}>}
*/
async function getMultiplicationLevelStats(windowDays = MASTERY_DEFAULTS.windowDays) {
+ const atDate = new Date();
const sessions = await getPostSessions();
// Window off the user's local today (DST-safe day math) so the cutoff stays
// consistent with the tz-correct session dates submitPostSession now stamps
// (issue #2681) — a UTC-day cutoff would skew the window edge by the tz offset.
const timezone = await getUserTimezone();
- const todayStr = todayInTimezone(timezone);
+ const todayStr = todayInTimezone(timezone, atDate);
const cutoffStr = windowDays > 0 ? ymdShift(todayStr, -windowDays) : null;
const byLevel = {};
@@ -1610,9 +1614,10 @@ async function getMultiplicationLevelStats(windowDays = MASTERY_DEFAULTS.windowD
}
async function getPowersLevelStats(windowDays = POWERS_MASTERY_DEFAULTS.windowDays) {
+ const atDate = new Date();
const sessions = await getPostSessions();
const timezone = await getUserTimezone();
- const todayStr = todayInTimezone(timezone);
+ const todayStr = todayInTimezone(timezone, atDate);
const cutoffStr = windowDays > 0 ? ymdShift(todayStr, -windowDays) : null;
const byLevel = {};
let floorLevel = 0;
@@ -1692,11 +1697,12 @@ export async function getPowersProgress() {
* @returns {Promise<{stats: Record<number, {samples,accuracy,avgResponseMs}>, floorLevel: number}>}
*/
async function getCognitiveLevelStats(type, windowDays = COGNITIVE_MASTERY_DEFAULTS.windowDays) {
+ const atDate = new Date();
const sessions = await getPostSessions();
// Window off the user's local today (DST-safe) so the cutoff stays consistent
// with the tz-correct session dates submitPostSession now stamps (issue #2681).
const timezone = await getUserTimezone();
- const todayStr = todayInTimezone(timezone);
+ const todayStr = todayInTimezone(timezone, atDate);
const cutoffStr = windowDays > 0 ? ymdShift(todayStr, -windowDays) : null;
const byLevel = {};
diff --git a/server/services/meatspacePost.test.js b/server/services/meatspacePost.test.js
index 6c13164cb0..9ba1bf39ba 100644
--- a/server/services/meatspacePost.test.js
+++ b/server/services/meatspacePost.test.js
@@ -20,9 +20,14 @@ vi.mock('../lib/fileUtils.js', () => ({
// assertion holds deterministically (an unpinned `{}` would fall back to the
// runner's system tz and break these suites off a non-UTC CI runner). tz-specific
// tests set settingsState.current to a real IANA zone.
-const settingsState = vi.hoisted(() => ({ current: { timezone: 'UTC' } }));
+const settingsState = vi.hoisted(() => ({ current: { timezone: 'UTC' }, onRead: null }));
vi.mock('../services/settings.js', () => ({
- getSettings: () => Promise.resolve(settingsState.current),
+ getSettings: () => {
+ const onRead = settingsState.onRead;
+ settingsState.onRead = null;
+ onRead?.();
+ return Promise.resolve(settingsState.current);
+ },
}));
import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';
@@ -1398,7 +1403,11 @@ describe('getPostStats — byModule averaging, days window cutoff, empty-window
describe('getPostStats / submitPostSession — timezone-correct day boundary (issue #2681)', () => {
beforeEach(() => { vi.clearAllMocks(); });
- afterEach(() => { vi.useRealTimers(); settingsState.current = { timezone: 'UTC' }; });
+ afterEach(() => {
+ vi.useRealTimers();
+ settingsState.current = { timezone: 'UTC' };
+ settingsState.onRead = null;
+ });
function mockSessions(sessions) {
readJSONFile.mockImplementation((path, defaultValue) => {
@@ -1464,6 +1473,21 @@ describe('getPostStats / submitPostSession — timezone-correct day boundary (is
expect(stats.overall).toBe(84);
});
+ it('anchors the read-side day to the request-start instant when settings resolve after midnight', async () => {
+ // The settings read crosses LA midnight. The loaded session still belongs to
+ // the request-start local day; todayInTimezone must use that captured instant
+ // rather than the clock after the awaited settings read.
+ freezeAt('2026-07-18T06:59:59.000Z', 'America/Los_Angeles');
+ settingsState.onRead = () => vi.setSystemTime(new Date('2026-07-18T07:00:01.000Z'));
+ mockSessions([
+ { date: '2026-07-17', score: 91, tasks: [{ module: 'mental-math', type: 'doubling-chain', score: 91 }] },
+ ]);
+
+ const stats = await getPostStats(30);
+ expect(stats.completedToday).toBe(true);
+ expect(stats.todayScore).toBe(91);
+ });
+
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.
diff --git a/server/services/meatspacePostTraining.js b/server/services/meatspacePostTraining.js
index cf7cf8f89c..e7bed65c2d 100644
--- a/server/services/meatspacePostTraining.js
+++ b/server/services/meatspacePostTraining.js
@@ -63,10 +63,11 @@ export async function submitTrainingEntry(entry) {
* ALL history; only the per-drill breakdown below is windowed.
*/
export async function getTrainingStats(days = 30) {
+ const atDate = new Date();
const data = await loadTrainingLog();
const allEntries = data.entries;
const timezone = await getUserTimezone();
- const todayStr = todayInTimezone(timezone);
+ const todayStr = todayInTimezone(timezone, atDate);
let entries = allEntries;
if (days > 0) {
diff --git a/server/services/postActivityStreak.js b/server/services/postActivityStreak.js
index 99dc1db41a..1aa80cd785 100644
--- a/server/services/postActivityStreak.js
+++ b/server/services/postActivityStreak.js
@@ -32,8 +32,9 @@ import { getUserTimezone, todayInTimezone } from '../lib/timezone.js';
* @param {string} [timezone] - defaults to the user's configured timezone.
*/
export async function getUnifiedActivityStreak(training, todayStr, timezone) {
+ const atDate = new Date();
const resolvedTimezone = timezone ?? await getUserTimezone();
- const day = todayStr ?? todayInTimezone(resolvedTimezone);
+ const day = todayStr ?? todayInTimezone(resolvedTimezone, atDate);
const sessions = await getPostSessions();
return computeUnifiedStreak(sessions, training, day, resolvedTimezone);
}