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
refactor: consolidate local midnight timezone helpers (#5572)
[._.]/ Adam Eivyc82ec74e2fc6
diff --git a/server/lib/timezone.js b/server/lib/timezone.jsindex 0fc5e0ac4d..c751dce592 100644--- a/server/lib/timezone.js+++ b/server/lib/timezone.js@@ -120,6 +120,10 @@ export function todayInTimezone(timezone, atDate = new Date()) {* @param {string} dayStr - Local day as `YYYY-MM-DD`* @param {string} tz - IANA timezone string* @returns {number} UTC timestamp (ms) of that day's local midnight+ *+ * `getUtcOffsetMs` uses a locale-string round trip that can mis-parse an+ * ambiguous wall-clock value at a DST transition. Sampling at the naive+ * midnight and refining the candidate avoids relying on that ambiguous value.*/export function anchorLocalMidnightUtc(dayStr, tz) {const naiveUtc = Date.parse(`${dayStr}T00:00:00Z`)@@ -148,6 +152,25 @@ export function localDayWindowUtc(timezone, atDate = new Date()) {}}+/**+ * Return the half-open UTC bounds for a local calendar day.+ * Unlike localDayWindowUtc, the end is the next local midnight, preserving+ * the actual 23- or 25-hour length of DST transition days.+ * @param {string} dateStr - Local day as `YYYY-MM-DD`+ * @param {string} timezone - IANA timezone string+ * @returns {{ start: Date, end: Date } | null}+ */+export function localDayRangeUtc(dateStr, timezone) {+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(dateStr || '').trim())+ if (!m) return null+ const [, y, mo, d] = m.map(Number)+ const start = new Date(anchorLocalMidnightUtc(dateStr, timezone))+ const next = new Date(Date.UTC(y, mo - 1, d + 1))+ const nextDate = `${next.getUTCFullYear()}-${String(next.getUTCMonth() + 1).padStart(2, '0')}-${String(next.getUTCDate()).padStart(2, '0')}`+ const end = new Date(anchorLocalMidnightUtc(nextDate, timezone))+ return { start, end }+}+// ---------------------------------------------------------------------------// HH:MM time-window primitives//diff --git a/server/lib/timezone.test.js b/server/lib/timezone.test.jsindex 202381b4a1..7381c24d34 100644--- a/server/lib/timezone.test.js+++ b/server/lib/timezone.test.js@@ -7,7 +7,7 @@ vi.mock('../services/settings.js', () => ({}))import { getSettings } from '../services/settings.js'-import { getLocalParts, getUtcOffsetMs, nextLocalTime, todayInTimezone, anchorLocalMidnightUtc, localDayWindowUtc, HHMM_RE, HHMM_STRICT_RE, parseHHMM, isWithinTimeWindow } from './timezone.js'+import { getLocalParts, getUtcOffsetMs, nextLocalTime, todayInTimezone, anchorLocalMidnightUtc, localDayWindowUtc, localDayRangeUtc, HHMM_RE, HHMM_STRICT_RE, parseHHMM, isWithinTimeWindow } from './timezone.js'import { getTimezoneUpdatedAt } from '../services/userTimezone.js'describe('timezone', () => {@@ -240,6 +240,22 @@ describe('timezone', () => {})})+ describe('localDayRangeUtc', () => {+ it.each([+ ['2026-03-08', '2026-03-08T08:00:00.000Z', '2026-03-09T07:00:00.000Z', 23],+ ['2026-11-01', '2026-11-01T07:00:00.000Z', '2026-11-02T08:00:00.000Z', 25],+ ])('preserves the %s DST day as a half-open %s → %s window', (date, start, end, hours) => {+ const range = localDayRangeUtc(date, 'America/Los_Angeles')+ expect(range.start.toISOString()).toBe(start)+ expect(range.end.toISOString()).toBe(end)+ expect(range.end.getTime() - range.start.getTime()).toBe(hours * 60 * 60 * 1000)+ })++ it('rejects malformed dates', () => {+ expect(localDayRangeUtc('not-a-date', 'UTC')).toBeNull()+ })+ })+describe('getTimezoneUpdatedAt (#2040)', () => {it('returns the stamped numeric timestamp when set', async () => {getSettings.mockResolvedValue({ timezone: 'UTC', timezoneUpdatedAt: 1700000000000 })diff --git a/server/services/humanActivity.js b/server/services/humanActivity.jsindex 03369f1478..7032ff7557 100644--- a/server/services/humanActivity.js+++ b/server/services/humanActivity.js@@ -23,9 +23,11 @@import { v4 as uuidv4 } from '../lib/uuid.js';import { ensureSchema, query } from '../lib/db.js';import { normalizeIdentifier } from '../lib/tribeMatch.js';-import { getLocalParts, getUtcOffsetMs, todayInTimezone } from '../lib/timezone.js';+import { getLocalParts, localDayRangeUtc, todayInTimezone, anchorLocalMidnightUtc } from '../lib/timezone.js';import { getUserTimezone } from './userTimezone.js';+export { localDayRangeUtc };+// ---------------------------------------------------------------------------// Pure helpers (exported for unit tests — no DB, no side effects).// ---------------------------------------------------------------------------@@ -49,39 +51,6 @@ export function localDayKey(when, timezone) {return `${p.year}-${String(p.month).padStart(2, '0')}-${String(p.day).padStart(2, '0')}`;}-// UTC instant of local midnight for a (y, m, d) calendar date in `timezone`.-// The offset is sampled at the approximate midnight, then the candidate is-// verified with the formatter-based getLocalParts and nudged by the exact-// landed-vs-desired delta (the same DST correction pattern as nextLocalTime in-// lib/timezone.js). getUtcOffsetMs alone is NOT re-sampled at the candidate —-// its toLocaleString round-trip mis-parses ambiguous wall-clock times right at-// a transition, which is exactly when the correction matters.-function localMidnightUtc(y, mo, d, timezone) {- const approxUtc = new Date(Date.UTC(y, mo - 1, d, 0, 0, 0));- const offset = getUtcOffsetMs(approxUtc, timezone);- let t = approxUtc.getTime() - offset;- const p = getLocalParts(new Date(t), timezone);- const desired = Date.UTC(y, mo - 1, d);- const landed = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute);- if (landed !== desired) t -= landed - desired;- return new Date(t);-}--// UTC [start, end) instants that bound a local calendar day (YYYY-MM-DD) in the-// given timezone. The end is the NEXT local date's midnight — not start + 24h —-// so DST transition days keep their true 23h/25h length instead of leaking an-// hour into (or dropping an hour from) the neighboring day.-export function localDayRangeUtc(dateStr, timezone) {- const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(dateStr || '').trim());- if (!m) return null;- const [, y, mo, d] = m.map(Number);- const start = localMidnightUtc(y, mo, d, timezone);- // Date.UTC rolls d+1 over month/year boundaries for us.- const next = new Date(Date.UTC(y, mo - 1, d + 1));- const end = localMidnightUtc(next.getUTCFullYear(), next.getUTCMonth() + 1, next.getUTCDate(), timezone);- return { start, end };-}-// Normalize a participant to { name, email, phone, personId } — trimmed, empty// fields dropped. Accepts a bare email string or a { name, email, phone } object.export function normalizeParticipant(p) {@@ -261,7 +230,7 @@ export function resolveEventInstant(value, timezone) {const m = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2}))?(?:\.\d+)?)?$/.exec(s);if (m && timezone) {const [, y, mo, d, hh, mm, ss] = m;- const midnight = localMidnightUtc(Number(y), Number(mo), Number(d), timezone);+ const midnight = new Date(anchorLocalMidnightUtc(`${y}-${mo}-${d}`, timezone));const dayMs = ((Number(hh) || 0) * 3600 + (Number(mm) || 0) * 60 + (Number(ss) || 0)) * 1000;return new Date(midnight.getTime() + dayMs);}