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: consolidate local-midnight DST math onto lib/timezone.js
Bryandero982cd1a91f5211
diff --git a/server/lib/README.md b/server/lib/README.mdindex cf8c4f5dc3..edf488d983 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. |+| `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`). || `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.jsindex ca0cda65d0..a86ac75135 100644--- a/server/lib/timezone.js+++ b/server/lib/timezone.js@@ -54,6 +54,13 @@ export function getLocalParts(utcDate, timezone) {/*** Get the UTC offset (in ms) for a timezone at a given UTC time.* 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.* @param {Date} utcDate - Reference UTC date* @param {string} timezone - IANA timezone string* @returns {number} Offset in milliseconds@@ -153,9 +160,12 @@ 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.+ * UTC `[start, end)` instants that bound a local calendar day (`YYYY-MM-DD`)+ * in `timezone`. The end is the next local date's boundary rather than a+ * fixed 24 hours after the start, preserving 23- and 25-hour DST days.+ * This remains separate from `localDayWindowUtc`, whose inclusive end serves+ * callers with a different boundary contract.+ ** @param {string} dateStr - Local day as `YYYY-MM-DD`* @param {string} timezone - IANA timezone string* @returns {{ start: Date, end: Date } | null}diff --git a/server/lib/timezone.test.js b/server/lib/timezone.test.jsindex 64267db7c3..c997550384 100644--- a/server/lib/timezone.test.js+++ b/server/lib/timezone.test.js@@ -241,6 +241,12 @@ describe('timezone', () => {})describe('localDayRangeUtc', () => {+ it('returns a 24h UTC window for a constant-offset local day', () => {+ const range = localDayRangeUtc('2026-07-04', 'America/Los_Angeles')+ expect(range.start.toISOString()).toBe('2026-07-04T07:00:00.000Z')+ expect(range.end.getTime() - range.start.getTime()).toBe(24 * 60 * 60 * 1000)+ })+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],@@ -260,6 +266,13 @@ describe('timezone', () => {expect(range.start.toISOString()).toBe('2026-03-08T08:00:00.000Z')expect(range.end.toISOString()).toBe('2026-03-09T07:00:00.000Z')})++ it('rolls the end boundary over month and year edges', () => {+ const monthEdge = localDayRangeUtc('2026-01-31', 'UTC')+ expect(monthEdge.end.toISOString()).toBe('2026-02-01T00:00:00.000Z')+ const yearEdge = localDayRangeUtc('2026-12-31', 'UTC')+ expect(yearEdge.end.toISOString()).toBe('2027-01-01T00:00:00.000Z')+ })})describe('getTimezoneUpdatedAt (#2040)', () => {diff --git a/server/services/goalScorecard.js b/server/services/goalScorecard.jsindex 75f2285b6b..7d2cc4916e 100644--- a/server/services/goalScorecard.js+++ b/server/services/goalScorecard.js@@ -27,9 +27,9 @@import { join } from 'path';import { atomicWrite, ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';-import { todayInTimezone } from '../lib/timezone.js';+import { todayInTimezone, localDayRangeUtc } from '../lib/timezone.js';import { getUserTimezone } from './userTimezone.js';-import { localDayRangeUtc, localDayKey, listEvents } from './humanActivity.js';+import { localDayKey, listEvents } from './humanActivity.js';import * as journal from './brainJournal.js';import { buildMarkers } from '../lib/markedSection.js';import { getProviderById, getActiveProvider } from './providers.js';diff --git a/server/services/humanActivity.js b/server/services/humanActivity.jsindex 7032ff7557..8b4c966dfd 100644--- a/server/services/humanActivity.js+++ b/server/services/humanActivity.js@@ -230,9 +230,9 @@ 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 = new Date(anchorLocalMidnightUtc(`${y}-${mo}-${d}`, timezone));+ const midnightMs = 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);+ return new Date(midnightMs + dayMs);}const parsed = new Date(s);return Number.isNaN(parsed.getTime()) ? null : parsed;diff --git a/server/services/humanActivity.test.js b/server/services/humanActivity.test.jsindex 38e3f3b2aa..6f597a3e23 100644--- a/server/services/humanActivity.test.js+++ b/server/services/humanActivity.test.js@@ -8,7 +8,6 @@ import { describe, it, expect } from 'vitest';import {shortSummary,localDayKey,- localDayRangeUtc,normalizeParticipant,normalizeParticipants,normalizeCandidate,@@ -36,45 +35,22 @@ describe('shortSummary', () => {});});-describe('localDayKey / localDayRangeUtc', () => {+describe('localDayKey', () => {it('derives the local day key in a given timezone', () => {// 2026-07-04T02:00:00Z is still 2026-07-03 in America/Los_Angeles (-07:00).expect(localDayKey('2026-07-04T02:00:00Z', 'America/Los_Angeles')).toBe('2026-07-03');// …and the same instant is already 2026-07-04 in UTC.expect(localDayKey('2026-07-04T02:00:00Z', 'UTC')).toBe('2026-07-04');});- it('returns a 24h UTC window bounding the local day', () => {- const range = localDayRangeUtc('2026-07-04', 'America/Los_Angeles');- expect(range).toBeTruthy();- // Local midnight PDT (-07:00) → 07:00Z.- expect(range.start.toISOString()).toBe('2026-07-04T07:00:00.000Z');- expect(range.end.getTime() - range.start.getTime()).toBe(24 * 60 * 60 * 1000);- });it('rejects a malformed date string', () => {- expect(localDayRangeUtc('not-a-date', 'UTC')).toBeNull();expect(localDayKey('not-a-date', 'UTC')).toBeNull();});- it('ends at the NEXT local midnight across DST transitions (25h fall-back, 23h spring-forward)', () => {- // 2026-11-01 America/Los_Angeles: clocks fall back — a 25-hour local day.- // start = midnight PDT (07:00Z); end = next midnight PST (08:00Z on 11-02).- const fallBack = localDayRangeUtc('2026-11-01', 'America/Los_Angeles');- expect(fallBack.start.toISOString()).toBe('2026-11-01T07:00:00.000Z');- expect(fallBack.end.toISOString()).toBe('2026-11-02T08:00:00.000Z');- expect(fallBack.end.getTime() - fallBack.start.getTime()).toBe(25 * 60 * 60 * 1000);- // 2026-03-08 America/Los_Angeles: clocks spring forward — a 23-hour local day.- const springForward = localDayRangeUtc('2026-03-08', 'America/Los_Angeles');- expect(springForward.start.toISOString()).toBe('2026-03-08T08:00:00.000Z');- expect(springForward.end.toISOString()).toBe('2026-03-09T07:00:00.000Z');- expect(springForward.end.getTime() - springForward.start.getTime()).toBe(23 * 60 * 60 * 1000);- });- it('rolls the end boundary over month and year edges', () => {- const monthEdge = localDayRangeUtc('2026-01-31', 'UTC');- expect(monthEdge.end.toISOString()).toBe('2026-02-01T00:00:00.000Z');- const yearEdge = localDayRangeUtc('2026-12-31', 'UTC');- expect(yearEdge.end.toISOString()).toBe('2027-01-01T00:00:00.000Z');- });});+// 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.+describe('participant normalization', () => {it('lowercases email, trims, drops empties', () => {expect(normalizeParticipant(' [email protected] ')).toEqual({ email: '[email protected]' });diff --git a/server/services/youtubeSync.js b/server/services/youtubeSync.jsindex 3da9d5b233..05bc2c2f8e 100644--- a/server/services/youtubeSync.js+++ b/server/services/youtubeSync.js@@ -30,11 +30,11 @@* exported and unit-tested against saved DOM-shaped fixtures — no browser or DB.*/import { dataPath, ensureDir, atomicWrite, tryReadFile, safeJSONParse, sleep } from '../lib/fileUtils.js';-import { todayInTimezone } from '../lib/timezone.js';+import { todayInTimezone, localDayRangeUtc } from '../lib/timezone.js';import { getUserTimezone } from './userTimezone.js';import { getSettings } from './settings.js';import { findOrOpenPage, listCdpPages, isAuthPage, evaluateOnPage } from './browserService.js';-import { localDayRangeUtc, shortSummary } from './humanActivity.js';+import { shortSummary } from './humanActivity.js';import { youtubeVideoIdFromUrl } from './youtubeImport.js';// ---------------------------------------------------------------------------