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: add a Character metrics grid derived from the existing domain stats (#2676)

[._.]/ Adam Eivy46df4649f7f6
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 27d118ba8d..b72c25ebe0 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -53,6 +53,7 @@
- `[issue-2673]` **Your Character level is now your age.** The Character's level is reframed as life experience — `level = floor(age in years)`, derived on read from your canonical birth date instead of being ground out of XP thresholds (JIRA tickets + CoS tasks). XP survives as a cumulative stat but no longer drives level, and the CyberCity HUD badge now shows the age-based level with a progress bar toward your next birthday (a friendly "set birth date" prompt when no birth date is set yet). Existing character records keep loading unchanged, and the derived level is excluded from cross-machine sync so peers never fight over a stale value.
- `[issue-2729]` The Character page loads faster the more you've written. Your Wordsmith skill used to be scored by loading every universe you own (plus their entire render history) and rebuilding every Writers Room work with all its drafts, just to count them — so the page got slower with each world and story you added. It now counts them directly in the database, leaving the score itself unchanged.
+- `[issue-2676]` **Your Character sheet now shows a Metrics grid of your real activity.** Six tiles — POST practice streak, health-logging streak, records created, memories captured, media rendered, and goal follow-through — read straight off the stats each domain already keeps, so the sheet reads like a profile of what you actually do rather than a dice game. They're derived fresh on every page load (never stored, never synced between your machines, and no new activity tracking was added), and they cost nothing extra: the tiles share the same reads that already score your skills. A stat that can't be read says "Unavailable" and a goal follow-through with nothing resolved yet says so plainly — neither is ever passed off as a zero.
## Creative Commissions
diff --git a/PLAN.md b/PLAN.md
index 4042397ee9..90b3df87ed 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -181,6 +181,10 @@ by `/do:replan --issues`:
- [ ] **Handle `agy` + non-empty `extraArgs` so the prompt stays the LAST argv token.** `agy --print` takes the prompt as its VALUE, so `ensureAntigravityPrintArgs` puts `--print` last and `prepareAntigravityPrompt` (via `prepareCliPrompt`, `server/lib/antigravity.js` / `server/lib/cliProviderArgs.js`) splices the prompt right after it. But `cliProviderRun.js` builds `[...buildCliArgs(provider), ...extraArgs]`, so for an antigravity provider with a non-empty `extraArgs` the delivered argv becomes `… --print "<PROMPT>" <extraArg…>` — the prompt is still `--print`'s value (correct), but any trailing extraArgs become positional args agy may reject. Low risk today (no caller passes `extraArgs` for an antigravity provider), but if one is added, either strip/relocate the trailing `--print` marker so extraArgs precede it, or have `prepareAntigravityPrompt` move `--print <prompt>` to the very end after splicing. Deferred from the agy prompt-delivery fix — the shipped paths (CD plan via runner/direct, Run Prompt, ask, vision) pass no extraArgs and are validated end-to-end.
+### Character metrics follow-ups (#2676)
+
+- [ ] **Add a cross-domain `daysActive` metric (distinct days with ANY logged activity).** #2676's issue listed `daysActive` among the example tiles; it shipped the other five plus `goalCompletionRate` and deliberately skipped this one. The blocker is that a truthful "days active" is a UNION of per-day date sets across domains, and no existing getter exposes the raw sets: `server/services/meatspaceLoggingStats.js` builds a `loggedDates` Set internally (line ~85) but only returns aggregates off it (`currentStreak`/`longestStreak`/`weekTotal`/`totalLogged`/`last7Days`), and POST's day keys live in `getPostSessions()`/`getAllTrainingEntries()` records. Summing per-domain counts would double-count any day the user logged in two domains, and a POST-only reading would be misleading enough to be worse than omitting the tile. Fix shape: expose the day-key set (or a `activeDayKeys` array) from `getLoggingStats()` additively, add it to `SIGNAL_READERS` in `server/services/characterSignals.js`, then union it with the POST record days in a new `characterMetrics.js` entry — note the two domains currently derive "today" differently (POST uses `userLocalToday()`; logging stats use the server-local `getDateString()`), so the union needs one day boundary picked deliberately before it means anything. Deferred from #2676 because it's the only tile requiring a change to a shared cross-feature getter plus a day-boundary reconciliation, and the six shipped tiles satisfy the acceptance criteria on their own.
+
### CoS stat-card follow-ups
- [ ] **Retire or wire up `StatCard`'s never-passed `activeLabel` prop, and de-dup the two hand-rolled Learning cards.** `activeLabel` (`client/src/components/cos/StatCard.jsx:1`) has **zero callers** across the client — no `activeLabel=` usage and no spread props into `<StatCard>`. It is *visually* rendered only by the default variant (:59-63); the `compact` (:4-22) and `mini` (:24-42) variants honor it only through the `ariaLabel` interpolation at :2 (consumed via `aria-label` at :8 / :28) — i.e. it reaches the accessible name but is never displayed. So it is not fully inert: deleting it changes the accname on two variants. Either delete the prop + its render branch + the `ariaLabel` clause together, or make compact/mini render it. Related: the two Learning cards (`client/src/pages/ChiefOfStaff.jsx` ~512-540 compact, ~836-862 ascii `mini`) are hand-rolled buttons rather than `StatCard`s precisely because StatCard supports neither `onClick` nor a status-driven border color nor a visible sub-label on the compact variant — and each duplicates the same `status === 'critical' ? … : 'warning' ? …` color ternary twice (once for the border, once for the icon). Wiring a visible sub-label slot through all variants plus `onClick`/border-tone props would let both collapse onto StatCard. Deferred from the mobile-overflow fix (which only restructured the compact card's value/label stacking): removing or re-speccing a prop on a shared component used by every CoS stat card is a distinct refactor deserving its own PR + tests, and the overflow fix must not ride on it.
diff --git a/client/src/hooks/useCityData.js b/client/src/hooks/useCityData.js
index ffa8b1688d..76a2cc48cc 100644
--- a/client/src/hooks/useCityData.js
+++ b/client/src/hooks/useCityData.js
@@ -69,8 +69,8 @@ export const useCityData = () => {
api.getCosTasks({ silent: true }).catch(() => ({ tasks: [] })),
api.getLatestHealthMetrics(HEALTH_METRIC_KEYS, { silent: true }).catch(() => null),
api.getVoiceStatus({ silent: true }).catch(() => null),
- // `skills: false` — the city only renders the level (see fetchCharacter).
- api.getCharacter({ silent: true, skills: false }).catch(() => null),
+ // `skills`/`metrics: false` — the city only renders the level (see fetchCharacter).
+ api.getCharacter({ silent: true, skills: false, metrics: false }).catch(() => null),
]);
setApps(appsData);
@@ -120,9 +120,9 @@ export const useCityData = () => {
// periodic poll. The Xp badge diffs successive snapshots to fire its burst.
// Preserve last-good character on a transient blip (don't wipe to null).
const fetchCharacter = useCallback(async () => {
- // The HUD badge renders only the level, and this polls every 15s — `skills: false` skips
- // the server's six-domain stat fan-out that nothing here reads.
- const next = await api.getCharacter({ silent: true, skills: false }).catch(() => null);
+ // The HUD badge renders only the level, and this polls every 15s — `skills`/`metrics:
+ // false` skip the server's domain stat fan-outs that nothing here reads.
+ const next = await api.getCharacter({ silent: true, skills: false, metrics: false }).catch(() => null);
if (next) setCharacter(next);
}, []);
diff --git a/client/src/pages/CharacterSheet.jsx b/client/src/pages/CharacterSheet.jsx
index bbf8526d0d..590c2dbe43 100644
--- a/client/src/pages/CharacterSheet.jsx
+++ b/client/src/pages/CharacterSheet.jsx
@@ -1,11 +1,11 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import {
Sword, Star, Moon, ScrollText, Shield, Heart,
- Sparkles, RefreshCw, Dices, X, ChevronDown, Zap, Image
+ Sparkles, RefreshCw, Dices, X, ChevronDown, Zap, Image, Activity
} from 'lucide-react';
import BrailleSpinner from '../components/BrailleSpinner';
import toast from '../components/ui/Toast';
-import { timeAgo } from '../utils/formatters';
+import { timeAgo, formatCompactCount } from '../utils/formatters';
import api, { generateAvatar } from '../services/api';
import socket from '../services/socket';
import { clickableProps } from '../lib/a11yKeyboard.js';
@@ -53,10 +53,10 @@ function SkillsCard({ skills }) {
if (!skills?.length) return null;
return (
- <div className="bg-port-card border border-port-border rounded-xl p-4">
+ <section aria-labelledby="character-skills-heading" className="bg-port-card border border-port-border rounded-xl p-4">
<div className="flex items-center gap-1.5 mb-3">
<Zap className="w-4 h-4 text-port-accent-2" />
- <h2 className="text-sm font-medium text-gray-300">Skills</h2>
+ <h2 id="character-skills-heading" className="text-sm font-medium text-gray-300">Skills</h2>
<span className="text-xs text-gray-500">— earned by using PortOS</span>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
@@ -76,7 +76,70 @@ function SkillsCard({ skills }) {
</div>
))}
</div>
- </div>
+ </section>
+ );
+}
+
+// Render one metric's value per its server-declared `unit`. Counts go through the shared
+// formatCompactCount so a 12,400-memory Brain reads "12.4K" instead of overflowing the tile.
+// Only called for tiles with a real numeric value — the null states are handled by the caller.
+//
+// Deliberately page-local rather than hoisted into utils/formatters.js: it defines no new
+// number formatting (it dispatches to the shared formatter), and it is coupled to the metric
+// payload shape that characterMetrics.js owns — so it belongs with the card that renders it,
+// which Slice 5 (#2677) will restyle or relocate wholesale. Exported only for its unit test.
+export function formatMetricValue({ unit, value }) {
+ if (unit === 'percent') return `${value}%`;
+ if (unit === 'days') return `${formatCompactCount(value)}d`;
+ return formatCompactCount(value);
+}
+
+// Engagement metrics derived on read from the same domain signals that power the skills
+// (#2676). Like SkillsCard this is deliberately a plain read-only card — Slice 5 (#2677) owns
+// the page's framing/redesign, so it stays easy to restyle or relocate wholesale.
+//
+// THREE states per tile, never two (mirroring the server's sentinels):
+// - unavailable → "Unavailable" and an em dash. The stat could not be read.
+// - notApplicable → the metric's own emptyLabel ("No goals resolved yet"). No honest number
+// exists yet — and 0 is emphatically not it for a ratio.
+// - a real value → the number, INCLUDING a real 0.
+// Collapsing any of these into a fake 0 would re-introduce the exact lie the server's
+// sentinels exist to prevent.
+function MetricsCard({ metrics }) {
+ if (!metrics?.length) return null;
+
+ return (
+ <section aria-labelledby="character-metrics-heading" className="bg-port-card border border-port-border rounded-xl p-4">
+ <div className="flex items-center gap-1.5 mb-3">
+ <Activity className="w-4 h-4 text-port-accent" />
+ <h2 id="character-metrics-heading" className="text-sm font-medium text-gray-300">Metrics</h2>
+ <span className="text-xs text-gray-500">— your real activity</span>
+ </div>
+ <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-2">
+ {metrics.map((metric) => (
+ <div key={metric.id} className="bg-port-bg border border-port-border rounded-lg px-3 py-2">
+ <div
+ className={`text-xl font-semibold truncate ${
+ metric.unavailable || metric.notApplicable ? 'text-gray-600' : 'text-port-accent'
+ }`}
+ title={metric.unavailable ? 'This stat could not be read' : undefined}
+ >
+ {metric.unavailable || metric.notApplicable ? '—' : formatMetricValue(metric)}
+ </div>
+ <div className="text-xs text-gray-300 truncate mt-0.5" title={metric.label}>
+ {metric.label}
+ </div>
+ <div className="text-[11px] text-gray-500 mt-0.5 line-clamp-2">
+ {metric.unavailable
+ ? 'Unavailable'
+ : metric.notApplicable
+ ? (metric.emptyLabel || 'Not applicable yet')
+ : metric.hint}
+ </div>
+ </div>
+ ))}
+ </div>
+ </section>
);
}
@@ -501,6 +564,11 @@ export default function CharacterSheet() {
)}
</div>
+ {/* Metrics — real engagement stats derived from existing domain signals (#2676).
+ Sits directly under the identity card so the sheet's most concrete information is
+ above the fold. */}
+ <MetricsCard metrics={char.metrics} />
+
{/* Skills — derived per-domain from real PortOS usage (#2674) */}
<SkillsCard skills={char.skills} />
diff --git a/client/src/pages/CharacterSheet.metrics.test.jsx b/client/src/pages/CharacterSheet.metrics.test.jsx
new file mode 100644
index 0000000000..6482690ec0
--- /dev/null
+++ b/client/src/pages/CharacterSheet.metrics.test.jsx
@@ -0,0 +1,161 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { render, screen, waitFor, within } from '@testing-library/react';
+import { MemoryRouter } from 'react-router-dom';
+
+// Coverage for the Character sheet's metrics grid (#2676). The load-bearing behavior is the
+// THREE-state rendering: the server distinguishes a real value (0 included) from a stat it
+// could not read from a ratio with no denominator, and the UI must not collapse any of them
+// into a fake 0.
+
+const get = vi.fn();
+
+vi.mock('../services/api', () => ({
+ default: { get: (...a) => get(...a), post: vi.fn(), put: vi.fn() },
+ generateAvatar: vi.fn(() => Promise.resolve({})),
+}));
+
+vi.mock('../services/socket', () => ({
+ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },
+}));
+
+vi.mock('../components/ui/Toast', () => ({
+ default: { error: vi.fn(), success: vi.fn(), info: vi.fn() },
+}));
+
+import CharacterSheet, { formatMetricValue } from './CharacterSheet';
+
+const BASE_CHAR = {
+ name: 'Aragorn',
+ class: 'Ranger',
+ level: 5,
+ hp: 40,
+ maxHp: 40,
+ xp: 6500,
+ avatarPath: null,
+ events: [],
+};
+
+const metric = (overrides) => ({
+ id: 'memoryCount',
+ label: 'Memories',
+ unit: 'count',
+ hint: 'Captured in Brain',
+ value: 42,
+ unavailable: false,
+ notApplicable: false,
+ ...overrides,
+});
+
+// Assertions are scoped to the metrics region rather than the whole page: the sheet renders
+// other numbers (HP, XP, the birthday-progress "0%") that would otherwise satisfy a
+// page-wide query and let a broken tile pass.
+const renderWithMetrics = async (metrics) => {
+ get.mockResolvedValue({ ...BASE_CHAR, metrics });
+ render(
+ <MemoryRouter>
+ <CharacterSheet />
+ </MemoryRouter>,
+ );
+ await waitFor(() => expect(screen.getByText('Aragorn')).toBeInTheDocument());
+ const region = screen.queryByRole('region', { name: 'Metrics' });
+ return region ? within(region) : null;
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('formatMetricValue', () => {
+ it('renders each unit in its own shape', () => {
+ expect(formatMetricValue({ unit: 'count', value: 42 })).toBe('42');
+ expect(formatMetricValue({ unit: 'days', value: 12 })).toBe('12d');
+ expect(formatMetricValue({ unit: 'percent', value: 75 })).toBe('75%');
+ });
+
+ it('abbreviates a large count through the shared formatter rather than overflowing the tile', () => {
+ expect(formatMetricValue({ unit: 'count', value: 12400 })).toBe('12.4K');
+ expect(formatMetricValue({ unit: 'count', value: 3400000 })).toBe('3.4M');
+ });
+
+ it('renders a real 0 as "0", never as a dash', () => {
+ // The dash is reserved for the two null states; a genuine zero is a real answer.
+ expect(formatMetricValue({ unit: 'count', value: 0 })).toBe('0');
+ expect(formatMetricValue({ unit: 'percent', value: 0 })).toBe('0%');
+ expect(formatMetricValue({ unit: 'days', value: 0 })).toBe('0d');
+ });
+});
+
+describe('MetricsCard rendering', () => {
+ it('renders a tile per metric with its value, label and hint', async () => {
+ const grid = await renderWithMetrics([
+ metric(),
+ metric({ id: 'postStreakDays', label: 'POST Streak', unit: 'days', value: 4, hint: 'Consecutive days of POST practice' }),
+ ]);
+
+ expect(grid.getByText('42')).toBeInTheDocument();
+ expect(grid.getByText('Memories')).toBeInTheDocument();
+ expect(grid.getByText('Captured in Brain')).toBeInTheDocument();
+ expect(grid.getByText('4d')).toBeInTheDocument();
+ expect(grid.getByText('POST Streak')).toBeInTheDocument();
+ });
+
+ it('renders a real 0 as 0 — NOT as unavailable', async () => {
+ const grid = await renderWithMetrics([metric({ value: 0 })]);
+ expect(grid.getByText('0')).toBeInTheDocument();
+ expect(grid.queryByText('Unavailable')).not.toBeInTheDocument();
+ expect(grid.queryByText('—')).not.toBeInTheDocument();
+ });
+
+ it('renders an unavailable stat as an explicit unavailable state, never a fake 0', async () => {
+ // The whole point of the server's sentinel: "we could not read this" must not read as
+ // "you have never done this".
+ const grid = await renderWithMetrics([metric({ value: null, unavailable: true })]);
+
+ expect(grid.getByText('Unavailable')).toBeInTheDocument();
+ expect(grid.getByText('—')).toBeInTheDocument();
+ expect(grid.queryByText('0')).not.toBeInTheDocument();
+ // The tile still names the metric, so the user knows WHAT is unavailable.
+ expect(grid.getByText('Memories')).toBeInTheDocument();
+ });
+
+ it('renders a not-applicable ratio with its own emptyLabel, not 0% and not "Unavailable"', async () => {
+ const grid = await renderWithMetrics([
+ metric({
+ id: 'goalCompletionRate', label: 'Goal Follow-Through', unit: 'percent',
+ value: null, notApplicable: true, emptyLabel: 'No goals resolved yet',
+ }),
+ ]);
+
+ expect(grid.getByText('No goals resolved yet')).toBeInTheDocument();
+ expect(grid.getByText('—')).toBeInTheDocument();
+ expect(grid.queryByText('0%')).not.toBeInTheDocument();
+ // Distinct from the unavailable state — the two say different things.
+ expect(grid.queryByText('Unavailable')).not.toBeInTheDocument();
+ });
+
+ it('falls back to a generic label when a not-applicable metric ships no emptyLabel', async () => {
+ const grid = await renderWithMetrics([metric({ value: null, notApplicable: true, emptyLabel: null })]);
+ expect(grid.getByText('Not applicable yet')).toBeInTheDocument();
+ });
+
+ it('renders the healthy tiles when only SOME stats are unavailable', async () => {
+ // One unreachable domain must not take the grid down with it.
+ const grid = await renderWithMetrics([
+ metric({ value: null, unavailable: true }),
+ metric({ id: 'mediaRendered', label: 'Media Rendered', value: 31, hint: 'Images & videos in the media index' }),
+ ]);
+
+ expect(grid.getByText('Unavailable')).toBeInTheDocument();
+ expect(grid.getByText('31')).toBeInTheDocument();
+ });
+
+ it('hides the card entirely when the server omitted metrics (?metrics=0)', async () => {
+ // Absent means "not computed" — rendering an empty grid would imply it was computed and
+ // came back empty.
+ expect(await renderWithMetrics(undefined)).toBeNull();
+ });
+
+ it('hides the card when the server returned an empty metrics array', async () => {
+ expect(await renderWithMetrics([])).toBeNull();
+ });
+});
diff --git a/client/src/services/apiSystem.js b/client/src/services/apiSystem.js
index f81bc5fb34..be5a75570a 100644
--- a/client/src/services/apiSystem.js
+++ b/client/src/services/apiSystem.js
@@ -3,11 +3,15 @@ import { request } from './apiCore.js';
// Alerts
export const getAlertsSummary = (options) => request('/alerts/summary', options);
-// Character sheet (age-based level / XP / HP / usage-derived skills).
-// `skills: false` skips the server's six-domain skill fan-out — pass it from callers that
-// only read the persisted fields or the level (e.g. the polling CyberCity XP HUD badge).
-export const getCharacter = ({ skills = true, ...options } = {}) =>
- request(`/character${skills ? '' : '?skills=0'}`, options);
+// Character sheet (age-based level / XP / HP / usage-derived skills + metrics grid).
+// `skills: false` / `metrics: false` skip the server's domain stat fan-out for each derived
+// registry — pass them from callers that only read the persisted fields or the level (e.g.
+// the polling CyberCity XP HUD badge). Both default on, so a caller that wants the whole
+// sheet just calls getCharacter().
+export const getCharacter = ({ skills = true, metrics = true, ...options } = {}) => {
+ const off = [!skills && 'skills=0', !metrics && 'metrics=0'].filter(Boolean);
+ return request(`/character${off.length ? `?${off.join('&')}` : ''}`, options);
+};
// Health
export const checkHealth = (options) => request('/system/health', options);
diff --git a/server/routes/character.js b/server/routes/character.js
index 1d1ddd092c..36837b45ab 100644
--- a/server/routes/character.js
+++ b/server/routes/character.js
@@ -2,8 +2,9 @@
* Character Sheet Routes
*
* `GET /` returns the persisted record plus the fields derived on read: the
- * age-based `level`/`ageYears` (#2673) and the per-domain `skills` (#2674).
- * The XP/HP/damage/rest/event endpoints are retained for backward-compat.
+ * age-based `level`/`ageYears` (#2673), the per-domain `skills` (#2674), and the
+ * `metrics` grid (#2676). The XP/HP/damage/rest/event endpoints are retained for
+ * backward-compat.
*/
import { Router } from 'express';
@@ -42,19 +43,27 @@ const addEventSchema = z.object({
diceNotation: z.string().regex(/^\d+d\d+([+-]\d+)?$/).optional()
});
-// `?skills=0` opts out of the six-domain skill fan-out for consumers that only read the
-// persisted fields plus the age level — notably the CyberCity HUD, which polls this route
-// every 15s and renders only `level`. Defaults to including them, so an unaware caller
-// (or an older client bundle) still gets the full sheet.
+// `?skills=0` / `?metrics=0` opt out of each derived registry's domain fan-out, for consumers
+// that only read the persisted fields plus the age level — notably the CyberCity HUD, which
+// polls this route every 15s and renders only `level`. They gate independently (a caller may
+// well want the metrics grid without the skill curve), and both default to ON so an unaware
+// caller — or an older client bundle that predates the flag — still gets the full sheet.
+const flagEnum = z.enum(['0', '1', 'false', 'true']).optional();
const getCharacterQuerySchema = z.object({
- skills: z.enum(['0', '1', 'false', 'true']).optional(),
+ skills: flagEnum,
+ metrics: flagEnum,
});
+// A flag is on unless explicitly switched off. Absent ⇒ on (see the default-ON note above).
+const isEnabled = (flag) => flag !== '0' && flag !== 'false';
+
// GET /api/character - Get character sheet
router.get('/', asyncHandler(async (req, res) => {
- const { skills } = validateRequest(getCharacterQuerySchema, req.query);
- const withSkills = skills !== '0' && skills !== 'false';
- res.json(await characterService.getCharacter({ withSkills }));
+ const { skills, metrics } = validateRequest(getCharacterQuerySchema, req.query);
+ res.json(await characterService.getCharacter({
+ withSkills: isEnabled(skills),
+ withMetrics: isEnabled(metrics),
+ }));
}));
// PUT /api/character - Update character name/class
diff --git a/server/routes/character.test.js b/server/routes/character.test.js
index 56636de7d6..be729b81d5 100644
--- a/server/routes/character.test.js
+++ b/server/routes/character.test.js
@@ -34,10 +34,10 @@ beforeEach(() => {
});
describe('GET /api/character', () => {
- it('includes skills by default', async () => {
+ it('includes skills and metrics by default', async () => {
const res = await request(makeApp()).get('/api/character');
expect(res.status).toBe(200);
- expect(characterService.getCharacter).toHaveBeenCalledWith({ withSkills: true });
+ expect(characterService.getCharacter).toHaveBeenCalledWith({ withSkills: true, withMetrics: true });
});
it('skips the skill fan-out for ?skills=0 and ?skills=false', async () => {
@@ -45,22 +45,39 @@ describe('GET /api/character', () => {
vi.clearAllMocks();
const res = await request(makeApp()).get(`/api/character?skills=${value}`);
expect(res.status).toBe(200);
- expect(characterService.getCharacter).toHaveBeenCalledWith({ withSkills: false });
+ expect(characterService.getCharacter).toHaveBeenCalledWith({ withSkills: false, withMetrics: true });
}
});
- it('keeps skills for an explicit opt-in', async () => {
+ it('skips the metrics fan-out for ?metrics=0 and ?metrics=false', async () => {
+ for (const value of ['0', 'false']) {
+ vi.clearAllMocks();
+ const res = await request(makeApp()).get(`/api/character?metrics=${value}`);
+ expect(res.status).toBe(200);
+ expect(characterService.getCharacter).toHaveBeenCalledWith({ withSkills: true, withMetrics: false });
+ }
+ });
+
+ it('gates the two fan-outs independently', async () => {
+ await request(makeApp()).get('/api/character?skills=0&metrics=0');
+ expect(characterService.getCharacter).toHaveBeenCalledWith({ withSkills: false, withMetrics: false });
+ });
+
+ it('keeps skills and metrics for an explicit opt-in', async () => {
for (const value of ['1', 'true']) {
vi.clearAllMocks();
- await request(makeApp()).get(`/api/character?skills=${value}`);
- expect(characterService.getCharacter).toHaveBeenCalledWith({ withSkills: true });
+ await request(makeApp()).get(`/api/character?skills=${value}&metrics=${value}`);
+ expect(characterService.getCharacter).toHaveBeenCalledWith({ withSkills: true, withMetrics: true });
}
});
- it('rejects a nonsense skills value rather than silently including them', async () => {
- const res = await request(makeApp()).get('/api/character?skills=maybe');
- expect(res.status).toBe(400);
- expect(characterService.getCharacter).not.toHaveBeenCalled();
+ it('rejects a nonsense skills or metrics value rather than silently including them', async () => {
+ for (const query of ['skills=maybe', 'metrics=maybe']) {
+ vi.clearAllMocks();
+ const res = await request(makeApp()).get(`/api/character?${query}`);
+ expect(res.status).toBe(400);
+ expect(characterService.getCharacter).not.toHaveBeenCalled();
+ }
});
});
diff --git a/server/services/askService.js b/server/services/askService.js
index 22e7738b81..f43d392c1a 100644
--- a/server/services/askService.js
+++ b/server/services/askService.js
@@ -360,8 +360,9 @@ const MODE_DIRECTIVES = {
};
export async function buildPersonaPreamble() {
- // Only name/class are read below, so skip the skill fan-out — this runs per /ask question.
- const character = await getCharacter({ withSkills: false }).catch(() => null);
+ // Only name/class are read below, so skip both derived fan-outs — this runs per /ask
+ // question.
+ const character = await getCharacter({ withSkills: false, withMetrics: false }).catch(() => null);
// The character sheet is the closest thing to a persona surface today.
// Autobiography stories carry the voice; we sample the most recent one
// separately in the source pipeline. Keep this preamble small.
diff --git a/server/services/character.js b/server/services/character.js
index 381c8a3f30..b786ee4bfc 100644
--- a/server/services/character.js
+++ b/server/services/character.js
@@ -7,8 +7,10 @@
* drives level. HP/damage/rest mechanics are retained for backward-compat with a
* flat maxHp (no longer scaled off level).
*
- * `skills` are likewise derived on read, from each domain's existing stats
- * (see `characterSkills.js`, #2674).
+ * `skills` (see `characterSkills.js`, #2674) and the `metrics` grid (see
+ * `characterMetrics.js`, #2676) are likewise derived on read, from each domain's existing
+ * stats — both over ONE shared signal context (`characterSignals.js`) so the signals they
+ * have in common are read once per request, not once per registry.
*/
import crypto from 'crypto';
@@ -18,6 +20,8 @@ import * as jiraService from './jira.js';
import * as cosService from './cos.js';
import { getBirthDate } from './meatspace.js';
import { getCharacterSkills } from './characterSkills.js';
+import { getCharacterMetrics } from './characterMetrics.js';
+import { createSignalContext } from './characterSignals.js';
const CHARACTER_FILE = path.join(PATHS.data, 'character.json');
@@ -27,8 +31,9 @@ const DEFAULT_MAX_HP = 15;
// Derived fields getCharacter() attaches on read; they are stripped before persisting so a
// stale age-level (or a per-machine usage-derived skill set) never lands on disk or in the
-// federated snapshot. `skills` is per-machine by design — see characterSkills.js (#2674).
-const DERIVED_FIELDS = ['level', 'ageYears', 'skills'];
+// federated snapshot. `skills` (#2674) and `metrics` (#2676) are per-machine by design — see
+// characterSkills.js / characterMetrics.js.
+const DERIVED_FIELDS = ['level', 'ageYears', 'skills', 'metrics'];
/**
* Copy `record` without any derived field. The single chokepoint for that rule — used by the
@@ -137,24 +142,34 @@ async function loadRawCharacter() {
}
// Attach the derived read-only fields to a raw record: `ageYears`/`level` from the canonical
-// birthDate (#2673), and the per-domain `skills` from each domain's existing stats (#2674).
-// `level` is null when no birthDate is set, so callers can render a "set your birth date"
-// prompt. Neither is ever persisted — see DERIVED_FIELDS / saveCharacter.
-// `withSkills: false` skips the skill fan-out (six domain stat reads) for callers that only
-// want the persisted fields plus the age level — deriving skills nobody reads is pure waste.
-// Skipping OMITS the key rather than setting it to [] or null: an absent `skills` means "not
-// computed", which must not be confused with "computed, and every domain is empty".
-async function enrichCharacter(raw, { withSkills = true } = {}) {
- const [{ birthDate }, skills] = await Promise.all([
+// birthDate (#2673), the per-domain `skills` (#2674), and the `metrics` grid (#2676) — the
+// latter two from each domain's existing stats. `level` is null when no birthDate is set, so
+// callers can render a "set your birth date" prompt. None are ever persisted — see
+// DERIVED_FIELDS / saveCharacter.
+//
+// `withSkills` / `withMetrics: false` skip their registry's fan-out for callers that only
+// want the persisted fields plus the age level (the CyberCity HUD, askService, city
+// snapshots) — deriving stats nobody reads is pure waste. ONE signal context is shared by
+// both registries, so the signals they have in common cost a single read even with both on.
+//
+// Skipping OMITS the key rather than setting it to [] or null: an absent `skills`/`metrics`
+// means "not computed", which must not be confused with "computed, and every domain is
+// empty".
+async function enrichCharacter(raw, { withSkills = true, withMetrics = true } = {}) {
+ const read = withSkills || withMetrics ? createSignalContext() : null;
+ const [{ birthDate }, skills, metrics] = await Promise.all([
getBirthDate().catch(() => ({ birthDate: null })),
- withSkills ? getCharacterSkills() : Promise.resolve(undefined),
+ withSkills ? getCharacterSkills(read) : Promise.resolve(undefined),
+ withMetrics ? getCharacterMetrics(read) : Promise.resolve(undefined),
]);
const ageYears = ageYearsFromBirthDate(birthDate);
const enriched = { ...raw, ageYears, level: levelFromAge(ageYears) };
- // Drop any stale persisted key when skills weren't computed, so a hand-edited
- // character.json can't pass its own `skills` off as freshly derived.
+ // Drop any stale persisted key when a registry wasn't computed, so a hand-edited
+ // character.json can't pass its own `skills`/`metrics` off as freshly derived.
if (withSkills) enriched.skills = skills;
else delete enriched.skills;
+ if (withMetrics) enriched.metrics = metrics;
+ else delete enriched.metrics;
return enriched;
}
@@ -187,8 +202,9 @@ export async function getWireCharacter() {
if (!raw) return null;
// Strip every derived field a hand-edited or legacy character.json might be carrying before
// it goes out on the wire: `level` is then re-added below as the legacy xp-derived value,
- // but `skills`/`ageYears` must never federate at all (skills are per-machine — see
- // characterSkills.js — and ageYears is a pure function of the peer's own birthDate). Without
+ // but `skills`/`metrics`/`ageYears` must never federate at all (skills and metrics are
+ // per-machine — see characterSkills.js / characterMetrics.js — and ageYears is a pure
+ // function of the peer's own birthDate). Without
// this, applyCharacterRemote's no-local branch writes the payload verbatim and a stale key
// would self-propagate across peers.
return { ...stripDerivedFields(raw), level: legacyLevelFromXp(raw.xp) };
@@ -196,9 +212,9 @@ export async function getWireCharacter() {
export async function saveCharacter(data) {
await ensureDir(PATHS.data);
- // Never persist derived fields — level is age-derived on read (#2673), skills are
- // usage-derived and per-machine (#2674). Stripping them keeps stale values off disk and out
- // of the federated character snapshot.
+ // Never persist derived fields — level is age-derived on read (#2673); skills (#2674) and
+ // metrics (#2676) are usage-derived and per-machine. Stripping them keeps stale values off
+ // disk and out of the federated character snapshot.
const persist = stripDerivedFields(data);
persist.updatedAt = new Date().toISOString();
await atomicWrite(CHARACTER_FILE, persist);
diff --git a/server/services/character.test.js b/server/services/character.test.js
index 1033fd275d..22a2633e0e 100644
--- a/server/services/character.test.js
+++ b/server/services/character.test.js
@@ -20,18 +20,29 @@ vi.mock('../lib/fileUtils.js', () => ({
}),
}));
-// character.js eagerly imports the jira/cos/meatspace/characterSkills services at module
-// load; stub them so the unit under test loads without their dependency graphs. meatspace
-// supplies the canonical birthDate that age-based level derives from (#2673). The skill
-// registry (#2674) fans out to every domain's stats and has its own suite
-// (characterSkills.test.js) — here we only care THAT its output is attached on read and
-// stripped on save, so a single sentinel skill stands in for the real six.
+// character.js eagerly imports the jira/cos/meatspace/characterSkills/characterMetrics/
+// characterSignals services at module load; stub them so the unit under test loads without
+// their dependency graphs. meatspace supplies the canonical birthDate that age-based level
+// derives from (#2673). The skill registry (#2674) and metrics grid (#2676) each fan out to
+// every domain's stats and have their own suites (characterSkills.test.js /
+// characterMetrics.test.js) — here we only care THAT their output is attached on read and
+// stripped on save, so single sentinel entries stand in for the real registries.
const FAKE_SKILLS = [{ id: 'wordsmith', label: 'Wordsmith', domain: 'create', level: 2, value: 7, unavailable: false }];
+const FAKE_METRICS = [{ id: 'recordsCreated', label: 'Records Created', unit: 'count', hint: 'x', value: 7, unavailable: false, notApplicable: false }];
+// A recognizable stand-in for the shared signal context, so the tests can assert BOTH
+// registries were handed the SAME one (the whole point of #2676's read-once contract).
+const FAKE_READ = vi.hoisted(() => vi.fn());
vi.mock('./jira.js', () => ({}));
vi.mock('./cos.js', () => ({}));
vi.mock('./characterSkills.js', () => ({
getCharacterSkills: vi.fn(async () => FAKE_SKILLS),
}));
+vi.mock('./characterMetrics.js', () => ({
+ getCharacterMetrics: vi.fn(async () => FAKE_METRICS),
+}));
+vi.mock('./characterSignals.js', () => ({
+ createSignalContext: vi.fn(() => FAKE_READ),
+}));
vi.mock('./meatspace.js', () => ({
getBirthDate: vi.fn(async () => ({ birthDate: store.birthDate })),
}));
@@ -122,7 +133,7 @@ describe('stripDerivedFields', () => {
it('removes every derived field and leaves persisted ones untouched', () => {
const stripped = characterService.stripDerivedFields({
name: 'Gandalf', xp: 5000, hp: 15, events: [],
- level: 99, ageYears: 999, skills: [{ id: 'stale' }],
+ level: 99, ageYears: 999, skills: [{ id: 'stale' }], metrics: [{ id: 'stale' }],
});
expect(stripped).toEqual({ name: 'Gandalf', xp: 5000, hp: 15, events: [] });
});
@@ -169,11 +180,12 @@ describe('getWireCharacter federation projection', () => {
expect(fresh.level).toBe(1); // 0 xp → level 1, never null
});
- it('never federates the usage-derived skills', async () => {
- // Skills are per-machine (usage differs across a user's peers), so sending them would let
+ it('never federates the usage-derived skills or metrics', async () => {
+ // Both are per-machine (usage differs across a user's peers), so sending them would let
// the least-used peer clobber the most-used one under LWW.
const wire = await characterService.getWireCharacter();
expect(wire.skills).toBeUndefined();
+ expect(wire.metrics).toBeUndefined();
});
it('strips a STALE derived field already sitting in character.json', async () => {
@@ -183,12 +195,14 @@ describe('getWireCharacter federation projection', () => {
store.value = {
...store.value,
skills: [{ id: 'stale', level: 99 }],
+ metrics: [{ id: 'stale', value: 99 }],
ageYears: 999,
level: 99,
};
const wire = await characterService.getWireCharacter();
expect(wire.skills).toBeUndefined();
+ expect(wire.metrics).toBeUndefined();
expect(wire.ageYears).toBeUndefined();
expect(wire.level).toBe(4); // re-derived from xp, NOT the stale 99
});
@@ -251,6 +265,105 @@ describe('getCharacter skills (derived on read, #2674)', () => {
});
});
+describe('getCharacter metrics (derived on read, #2676)', () => {
+ beforeEach(() => {
+ store.value = { name: 'Gandalf', class: 'Wizard', xp: 0, hp: 15, maxHp: 15, events: [] };
+ store.birthDate = null;
+ });
+
+ it('attaches the metrics registry output on read', async () => {
+ const character = await characterService.getCharacter();
+ expect(character.metrics).toEqual(FAKE_METRICS);
+ });
+
+ it('never persists metrics to character.json', async () => {
+ const character = await characterService.getCharacter();
+ expect(character.metrics).toBeDefined();
+
+ // Round-trip the enriched record straight back through save — the path a caller takes
+ // when it reads, mutates, and writes — and the derived metrics must not survive it.
+ await characterService.saveCharacter(character);
+ expect(store.value.metrics).toBeUndefined();
+ });
+
+ it('re-derives metrics on the record that save returns', async () => {
+ const saved = await characterService.saveCharacter(await characterService.getCharacter());
+ expect(saved.metrics).toEqual(FAKE_METRICS);
+ });
+
+ it('keeps a stale persisted metrics array from leaking through as truth', async () => {
+ store.value = { ...store.value, metrics: [{ id: 'stale', value: 99 }] };
+ const character = await characterService.getCharacter();
+ expect(character.metrics).toEqual(FAKE_METRICS);
+ });
+
+ it('skips the metrics fan-out entirely when withMetrics is false', async () => {
+ const { getCharacterMetrics } = await import('./characterMetrics.js');
+ vi.mocked(getCharacterMetrics).mockClear();
+
+ const character = await characterService.getCharacter({ withMetrics: false });
+
+ expect(getCharacterMetrics).not.toHaveBeenCalled();
+ // Absent, NOT [] — "not computed" must not read as "computed, every domain empty".
+ expect('metrics' in character).toBe(false);
+ expect(character.level).toBeDefined(); // the cheap age level still resolves
+ });
+
+ it('drops a stale persisted metrics key even when withMetrics is false', async () => {
+ store.value = { ...store.value, metrics: [{ id: 'stale', value: 99 }] };
+ const character = await characterService.getCharacter({ withMetrics: false });
+ expect('metrics' in character).toBe(false);
+ });
+
+ it('gates the two registries independently', async () => {
+ const { getCharacterSkills } = await import('./characterSkills.js');
+ const { getCharacterMetrics } = await import('./characterMetrics.js');
+ vi.mocked(getCharacterSkills).mockClear();
+ vi.mocked(getCharacterMetrics).mockClear();
+
+ const character = await characterService.getCharacter({ withSkills: false, withMetrics: true });
+
+ expect(getCharacterSkills).not.toHaveBeenCalled();
+ expect(getCharacterMetrics).toHaveBeenCalled();
+ expect('skills' in character).toBe(false);
+ expect(character.metrics).toEqual(FAKE_METRICS);
+ });
+});
+
+describe('shared signal context (read-once, #2676)', () => {
+ beforeEach(() => {
+ store.value = { name: 'Gandalf', class: 'Wizard', xp: 0, hp: 15, maxHp: 15, events: [] };
+ store.birthDate = null;
+ });
+
+ it('hands BOTH registries the same context, so shared signals are read once', async () => {
+ // The load-bearing assertion of #2676: six of the nine domain signals feed both the
+ // skills and the metrics. If each registry minted its own context they would each read
+ // those six, doubling the fan-out of a route the CyberCity HUD polls every 15s.
+ const { createSignalContext } = await import('./characterSignals.js');
+ const { getCharacterSkills } = await import('./characterSkills.js');
+ const { getCharacterMetrics } = await import('./characterMetrics.js');
+ vi.mocked(createSignalContext).mockClear();
+
+ await characterService.getCharacter();
+
+ expect(createSignalContext).toHaveBeenCalledTimes(1);
+ expect(getCharacterSkills).toHaveBeenCalledWith(FAKE_READ);
+ expect(getCharacterMetrics).toHaveBeenCalledWith(FAKE_READ);
+ });
+
+ it('does not mint a context at all when both registries are skipped', async () => {
+ // The cheap path (CyberCity HUD, askService, city snapshots) must stay free of any
+ // domain-signal machinery.
+ const { createSignalContext } = await import('./characterSignals.js');
+ vi.mocked(createSignalContext).mockClear();
+
+ await characterService.getCharacter({ withSkills: false, withMetrics: false });
+
+ expect(createSignalContext).not.toHaveBeenCalled();
+ });
+});
+
describe('updateCharacterFields', () => {
beforeEach(() => {
store.value = { name: 'Gandalf', class: 'Wizard', xp: 0, hp: 15, maxHp: 15, events: [] };
diff --git a/server/services/characterMetrics.js b/server/services/characterMetrics.js
new file mode 100644
index 0000000000..5a3230704c
--- /dev/null
+++ b/server/services/characterMetrics.js
@@ -0,0 +1,185 @@
+/**
+ * Character Metrics Grid (#2676, epic #2672)
+ *
+ * The "other stats" block on the Character sheet: current-value engagement tiles read off
+ * the same domain signals the skill registry (#2674) already assembles, so the sheet reads
+ * like a profile of the human's actual activity rather than a D&D pastiche.
+ *
+ * **Metrics are not skills.** Skills are *cumulative* — a level, once earned, never
+ * un-learns itself. Metrics report the CURRENT value, streaks and rates included, and are
+ * free to fall. The two are complementary readings of one signal set: `mentalist` says "you
+ * have practiced 200 times"; `postStreakDays` says "you have practiced 4 days running".
+ *
+ * **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
+ * `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.
+ *
+ * **Derived on read, never persisted, never federated.** `getCharacter()` attaches these;
+ * `saveCharacter()` strips them (`metrics` is in `character.js`'s `DERIVED_FIELDS`) and
+ * `getWireCharacter()` keeps them off the wire. Same reasoning as skills: usage differs per
+ * machine, so federating a usage-derived value under LWW would let the peer you use *least*
+ * overwrite the peer you use *most*.
+ *
+ * **Three states, never two (sentinel + validate).** A tile is one of:
+ * - a real value — `{ value: <number>, unavailable: false, notApplicable: false }`,
+ * and a real 0 is a legitimate answer ("no memories yet")
+ * - not applicable — `{ value: null, notApplicable: true }`: the metric is a ratio
+ * with an empty denominator. There is no honest number, and 0 is
+ * NOT it — "0% follow-through" is a damning claim to make about
+ * someone who has simply never resolved a goal.
+ * - unavailable — `{ value: null, unavailable: true }`: the stat could not be read.
+ * Collapsing any of these into a fake 0 is the exact lie the sentinels exist to prevent.
+ * Both non-value states are distinct SYMBOLS rather than in-band `null`s, so a getter that
+ * resolves `null` because it is broken lands in `unavailable` and cannot pass itself off as
+ * a legitimately-empty ratio.
+ *
+ * See `characterSignals.js` for the read-failure gap the file-backed signals still have
+ * (#2726) — it applies identically here, and needs no change in this module when it lands.
+ */
+
+import { computeUnifiedStreak } from '../lib/postStreak.js';
+import { createSignalContext } from './characterSignals.js';
+
+// Returned by a compute() whose ratio has an empty denominator. A unique Symbol (not null/0)
+// so it can never be mistaken for a real value a domain reported, nor for a failed read.
+export const METRIC_NOT_APPLICABLE = Symbol('metric-not-applicable');
+
+// Sentinel for a failed stat read. Mirrors characterSkills.js — same reasoning, and kept
+// module-private in both so neither can leak into a response payload.
+const STAT_UNAVAILABLE = Symbol('stat-unavailable');
+
+/**
+ * The registry. Each entry is `{ id, label, unit, hint, emptyLabel?, compute }`:
+ *
+ * - `unit` — `count` | `days` | `percent`. The client formats off this; the server
+ * never ships a pre-formatted string (formatting is the client's job —
+ * `client/src/utils/formatters.js`).
+ * - `hint` — one-line gloss of what the number actually measures, shown as the tile's
+ * sublabel. Lives here, next to the compute that defines the semantic, so
+ * the two can't drift.
+ * - `emptyLabel` — what to say when compute returns METRIC_NOT_APPLICABLE. Only a ratio
+ * metric needs one.
+ * - `compute(read)` — resolves to a non-negative number, or METRIC_NOT_APPLICABLE.
+ */
+export const METRICS = [
+ {
+ id: 'postStreakDays',
+ label: 'POST Streak',
+ unit: 'days',
+ hint: 'Consecutive days of POST practice',
+ // The unified sessions-OR-training streak — the same helper (and the same user-timezone
+ // day boundary) the Progress page and the dashboard widgets use, so the Character sheet
+ // can't quote a different streak than the rest of PortOS (#2091).
+ compute: async (read) => {
+ const [sessions, training, today] = await Promise.all([
+ read('postSessions'),
+ read('postTraining'),
+ read('postToday'),
+ ]);
+ return computeUnifiedStreak(sessions, training, today).current;
+ },
+ },
+ {
+ id: 'healthLoggingStreak',
+ label: 'Health Streak',
+ unit: 'days',
+ hint: 'Consecutive days with a health log',
+ compute: async (read) => (await read('loggingStats')).currentStreak,
+ },
+ {
+ id: 'recordsCreated',
+ label: 'Records Created',
+ unit: 'count',
+ hint: 'Universes, works, catalog entries & scraps',
+ // Same four tallies Wordsmith levels off — reported raw here rather than on the log
+ // curve. Shares every read with that skill via the signal context.
+ compute: async (read) => {
+ const [universeCount, workCount, catalog] = await Promise.all([
+ read('universeCount'),
+ read('workCount'),
+ read('catalogStats'),
+ ]);
+ return universeCount + workCount + catalog.total + catalog.scraps;
+ },
+ },
+ {
+ id: 'memoryCount',
+ label: 'Memories',
+ unit: 'count',
+ hint: 'Captured in Brain',
+ compute: async (read) => read('memoryCount'),
+ },
+ {
+ id: 'mediaRendered',
+ label: 'Media Rendered',
+ unit: 'count',
+ hint: 'Images & videos in the media index',
+ compute: async (read) => read('assetCount'),
+ },
+ {
+ id: 'goalCompletionRate',
+ label: 'Goal Follow-Through',
+ unit: 'percent',
+ hint: 'Of goals you resolved, the share you finished',
+ emptyLabel: 'No goals resolved yet',
+ // Denominator is RESOLVED goals (completed + abandoned), not all goals. Counting `active`
+ // goals as incomplete would make the rate drop the moment you file an ambitious goal and
+ // punish having work in flight — it would measure caution, not follow-through. With no
+ // resolved goals the ratio is undefined, which is NOT 0% (see the header's three states).
+ compute: async (read) => {
+ const { goals } = await read('goals');
+ const completed = (goals || []).filter((g) => g?.status === 'completed').length;
+ const abandoned = (goals || []).filter((g) => g?.status === 'abandoned').length;
+ const resolved = completed + abandoned;
+ if (resolved === 0) return METRIC_NOT_APPLICABLE;
+ return Math.round((completed / resolved) * 100);
+ },
+ },
+];
+
+/**
+ * Resolve one metric to its response shape, classifying the three states the header
+ * describes. Failure paths kept distinct on purpose:
+ * - `compute` rejects → unavailable (the domain could not be read)
+ * - `compute` resolves non-finite → unavailable (the domain lied; a fake 0 would read as
+ * real activity data)
+ * - `compute` returns the N/A symbol → notApplicable (no honest number exists yet)
+ * - `compute` resolves 0 → a real, earned 0
+ */
+async function readMetric(metric, read) {
+ const raw = await metric.compute(read).catch((err) => {
+ // `err?.message ?? err` — a non-Error rejection (a thrown string, a rejected `undefined`)
+ // would otherwise throw *inside* the catch and defeat the per-metric containment below.
+ console.warn(`⚠️ Character metric ${metric.id}: stat read failed — ${err?.message ?? err}`);
+ return STAT_UNAVAILABLE;
+ });
+
+ const base = { id: metric.id, label: metric.label, unit: metric.unit, hint: metric.hint };
+
+ if (raw === METRIC_NOT_APPLICABLE) {
+ return { ...base, value: null, unavailable: false, notApplicable: true, emptyLabel: metric.emptyLabel ?? null };
+ }
+
+ if (raw === STAT_UNAVAILABLE || !Number.isFinite(raw) || raw < 0) {
+ if (raw !== STAT_UNAVAILABLE) {
+ console.warn(`⚠️ Character metric ${metric.id}: stat returned a non-countable value`);
+ }
+ // value stays null — NOT 0 — so no consumer can render an unread domain as an idle one.
+ return { ...base, value: null, unavailable: true, notApplicable: false };
+ }
+
+ return { ...base, value: raw, unavailable: false, notApplicable: false };
+}
+
+/**
+ * Compute every metric. Signals are read in parallel and each failure is contained to its own
+ * tile, so one unreachable domain (Postgres down for the memory/catalog reads, say) degrades
+ * that tile to `unavailable` instead of failing the whole `GET /api/character`.
+ *
+ * `read` is the shared signal context — pass the SAME one the skills got (see
+ * `getCharacterSkills`) or the six signals the two registries share get read twice.
+ */
+export async function getCharacterMetrics(read = createSignalContext()) {
+ return Promise.all(METRICS.map((metric) => readMetric(metric, read)));
+}
diff --git a/server/services/characterMetrics.test.js b/server/services/characterMetrics.test.js
new file mode 100644
index 0000000000..f158013db1
--- /dev/null
+++ b/server/services/characterMetrics.test.js
@@ -0,0 +1,378 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// Each domain's stat getter is stubbed so the registry can be driven to its interesting
+// states — populated, empty, not-applicable, and read-failure — without any of the real
+// dependency graphs (Postgres, the universe store, the meatspace files) loading. Mirrors
+// characterSkills.test.js, since both registries fan out over the same signal context.
+const stats = vi.hoisted(() => ({
+ universes: 0,
+ works: 0,
+ catalog: { total: 0, scraps: 0 },
+ sessions: [],
+ training: [],
+ today: '2026-07-17',
+ logging: { currentStreak: 0, totalLogged: 0 },
+ goals: { goals: [] },
+ memories: 0,
+ assets: 0,
+}));
+
+// A domain "fails" by having its stub reject — the same way a real getter surfaces an
+// unreachable Postgres or an unreadable data file.
+const fail = (name) => () => Promise.reject(new Error(`${name} unavailable`));
+
+vi.mock('./universeBuilder.js', () => ({ countUniverses: vi.fn(async () => stats.universes) }));
+vi.mock('./writersRoom/local.js', () => ({ countWorks: vi.fn(async () => stats.works) }));
+vi.mock('./catalogDB.js', () => ({ getCatalogStats: vi.fn(async () => stats.catalog) }));
+vi.mock('./meatspacePost.js', () => ({ getPostSessions: vi.fn(async () => stats.sessions) }));
+vi.mock('./meatspacePostTraining.js', () => ({ getAllTrainingEntries: vi.fn(async () => stats.training) }));
+vi.mock('./meatspaceLoggingStats.js', () => ({ getLoggingStats: vi.fn(async () => stats.logging) }));
+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) }));
+
+import { getCharacterMetrics, METRICS, METRIC_NOT_APPLICABLE } from './characterMetrics.js';
+import { createSignalContext } from './characterSignals.js';
+import { getCharacterSkills } from './characterSkills.js';
+import { countUniverses } from './universeBuilder.js';
+import { getCatalogStats } from './catalogDB.js';
+import { getLoggingStats } from './meatspaceLoggingStats.js';
+import { getGoals } from './identity/goals.js';
+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';
+
+const goal = (status) => ({ status });
+
+// Restore every stat to the "brand new install" baseline between tests so a test that
+// populates one domain can't leak into the next one's empty-domain assertions.
+beforeEach(() => {
+ stats.universes = 0;
+ stats.works = 0;
+ stats.catalog = { total: 0, scraps: 0 };
+ stats.sessions = [];
+ stats.training = [];
+ stats.today = '2026-07-17';
+ stats.logging = { currentStreak: 0, totalLogged: 0 };
+ stats.goals = { goals: [] };
+ stats.memories = 0;
+ stats.assets = 0;
+ vi.mocked(countUniverses).mockImplementation(async () => stats.universes);
+ vi.mocked(countWorks).mockImplementation(async () => stats.works);
+ vi.mocked(getCatalogStats).mockImplementation(async () => stats.catalog);
+ vi.mocked(getPostSessions).mockImplementation(async () => stats.sessions);
+ vi.mocked(getLoggingStats).mockImplementation(async () => stats.logging);
+ vi.mocked(getGoals).mockImplementation(async () => stats.goals);
+ vi.mocked(countMemories).mockImplementation(async () => stats.memories);
+ vi.mocked(countAssets).mockImplementation(async () => stats.assets);
+ vi.mocked(userLocalToday).mockImplementation(async () => stats.today);
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+const byId = (metrics, id) => metrics.find((m) => m.id === id);
+
+describe('the registry', () => {
+ it('declares a unique id, label, unit, hint and compute for each metric', () => {
+ const ids = new Set();
+ for (const metric of METRICS) {
+ expect(metric.id).toMatch(/^[a-zA-Z]+$/);
+ expect(ids.has(metric.id)).toBe(false);
+ ids.add(metric.id);
+ expect(metric.label).toBeTruthy();
+ expect(metric.hint).toBeTruthy();
+ expect(['count', 'days', 'percent']).toContain(metric.unit);
+ expect(typeof metric.compute).toBe('function');
+ }
+ });
+
+ it('ships at least the three real metrics the acceptance criteria require', async () => {
+ expect(METRICS.length).toBeGreaterThanOrEqual(3);
+ });
+
+ it('declares an emptyLabel for every metric that can be not-applicable', async () => {
+ // A ratio metric with no denominator renders its emptyLabel; shipping one without would
+ // leave the tile saying a bare, meaningless "Not applicable yet".
+ stats.goals = { goals: [] };
+ const metrics = await getCharacterMetrics();
+ for (const metric of metrics.filter((m) => m.notApplicable)) {
+ expect(metric.emptyLabel).toBeTruthy();
+ }
+ });
+});
+
+describe('getCharacterMetrics — empty domains', () => {
+ it('reports a real, earned 0 for every countable metric on a fresh install', async () => {
+ const metrics = await getCharacterMetrics();
+
+ expect(metrics).toHaveLength(METRICS.length);
+ // Every metric EXCEPT the ratio has a legitimate 0 answer; none of them are unavailable.
+ // If a signal id were typo'd, its read would throw and this would go red — which is
+ // exactly the guard that lets characterSignals.js throw rather than reject.
+ for (const metric of metrics) {
+ expect(metric.unavailable).toBe(false);
+ if (!metric.notApplicable) expect(metric.value).toBe(0);
+ }
+ });
+
+ it('distinguishes a real 0 from an unread stat', async () => {
+ const memories = byId(await getCharacterMetrics(), 'memoryCount');
+ expect(memories).toMatchObject({ value: 0, unavailable: false, notApplicable: false });
+ expect(memories.value).not.toBeNull();
+ });
+});
+
+describe('getCharacterMetrics — populated domains', () => {
+ it('derives recordsCreated from universes + works + catalog entries + scraps', async () => {
+ stats.universes = 3;
+ stats.works = 2;
+ stats.catalog = { total: 8, scraps: 2 };
+ expect(byId(await getCharacterMetrics(), 'recordsCreated')).toMatchObject({
+ value: 15, unit: 'count', unavailable: false,
+ });
+ });
+
+ it('derives postStreakDays from the unified sessions-OR-training streak', async () => {
+ // Three consecutive days ending today: one scored session, two training entries. The
+ // unified streak counts a day active on EITHER, so this must be 3 and not 1.
+ stats.sessions = [{ date: '2026-07-17' }];
+ stats.training = [{ date: '2026-07-16' }, { date: '2026-07-15' }];
+ expect(byId(await getCharacterMetrics(), 'postStreakDays')).toMatchObject({
+ value: 3, unit: 'days', unavailable: false,
+ });
+ });
+
+ it('anchors the POST streak to the USER timezone day, not the server clock', async () => {
+ // Otherwise the sheet's streak could disagree with the Progress page's by a day.
+ stats.today = '2026-07-17';
+ stats.sessions = [{ date: '2026-07-17' }, { date: '2026-07-16' }];
+ expect(byId(await getCharacterMetrics(), 'postStreakDays').value).toBe(2);
+
+ // Same records, a user timezone already a day ahead: today is unlogged, but the grace
+ // window keeps yesterday's run alive.
+ stats.today = '2026-07-18';
+ expect(byId(await getCharacterMetrics(), 'postStreakDays').value).toBe(2);
+ expect(userLocalToday).toHaveBeenCalled();
+ });
+
+ it('reports a broken POST streak as a real 0, not as unavailable', async () => {
+ stats.today = '2026-07-17';
+ stats.sessions = [{ date: '2026-01-01' }]; // active once, long ago
+ expect(byId(await getCharacterMetrics(), 'postStreakDays')).toMatchObject({
+ value: 0, unavailable: false, notApplicable: false,
+ });
+ });
+
+ it('derives healthLoggingStreak from the logging stats current streak', async () => {
+ stats.logging = { currentStreak: 12, totalLogged: 40 };
+ expect(byId(await getCharacterMetrics(), 'healthLoggingStreak')).toMatchObject({
+ value: 12, unit: 'days', unavailable: false,
+ });
+ });
+
+ it('derives memoryCount and mediaRendered from their tallies', async () => {
+ stats.memories = 250;
+ stats.assets = 31;
+ const metrics = await getCharacterMetrics();
+ expect(byId(metrics, 'memoryCount').value).toBe(250);
+ expect(byId(metrics, 'mediaRendered').value).toBe(31);
+ });
+});
+
+describe('getCharacterMetrics — goalCompletionRate', () => {
+ it('is the completed share of RESOLVED goals', async () => {
+ stats.goals = { goals: [goal('completed'), goal('completed'), goal('completed'), goal('abandoned')] };
+ expect(byId(await getCharacterMetrics(), 'goalCompletionRate')).toMatchObject({
+ value: 75, unit: 'percent', unavailable: false, notApplicable: false,
+ });
+ });
+
+ it('does not count ACTIVE goals against you', async () => {
+ // Filing an ambitious goal must not drop your follow-through — the rate would then measure
+ // caution rather than follow-through.
+ stats.goals = { goals: [goal('completed'), goal('active'), goal('active'), goal('active')] };
+ expect(byId(await getCharacterMetrics(), 'goalCompletionRate').value).toBe(100);
+ });
+
+ it('reports NOT APPLICABLE — never 0% — when no goal has been resolved', async () => {
+ // The load-bearing case for the third state: "0% follow-through" is a damning claim to
+ // make about someone who has simply never finished OR abandoned a goal.
+ stats.goals = { goals: [goal('active'), goal('active')] };
+ const rate = byId(await getCharacterMetrics(), 'goalCompletionRate');
+ expect(rate).toMatchObject({ value: null, unavailable: false, notApplicable: true });
+ expect(rate.value).not.toBe(0);
+ expect(rate.emptyLabel).toBeTruthy();
+ });
+
+ it('reports not-applicable on a brand new install with no goals at all', async () => {
+ stats.goals = { goals: [] };
+ expect(byId(await getCharacterMetrics(), 'goalCompletionRate')).toMatchObject({
+ value: null, notApplicable: true, unavailable: false,
+ });
+ });
+
+ it('reports a REAL 0% when every resolved goal was abandoned', async () => {
+ // The mirror of the case above: here 0 is the honest answer and must NOT be suppressed.
+ stats.goals = { goals: [goal('abandoned'), goal('abandoned')] };
+ expect(byId(await getCharacterMetrics(), 'goalCompletionRate')).toMatchObject({
+ value: 0, notApplicable: false, unavailable: false,
+ });
+ });
+
+ it('tolerates a goals payload with missing/odd entries', async () => {
+ stats.goals = { goals: [null, undefined, {}, goal('completed')] };
+ expect(byId(await getCharacterMetrics(), 'goalCompletionRate').value).toBe(100);
+ });
+
+ it('treats a goals payload with no goals array as not-applicable, not a crash', async () => {
+ stats.goals = {};
+ expect(byId(await getCharacterMetrics(), 'goalCompletionRate')).toMatchObject({
+ notApplicable: true, unavailable: false,
+ });
+ });
+});
+
+// NOTE ON WHAT THIS SUITE PROVES: these tests drive failure by making a stubbed getter
+// reject, which exercises readMetric's classification — the registry's own job. It does NOT
+// prove the real wiring can reach `unavailable` for the file-backed signals (postSessions,
+// postTraining, loggingStats, goals), which bottom out in readJSONFile and swallow read
+// errors. That gap is real, documented in characterSignals.js / characterSkills.js, and
+// tracked in #2726. Do not read a green run here as "every domain reports failures correctly".
+describe('getCharacterMetrics — stat-read failure (must NOT collapse into a fake 0)', () => {
+ it('marks a metric unavailable with a null value when its stat read rejects', async () => {
+ vi.mocked(countMemories).mockImplementation(fail('memory backend'));
+
+ const memories = byId(await getCharacterMetrics(), 'memoryCount');
+ expect(memories.unavailable).toBe(true);
+ // Null, not 0 — a 0 would read as "you have never saved a memory", which is a lie.
+ expect(memories.value).toBeNull();
+ expect(memories.value).not.toBe(0);
+ });
+
+ it('keeps unavailable DISTINCT from not-applicable', async () => {
+ // Both render a dash, but they say different things ("we could not tell" vs "there is no
+ // number yet") and the UI must be able to tell them apart.
+ vi.mocked(getGoals).mockImplementation(fail('goals'));
+ expect(byId(await getCharacterMetrics(), 'goalCompletionRate')).toMatchObject({
+ value: null, unavailable: true, notApplicable: false,
+ });
+ });
+
+ it('contains a failure to its own metric — other domains still report', async () => {
+ stats.logging = { currentStreak: 5, totalLogged: 40 };
+ vi.mocked(countMemories).mockImplementation(fail('memory backend'));
+
+ const metrics = await getCharacterMetrics();
+ expect(byId(metrics, 'memoryCount').unavailable).toBe(true);
+ expect(byId(metrics, 'healthLoggingStreak')).toMatchObject({ value: 5, unavailable: false });
+ expect(metrics).toHaveLength(METRICS.length);
+ });
+
+ it('never rejects, even when every domain is unreadable', async () => {
+ vi.mocked(countUniverses).mockImplementation(fail('universe store'));
+ vi.mocked(getCatalogStats).mockImplementation(fail('catalog'));
+ vi.mocked(getLoggingStats).mockImplementation(fail('logging stats'));
+ vi.mocked(getGoals).mockImplementation(fail('goals'));
+ vi.mocked(countMemories).mockImplementation(fail('memory backend'));
+ vi.mocked(countAssets).mockImplementation(fail('media index'));
+ vi.mocked(getPostSessions).mockImplementation(fail('post sessions'));
+
+ const metrics = await getCharacterMetrics();
+ expect(metrics).toHaveLength(METRICS.length);
+ for (const metric of metrics) {
+ expect(metric).toMatchObject({ value: null, unavailable: true });
+ }
+ });
+
+ it('marks a partially-failed multi-read metric unavailable rather than under-counting', async () => {
+ // recordsCreated reads three stores. If only the catalog is down, reporting just the
+ // universe count would silently understate it — "can't tell" is the honest answer.
+ stats.universes = 3;
+ vi.mocked(getCatalogStats).mockImplementation(fail('catalog'));
+
+ expect(byId(await getCharacterMetrics(), 'recordsCreated')).toMatchObject({
+ value: null, unavailable: true,
+ });
+ });
+
+ it('treats a non-finite stat value as unavailable, not as 0', async () => {
+ // A getter that resolves undefined/NaN is a broken read, not an idle domain. Note `null`
+ // is in this list on purpose: a broken getter returning null must NOT be able to pass
+ // itself off as the not-applicable state (which is a Symbol, not null).
+ for (const broken of [undefined, null, NaN, Infinity, 'twelve']) {
+ vi.mocked(countMemories).mockImplementation(async () => broken);
+ expect(byId(await getCharacterMetrics(), 'memoryCount')).toMatchObject({
+ value: null, unavailable: true, notApplicable: false,
+ });
+ }
+ });
+
+ it('treats a negative stat value as unavailable, not as 0', async () => {
+ vi.mocked(countMemories).mockImplementation(async () => -3);
+ expect(byId(await getCharacterMetrics(), 'memoryCount')).toMatchObject({
+ value: null, unavailable: true,
+ });
+ });
+
+ it('keeps id/label/unit/hint on an unavailable metric so the UI can still name it', async () => {
+ vi.mocked(countMemories).mockImplementation(fail('memory backend'));
+ expect(byId(await getCharacterMetrics(), 'memoryCount')).toMatchObject({
+ id: 'memoryCount', label: 'Memories', unit: 'count', hint: 'Captured in Brain',
+ });
+ });
+
+ it('never leaks a sentinel Symbol into the response payload', async () => {
+ vi.mocked(countMemories).mockImplementation(fail('memory backend'));
+ stats.goals = { goals: [] }; // drives the not-applicable path too
+ for (const metric of await getCharacterMetrics()) {
+ for (const value of Object.values(metric)) {
+ expect(typeof value).not.toBe('symbol');
+ }
+ // And it must survive the JSON round-trip the route puts it through.
+ expect(() => JSON.stringify(metric)).not.toThrow();
+ }
+ });
+
+ it('exports METRIC_NOT_APPLICABLE as a Symbol, not an in-band value', async () => {
+ // If it were null/0/-1, a broken getter returning that value would silently claim the
+ // not-applicable state instead of being classified as a failed read.
+ expect(typeof METRIC_NOT_APPLICABLE).toBe('symbol');
+ });
+});
+
+describe('sharing the signal context with the skills registry (#2676)', () => {
+ it('reads a shared signal ONCE across both registries', async () => {
+ // The acceptance criterion: metrics must not add reads. universeCount feeds Wordsmith AND
+ // recordsCreated; with one context between them it is read exactly once.
+ stats.universes = 3;
+ for (const stub of [countUniverses, countMemories, getLoggingStats]) vi.mocked(stub).mockClear();
+
+ const read = createSignalContext();
+ await Promise.all([getCharacterSkills(read), getCharacterMetrics(read)]);
+
+ expect(countUniverses).toHaveBeenCalledTimes(1);
+ expect(countMemories).toHaveBeenCalledTimes(1);
+ expect(getLoggingStats).toHaveBeenCalledTimes(1);
+ });
+
+ it('reads a shared signal twice when the registries are given separate contexts', async () => {
+ // Pins the negative: this is the waste the shared context exists to remove, so a future
+ // refactor that drops the shared context has a failing test pointing at why.
+ vi.mocked(countUniverses).mockClear();
+
+ await Promise.all([getCharacterSkills(createSignalContext()), getCharacterMetrics(createSignalContext())]);
+
+ expect(countUniverses).toHaveBeenCalledTimes(2);
+ });
+
+ it('still works standalone, minting its own context when none is passed', async () => {
+ stats.memories = 8;
+ expect(byId(await getCharacterMetrics(), 'memoryCount').value).toBe(8);
+ });
+});
diff --git a/server/services/characterSignals.js b/server/services/characterSignals.js
new file mode 100644
index 0000000000..fda945663e
--- /dev/null
+++ b/server/services/characterSignals.js
@@ -0,0 +1,108 @@
+/**
+ * Character Signal Context (#2676, epic #2672)
+ *
+ * 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 —
+ * 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
+ * registries now take a `read` function instead of importing the getters directly.
+ *
+ * **Per-request, never module-level.** `createSignalContext()` mints a fresh cache per
+ * `getCharacter()` call. A module-level cache would be a correctness bug, not an
+ * optimization: these stats change as the user uses PortOS, and a sheet that never notices
+ * the session you just logged is worse than a slow one.
+ *
+ * **Failures propagate; they are not classified here.** A reader that rejects makes `read()`
+ * reject with the same error, and the *consumer* decides what that means (both registries
+ * turn it into an explicit `unavailable`, never a fake 0 — see `readSkill` / `readMetric`).
+ * This module stays a cache, not a policy: the memoized entry settles to a discriminated
+ * `{ ok }` result so a cached rejection can never surface as an unhandled rejection, and
+ * `read()` re-throws it fresh to each caller.
+ *
+ * **Known gap (#2726).** Only the DB-backed readers (`universeCount`, `workCount`,
+ * `catalogStats`, `memoryCount`, `assetCount`) actually reject on failure. `postSessions`,
+ * `postTraining`, `loggingStats`, and `goals` bottom out in `readJSONFile`, which returns its
+ * default on *every* read error — so an unreadable file is indistinguishable here from an
+ * empty one. Documented at length in `characterSkills.js`; the strict-read variants that
+ * close it are tracked in #2726. Nothing here changes when they land — the moment a getter
+ * starts rejecting, both registries already classify it correctly.
+ */
+
+import { countUniverses } from './universeBuilder.js';
+import { countWorks } from './writersRoom/local.js';
+import { getCatalogStats } from './catalogDB.js';
+import { getPostSessions } from './meatspacePost.js';
+import { getAllTrainingEntries } from './meatspacePostTraining.js';
+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';
+
+/**
+ * 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` /
+ * `countWorks` / `countMemories` / `countAssets` are `COUNT(*)`s (#2729), so no consumer can
+ * accidentally materialize every record just to read a `.length`.
+ */
+export const SIGNAL_READERS = {
+ universeCount: () => countUniverses(),
+ workCount: () => countWorks(),
+ catalogStats: () => getCatalogStats(),
+ postSessions: () => getPostSessions(),
+ postTraining: () => getAllTrainingEntries(),
+ // Today's `YYYY-MM-DD` in the USER's configured timezone — the same day boundary
+ // meatspacePost.js anchors its streaks to. Deriving "today" from the server's local clock
+ // 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(),
+ goals: () => getGoals(),
+ memoryCount: () => countMemories({}),
+ assetCount: () => countAssets(),
+};
+
+/**
+ * Mint a read-once context. Returns `read(signalId)` → a promise of that signal's value,
+ * resolving the underlying getter at most once no matter how many skills/metrics ask.
+ *
+ * Throws synchronously on an unknown signal id. That is deliberate rather than a rejection:
+ * a rejection would be caught by the caller's `unavailable` classification and a typo'd id
+ * would masquerade as "this domain is down" forever. The registry suites drive every
+ * skill/metric through a fully-stubbed context and assert nothing comes back unavailable,
+ * which turns such a typo into a red test instead of a silent lie.
+ */
+export function createSignalContext() {
+ const cache = new Map();
+
+ return function read(signalId) {
+ const reader = SIGNAL_READERS[signalId];
+ if (!reader) throw new Error(`Unknown character signal: ${signalId}`);
+
+ if (!cache.has(signalId)) {
+ // Settle to `{ ok }` so the MEMOIZED promise never rejects: a cached rejected promise
+ // that a later consumer doesn't await would surface as an unhandled rejection and (under
+ // Node's default policy) take the process down. `Promise.resolve().then(reader)` also
+ // normalizes a getter that throws synchronously into a rejection.
+ cache.set(
+ signalId,
+ Promise.resolve()
+ .then(reader)
+ .then((value) => ({ ok: true, value }), (error) => ({ ok: false, error }))
+ );
+ }
+
+ // A fresh derived promise per call, rejecting with the original error — so every consumer
+ // sees the failure and classifies it itself.
+ return cache.get(signalId).then((result) => {
+ if (!result.ok) throw result.error;
+ return result.value;
+ });
+ };
+}
diff --git a/server/services/characterSignals.test.js b/server/services/characterSignals.test.js
new file mode 100644
index 0000000000..7abba110ac
--- /dev/null
+++ b/server/services/characterSignals.test.js
@@ -0,0 +1,157 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// Every domain getter is stubbed so the context can be driven without any of the real
+// dependency graphs (Postgres, the universe store, the meatspace files) loading. Each stub
+// counts its calls — the whole point of this module is that a signal is read ONCE per
+// context no matter how many skills/metrics ask for it.
+const calls = vi.hoisted(() => ({ universes: 0, sessions: 0, memories: 0 }));
+
+vi.mock('./universeBuilder.js', () => ({
+ countUniverses: vi.fn(async () => { calls.universes += 1; return 3; }),
+}));
+vi.mock('./writersRoom/local.js', () => ({ countWorks: vi.fn(async () => 1) }));
+vi.mock('./catalogDB.js', () => ({ getCatalogStats: vi.fn(async () => ({ total: 2, scraps: 1 })) }));
+vi.mock('./meatspacePost.js', () => ({
+ getPostSessions: vi.fn(async () => { calls.sessions += 1; return [{ date: '2026-07-17' }]; }),
+}));
+vi.mock('./meatspacePostTraining.js', () => ({ getAllTrainingEntries: vi.fn(async () => []) }));
+vi.mock('./meatspaceLoggingStats.js', () => ({ getLoggingStats: vi.fn(async () => ({ currentStreak: 4, totalLogged: 9 })) }));
+vi.mock('./identity/goals.js', () => ({ getGoals: vi.fn(async () => ({ goals: [] })) }));
+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') }));
+
+import { createSignalContext, SIGNAL_READERS } from './characterSignals.js';
+import { countUniverses } from './universeBuilder.js';
+import { countMemories } from './memoryBackend.js';
+
+beforeEach(() => {
+ calls.universes = 0;
+ calls.sessions = 0;
+ calls.memories = 0;
+ vi.mocked(countUniverses).mockImplementation(async () => { calls.universes += 1; return 3; });
+ vi.mocked(countMemories).mockImplementation(async () => { calls.memories += 1; return 42; });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('the signal registry', () => {
+ it('exposes every signal the skills and metrics registries read', () => {
+ // A signal removed from here silently breaks whichever registry reads it (the read throws
+ // → 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',
+ ]);
+ });
+
+ it('declares every reader as a function', () => {
+ for (const reader of Object.values(SIGNAL_READERS)) {
+ expect(typeof reader).toBe('function');
+ }
+ });
+});
+
+describe('createSignalContext — read-once', () => {
+ it('resolves a signal to its getter value', async () => {
+ const read = createSignalContext();
+ await expect(read('universeCount')).resolves.toBe(3);
+ await expect(read('memoryCount')).resolves.toBe(42);
+ await expect(read('catalogStats')).resolves.toEqual({ total: 2, scraps: 1 });
+ });
+
+ it('reads a signal ONCE however many consumers ask for it', async () => {
+ // The reason this module exists: Wordsmith and recordsCreated both want universeCount.
+ const read = createSignalContext();
+ const [a, b, c] = await Promise.all([read('universeCount'), read('universeCount'), read('universeCount')]);
+ expect([a, b, c]).toEqual([3, 3, 3]);
+ expect(calls.universes).toBe(1);
+ });
+
+ it('memoizes across sequential reads too, not just concurrent ones', async () => {
+ const read = createSignalContext();
+ await read('postSessions');
+ await read('postSessions');
+ expect(calls.sessions).toBe(1);
+ });
+
+ it('gives each context its OWN cache, so a later request sees fresh stats', async () => {
+ // A module-level cache would be a correctness bug: the sheet would never notice the
+ // session the user just logged.
+ await createSignalContext()('universeCount');
+ await createSignalContext()('universeCount');
+ expect(calls.universes).toBe(2);
+ });
+});
+
+describe('createSignalContext — failures propagate, they are not classified', () => {
+ it('rejects with the getter\'s own error so the consumer can classify it', async () => {
+ const boom = new Error('memory backend unavailable');
+ vi.mocked(countMemories).mockImplementation(async () => { throw boom; });
+
+ const read = createSignalContext();
+ await expect(read('memoryCount')).rejects.toBe(boom);
+ });
+
+ it('caches a failure and re-throws it to every consumer', async () => {
+ let hits = 0;
+ vi.mocked(countMemories).mockImplementation(async () => { hits += 1; throw new Error('down'); });
+
+ const read = createSignalContext();
+ await expect(read('memoryCount')).rejects.toThrow('down');
+ await expect(read('memoryCount')).rejects.toThrow('down');
+ // A failing signal must not be retried per consumer — that would stampede a downed
+ // Postgres once per skill AND once per metric that reads it.
+ expect(hits).toBe(1);
+ });
+
+ it('contains a failure to its own signal — other signals still resolve', async () => {
+ vi.mocked(countMemories).mockImplementation(async () => { throw new Error('down'); });
+
+ const read = createSignalContext();
+ await expect(read('memoryCount')).rejects.toThrow('down');
+ await expect(read('universeCount')).resolves.toBe(3);
+ });
+
+ it('normalizes a getter that throws SYNCHRONOUSLY into a rejection', async () => {
+ // Otherwise the throw would escape read() synchronously and blow past the consumer's
+ // `.catch()`-based unavailable classification.
+ vi.mocked(countMemories).mockImplementation(() => { throw new Error('sync boom'); });
+
+ const read = createSignalContext();
+ await expect(read('memoryCount')).rejects.toThrow('sync boom');
+ });
+
+ it('never leaves an unhandled rejection behind when a failed signal goes unawaited', async () => {
+ // The memoized promise must settle to a discriminated result rather than reject: a cached
+ // rejected promise nobody awaits would take the process down under Node's default policy.
+ const unhandled = vi.fn();
+ process.on('unhandledRejection', unhandled);
+ vi.mocked(countMemories).mockImplementation(async () => { throw new Error('down'); });
+
+ const read = createSignalContext();
+ read('memoryCount').catch(() => {}); // one consumer handles it
+ read('memoryCount'); // a second reads it and drops the promise on the floor
+
+ // Let the microtask queue drain and the rejection surface if it is going to.
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ process.off('unhandledRejection', unhandled);
+
+ // The dropped derived promise is the caller's problem, but the CACHED one must never be
+ // the source of an unhandled rejection.
+ expect(unhandled.mock.calls.filter(([err]) => err?.message === 'down').length).toBeLessThanOrEqual(1);
+ });
+});
+
+describe('createSignalContext — unknown signal', () => {
+ it('throws synchronously rather than rejecting', async () => {
+ // A rejection would be swallowed by the consumer's unavailable classification and a typo'd
+ // signal id would masquerade as "this domain is down" forever.
+ const read = createSignalContext();
+ expect(() => read('nopeNotASignal')).toThrow('Unknown character signal: nopeNotASignal');
+ });
+});
diff --git a/server/services/characterSkills.js b/server/services/characterSkills.js
index 8df058082c..4b241ea5af 100644
--- a/server/services/characterSkills.js
+++ b/server/services/characterSkills.js
@@ -20,6 +20,11 @@
* collapse: a fake 0 would read as "you have never written anything" when the
* truth is "we could not tell".
*
+ * **Reads come from a shared context.** Each `compute()` takes a `read(signalId)` from
+ * `characterSignals.js` rather than importing a domain getter itself, so the six skills and
+ * the metrics grid (#2676) — which derive from the same nine signals — cost ONE read per
+ * signal per request, not one per consumer.
+ *
* **Known gap in that guarantee (#2726).** `readSkill` honours whatever a domain
* reports, but it can only *detect* a failure the getter actually surfaces — by
* rejecting, or by resolving something non-countable. Today only the DB-backed
@@ -38,15 +43,7 @@
* reporting failure, `readSkill` already classifies it correctly.
*/
-import { countUniverses } from './universeBuilder.js';
-import { countWorks } from './writersRoom/local.js';
-import { getCatalogStats } from './catalogDB.js';
-import { getPostSessions } from './meatspacePost.js';
-import { getAllTrainingEntries } from './meatspacePostTraining.js';
-import { getLoggingStats } from './meatspaceLoggingStats.js';
-import { getGoals } from './identity/goals.js';
-import { countMemories } from './memoryBackend.js';
-import { countAssets } from './mediaAssetIndex/db.js';
+import { createSignalContext } from './characterSignals.js';
// Skills plateau rather than growing without bound — past this the curve is
// noise, and an unbounded level would dwarf the age-based character level.
@@ -82,12 +79,14 @@ const STAT_UNAVAILABLE = Symbol('stat-unavailable');
/**
* The registry. Each entry is `{ id, label, domain, scale, compute }`, where
- * `compute` resolves to a single non-negative number: the domain's cumulative
- * engagement.
+ * `compute(read)` resolves to a single non-negative number: the domain's cumulative
+ * engagement. `read` is the shared signal context (`characterSignals.js`) — never import a
+ * domain getter here, or this skill's reads stop being shared with the metrics grid.
*
* Values are **cumulative**, never streak-based: a streak resets to 0 after one
* missed day, and a skill you have already earned should not un-learn itself
- * because you took a week off.
+ * because you took a week off. (The metrics grid reports the *streaks* off the same
+ * signals — the two are complementary readings, not duplicates.)
*/
export const SKILLS = [
{
@@ -106,11 +105,11 @@ export const SKILLS = [
// COUNT(*)s that exclude tombstones exactly as listUniverses()/listWorks() filter them,
// so this no longer materializes every universe record, the universe-run history, or
// every work's rebuilt manifest just to read a `.length`.
- compute: async () => {
+ compute: async (read) => {
const [universeCount, workCount, catalog] = await Promise.all([
- countUniverses(),
- countWorks(),
- getCatalogStats(),
+ read('universeCount'),
+ read('workCount'),
+ read('catalogStats'),
]);
return universeCount + workCount + catalog.total + catalog.scraps;
},
@@ -123,8 +122,8 @@ export const SKILLS = [
// Scored sessions + training-log entries (Morse / memory practice) — the same
// "either counts as activity" union the unified POST streak uses, so this
// can't disagree with what the Progress page calls practice.
- compute: async () => {
- const [sessions, training] = await Promise.all([getPostSessions(), getAllTrainingEntries()]);
+ compute: async (read) => {
+ const [sessions, training] = await Promise.all([read('postSessions'), read('postTraining')]);
return sessions.length + training.length;
},
},
@@ -135,7 +134,7 @@ export const SKILLS = [
// Health logs are near-daily and cheap to record, so the curve is stretched
// to keep a single week of logging from vaulting to level 3.
scale: 5,
- compute: async () => (await getLoggingStats()).totalLogged,
+ compute: async (read) => (await read('loggingStats')).totalLogged,
},
{
id: 'strategist',
@@ -144,8 +143,8 @@ export const SKILLS = [
scale: 3,
// Goal *discipline*, not goal count: check-ins plus recorded progress steps.
// Filing ten goals and never revisiting them is not strategy.
- compute: async () => {
- const { goals } = await getGoals();
+ compute: async (read) => {
+ const { goals } = await read('goals');
return (goals || []).reduce(
(sum, goal) => sum + (goal.checkIns?.length || 0) + (goal.progressHistory?.length || 0),
0
@@ -159,7 +158,7 @@ export const SKILLS = [
// Memories accrue fastest of any domain (a single Brain capture can mint
// several), so this needs the flattest curve of the six.
scale: 10,
- compute: async () => countMemories({}),
+ compute: async (read) => read('memoryCount'),
},
{
id: 'auteur',
@@ -167,7 +166,7 @@ export const SKILLS = [
domain: 'media',
scale: 5,
// Rendered images + videos in the durable media asset index.
- compute: async () => countAssets(),
+ compute: async (read) => read('assetCount'),
},
];
@@ -179,8 +178,8 @@ export const SKILLS = [
* would silently read as "no activity")
* - `compute` resolves 0 → a real, earned level 0
*/
-async function readSkill(skill) {
- const raw = await skill.compute().catch((err) => {
+async function readSkill(skill, read) {
+ const raw = await skill.compute(read).catch((err) => {
// `err?.message ?? err` — a non-Error rejection (a thrown string, a rejected `undefined`)
// would otherwise throw *inside* the catch and defeat the per-skill containment below.
console.warn(`⚠️ Character skill ${skill.id}: stat read failed — ${err?.message ?? err}`);
@@ -206,7 +205,12 @@ async function readSkill(skill) {
* to its own skill, so one unreachable domain (e.g. Postgres down for the catalog
* or memory reads) degrades that entry to `unavailable` instead of failing the
* whole `GET /api/character`.
+ *
+ * `read` is the shared signal context. Callers deriving MORE than skills from the same
+ * request (`getCharacter()` also derives the metrics grid) must mint ONE context and pass it
+ * to both, or the signals the two registries share get read twice. Defaults to a private
+ * context so a skills-only caller stays a one-liner.
*/
-export async function getCharacterSkills() {
- return Promise.all(SKILLS.map(readSkill));
+export async function getCharacterSkills(read = createSignalContext()) {
+ return Promise.all(SKILLS.map((skill) => readSkill(skill, read)));
}
diff --git a/server/services/citysnapshots.js b/server/services/citysnapshots.js
index 470378fa8c..da92be3965 100644
--- a/server/services/citysnapshots.js
+++ b/server/services/citysnapshots.js
@@ -159,9 +159,9 @@ async function buildSnapshot() {
getPeers().catch(() => FAILED),
backup.getState().catch(() => FAILED),
getCountsByType().catch(() => FAILED),
- // Only `character.level` is snapshotted (see the frame below), so skip the skill
- // fan-out — this runs on every snapshot tick.
- getCharacter({ withSkills: false }).catch(() => FAILED),
+ // Only `character.level` is snapshotted (see the frame below), so skip both derived
+ // fan-outs — this runs on every snapshot tick.
+ getCharacter({ withSkills: false, withMetrics: false }).catch(() => FAILED),
getMemoryStats().catch(() => FAILED),
getDiskPercent().catch(() => null),
]);