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

feat: count Character daysActive as a union of health + POST day sets, not a sum (#4120)

[._.]/ Adam Eivyc3a00b7e97b7
diff --git a/server/lib/README.md b/server/lib/README.md
index 952c030290..0b14d76c29 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -298,6 +298,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `songPractice.js` | SongBook repertoire practice scheduling (#4102) — the pure core behind `POST /api/brain/songbook/:id/practice`. `applySongPractice(song, quality, now)` → `{ stage, practice }`, the exact partial to hand `brainStorage.updateWith`: it advances the shared `spacedRepetition` schedule from a 0..5 self-grade and moves the song's `stage` along `SONG_STAGE_ORDER` (≥ `SONG_PROMOTE_MIN_QUALITY` promotes, ≤ `SONG_REGRESS_MAX_QUALITY` regresses, a 3 holds). Promotion is gated to once per practice day (regression never is), and a practiced song floors at `learning` — `new` means "never picked up", which stops being true after one session. `songPracticeOrDefault(song)` derives the schedule on READ for every song predating the feature (nothing is backfilled to disk: a migration would restamp `updatedAt` on every record and spray federation churn, and would break the `data.reference/` seeds' byte-identity). `nextSongStage` no-ops on a stage this install doesn't recognize, so a practice log can't rewrite a value synced from a newer peer. `isSongDue(song, now)` mirrors the client's `songDueAt` in `client/src/components/songbook/constants.js`. Pure. |
| `postTopics.js` | Pure POST practice-topic registry — `POST_TOPICS` (`{ id, label, module, surface, drillTypes }`) is the single source of truth for "what am I studying?", plus `resolveTopicForDrillType` / `isTopicEnabled` / `isMemoryItemEnabled`. Gates session composition and recommendations, including Memory's composed and dedicated practice routes plus standalone Morse. Mirrored to the client's post `constants.js` (parity test). |
| `postStreak.js` | Pure DST-safe POST practice-streak math — the single `computePostStreaks` implementation shared by scored sessions and the training log, plus `computeUnifiedStreak` (a day is active with EITHER a session or a practice entry) and `normalizeYmd` (day-key prefix for a date that may be a full ISO timestamp). |
+| `activeDays.js` | Cross-domain "days active" set math (#4120) — `unionActiveDayKeys(sources, timezone)` unions several domains' stored date values into one sorted array of user-local `YYYY-MM-DD` keys (`.length` is the honest day count; summing per-domain counts would double-count any day logged in two domains), and `toUserDayKey(value, timezone)` is its per-value normalizer. Owns the day-boundary reconciliation between POST (stamps `userLocalToday()`) and the health logs (stamp the server-local `getDateString()`): a value carrying an INSTANT (the pre-#2681 full-ISO shape some legacy training entries still store) is re-keyed into the user's timezone rather than `split('T')[0]`'d to the UTC day, while a value that is already a bare day LABEL is taken as authored — there is no instant left to re-derive from, so retro-normalizing stored health keys is out of scope by construction, not by omission. Non-day values are dropped rather than coerced. Pure. |
| `planIds.js` | Utilities for PLAN.md `[slug]` IDs. |
| `renderSlot.js` | Render-slot helpers for `(proof\|final)Image` per stage. |
| `renderTargets.js` | Render-target alphabet (#3231): `RENDER_TARGET`/`RENDER_TARGETS` name every creative surface that enqueues renders (universe-bible, sprite-reference, music-video, …) — the keys into `settings.renderDefaults` — plus the `RENDER_TARGET_BACKEND_AUTO` fall-through sentinel. Dependency-free leaf; resolved per surface by `services/imageGen/cloudProviderConfig.js#resolveRenderTargetConfig`. |
diff --git a/server/lib/activeDays.js b/server/lib/activeDays.js
new file mode 100644
index 0000000000..a941cd3853
--- /dev/null
+++ b/server/lib/activeDays.js
@@ -0,0 +1,80 @@
+/**
+ * Cross-domain "active days" set math (#4120).
+ *
+ * A truthful "days active" is the UNION of the per-day date sets each domain contributes —
+ * never the SUM of per-domain day counts, which double-counts every day the user logged in two
+ * domains. This module owns that union, plus the one thing that makes it meaningful: agreeing
+ * on where a day starts.
+ *
+ * ## The day boundary
+ *
+ * PortOS has two day-key conventions in the wild:
+ * - POST (`meatspacePost.js`, `meatspacePostTraining.js`, `meatspacePostMemory.js`) stamps
+ * `date` from `userLocalToday()` — the USER's configured timezone (#2681).
+ * - The health logs (`meatspaceAlcohol/Nicotine/Health.js`) stamp `date` from the
+ * server-local `getDateString()`. The process runs `TZ=UTC`, so those are UTC days.
+ *
+ * **The user-local day is canonical here**, because it is the boundary every user-facing
+ * per-day feature already reads against (POST streaks, the Daily Driver) and the one the human
+ * looking at the tile actually lives in.
+ *
+ * **What that can and cannot fix, precisely:**
+ * - A value carrying an INSTANT (a full ISO timestamp — the pre-#2681 shape some legacy
+ * training-log entries still store in `date`) is re-keyed to the user's timezone here. This
+ * is a real correction: the usual `String(date).split('T')[0]` takes the UTC day, which
+ * files a local-evening practice on tomorrow.
+ * - A value that is already a bare `YYYY-MM-DD` LABEL is taken as authored. There is no
+ * instant left to re-derive from — the health-log records carry no timestamp beside their
+ * day key — so normalizing the stored health keys is not possible on read, and a migration
+ * could not do it either for want of the input. Retro-normalizing stored keys is therefore
+ * explicitly OUT OF SCOPE; the union normalizes what it can and takes the rest as authored.
+ * The residual error is bounded and small: only a health entry logged within the
+ * UTC-vs-local offset window can land on an adjacent key, which shifts one day label rather
+ * than inventing or losing days in bulk.
+ *
+ * Pure and dependency-light on purpose (mirrors `postStreak.js`): the only import is
+ * `todayInTimezone`, itself a pure formatter, so the single source of truth for "which day is
+ * this instant in the user's timezone" is not forked.
+ */
+
+import { todayInTimezone } from './timezone.js';
+
+// A day key is exactly `YYYY-MM-DD`. Anything else is not a day and must not be counted as one
+// — validate rather than coerce, or a junk value inflates the tally by a phantom day.
+const DAY_KEY_RE = /^\d{4}-\d{2}-\d{2}$/;
+
+/**
+ * Normalize one stored date value to a user-local `YYYY-MM-DD` day key.
+ *
+ * @param {unknown} value - a bare day key, or a full ISO timestamp
+ * @param {string} timezone - IANA timezone (from `getUserTimezone()`)
+ * @returns {string|null} the day key, or `null` when the value is not a date at all
+ */
+export function toUserDayKey(value, timezone) {
+ if (typeof value !== 'string' || !value) return null;
+
+ // No time component → a day LABEL, not an instant. Take it as authored (see header).
+ if (!value.includes('T')) return DAY_KEY_RE.test(value) ? value : null;
+
+ const at = new Date(value);
+ if (Number.isNaN(at.getTime())) return null;
+ return todayInTimezone(timezone, at);
+}
+
+/**
+ * Union several domains' date values into one sorted set of user-local day keys.
+ *
+ * @param {Array<Array<unknown>|null|undefined>} sources - one array of date values per domain
+ * @param {string} timezone - IANA timezone (from `getUserTimezone()`)
+ * @returns {string[]} sorted, de-duplicated day keys. `.length` is the honest "days active".
+ */
+export function unionActiveDayKeys(sources, timezone) {
+ const days = new Set();
+ for (const source of sources || []) {
+ for (const value of source || []) {
+ const key = toUserDayKey(value, timezone);
+ if (key) days.add(key);
+ }
+ }
+ return [...days].sort();
+}
diff --git a/server/lib/activeDays.test.js b/server/lib/activeDays.test.js
new file mode 100644
index 0000000000..bbf02861a8
--- /dev/null
+++ b/server/lib/activeDays.test.js
@@ -0,0 +1,92 @@
+import { describe, it, expect } from 'vitest';
+import { toUserDayKey, unionActiveDayKeys } from './activeDays.js';
+
+// A fixed, obviously-fake timezone well behind UTC, so a late-UTC instant lands on the PREVIOUS
+// local day and the re-keying is observable rather than a no-op.
+const TZ = 'America/Los_Angeles';
+
+describe('toUserDayKey', () => {
+ it('takes a bare day label as authored', () => {
+ // The health logs store only a day key — no instant survives to re-derive it from, so the
+ // label is the best available answer and must not be shifted by the timezone.
+ expect(toUserDayKey('2026-03-14', TZ)).toBe('2026-03-14');
+ expect(toUserDayKey('2026-03-14', 'Pacific/Kiritimati')).toBe('2026-03-14');
+ });
+
+ it('re-keys a full ISO instant into the USER local day, not the UTC day', () => {
+ // The load-bearing case: `split('T')[0]` on this value yields 2026-03-15 (the UTC day),
+ // which files a 7pm-local practice on tomorrow.
+ expect(toUserDayKey('2026-03-15T02:30:00.000Z', TZ)).toBe('2026-03-14');
+ expect('2026-03-15T02:30:00.000Z'.split('T')[0]).toBe('2026-03-15');
+ });
+
+ it('keeps an instant that does not cross the boundary on its own day', () => {
+ expect(toUserDayKey('2026-03-14T18:00:00.000Z', TZ)).toBe('2026-03-14');
+ });
+
+ it('re-keys forward for a timezone AHEAD of UTC', () => {
+ // Same instant, a user in Tokyo: the local day is already the 15th.
+ expect(toUserDayKey('2026-03-14T18:00:00.000Z', 'Asia/Tokyo')).toBe('2026-03-15');
+ });
+
+ it('returns null for values that are not days at all', () => {
+ // Dropped, never coerced — a junk value that counted would invent a day the user never had.
+ for (const junk of [null, undefined, '', 'someday', '2026-3-4', 42, {}, [], new Date()]) {
+ expect(toUserDayKey(junk, TZ)).toBeNull();
+ }
+ });
+
+ it('returns null for an unparseable timestamp rather than its literal prefix', () => {
+ expect(toUserDayKey('not-a-date T nope', TZ)).toBeNull();
+ expect(toUserDayKey('2026-13-45T99:99:99Z', TZ)).toBeNull();
+ });
+});
+
+describe('unionActiveDayKeys', () => {
+ it('counts a day logged in two domains exactly ONCE', () => {
+ // The whole reason this is a union and not a sum of per-domain counts.
+ const days = unionActiveDayKeys([
+ ['2026-03-14', '2026-03-15'], // health logs
+ ['2026-03-14'], // POST sessions
+ ['2026-03-14'], // POST training
+ ], TZ);
+
+ expect(days).toEqual(['2026-03-14', '2026-03-15']);
+ expect(days).toHaveLength(2); // NOT 4
+ });
+
+ it('de-dupes across the day-boundary normalization too', () => {
+ // A health entry stamped 2026-03-14 and a legacy training entry whose UTC-day prefix reads
+ // 2026-03-15 are the SAME local day. A `split('T')[0]` union would report two.
+ const days = unionActiveDayKeys([
+ ['2026-03-14'],
+ ['2026-03-15T02:30:00.000Z'],
+ ], TZ);
+
+ expect(days).toEqual(['2026-03-14']);
+ });
+
+ it('returns an empty array on a brand-new install', () => {
+ expect(unionActiveDayKeys([[], [], []], TZ)).toEqual([]);
+ expect(unionActiveDayKeys([], TZ)).toEqual([]);
+ });
+
+ it('tolerates absent sources and absent values without inventing days', () => {
+ expect(unionActiveDayKeys([null, undefined, ['2026-03-14', null, undefined, '']], TZ))
+ .toEqual(['2026-03-14']);
+ expect(unionActiveDayKeys(null, TZ)).toEqual([]);
+ });
+
+ it('returns the keys sorted ascending', () => {
+ expect(unionActiveDayKeys([['2026-03-15', '2026-01-02'], ['2026-02-09']], TZ))
+ .toEqual(['2026-01-02', '2026-02-09', '2026-03-15']);
+ });
+
+ it('unions the same records to a different total for a user in a different timezone', () => {
+ // Pins that the day boundary is genuinely applied rather than decorative: two instants
+ // four hours apart are one local day in Los Angeles and two in Tokyo.
+ const sources = [['2026-03-14T14:00:00.000Z', '2026-03-14T18:00:00.000Z']];
+ expect(unionActiveDayKeys(sources, TZ)).toHaveLength(1);
+ expect(unionActiveDayKeys(sources, 'Asia/Tokyo')).toHaveLength(2);
+ });
+});
diff --git a/server/lib/index.js b/server/lib/index.js
index 464de06947..157d679642 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -276,6 +276,7 @@ export * from './postMultiplicationLadder.js';
export * from './postPowersLadder.js';
export * from './postProgression.js';
export * from './postStreak.js';
+export * from './activeDays.js';
export * from './postTopics.js';
export * from './spacedRepetition.js';
export * from './songPractice.js';
diff --git a/server/services/characterMetrics.js b/server/services/characterMetrics.js
index 23e65d3cfb..8d26c09dc0 100644
--- a/server/services/characterMetrics.js
+++ b/server/services/characterMetrics.js
@@ -19,10 +19,12 @@
* index that deliberately holds downloads and uploads, so it cannot be called "rendered".
* When picking a new signal, check what the UI actually records before naming the tile.
*
- * **No new reads.** Every `compute()` composes signals from `characterSignals.js`, the same
- * context the skills fan out over — so the six tiles below add ZERO stat reads to
+ * **No new DOMAIN reads.** Every `compute()` composes signals from `characterSignals.js`, the
+ * same context the skills fan out over — so the tiles below add no stat reads to
* `GET /api/character`, and a domain the user has never touched still costs nothing extra.
- * There is deliberately no new usage-event tracking behind any of this.
+ * (`daysActive` added the one non-domain signal, `userTimezone` — a `getSettings()` read, not a
+ * stat — because a cross-domain day union has to pick a day boundary; see #4120.) There is
+ * deliberately no new usage-event tracking behind any of this.
*
* **Derived on read, never persisted, never federated.** `getCharacter()` attaches these;
* `saveCharacter()` strips them (`metrics` is in `character.js`'s `DERIVED_FIELDS`) and
@@ -48,6 +50,7 @@
*/
import { computeUnifiedStreak } from '../lib/postStreak.js';
+import { unionActiveDayKeys } from '../lib/activeDays.js';
import { createSignalContext } from './characterSignals.js';
// Returned by a compute() whose ratio has an empty denominator. A unique Symbol (not null/0)
@@ -96,6 +99,43 @@ export const METRICS = [
hint: 'Consecutive days with a health log',
compute: async (read) => (await read('loggingStats')).currentStreak,
},
+ {
+ id: 'daysActive',
+ label: 'Days Active',
+ unit: 'days',
+ hint: 'Distinct days with any logged activity',
+ // A UNION of day sets, never a SUM of per-domain day counts. Summing would double-count
+ // every day the user both practiced POST and logged a health entry — the exact reason this
+ // tile was cut from #2676 rather than approximated: a POST-only or a summed reading is
+ // wrong in a way the number itself doesn't advertise.
+ //
+ // The two domains disagreed about where a day starts (POST stamps `userLocalToday()`, the
+ // health logs stamp the server-local `getDateString()`), so the union standardizes on the
+ // USER-local day and normalizes on read. `server/lib/activeDays.js` owns that decision and
+ // documents exactly what it can and cannot fix — notably that a stored bare day LABEL is
+ // taken as authored, because no instant survives to re-derive it from.
+ //
+ // Missing keys are a FAILED read, not an idle install: each source is validated as an
+ // array and a throw here lands in `readMetric`'s `unavailable`, so a shape mismatch can
+ // never render as a confident "0 days active" for someone with years of history.
+ compute: async (read) => {
+ const [logging, sessions, training, timezone] = await Promise.all([
+ read('loggingStats'),
+ read('postSessions'),
+ read('postTraining'),
+ read('userTimezone'),
+ ]);
+ if (!Array.isArray(logging?.activeDayKeys)) throw new Error('logging stats reported no activeDayKeys');
+ if (!Array.isArray(sessions)) throw new Error('POST sessions unreadable');
+ if (!Array.isArray(training)) throw new Error('POST training log unreadable');
+
+ return unionActiveDayKeys([
+ logging.activeDayKeys,
+ sessions.map((s) => s?.date),
+ training.map((e) => e?.date),
+ ], timezone).length;
+ },
+ },
{
id: 'recordsCreated',
label: 'Records Created',
diff --git a/server/services/characterMetrics.test.js b/server/services/characterMetrics.test.js
index fbad2cdd51..f603b3b40e 100644
--- a/server/services/characterMetrics.test.js
+++ b/server/services/characterMetrics.test.js
@@ -11,7 +11,10 @@ const stats = vi.hoisted(() => ({
sessions: [],
training: [],
today: '2026-07-17',
- logging: { currentStreak: 0, totalLogged: 0 },
+ // Obviously-fake fixed timezone, well behind UTC, so a late-UTC instant lands on the previous
+ // local day and daysActive's day-boundary normalization is observable.
+ timezone: 'America/Los_Angeles',
+ logging: { currentStreak: 0, totalLogged: 0, activeDayKeys: [] },
goals: { goals: [] },
memories: 0,
assets: 0,
@@ -30,7 +33,15 @@ vi.mock('./meatspaceLoggingStats.js', () => ({ getLoggingStats: vi.fn(async () =
vi.mock('./identity/goals.js', () => ({ getGoals: vi.fn(async () => stats.goals) }));
vi.mock('./memoryBackend.js', () => ({ countMemories: vi.fn(async () => stats.memories) }));
vi.mock('./mediaAssetIndex/db.js', () => ({ countAssets: vi.fn(async () => stats.assets) }));
-vi.mock('../lib/timezone.js', () => ({ userLocalToday: vi.fn(async () => stats.today) }));
+// PARTIAL mock: only the two settings-backed reads are stubbed. `todayInTimezone` must stay
+// REAL — `lib/activeDays.js` (behind the daysActive tile) derives its day keys through it, and
+// a factory that dropped it would leave that tile throwing on an undefined import and reading
+// `unavailable` for reasons that have nothing to do with the behavior under test.
+vi.mock('../lib/timezone.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ userLocalToday: vi.fn(async () => stats.today),
+ getUserTimezone: vi.fn(async () => stats.timezone),
+}));
import { getCharacterMetrics, METRICS, METRIC_NOT_APPLICABLE } from './characterMetrics.js';
import { createSignalContext } from './characterSignals.js';
@@ -43,7 +54,8 @@ import { countMemories } from './memoryBackend.js';
import { countAssets } from './mediaAssetIndex/db.js';
import { countWorks } from './writersRoom/local.js';
import { getPostSessions } from './meatspacePost.js';
-import { userLocalToday } from '../lib/timezone.js';
+import { getAllTrainingEntries } from './meatspacePostTraining.js';
+import { userLocalToday, getUserTimezone } from '../lib/timezone.js';
const goal = (status) => ({ status });
@@ -56,7 +68,8 @@ beforeEach(() => {
stats.sessions = [];
stats.training = [];
stats.today = '2026-07-17';
- stats.logging = { currentStreak: 0, totalLogged: 0 };
+ stats.timezone = 'America/Los_Angeles';
+ stats.logging = { currentStreak: 0, totalLogged: 0, activeDayKeys: [] };
stats.goals = { goals: [] };
stats.memories = 0;
stats.assets = 0;
@@ -68,7 +81,9 @@ beforeEach(() => {
vi.mocked(getGoals).mockImplementation(async () => stats.goals);
vi.mocked(countMemories).mockImplementation(async () => stats.memories);
vi.mocked(countAssets).mockImplementation(async () => stats.assets);
+ vi.mocked(getAllTrainingEntries).mockImplementation(async () => stats.training);
vi.mocked(userLocalToday).mockImplementation(async () => stats.today);
+ vi.mocked(getUserTimezone).mockImplementation(async () => stats.timezone);
vi.spyOn(console, 'warn').mockImplementation(() => {});
});
@@ -228,6 +243,92 @@ describe('getCharacterMetrics — populated domains', () => {
});
});
+describe('getCharacterMetrics — daysActive (#4120)', () => {
+ it('UNIONS day sets across domains — a day logged twice counts once', async () => {
+ // The load-bearing property, and the reason this tile was cut from #2676 rather than
+ // approximated: summing per-domain day counts would report 5 for three real days.
+ stats.logging = { currentStreak: 0, totalLogged: 0, activeDayKeys: ['2026-03-12', '2026-03-14'] };
+ stats.sessions = [{ date: '2026-03-14' }];
+ stats.training = [{ date: '2026-03-14' }, { date: '2026-03-13' }];
+
+ expect(byId(await getCharacterMetrics(), 'daysActive')).toMatchObject({
+ value: 3, unit: 'days', unavailable: false, notApplicable: false,
+ });
+ });
+
+ it('reports a real, earned 0 on an install with no activity anywhere', async () => {
+ // 0 is the honest answer here — NOT unavailable, and not not-applicable.
+ expect(byId(await getCharacterMetrics(), 'daysActive')).toMatchObject({
+ value: 0, unavailable: false, notApplicable: false,
+ });
+ });
+
+ it('counts a POST-only install without needing a health log', async () => {
+ stats.sessions = [{ date: '2026-03-14' }, { date: '2026-03-15' }];
+ expect(byId(await getCharacterMetrics(), 'daysActive').value).toBe(2);
+ });
+
+ it('normalizes the day boundary so the two domains agree on where a day starts', async () => {
+ // A health entry stamped with the server-local (UTC) day, and a LEGACY training entry that
+ // still stores a full ISO instant. Splitting that instant on 'T' yields the UTC day
+ // 2026-03-15, so a naive union would report two days; in the user's timezone it is the
+ // evening of 2026-03-14 — the same day the health entry is on. ONE day, not two.
+ stats.logging = { currentStreak: 0, totalLogged: 0, activeDayKeys: ['2026-03-14'] };
+ stats.training = [{ date: '2026-03-15T02:30:00.000Z' }];
+
+ expect(byId(await getCharacterMetrics(), 'daysActive').value).toBe(1);
+ });
+
+ it('re-keys that instant against the USER timezone, not the server clock', async () => {
+ // Same records, a user configured a day ahead of UTC: now the instant really is its own
+ // local day, so the union grows to two. Pins that the timezone is actually consulted.
+ stats.logging = { currentStreak: 0, totalLogged: 0, activeDayKeys: ['2026-03-14'] };
+ stats.training = [{ date: '2026-03-14T18:00:00.000Z' }];
+
+ expect(byId(await getCharacterMetrics(), 'daysActive').value).toBe(1);
+
+ stats.timezone = 'Asia/Tokyo';
+ expect(byId(await getCharacterMetrics(), 'daysActive').value).toBe(2);
+ expect(getUserTimezone).toHaveBeenCalled();
+ });
+
+ it('is unavailable — never 0 — when the health-log day keys could not be read', async () => {
+ // A shape that reports aggregates but no day keys is a FAILED read, not an idle install.
+ // Rendering 0 for someone with years of history is the exact lie the sentinels prevent.
+ stats.logging = { currentStreak: 9, totalLogged: 40 };
+ stats.sessions = [{ date: '2026-03-14' }];
+
+ const tile = byId(await getCharacterMetrics(), 'daysActive');
+ expect(tile).toMatchObject({ value: null, unavailable: true, notApplicable: false });
+ expect(tile.value).not.toBe(0);
+ });
+
+ it('is unavailable when a POST source is unreadable rather than under-counting', async () => {
+ stats.logging = { currentStreak: 0, totalLogged: 0, activeDayKeys: ['2026-03-14'] };
+ vi.mocked(getAllTrainingEntries).mockImplementation(fail('training log'));
+
+ expect(byId(await getCharacterMetrics(), 'daysActive')).toMatchObject({
+ value: null, unavailable: true,
+ });
+ });
+
+ it('ignores entries with no usable date instead of counting them as a day', async () => {
+ stats.logging = { currentStreak: 0, totalLogged: 0, activeDayKeys: ['2026-03-14'] };
+ stats.sessions = [{}, { date: null }, { date: 'someday' }];
+
+ expect(byId(await getCharacterMetrics(), 'daysActive').value).toBe(1);
+ });
+
+ it('reads the health-log day keys through the SHARED signal, adding no extra read', async () => {
+ // The tile reuses the loggingStats signal healthLoggingStreak already reads, so it costs
+ // nothing beyond the one settings read for the timezone.
+ vi.mocked(getLoggingStats).mockClear();
+ await getCharacterMetrics();
+ expect(getLoggingStats).toHaveBeenCalledTimes(1);
+ expect(getLoggingStats).toHaveBeenCalledWith({ strict: true, withActiveDayKeys: true });
+ });
+});
+
describe('getCharacterMetrics — goalCompletionRate', () => {
it('is the completed share of ALL goals', async () => {
stats.goals = { goals: [goal('completed'), goal('completed'), goal('active'), goal('active')] };
diff --git a/server/services/characterSignals.js b/server/services/characterSignals.js
index 2847007762..5f82ee5453 100644
--- a/server/services/characterSignals.js
+++ b/server/services/characterSignals.js
@@ -4,7 +4,7 @@
* ONE read per domain stat, shared by every surface `getCharacter()` derives on read.
*
* The Character sheet now derives two things from the same domain stats: the per-domain
- * `skills` (#2674) and the `metrics` grid (#2676). Six of the nine signals below feed BOTH —
+ * `skills` (#2674) and the `metrics` grid (#2676). Most of the signals below feed BOTH —
* Wordsmith and `recordsCreated` are the same three reads, Mentalist and `postStreakDays` are
* the same two, and so on. Letting each registry call the getters itself would have doubled
* the fan-out of a route the CyberCity HUD polls every 15s, so the reads moved here and both
@@ -42,16 +42,18 @@ import { getLoggingStats } from './meatspaceLoggingStats.js';
import { getGoals } from './identity/goals.js';
import { countMemories } from './memoryBackend.js';
import { countAssets } from './mediaAssetIndex/db.js';
-import { userLocalToday } from '../lib/timezone.js';
+import { getUserTimezone, userLocalToday } from '../lib/timezone.js';
/**
* Every domain stat the derived Character surfaces are allowed to read, keyed by signal id.
* Adding a signal here is the ONLY way to add a read — a registry that reaches for a getter
* directly re-opens the duplicate-read hole this module exists to close.
*
- * All nine are tallies or already-aggregated summaries, never listings: `countUniverses` /
+ * These are tallies or already-aggregated summaries, never listings: `countUniverses` /
* `countWorks` / `countMemories` / `countAssets` are `COUNT(*)`s (#2729), so no consumer can
- * accidentally materialize every record just to read a `.length`.
+ * accidentally materialize every record just to read a `.length`. `loggingStats`'
+ * `activeDayKeys` is the one bounded exception — a de-duplicated day key per ACTIVE DAY, not
+ * per record — because a day-set union has no aggregate form (#4120).
*
* The file-backed readers pass `{ strict: true }` — see the header. Keep it on any reader
* added here whose source can swallow a read error, or the signal silently becomes a lie
@@ -68,7 +70,16 @@ export const SIGNAL_READERS = {
// instead would let the Character sheet's POST streak disagree with the Progress page's by
// a day for any user whose configured timezone isn't the server's.
postToday: () => userLocalToday(),
- loggingStats: () => getLoggingStats({ strict: true }),
+ // The user's IANA timezone itself, for consumers that must re-key a stored INSTANT to the
+ // user's day rather than just compare against today (`daysActive` — see
+ // `server/lib/activeDays.js`). Same settings read `postToday` bottoms out in, so keeping it
+ // as its own signal costs one extra `getSettings()` per request and keeps the day-boundary
+ // decision in ONE place instead of forking a second "which day is this?" implementation.
+ userTimezone: () => getUserTimezone(),
+ // `withActiveDayKeys` (#4120): the raw union of stored health-log day keys, which the
+ // cross-domain `daysActive` metric unions with POST's days. Opt-in at the service so the
+ // polled dashboard endpoint doesn't ship an ever-growing key list it never reads.
+ loggingStats: () => getLoggingStats({ strict: true, withActiveDayKeys: true }),
goals: () => getGoals({ strict: true }),
memoryCount: () => countMemories({}),
assetCount: () => countAssets(),
diff --git a/server/services/characterSignals.test.js b/server/services/characterSignals.test.js
index 66e83a329f..57dd8d67c4 100644
--- a/server/services/characterSignals.test.js
+++ b/server/services/characterSignals.test.js
@@ -21,7 +21,13 @@ vi.mock('./memoryBackend.js', () => ({
countMemories: vi.fn(async () => { calls.memories += 1; return 42; }),
}));
vi.mock('./mediaAssetIndex/db.js', () => ({ countAssets: vi.fn(async () => 7) }));
-vi.mock('../lib/timezone.js', () => ({ userLocalToday: vi.fn(async () => '2026-07-17') }));
+// PARTIAL mock — only the settings-backed reads are stubbed, so the pure `todayInTimezone`
+// that `lib/activeDays.js` derives day keys through stays real.
+vi.mock('../lib/timezone.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ userLocalToday: vi.fn(async () => '2026-07-17'),
+ getUserTimezone: vi.fn(async () => 'America/Los_Angeles'),
+}));
import { createSignalContext, SIGNAL_READERS } from './characterSignals.js';
import { countUniverses } from './universeBuilder.js';
@@ -45,7 +51,8 @@ describe('the signal registry', () => {
// → the consumer classifies it `unavailable` → the tile lies about the domain being down).
expect(Object.keys(SIGNAL_READERS).sort()).toEqual([
'assetCount', 'catalogStats', 'goals', 'loggingStats', 'memoryCount',
- 'postSessions', 'postToday', 'postTraining', 'universeCount', 'workCount',
+ 'postSessions', 'postToday', 'postTraining', 'universeCount', 'userTimezone',
+ 'workCount',
]);
});
diff --git a/server/services/meatspaceLoggingStats.js b/server/services/meatspaceLoggingStats.js
index caad97d721..4a91f356fc 100644
--- a/server/services/meatspaceLoggingStats.js
+++ b/server/services/meatspaceLoggingStats.js
@@ -72,8 +72,20 @@ function calculateLongestStreak(loggedDates) {
}
/**
- * @param {{ strict?: boolean }} [options] - `strict: true` propagates a domain's read
- * failure instead of substituting an empty entry list for it (#2726).
+ * @param {{ strict?: boolean, withActiveDayKeys?: boolean }} [options]
+ *
+ * `withActiveDayKeys: true` additionally returns `activeDayKeys` — the sorted union of every
+ * stored day key across the five domains, i.e. the raw `loggedDates` set the aggregates below
+ * are derived from. Opt-in rather than always-on because `GET /api/meatspace/logging-stats`
+ * ships this whole object to a dashboard widget that polls it, and the key list grows without
+ * bound with install age; the only caller that needs the raw days is the Character sheet's
+ * cross-domain `daysActive` tile, which must UNION them with POST's days rather than sum two
+ * per-domain counts (#4120). The keys are returned AS STORED (server-local `getDateString()`
+ * day labels) — see `server/lib/activeDays.js` for the day-boundary reconciliation the union
+ * applies on read.
+ *
+ * `strict: true` propagates a domain's read failure instead of substituting an empty entry
+ * list for it (#2726).
*
* The default per-domain `.catch(() => [])` is right for the dashboard widget: one
* unreadable file shouldn't blank the whole streak card. It is wrong for anything
@@ -82,7 +94,7 @@ function calculateLongestStreak(loggedDates) {
* rather than "we could not tell". Under strict the first failure rejects, and the
* caller renders that as explicitly unavailable.
*/
-export async function getLoggingStats({ strict = false } = {}) {
+export async function getLoggingStats({ strict = false, withActiveDayKeys = false } = {}) {
const loadEntries = async (d) => {
if (!strict) return (await d.load().catch(() => [])) || [];
const entries = await d.load({ strict: true });
@@ -148,5 +160,9 @@ export async function getLoggingStats({ strict = false } = {}) {
totalLogged,
domains,
last7Days,
+ // Sorted so the array is stable and diffable; a Set would not survive the JSON round-trip
+ // this object takes through the route. Absent (not `[]`) when the caller did not ask —
+ // "you did not request the day keys" must stay distinguishable from "there are none".
+ ...(withActiveDayKeys ? { activeDayKeys: [...loggedDates].sort() } : {}),
};
}
diff --git a/server/services/meatspaceLoggingStats.test.js b/server/services/meatspaceLoggingStats.test.js
index b3558820a8..63a5a49a4f 100644
--- a/server/services/meatspaceLoggingStats.test.js
+++ b/server/services/meatspaceLoggingStats.test.js
@@ -97,6 +97,33 @@ describe('getLoggingStats', () => {
expect(stats.currentStreak).toBe(1);
});
+ describe('activeDayKeys (#4120)', () => {
+ it('omits the key list unless the caller asks for it', async () => {
+ // The dashboard widget polls GET /api/meatspace/logging-stats and never reads the raw
+ // days; shipping an ever-growing key list to it would be pure payload bloat.
+ mockWorkouts.mockResolvedValue([{ date: daysAgo(0) }]);
+ expect('activeDayKeys' in (await getLoggingStats())).toBe(false);
+ });
+
+ it('returns the sorted union of stored day keys across domains', async () => {
+ // Same day in two domains contributes ONE key — the union the daysActive tile needs.
+ mockAlcohol.mockResolvedValue([{ date: '2026-03-14' }, { date: '2026-03-12' }]);
+ mockNicotine.mockResolvedValue([{ date: '2026-03-14' }]);
+ mockWorkouts.mockResolvedValue([{ date: '2026-03-13' }]);
+
+ const stats = await getLoggingStats({ withActiveDayKeys: true });
+ expect(stats.activeDayKeys).toEqual(['2026-03-12', '2026-03-13', '2026-03-14']);
+ // ...while totalLogged still counts RECORDS, so the two readings stay distinct.
+ expect(stats.totalLogged).toBe(4);
+ });
+
+ it('returns an empty array — not a missing key — on a fresh install', async () => {
+ // Present-but-empty must stay distinguishable from "you did not ask", so a consumer can
+ // tell "no activity yet" from "this shape predates the flag".
+ expect((await getLoggingStats({ withActiveDayKeys: true })).activeDayKeys).toEqual([]);
+ });
+ });
+
it('survives a domain getter that rejects', async () => {
mockBody.mockRejectedValue(new Error('disk gone'));
mockWorkouts.mockResolvedValue([{ date: daysAgo(0) }]);