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: derive Tribe last-contact day from user timezone, not server UTC offset (#8451)
[._.]/ Adam Eivye38bf62dcfb4
diff --git a/server/lib/db.js b/server/lib/db.jsindex d7aa7c9ad1..12ed2ec4a2 100644--- a/server/lib/db.js+++ b/server/lib/db.js@@ -10,6 +10,14 @@ import { isTestRunner } from './runtimeEnv.js';const { Pool } = pg;+// DATE (OID 1082) ships from node-pg as a JS `Date` at LOCAL midnight, so a caller+// that reads it back with `toISOString().slice(0, 10)` (the ubiquitous `isoDate()`+// pattern — see tribe.js) gets the PREVIOUS day on every server east of UTC. Return+// the raw `YYYY-MM-DD` string Postgres sends instead: every consumer of a DATE+// column in this codebase already accepts (or, per `asDay()` in postRunDb.js,+// specifically tolerates) a plain day-key string (#8451).+pg.types.setTypeParser(1082, (value) => value);+if (!process.env.PGPASSWORD) {console.warn('⚠️ PGPASSWORD not set — using default. Set PGPASSWORD env var for production.');}diff --git a/server/lib/db.schemaLifecycle.test.js b/server/lib/db.schemaLifecycle.test.jsindex 122b516ee2..efc13b1e3a 100644--- a/server/lib/db.schemaLifecycle.test.js+++ b/server/lib/db.schemaLifecycle.test.js@@ -3,10 +3,13 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const state = vi.hoisted(() => ({query: vi.fn(), release: vi.fn(), connect: vi.fn(),}));-vi.mock('pg', () => ({ default: { Pool: class {- on() {}- connect = state.connect;-} } }));+vi.mock('pg', () => ({ default: {+ Pool: class {+ on() {}+ connect = state.connect;+ },+ types: { setTypeParser: vi.fn() },+} }));vi.mock('./db/schema/index.js', () => ({buildUpgradeDdl: () => ['upgrade schema'],buildCatalogDdl: () => ['repair catalog'],diff --git a/server/lib/db.transaction.test.js b/server/lib/db.transaction.test.jsindex 30c134798d..157262b1e7 100644--- a/server/lib/db.transaction.test.js+++ b/server/lib/db.transaction.test.js@@ -10,6 +10,7 @@ const pool = vi.hoisted(() => ({vi.mock('pg', () => ({default: {Pool: vi.fn(function Pool() { return pool; }),+ types: { setTypeParser: vi.fn() },},}));diff --git a/server/services/tribe.db.test.js b/server/services/tribe.db.test.jsnew file mode 100644index 0000000000..040713055d--- /dev/null+++ b/server/services/tribe.db.test.js@@ -0,0 +1,86 @@+/**+ * Postgres-backed proof for #8451: `tribe_people.last_contact_on` (a `DATE`)+ * must not drift by a day depending on the server process's UTC offset.+ *+ * Before the fix, node-pg had no type parser registered for `DATE` (OID 1082),+ * so it returned `last_contact_on` as a JS `Date` at LOCAL midnight. Every+ * read-modify-write of a person (`getPerson` → `updatePerson`) then re-derived+ * the date with `toISOString().slice(0, 10)`, which is the PREVIOUS calendar+ * day on any server east of UTC (e.g. Europe/Berlin) — so saving a person's+ * notes silently aged their last-contact date by one day, every time.+ *+ * `*.db.test.js` → runs ONLY via `npm run test:db` against `portos_test`+ * (registered in vitest.config.db.js). Every assertion is scoped to this run's+ * own ids so concurrent suites sharing the test DB are unaffected. Fixtures use+ * placeholder names and handles only.+ */+import { afterAll, beforeAll, describe, expect, it } from 'vitest';+import { checkHealth, close, ensureSchema, query } from '../lib/db.js';+import { requireDbOrSkip } from '../lib/dbTestGate.js';+import * as tribe from './tribe.js';++let dbReady = false;+let skipReason = '';+{+ const health = await checkHealth().catch((e) => ({ connected: false, error: e?.message }));+ if (!health.connected) {+ skipReason = `Postgres not reachable (${health.error || 'no connection'})`;+ } else {+ await ensureSchema().catch(() => {});+ dbReady = true;+ }+}+const runDb = requireDbOrSkip('services/tribe.db.test', dbReady, skipReason);++const nonce = `tribedate-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;+const createdPersonIds = [];++afterAll(async () => {+ if (!dbReady) return;+ if (createdPersonIds.length) {+ await query('DELETE FROM tribe_people WHERE id = ANY($1::uuid[])', [createdPersonIds]).catch(() => {});+ }+ await close();+});++// Force the process onto a UTC+ timezone (matching the acceptance criterion) so+// this test reproduces the drift the un-registered DATE type parser caused,+// regardless of the machine actually running the suite.+let originalTZ;+beforeAll(() => {+ originalTZ = process.env.TZ;+ process.env.TZ = 'Europe/Berlin';+});+afterAll(() => {+ if (originalTZ === undefined) delete process.env.TZ;+ else process.env.TZ = originalTZ;+});++describe.skipIf(!runDb)('tribe last_contact_on — UTC-offset round-trip (#8451)', () => {+ it('leaves last_contact_on unchanged across a read-modify-write that never touches it', async () => {+ const person = await tribe.createPerson({ name: `Example Person ${nonce}` });+ createdPersonIds.push(person.id);+ await tribe.createTouchpoint(person.id, { happenedAt: '2026-06-15T12:00:00.000Z', channel: 'call' });++ const before = await tribe.getPerson(person.id);+ expect(before.lastContact).toBe('2026-06-15');++ // A save that never mentions lastContact must not perturb it — this is+ // exactly the updatePerson(id, { notes }) path #8451 flagged.+ const updated = await tribe.updatePerson(person.id, { notes: 'updated notes' });+ expect(updated.lastContact).toBe('2026-06-15');++ const after = await tribe.getPerson(person.id);+ expect(after.lastContact).toBe('2026-06-15');+ });++ it('stores the raw YYYY-MM-DD DATE value as a string, not a JS Date at local midnight', async () => {+ const person = await tribe.createPerson({ name: `Example Person ${nonce}-raw` });+ createdPersonIds.push(person.id);+ await tribe.createTouchpoint(person.id, { happenedAt: '2026-03-01T08:00:00.000Z', channel: 'call' });++ const { rows } = await query('SELECT last_contact_on FROM tribe_people WHERE id = $1', [person.id]);+ expect(typeof rows[0].last_contact_on).toBe('string');+ expect(rows[0].last_contact_on).toBe('2026-03-01');+ });+});diff --git a/server/services/tribe.js b/server/services/tribe.jsindex b97a54c3d7..e6edf11185 100644--- a/server/services/tribe.js+++ b/server/services/tribe.js@@ -17,6 +17,8 @@ import { ensureSchema, query, withTransaction } from '../lib/db.js';import { ServerError } from '../lib/errorHandler.js';import { cadenceStatus, DEFAULT_RING_CADENCE } from '../lib/tribeCadence.js';import { buildPersonMatchIndex, matchPeople, normalizeIdentifier, normalizePhone } from '../lib/tribeMatch.js';+import { toUserDayKey } from '../lib/activeDays.js';+import { getUserTimezone } from './userTimezone.js';import * as calendarSync from './calendarSync.js';export function isoDate(value) {@@ -483,8 +485,15 @@ export async function createTouchpoint(personId, data = {}) {export async function createCalendarTouchpoint(personId, { accountId, eventId, summary }) {const event = await calendarSync.getEvent(accountId, eventId);if (!event) throw new ServerError('Calendar event not found', { status: 404 });+ const happenedAt = event.startTime || event.endTime || new Date().toISOString();+ // `last_contact_on` is a user-facing calendar day, not a UTC one — an evening+ // event must land on the day the user experienced it, not tomorrow's UTC date+ // (#8451). `createTouchpoint` uses `localDate` (falling back to the raw instant+ // only when the caller doesn't supply one).+ const localDate = toUserDayKey(happenedAt, await getUserTimezone());return createTouchpoint(personId, {- happenedAt: event.startTime || event.endTime || new Date().toISOString(),+ happenedAt,+ localDate,channel: event.location || 'Calendar',summary: summary || event.title || 'Calendar touchpoint',source: 'calendar',@@ -517,6 +526,12 @@ export async function createCalendarTouchpoint(personId, { accountId, eventId, s// advance instead of re-implementing it (#34).export async function autoCreateTouchpoint(personId, data) {const happenedAt = data.happenedAt || new Date().toISOString();+ // Advance last_contact_on by the user's LOCAL calendar day, not the UTC day the+ // raw instant's date part happens to fall on — an evening meeting/message must+ // not advance the contact date to a day that, locally, hasn't happened yet+ // (#8451). Falls back to the raw instant only if it doesn't parse as a date at+ // all (toUserDayKey returns null), matching the manual-touchpoint fallback.+ const contactDay = toUserDayKey(happenedAt, await getUserTimezone()) || happenedAt;return withTransaction(async (client) => {const result = await client.query(`INSERT INTO tribe_touchpoints (@@ -551,7 +566,7 @@ export async function autoCreateTouchpoint(personId, data) {SET last_contact_on = GREATEST(COALESCE(last_contact_on, DATE '1900-01-01'), $2::date),updated_at = NOW()WHERE id = $1`,- [personId, happenedAt],+ [personId, contactDay],);return rowToTouchpoint(result.rows[0]);});diff --git a/server/services/tribe.test.js b/server/services/tribe.test.jsindex f10b871c98..6b13cf5c99 100644--- a/server/services/tribe.test.js+++ b/server/services/tribe.test.js@@ -9,12 +9,26 @@ vi.mock('../lib/db.js', () => ({withTransaction: vi.fn(),}));+// Fixed, mockable timezone for autoCreateTouchpoint's user-local-day derivation+// (#8451) — otherwise it would read the real (or unset) `settings.json` and make+// the last-contact-day assertions depend on this machine's configured timezone.+vi.mock('./userTimezone.js', () => ({+ getUserTimezone: vi.fn().mockResolvedValue('America/Los_Angeles'),+}));++vi.mock('./calendarSync.js', () => ({+ getEvent: vi.fn(),+}));+import { query, withTransaction } from '../lib/db.js';+import { getUserTimezone } from './userTimezone.js';+import { getEvent } from './calendarSync.js';import {listPeople,getPerson,createPerson,createTouchpoint,+ createCalendarTouchpoint,normalizeTags,normalizeEmails,isoDate,@@ -23,6 +37,7 @@ import {rowToTouchpoint,personCadenceStatus,getCareSummary,+ autoCreateTouchpoint,autoLogTouchpoints,findDuplicateTribeIdentifiers,checkDuplicateTribeIdentifiers,@@ -239,6 +254,80 @@ describe('tribe service — createTouchpoint', () => {});});+describe('tribe service — createCalendarTouchpoint (#8451 UTC-offset day shift)', () => {+ beforeEach(() => {+ query.mockReset();+ withTransaction.mockReset();+ getEvent.mockReset();+ getUserTimezone.mockClear();+ });++ it('stores the user-local day for an evening calendar event, not its UTC day', async () => {+ getEvent.mockResolvedValue({+ title: 'Dinner',+ startTime: '2026-09-11T01:00:00.000Z', // 2026-09-10 18:00 America/Los_Angeles+ endTime: '2026-09-11T02:00:00.000Z',+ });+ query.mockResolvedValue({ rows: [{ id: 'person-1', name: 'Example Person', ring: 'tribe', cadence_days: 45 }] });+ const clientQuery = vi.fn()+ .mockResolvedValueOnce({ rows: [{ id: 'touch-1', person_id: 'person-1' }] })+ .mockResolvedValueOnce({ rows: [] });+ withTransaction.mockImplementation(async (fn) => fn({ query: clientQuery }));++ await createCalendarTouchpoint('person-1', { accountId: 'acct-1', eventId: 'evt-1' });++ expect(clientQuery).toHaveBeenNthCalledWith(+ 2,+ expect.stringContaining('SET last_contact_on'),+ ['person-1', '2026-09-10', 'Calendar'],+ );+ });+});++describe('tribe service — autoCreateTouchpoint (#8451 UTC-offset day shift)', () => {+ beforeEach(() => {+ withTransaction.mockReset();+ getUserTimezone.mockClear();+ });++ it('advances last_contact_on to the user-LOCAL day, not the UTC day, for a late-evening instant', async () => {+ // 2026-09-11T01:00:00Z is 2026-09-10 18:00 in America/Los_Angeles (mocked+ // above) — an evening touchpoint that must not be dated tomorrow.+ const clientQuery = vi.fn()+ .mockResolvedValueOnce({ rows: [{ id: 'touch-1', person_id: 'person-1' }] })+ .mockResolvedValueOnce({ rows: [] });+ withTransaction.mockImplementation(async (fn) => fn({ query: clientQuery }));++ await autoCreateTouchpoint('person-1', {+ happenedAt: '2026-09-11T01:00:00.000Z',+ source: 'calendar',+ dedupeKey: 'cal:a:e1',+ });++ expect(clientQuery).toHaveBeenNthCalledWith(+ 2,+ expect.stringContaining('SET last_contact_on'),+ ['person-1', '2026-09-10'],+ );+ });++ it('stores happened_at as the full raw instant (unaffected by the local-day derivation)', async () => {+ const clientQuery = vi.fn()+ .mockResolvedValueOnce({ rows: [{ id: 'touch-1', person_id: 'person-1' }] })+ .mockResolvedValueOnce({ rows: [] });+ withTransaction.mockImplementation(async (fn) => fn({ query: clientQuery }));++ await autoCreateTouchpoint('person-1', {+ happenedAt: '2026-09-11T01:00:00.000Z',+ source: 'calendar',+ dedupeKey: 'cal:a:e1',+ });++ const [, insertParams] = clientQuery.mock.calls[0];+ expect(insertParams[2]).toBe('2026-09-11T01:00:00.000Z'); // happened_at column+ });+});+describe('tribe service — personCadenceStatus', () => {it('external people are never overdue', () => {expect(personCadenceStatus({ ring: 'external', lastContact: daysAgo(999), cadenceDays: 7 }))diff --git a/server/vitest.config.db.js b/server/vitest.config.db.jsindex d9a6e398f7..6c84973d2e 100644--- a/server/vitest.config.db.js+++ b/server/vitest.config.db.js@@ -40,6 +40,7 @@ export const DB_TEST_INCLUDE = ['lib/db/schema/beeper.db.test.js','services/beeperConversations.db.test.js','services/beeperTribe.db.test.js',+ 'services/tribe.db.test.js','services/tribePurge.db.test.js','services/beeperSync.db.test.js','services/creativeDirector/projectsDB.test.js',