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

refactor: simplify the signal cache and close the sync-throw containment gap (#2676)

[._.]/ Adam Eivy4e1e75372d33
diff --git a/client/src/pages/CharacterSheet.jsx b/client/src/pages/CharacterSheet.jsx
index 590c2dbe43..9f0a04c3dd 100644
--- a/client/src/pages/CharacterSheet.jsx
+++ b/client/src/pages/CharacterSheet.jsx
@@ -80,9 +80,11 @@ function SkillsCard({ skills }) {
);
}
-// 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.
+// Render one metric's value per its server-declared `unit`. Only unbounded COUNTS go through
+// formatCompactCount, so a 12,400-memory Brain reads "12.4K" instead of overflowing the tile;
+// day counts stay literal (a 1200-day streak is "1200d", not a nonsense "1.2Kd") and percents
+// are 0-100 by construction. 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
@@ -90,7 +92,7 @@ function SkillsCard({ skills }) {
// 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`;
+ if (unit === 'days') return `${value}d`;
return formatCompactCount(value);
}
diff --git a/client/src/pages/CharacterSheet.metrics.test.jsx b/client/src/pages/CharacterSheet.metrics.test.jsx
index 6482690ec0..5172fee9ee 100644
--- a/client/src/pages/CharacterSheet.metrics.test.jsx
+++ b/client/src/pages/CharacterSheet.metrics.test.jsx
@@ -77,6 +77,11 @@ describe('formatMetricValue', () => {
expect(formatMetricValue({ unit: 'count', value: 3400000 })).toBe('3.4M');
});
+ it('leaves a long day count literal rather than abbreviating it to a nonsense unit', () => {
+ // A multi-year health-logging streak is reachable; "1.2Kd" is not a duration anyone reads.
+ expect(formatMetricValue({ unit: 'days', value: 1200 })).toBe('1200d');
+ });
+
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');
diff --git a/server/services/characterMetrics.js b/server/services/characterMetrics.js
index 5a3230704c..84216a2eaa 100644
--- a/server/services/characterMetrics.js
+++ b/server/services/characterMetrics.js
@@ -129,9 +129,15 @@ export const METRICS = [
// 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;
+ // One pass, and the denominator is derived from the SAME predicate set as the numerator
+ // — so adding a third resolved status can't leave the two out of sync.
+ let completed = 0;
+ let resolved = 0;
+ for (const g of goals || []) {
+ if (g?.status !== 'completed' && g?.status !== 'abandoned') continue;
+ resolved += 1;
+ if (g.status === 'completed') completed += 1;
+ }
if (resolved === 0) return METRIC_NOT_APPLICABLE;
return Math.round((completed / resolved) * 100);
},
@@ -148,17 +154,28 @@ export const METRICS = [
* - `compute` resolves 0 → a real, earned 0
*/
async function readMetric(metric, read) {
- const raw = await metric.compute(read).catch((err) => {
+ // `Promise.resolve().then(...)` rather than `metric.compute(read).catch(...)`: a compute
+ // declared without `async` that throws synchronously would otherwise escape before `.catch`
+ // is attached, rejecting the whole GET instead of degrading this one tile.
+ const raw = await Promise.resolve().then(() => 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 };
+ // One uniform shape across all three states — every key is always present, so a consumer
+ // never has to distinguish "absent key" from "null value" on top of everything else.
+ const base = {
+ id: metric.id,
+ label: metric.label,
+ unit: metric.unit,
+ hint: metric.hint,
+ emptyLabel: metric.emptyLabel ?? null,
+ };
if (raw === METRIC_NOT_APPLICABLE) {
- return { ...base, value: null, unavailable: false, notApplicable: true, emptyLabel: metric.emptyLabel ?? null };
+ return { ...base, value: null, unavailable: false, notApplicable: true };
}
if (raw === STAT_UNAVAILABLE || !Number.isFinite(raw) || raw < 0) {
diff --git a/server/services/characterMetrics.test.js b/server/services/characterMetrics.test.js
index f158013db1..85dd5e5d49 100644
--- a/server/services/characterMetrics.test.js
+++ b/server/services/characterMetrics.test.js
@@ -92,10 +92,25 @@ describe('the registry', () => {
}
});
- it('ships at least the three real metrics the acceptance criteria require', async () => {
+ it('ships at least the three real metrics the acceptance criteria require', () => {
expect(METRICS.length).toBeGreaterThanOrEqual(3);
});
+ it('contains a synchronously-thrown compute to its own tile rather than failing the whole read', async () => {
+ // Every shipped compute is async, so a sync throw can only come from a future entry
+ // declared without `async` — which must degrade ONE tile, not reject GET /api/character.
+ const exploding = { id: 'boom', label: 'Boom', unit: 'count', hint: 'x', compute: () => { throw new Error('sync boom'); } };
+ METRICS.push(exploding);
+ try {
+ const metrics = await getCharacterMetrics();
+ expect(byId(metrics, 'boom')).toMatchObject({ value: null, unavailable: true });
+ // ...and the real tiles still report.
+ expect(byId(metrics, 'memoryCount').unavailable).toBe(false);
+ } finally {
+ METRICS.pop();
+ }
+ });
+
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".
@@ -105,6 +120,20 @@ describe('the registry', () => {
expect(metric.emptyLabel).toBeTruthy();
}
});
+
+ it('returns one uniform key set across all three states', async () => {
+ // A consumer should never have to tell "absent key" apart from "null value" on top of the
+ // three states themselves.
+ stats.goals = { goals: [] }; // drives notApplicable
+ vi.mocked(countMemories).mockImplementation(fail('memory backend')); // drives unavailable
+ stats.assets = 5; // drives a real value
+
+ const metrics = await getCharacterMetrics();
+ const shape = ['emptyLabel', 'hint', 'id', 'label', 'notApplicable', 'unavailable', 'unit', 'value'];
+ for (const metric of metrics) {
+ expect(Object.keys(metric).sort()).toEqual(shape);
+ }
+ });
});
describe('getCharacterMetrics — empty domains', () => {
diff --git a/server/services/characterSignals.js b/server/services/characterSignals.js
index fda945663e..78c330a91b 100644
--- a/server/services/characterSignals.js
+++ b/server/services/characterSignals.js
@@ -18,9 +18,9 @@
* **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.
+ * This module stays a cache, not a policy. A failed read is cached like any other, so a
+ * downed Postgres is hit once per request rather than once per skill AND once per metric
+ * that reads it.
*
* **Known gap (#2726).** Only the DB-backed readers (`universeCount`, `workCount`,
* `catalogStats`, `memoryCount`, `assetCount`) actually reject on failure. `postSessions`,
@@ -85,24 +85,13 @@ export function createSignalContext() {
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 }))
- );
- }
+ // `Promise.resolve().then(reader)` rather than `reader()`: it normalizes a getter that
+ // throws SYNCHRONOUSLY into a rejection, so a consumer's `.catch()`-based unavailable
+ // classification always sees it instead of the throw escaping `read()` and rejecting the
+ // whole GET. A settled promise re-delivers its value (or re-throws its error) to every
+ // later awaiter, so caching the promise is all the memoization either case needs.
+ if (!cache.has(signalId)) cache.set(signalId, Promise.resolve().then(reader));
- // 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;
- });
+ return cache.get(signalId);
};
}
diff --git a/server/services/characterSignals.test.js b/server/services/characterSignals.test.js
index 7abba110ac..66e83a329f 100644
--- a/server/services/characterSignals.test.js
+++ b/server/services/characterSignals.test.js
@@ -126,24 +126,37 @@ describe('createSignalContext — failures propagate, they are not classified',
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.
+ it('re-throws a cached failure to a consumer that reads it AFTER it already settled', async () => {
+ // The two registries do not read in lockstep — a metric can reach a signal a skill already
+ // resolved (and failed on) ticks earlier. A settled rejected promise must still reject for
+ // that late reader rather than resolving undefined.
+ vi.mocked(countMemories).mockImplementation(async () => { throw new Error('down'); });
+
+ const read = createSignalContext();
+ await expect(read('memoryCount')).rejects.toThrow('down');
+ await new Promise((resolve) => setTimeout(resolve, 5)); // let it fully settle
+
+ await expect(read('memoryCount')).rejects.toThrow('down');
+ });
+
+ it('raises no unhandled rejection when every consumer handles the failure', async () => {
+ // The realistic shape: both registries read a downed signal and each classifies it. Node's
+ // default policy kills the process on an unhandled rejection, so a shared cached rejection
+ // fanning out to several awaiters must not produce one.
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
+ await Promise.all([
+ read('memoryCount').catch(() => 'skill-classified-it'),
+ read('memoryCount').catch(() => 'metric-classified-it'),
+ ]);
- // 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);
+ expect(unhandled.mock.calls.filter(([err]) => err?.message === 'down')).toHaveLength(0);
});
});
diff --git a/server/services/characterSkills.js b/server/services/characterSkills.js
index 4b241ea5af..bca238a9f9 100644
--- a/server/services/characterSkills.js
+++ b/server/services/characterSkills.js
@@ -179,7 +179,10 @@ export const SKILLS = [
* - `compute` resolves 0 → a real, earned level 0
*/
async function readSkill(skill, read) {
- const raw = await skill.compute(read).catch((err) => {
+ // `Promise.resolve().then(...)` rather than `skill.compute(read).catch(...)`: a compute
+ // declared without `async` that throws synchronously would otherwise escape before `.catch`
+ // is attached, rejecting the whole GET instead of degrading this one skill.
+ const raw = await Promise.resolve().then(() => 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}`);