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: handle local dates with midnight DST transitions

Adam Eivy466100b1b0af
diff --git a/server/lib/README.md b/server/lib/README.md
index edf488d983..4fecd72bb7 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -409,7 +409,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `ports.js` | Canonical PORTS object (re-exported from `ecosystem.config.cjs`). |
| `platform.js` | Platform/OS detection helpers — listening-port probes plus `isAppleSilicon()` (arm64 darwin; gates MLX model features, detect at the route boundary). |
| `signalCrypto.js` | Pure, dependency-free crypto for reading Signal Desktop's encrypted chat DB (#2154): SQLCipher-4 page decryption (`decryptSqlcipherDatabase`, `deriveSqlcipherKeys`, `sqlcipherPageHmac` — PBKDF2-SHA512 HMAC key + AES-256-CBC per page + HMAC-SHA512 verify → plaintext SQLite buffer the built-in `node:sqlite` can open) and Chromium/Electron `safeStorage` unwrap (`decryptSafeStorageValue`, `deriveSafeStorageKey` — macOS AES-128-CBC + PBKDF2-SHA1 over the keychain password). All functions return `{ ok, ... }` reports (never throw) for graceful degradation. Consumed by `services/signalSync.js`. |
-| `timezone.js` | Timezone utilities for scheduling — all Date math is UTC-internal (server runs `TZ=UTC`); these convert to/from the user's configured local timezone. `getLocalParts(utcDate, timezone)` / `getUtcOffsetMs(utcDate, timezone)` are the primitives; `nextLocalTime(afterMs, hours, minutes, timezone)` finds the next UTC instant matching a local HH:MM. `anchorLocalMidnightUtc(dayStr, tz)` is the single DST-safe "local midnight → UTC" implementation (#5572, two-pass offset refinement, evaluated AT the target day rather than "now" so an elsewhere-in-day DST transition can't shift it) — `localDayWindowUtc(timezone, atDate?)` wraps it as an inclusive `startDate`/`endDate` ISO-string window (calendar agenda route, voice `calendar_today`), while `localDayRangeUtc(dateStr, timezone)` wraps it as a half-open `{ start, end }` `Date` pair ending at the NEXT local midnight — not `start` + 24h — so DST-transition days keep their true 23h/25h length (human-activity timeline + its YouTube/goal-scorecard consumers). Also owns the shared `HH:MM` time-window primitives: `HHMM_RE`/`HHMM_STRICT_RE`, `parseHHMM`, `isWithinTimeWindow` (mirrored client-side in `client/src/utils/timeWindow.js`). |
+| `timezone.js` | Timezone utilities for scheduling. `getLocalParts(utcDate, timezone)` / `getUtcOffsetMs(utcDate, timezone)` are the primitives; `nextLocalTime(afterMs, hours, minutes, timezone)` finds the next UTC instant matching a local HH:MM. `anchorLocalMidnightUtc(dayStr, tz)` resolves the first UTC instant belonging to a local date, including zones whose DST transition skips 00:00; `localDayWindowUtc(timezone, atDate?)` exposes an inclusive ISO-string window, while `localDayRangeUtc(dateStr, timezone)` returns a validated half-open `{ start, end }` `Date` pair ending at the next local-date boundary so 23h/25h transition days remain exact. Also owns `HHMM_RE`/`HHMM_STRICT_RE`, `parseHHMM`, and `isWithinTimeWindow` (mirrored client-side in `client/src/utils/timeWindow.js`). |
| `tribeCadence.js` | Authoritative, pure Tribe care-cadence rules (single source of truth, mirrored to `client/src/lib/tribeCadence.js`): `cadenceStatus(entity)` → `{ state: external/missing/overdue/soon/steady, daysRemaining, daysOverdue }`, `daysSinceDate(dateStr)`, `DEFAULT_CADENCE_DAYS` (45), `SOON_WINDOW_DAYS` (7). Consumed by `personCadenceStatus` / `getCareSummary` in `services/tribe.js` (proactive alert + Care widget) and by the client Tribe page/map. |
| `tribeMatch.js` | Pure, deterministic matcher mapping a calendar attendee / message counterpart (`{ email, phone, name }`) to a tracked Tribe person for auto-logged touchpoints (#2033, #2151): `buildPersonMatchIndex(people)` → `{ byIdentifier, byPhone, byName }`, `matchPerson(identity, index)` (email/handle authoritative, then E.164 phone, then exact unique name fallback — no fuzzy matching), `matchPeople(identities, index)` → de-duplicated Set of personIds, `normalizeIdentifier(value)`, `normalizePhone(value)` (E.164 normalization for iMessage/Signal handles), `identityFromHandle(handle)` (classify a raw `chat.db` handle into email-or-phone). Consumed by `autoLogTouchpoints` in `services/tribe.js` from the calendar, message, and iMessage sync producers. |
| `viteAllowedHosts.js` | Detect and remediate a managed app's Vite `server.allowedHosts`. `findViteConfig(repoPath)` locates the config; `parseAllowedHosts(src)` / `hostIsAllowed(parsed, host)` decide whether a Tailscale/IP host would be accepted (mirrors Vite's localhost+IP-always-allowed and leading-dot-suffix rules); `rewriteAllowedHosts(src)` deterministically injects `allowedHosts: true` (or bails `ok:false` on ambiguous shapes so the caller can fall back to an LLM fix); `checkViteHost(repoPath, host)` is the one-shot status used by `GET /api/apps/:id/vite-host-check`. |
diff --git a/server/lib/timezone.js b/server/lib/timezone.js
index a86ac75135..5f78414f53 100644
--- a/server/lib/timezone.js
+++ b/server/lib/timezone.js
@@ -56,11 +56,8 @@ export function getLocalParts(utcDate, timezone) {
* Positive = ahead of UTC (e.g., +9h for Tokyo), negative = behind (e.g., -7h for PDT).
*
* Callers doing DST-safe midnight anchoring (`anchorLocalMidnightUtc` below)
- * re-sample this at their candidate instant rather than trusting a single
- * call made at the approximate time — this function's own `toLocaleString`
- * round-trip mis-parses ambiguous wall-clock times right at a transition
- * (the same local time occurs twice on a fall-back day), which is exactly
- * when that correction matters.
+ * re-sample this at their candidate instant because the offset can change
+ * between the approximate UTC time and the target local boundary.
* @param {Date} utcDate - Reference UTC date
* @param {string} timezone - IANA timezone string
* @returns {number} Offset in milliseconds
@@ -116,28 +113,72 @@ export function todayInTimezone(timezone, atDate = new Date()) {
return `${parts.year}-${String(parts.month).padStart(2, '0')}-${String(parts.day).padStart(2, '0')}`
}
+const DAY_MS = 24 * 60 * 60 * 1000
+const LOCAL_DAY_SEARCH_RADIUS_MS = 36 * 60 * 60 * 1000
+
+function parseIsoDay(dayStr) {
+ const normalized = String(dayStr || '').trim()
+ const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(normalized)
+ if (!match || Number(match[1]) === 0) return null
+ const utcMs = Date.parse(`${normalized}T00:00:00Z`)
+ if (!Number.isFinite(utcMs) || new Date(utcMs).toISOString().slice(0, 10) !== normalized) return null
+ const [, year, month, day] = match.map(Number)
+ return { normalized, utcMs, ordinal: year * 10_000 + month * 100 + day }
+}
+
+function localDayOrdinalAt(utcMs, timezone) {
+ const { year, month, day } = getLocalParts(new Date(utcMs), timezone)
+ return year * 10_000 + month * 100 + day
+}
+
+function findLocalDayBoundary(parsed, tz) {
+ // Keep the common path cheap: offset refinement lands exactly on midnight
+ // for ordinary days and transitions that happen later in the day.
+ const firstOffset = getUtcOffsetMs(new Date(parsed.utcMs), tz)
+ const candidate = parsed.utcMs - firstOffset
+ const refinedOffset = getUtcOffsetMs(new Date(candidate), tz)
+ const refined = parsed.utcMs - refinedOffset
+ const refinedParts = getLocalParts(new Date(refined), tz)
+ const refinedOrdinal = refinedParts.year * 10_000 + refinedParts.month * 100 + refinedParts.day
+ if (
+ refinedOrdinal === parsed.ordinal
+ && refinedParts.hour === 0
+ && refinedParts.minute === 0
+ && localDayOrdinalAt(refined - 1, tz) < parsed.ordinal
+ ) {
+ return refined
+ }
+
+ // Midnight-offset arithmetic can oscillate across a transition that occurs
+ // at 00:00. Local calendar dates remain ordered across UTC instants, so find
+ // the first instant whose local date is not before the requested date.
+ let low = parsed.utcMs - LOCAL_DAY_SEARCH_RADIUS_MS
+ let high = parsed.utcMs + LOCAL_DAY_SEARCH_RADIUS_MS
+ if (localDayOrdinalAt(low, tz) >= parsed.ordinal || localDayOrdinalAt(high, tz) < parsed.ordinal) return NaN
+ while (low < high) {
+ const mid = low + Math.floor((high - low) / 2)
+ if (localDayOrdinalAt(mid, tz) < parsed.ordinal) low = mid + 1
+ else high = mid
+ }
+ return low
+}
+
/**
- * UTC timestamp (ms) of local midnight for the `YYYY-MM-DD` day string in `tz`.
- * The server runs TZ=UTC, so we subtract the TZ offset from the naive UTC parse
- * of the day string. Evaluate the offset AT the target day's midnight (not at
- * `now`) so a DST transition elsewhere in the day can't shift the result by an
- * hour. The naive parse lands within ~14h of local midnight — close enough that
- * re-evaluating the offset at that candidate instant converges to the correct
- * offset across a DST boundary.
+ * UTC timestamp (ms) of the first instant belonging to the `YYYY-MM-DD`
+ * local day in `tz`. This is normally local midnight. When a timezone jumps
+ * forward at 00:00 and midnight does not exist, it is the first representable
+ * instant on that date rather than an instant from the previous local day.
* @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.
+ * @returns {number} UTC timestamp (ms), or `NaN` for an invalid or skipped date
*/
export function anchorLocalMidnightUtc(dayStr, tz) {
- const naiveUtc = Date.parse(`${dayStr}T00:00:00Z`)
- const firstOffset = getUtcOffsetMs(new Date(naiveUtc), tz)
- const candidate = naiveUtc - firstOffset
- const refinedOffset = getUtcOffsetMs(new Date(candidate), tz)
- return naiveUtc - refinedOffset
+ const parsed = parseIsoDay(dayStr)
+ if (!parsed) return NaN
+ const boundary = findLocalDayBoundary(parsed, tz)
+ return Number.isFinite(boundary) && localDayOrdinalAt(boundary, tz) === parsed.ordinal
+ ? boundary
+ : NaN
}
/**
@@ -171,15 +212,20 @@ export function localDayWindowUtc(timezone, atDate = new Date()) {
* @returns {{ start: Date, end: Date } | null}
*/
export function localDayRangeUtc(dateStr, timezone) {
- const normalizedDate = String(dateStr || '').trim()
- const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(normalizedDate)
- if (!m) return null
- const [, y, mo, d] = m.map(Number)
- const start = new Date(anchorLocalMidnightUtc(normalizedDate, 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 }
+ const parsed = parseIsoDay(dateStr)
+ if (!parsed) return null
+ const startMs = anchorLocalMidnightUtc(parsed.normalized, timezone)
+ // A timezone can skip a complete calendar date when it crosses the date
+ // line. That is not a valid local-day range, even though the next boundary
+ // is well-defined for the preceding day's end.
+ if (!Number.isFinite(startMs) || localDayOrdinalAt(startMs, timezone) !== parsed.ordinal) return null
+
+ // ISO arithmetic avoids Date.UTC's special 1900 offset for years 00–99.
+ const nextDate = new Date(parsed.utcMs + DAY_MS).toISOString().slice(0, 10)
+ const nextParsed = parseIsoDay(nextDate)
+ const endMs = nextParsed ? findLocalDayBoundary(nextParsed, timezone) : NaN
+ if (!Number.isFinite(endMs)) return null
+ return { start: new Date(startMs), end: new Date(endMs) }
}
// ---------------------------------------------------------------------------
diff --git a/server/lib/timezone.test.js b/server/lib/timezone.test.js
index c997550384..f851ebdbc3 100644
--- a/server/lib/timezone.test.js
+++ b/server/lib/timezone.test.js
@@ -222,6 +222,14 @@ describe('timezone', () => {
expect(localClock(anchor, 'America/Los_Angeles')).toBe('00:00')
})
+ it('uses the first representable instant when a timezone skips midnight', () => {
+ const anchor = anchorLocalMidnightUtc('2026-03-08', 'America/Havana')
+ expect(anchor).toBe(Date.parse('2026-03-08T05:00:00Z'))
+ expect(localClock(anchor, 'America/Havana')).toBe('01:00')
+ expect(todayInTimezone('America/Havana', new Date(anchor - 1))).toBe('2026-03-07')
+ expect(todayInTimezone('America/Havana', new Date(anchor))).toBe('2026-03-08')
+ })
+
it('handles timezones ahead of UTC', () => {
const anchor = anchorLocalMidnightUtc('2026-04-17', 'Asia/Tokyo')
expect(anchor).toBe(Date.parse('2026-04-17T00:00:00Z') - 9 * 3600 * 1000)
@@ -259,6 +267,8 @@ describe('timezone', () => {
it('rejects malformed dates', () => {
expect(localDayRangeUtc('not-a-date', 'UTC')).toBeNull()
+ expect(localDayRangeUtc('2026-02-31', 'UTC')).toBeNull()
+ expect(localDayRangeUtc('2026-13-01', 'UTC')).toBeNull()
})
it('trims surrounding whitespace before anchoring', () => {
@@ -273,6 +283,24 @@ describe('timezone', () => {
const yearEdge = localDayRangeUtc('2026-12-31', 'UTC')
expect(yearEdge.end.toISOString()).toBe('2027-01-01T00:00:00.000Z')
})
+
+ it('bounds a midnight-skipping DST day without including the prior date', () => {
+ const range = localDayRangeUtc('2026-03-08', 'America/Havana')
+ expect(range.start.toISOString()).toBe('2026-03-08T05:00:00.000Z')
+ expect(range.end.toISOString()).toBe('2026-03-09T04:00:00.000Z')
+ expect(range.end.getTime() - range.start.getTime()).toBe(23 * 60 * 60 * 1000)
+ })
+
+ it('handles years below 100 without Date.UTC\'s 1900 offset', () => {
+ const range = localDayRangeUtc('0099-12-31', 'UTC')
+ expect(range.start.toISOString()).toBe('0099-12-31T00:00:00.000Z')
+ expect(range.end.toISOString()).toBe('0100-01-01T00:00:00.000Z')
+ })
+
+ it('rejects a calendar date skipped entirely by its timezone', () => {
+ expect(localDayRangeUtc('2011-12-30', 'Pacific/Apia')).toBeNull()
+ expect(Number.isNaN(anchorLocalMidnightUtc('2011-12-30', 'Pacific/Apia'))).toBe(true)
+ })
})
describe('getTimezoneUpdatedAt (#2040)', () => {
diff --git a/server/services/humanActivity.test.js b/server/services/humanActivity.test.js
index 6f597a3e23..2ca6b0f99c 100644
--- a/server/services/humanActivity.test.js
+++ b/server/services/humanActivity.test.js
@@ -5,9 +5,11 @@
* listEvents / getDaySummary idempotency) is covered in humanActivity.db.test.js.
*/
import { describe, it, expect } from 'vitest';
+import { localDayRangeUtc as canonicalLocalDayRangeUtc } from '../lib/timezone.js';
import {
shortSummary,
localDayKey,
+ localDayRangeUtc,
normalizeParticipant,
normalizeParticipants,
normalizeCandidate,
@@ -47,6 +49,10 @@ describe('localDayKey', () => {
});
});
+it('keeps the localDayRangeUtc compatibility export wired to lib/timezone.js', () => {
+ expect(localDayRangeUtc).toBe(canonicalLocalDayRangeUtc);
+});
+
// localDayRangeUtc itself (24h window, DST 23h/25h days, month/year rollover,
// malformed input) is now owned and tested by lib/timezone.js (#5572) — see
// timezone.test.js's own `localDayRangeUtc` describe block.