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

fix: re-derive longevity time horizons on read so goal urgency stops drifting (#4122)

[._.]/ Adam Eivyd62e77f2e0ac
diff --git a/.changelog/next/fixed-issue-4122.md b/.changelog/next/fixed-issue-4122.md
new file mode 100644
index 0000000000..12adc0f685
--- /dev/null
+++ b/.changelog/next/fixed-issue-4122.md
@@ -0,0 +1 @@
+- Goal urgency and time horizons are recomputed from your birth date on every read, so `yearsRemaining` no longer stays frozen at whatever the last longevity derive stamped
diff --git a/client/src/components/character/GoalsCard.jsx b/client/src/components/character/GoalsCard.jsx
index dabec8ad14..f2dcf7dba2 100644
--- a/client/src/components/character/GoalsCard.jsx
+++ b/client/src/components/character/GoalsCard.jsx
@@ -89,14 +89,12 @@ export default function GoalsCard() {
// so the two surfaces can never show contradictory urgency. (Enriching the flat endpoint
// instead would change a shared API's semantics.)
//
- // Two honest limits on how fresh that is, both the goals feature's to fix (see #4122),
- // and both landing on "sorts last" rather than on a wrong number:
- // - The tree only re-derives for goals it considers active (`goals.js` gates on a
- // strict status), so the status-less goals `isActive` admits keep whatever urgency
- // they carry — for MortalLoom-synced goals, none at all.
- // - The horizons it derives against are only as fresh as the last deriveLongevity()
- // run. Every urgency consumer shares that, and re-deriving from this read-only card
- // would write on a read path AND make the sheet disagree with /goals.
+ // The horizons that urgency is derived against are now recomputed server-side on every
+ // read (#4122), so the number is current no matter how long ago deriveLongevity() ran.
+ // One honest limit remains, and it lands on "sorts last" rather than on a wrong number:
+ // the tree only re-derives for goals it considers active (`goals.js` gates on a strict
+ // status), so the status-less goals `isActive` admits keep whatever urgency they carry —
+ // for MortalLoom-synced goals, none at all.
//
// silent: this card owns its own error UI (the message below), so letting request() toast
// as well would surface the same failure twice.
diff --git a/server/services/identity/goals.js b/server/services/identity/goals.js
index e131342007..219fd8ac92 100644
--- a/server/services/identity/goals.js
+++ b/server/services/identity/goals.js
@@ -15,7 +15,16 @@ import {
loadJSON,
saveJSON
} from './store.js';
-import { deriveLongevity } from './longevity.js';
+import { applyFreshTimeHorizons, deriveLongevity } from './longevity.js';
+
+/**
+ * Read the longevity snapshot with `timeHorizons` re-derived against today (#4122).
+ * `goals` is passed in rather than re-read because every caller here already holds it.
+ */
+async function loadLongevityFor(goals) {
+ const longevity = await loadJSON(LONGEVITY_FILE, DEFAULT_LONGEVITY);
+ return applyFreshTimeHorizons(longevity, goals?.birthDate);
+}
// === Pure Functions (exported for testing) ===
@@ -213,6 +222,21 @@ export async function getGoals(options) {
}
}
if (needsSave) await saveJSON(GOALS_FILE, data);
+
+ // Urgency is only *persisted* when a goal is written or a birth date is set, so the
+ // stored value is as old as that write — and it ranks off `timeHorizons.yearsRemaining`,
+ // which drifts every day. Re-derive it here (after the migration save, so this read-path
+ // refresh never triggers a write of its own) against today's horizons, so every consumer
+ // of getGoals — jobGates, goalCheckIn, telegram — sees a current number (#4122).
+ // Left alone when the horizons can't be recomputed: an install with no birth date keeps
+ // whatever it had rather than having its urgencies silently blanked.
+ const longevity = await loadLongevityFor(data);
+ if (longevity.timeHorizons) {
+ for (const goal of data.goals) {
+ if (goal.status === 'active') goal.urgency = computeGoalUrgency(goal, longevity.timeHorizons);
+ }
+ }
+
return data;
}
@@ -246,7 +270,7 @@ export async function setBirthDate(birthDate) {
export async function createGoal({ title, description, horizon, category, goalType, parentId, tags, targetDate, timeBlockConfig, featureAreas }) {
const goals = await getGoals();
- const longevity = await loadJSON(LONGEVITY_FILE, DEFAULT_LONGEVITY);
+ const longevity = await loadLongevityFor(goals);
// Validate parentId references an existing goal
if (parentId && !goals.goals.find(g => g.id === parentId)) {
@@ -321,7 +345,7 @@ export async function updateGoal(goalId, updates) {
goal.updatedAt = new Date().toISOString();
// Recalculate urgency if horizon changed
- const longevity = await loadJSON(LONGEVITY_FILE, DEFAULT_LONGEVITY);
+ const longevity = await loadLongevityFor(goals);
if (longevity.timeHorizons) {
goal.urgency = computeGoalUrgency(goal, longevity.timeHorizons);
}
@@ -354,7 +378,7 @@ export async function deleteGoal(goalId) {
export async function getGoalsTree() {
const goals = await getGoals();
- const longevity = await loadJSON(LONGEVITY_FILE, DEFAULT_LONGEVITY);
+ const longevity = await loadLongevityFor(goals);
const activities = await getActivities();
// Enrich goals with urgency, feasibility, velocity, and time tracking
diff --git a/server/services/identity/insights.js b/server/services/identity/insights.js
index cbce5f76ff..3b3edc73b5 100644
--- a/server/services/identity/insights.js
+++ b/server/services/identity/insights.js
@@ -7,6 +7,7 @@ import {
DEFAULT_GOALS,
loadJSON
} from './store.js';
+import { applyFreshTimeHorizons } from './longevity.js';
const INSIGHT_RULES = [
{
@@ -196,12 +197,16 @@ const INSIGHT_RULES = [
];
export async function getCrossInsights() {
- const [chronotype, longevity, goalsData] = await Promise.all([
+ const [chronotype, storedLongevity, goalsData] = await Promise.all([
loadJSON(CHRONOTYPE_FILE, DEFAULT_CHRONOTYPE),
loadJSON(LONGEVITY_FILE, DEFAULT_LONGEVITY),
loadJSON(GOALS_FILE, DEFAULT_GOALS)
]);
+ // The goal-timeline rules read `timeHorizons.yearsRemaining` straight off the
+ // snapshot, so re-derive it against today before evaluating them (#4122).
+ const longevity = applyFreshTimeHorizons(storedLongevity, goalsData?.birthDate);
+
const context = { chronotype, longevity, goals: goalsData };
// Rules return partial objects; engine injects id/category from rule definition
diff --git a/server/services/identity/longevity.js b/server/services/identity/longevity.js
index cf17a01c0f..ba2ab7d693 100644
--- a/server/services/identity/longevity.js
+++ b/server/services/identity/longevity.js
@@ -9,12 +9,45 @@ import {
} from './store.js';
import {
computeLifeExpectancy,
+ computeTimeHorizons,
extractLongevityMarkers,
extractCardiovascularMarkers
} from './markers.js';
+/**
+ * Overlay freshly-computed `timeHorizons` onto a stored longevity snapshot.
+ *
+ * `deriveLongevity()` only runs on `setBirthDate` or an explicit derive, so the
+ * persisted `timeHorizons.yearsRemaining` is frozen as of that run and drifts a
+ * little further from the truth every day (#4122). Every read path funnels through
+ * here so urgency, feasibility and the insight rules rank on today's number.
+ *
+ * When the horizons can't be recomputed — no birth date, or no derived life
+ * expectancy to measure against — the stored snapshot is returned untouched.
+ * Nulling it there would turn "we lost the inputs" into "you have no horizons",
+ * which is a different and more misleading claim than a slightly stale number.
+ */
+export function applyFreshTimeHorizons(longevity, birthDate) {
+ const timeHorizons = computeTimeHorizons(birthDate, longevity?.lifeExpectancy?.adjusted);
+ if (!timeHorizons) return longevity;
+ return { ...longevity, timeHorizons };
+}
+
+/**
+ * Load the persisted longevity snapshot with `timeHorizons` re-derived against
+ * today. Callers that already hold the goals record should call
+ * `applyFreshTimeHorizons` directly rather than paying for the extra read here.
+ */
+export async function readLongevity() {
+ const [longevity, goals] = await Promise.all([
+ loadJSON(LONGEVITY_FILE, DEFAULT_LONGEVITY),
+ loadJSON(GOALS_FILE, DEFAULT_GOALS)
+ ]);
+ return applyFreshTimeHorizons(longevity, goals?.birthDate);
+}
+
export async function getLongevity() {
- const existing = await loadJSON(LONGEVITY_FILE, DEFAULT_LONGEVITY);
+ const existing = await readLongevity();
if (existing.derivedAt) return existing;
return deriveLongevity();
}
diff --git a/server/services/identity/longevity.test.js b/server/services/identity/longevity.test.js
new file mode 100644
index 0000000000..c7340aea9c
--- /dev/null
+++ b/server/services/identity/longevity.test.js
@@ -0,0 +1,242 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Birth dates are personal data, so every fixture below is computed relative to
+// "now" instead of being transcribed from anywhere — which also keeps the
+// assertions stable as the calendar moves.
+const YEAR_MS = 365.25 * 24 * 60 * 60 * 1000;
+const birthDateYearsAgo = years => new Date(Date.now() - years * YEAR_MS).toISOString().slice(0, 10);
+
+const h = vi.hoisted(() => ({ goalsData: null, longevityData: null }));
+
+vi.mock('./store.js', () => ({
+ GOALS_FILE: 'goals.json',
+ LONGEVITY_FILE: 'longevity.json',
+ DEFAULT_GOALS: { goals: [], birthDate: null, lifeExpectancy: null, timeHorizons: null },
+ DEFAULT_LONGEVITY: { lifeExpectancy: { adjusted: null }, derivedAt: null },
+ loadJSON: vi.fn(async file => (file === 'goals.json' ? h.goalsData : h.longevityData)),
+ saveJSON: vi.fn(async (file, data) => {
+ if (file === 'goals.json') h.goalsData = data;
+ else h.longevityData = data;
+ })
+}));
+
+vi.mock('../genome.js', () => ({ getGenomeSummary: vi.fn(async () => ({ savedMarkers: {} })) }));
+vi.mock('../meatspaceCalendar.js', () => ({ getActivities: vi.fn(async () => []) }));
+
+const { computeTimeHorizons } = await import('./markers.js');
+const { applyFreshTimeHorizons, readLongevity, getLongevity } = await import('./longevity.js');
+const { getGoals, getGoalsTree, computeGoalUrgency } = await import('./goals.js');
+const { saveJSON } = await import('./store.js');
+
+// A stored snapshot whose horizons were computed a year before "now": at age 44
+// against an 80-year adjusted expectancy the derive stamped 36 years remaining.
+// A year on, the truth is 35 — the drift this module exists to correct.
+const staleSnapshotAYearOld = () => ({
+ lifeExpectancy: { baseline: 78.5, adjusted: 80 },
+ timeHorizons: { ageYears: 44, yearsRemaining: 36, healthyYearsRemaining: 30.6, percentLifeComplete: 55 },
+ derivedAt: new Date(Date.now() - YEAR_MS).toISOString()
+});
+
+// Fully-normalized so getGoals' lazy migration has nothing to backfill (and so
+// never writes) — this suite asserts the read path stays a read path.
+const normalizedGoal = overrides => ({
+ id: 'goal-1',
+ title: 'Example Goal',
+ description: '',
+ horizon: '10-year',
+ category: 'mastery',
+ goalType: 'standard',
+ status: 'active',
+ parentId: null,
+ tags: [],
+ linkedActivities: [],
+ linkedCalendars: [],
+ featureAreas: [],
+ targetDate: null,
+ timeBlockConfig: null,
+ scheduledEvents: [],
+ checkIns: [],
+ milestones: [],
+ progress: 0,
+ progressHistory: [],
+ todos: [],
+ urgency: null,
+ ...overrides
+});
+
+beforeEach(() => {
+ h.goalsData = { goals: [], birthDate: null, lifeExpectancy: null, timeHorizons: null };
+ h.longevityData = { lifeExpectancy: { adjusted: null }, derivedAt: null };
+ saveJSON.mockClear();
+});
+
+describe('computeTimeHorizons', () => {
+ it('derives horizons from a birth date against an adjusted life expectancy', () => {
+ const horizons = computeTimeHorizons(birthDateYearsAgo(45), 80);
+
+ expect(horizons.ageYears).toBeCloseTo(45, 1);
+ expect(horizons.yearsRemaining).toBeCloseTo(35, 1);
+ expect(horizons.healthyYearsRemaining).toBeCloseTo(29.8, 1);
+ expect(horizons.percentLifeComplete).toBeCloseTo(56.3, 1);
+ });
+
+ it('returns null — not a zeroed shape — when the birth date is missing', () => {
+ // "We cannot compute horizons" must stay distinguishable from "no time left".
+ expect(computeTimeHorizons(null, 80)).toBeNull();
+ expect(computeTimeHorizons(undefined, 80)).toBeNull();
+ expect(computeTimeHorizons('', 80)).toBeNull();
+ });
+
+ it('returns null when no life expectancy has been derived yet', () => {
+ expect(computeTimeHorizons(birthDateYearsAgo(45), null)).toBeNull();
+ expect(computeTimeHorizons(birthDateYearsAgo(45), undefined)).toBeNull();
+ });
+
+ it('returns null for an unparseable birth date rather than NaN horizons', () => {
+ expect(computeTimeHorizons('not-a-date', 80)).toBeNull();
+ });
+
+ it('clamps a birth date already past the life expectancy', () => {
+ const horizons = computeTimeHorizons(birthDateYearsAgo(95), 80);
+
+ expect(horizons.yearsRemaining).toBe(0);
+ expect(horizons.healthyYearsRemaining).toBe(0);
+ expect(horizons.percentLifeComplete).toBe(100);
+ });
+});
+
+describe('applyFreshTimeHorizons', () => {
+ it('replaces a year-old snapshot with horizons measured from today', () => {
+ const stored = staleSnapshotAYearOld();
+
+ const fresh = applyFreshTimeHorizons(stored, birthDateYearsAgo(45));
+
+ expect(fresh.timeHorizons.yearsRemaining).toBeCloseTo(35, 1);
+ expect(fresh.timeHorizons.yearsRemaining).toBeLessThan(stored.timeHorizons.yearsRemaining);
+ expect(fresh.timeHorizons.ageYears).toBeCloseTo(45, 1);
+ // Non-mutating: the caller's snapshot is untouched.
+ expect(stored.timeHorizons.yearsRemaining).toBe(36);
+ });
+
+ it('leaves everything else on the snapshot alone', () => {
+ const stored = staleSnapshotAYearOld();
+
+ const fresh = applyFreshTimeHorizons(stored, birthDateYearsAgo(45));
+
+ expect(fresh.derivedAt).toBe(stored.derivedAt);
+ expect(fresh.lifeExpectancy).toEqual(stored.lifeExpectancy);
+ });
+
+ it('keeps the stored snapshot when there is no birth date to re-derive from', () => {
+ const stored = staleSnapshotAYearOld();
+
+ // Degrades to the last known value rather than blanking it — absent inputs
+ // mean "cannot recompute", not "there are no horizons".
+ expect(applyFreshTimeHorizons(stored, null)).toBe(stored);
+ expect(applyFreshTimeHorizons(stored, undefined).timeHorizons.yearsRemaining).toBe(36);
+ });
+
+ it('keeps the stored snapshot when no life expectancy has been derived', () => {
+ const stored = { lifeExpectancy: { adjusted: null }, timeHorizons: null, derivedAt: null };
+
+ expect(applyFreshTimeHorizons(stored, birthDateYearsAgo(45))).toBe(stored);
+ });
+});
+
+describe('readLongevity / getLongevity', () => {
+ it('re-derives horizons against the stored birth date on read', async () => {
+ h.longevityData = staleSnapshotAYearOld();
+ h.goalsData = { ...h.goalsData, birthDate: birthDateYearsAgo(45) };
+
+ const longevity = await readLongevity();
+
+ expect(longevity.timeHorizons.yearsRemaining).toBeCloseTo(35, 1);
+ expect(saveJSON).not.toHaveBeenCalled();
+ });
+
+ it('getLongevity hands back a fresh snapshot without re-running the derive', async () => {
+ h.longevityData = staleSnapshotAYearOld();
+ h.goalsData = { ...h.goalsData, birthDate: birthDateYearsAgo(45) };
+
+ const longevity = await getLongevity();
+
+ expect(longevity.derivedAt).toBe(h.longevityData.derivedAt);
+ expect(longevity.timeHorizons.yearsRemaining).toBeCloseTo(35, 1);
+ expect(saveJSON).not.toHaveBeenCalled();
+ });
+});
+
+describe('goal urgency ranks on the re-derived horizons', () => {
+ // Age 70 against an 80-year expectancy → 10 years remaining, 8.5 healthy. A
+ // 10-year goal therefore scores rawUrgency 0.5 + 0.2 health pressure = 0.7,
+ // while the stale snapshot's 40 remaining years would score a flat 0.
+ const staleGenerousSnapshot = () => ({
+ lifeExpectancy: { baseline: 78.5, adjusted: 80 },
+ timeHorizons: { ageYears: 40, yearsRemaining: 40, healthyYearsRemaining: 34, percentLifeComplete: 50 },
+ derivedAt: new Date(Date.now() - 30 * YEAR_MS).toISOString()
+ });
+
+ beforeEach(() => {
+ h.longevityData = staleGenerousSnapshot();
+ h.goalsData = {
+ goals: [normalizedGoal({ urgency: 0 })],
+ birthDate: birthDateYearsAgo(70),
+ lifeExpectancy: null,
+ timeHorizons: null
+ };
+ });
+
+ it('getGoalsTree enriches urgency from today\'s horizons, not the snapshot', async () => {
+ const tree = await getGoalsTree();
+
+ const staleUrgency = computeGoalUrgency({ horizon: '10-year' }, staleGenerousSnapshot().timeHorizons);
+ expect(staleUrgency).toBe(0);
+
+ expect(tree.flat[0].urgency).toBeCloseTo(0.7, 2);
+ expect(tree.timeHorizons.yearsRemaining).toBeCloseTo(10, 1);
+ });
+
+ it('getGoalsTree orders goals by the re-derived urgency', async () => {
+ h.goalsData.goals = [
+ normalizedGoal({ id: 'goal-short', horizon: '1-year' }),
+ normalizedGoal({ id: 'goal-long', horizon: 'lifetime' })
+ ];
+
+ const tree = await getGoalsTree();
+ const byId = Object.fromEntries(tree.flat.map(g => [g.id, g.urgency]));
+
+ // With only ~10 years left a lifetime goal is far more urgent than a 1-year one.
+ expect(byId['goal-long']).toBeGreaterThan(byId['goal-short']);
+ });
+
+ it('getGoals refreshes the persisted urgency in memory without writing', async () => {
+ // jobGates / goalCheckIn / telegram all read goals through here, so the
+ // refresh has to land before the record leaves this function.
+ const data = await getGoals();
+
+ expect(data.goals[0].urgency).toBeCloseTo(0.7, 2);
+ expect(saveJSON).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the stored horizons when there is no birth date', async () => {
+ // Nothing to re-derive from, so this degrades to exactly the pre-fix
+ // behavior — the snapshot's own horizons — rather than fabricating any.
+ h.goalsData.birthDate = null;
+
+ const tree = await getGoalsTree();
+
+ expect(tree.timeHorizons).toEqual(staleGenerousSnapshot().timeHorizons);
+ expect(tree.flat[0].urgency).toBe(0);
+ });
+
+ it('leaves urgency untouched when neither a birth date nor stored horizons exist', async () => {
+ h.goalsData.birthDate = null;
+ h.goalsData.goals = [normalizedGoal({ urgency: 0.42 })];
+ h.longevityData = { lifeExpectancy: { adjusted: null }, timeHorizons: null, derivedAt: null };
+
+ const data = await getGoals();
+
+ // No horizons anywhere is "unknown", not "zero urgency".
+ expect(data.goals[0].urgency).toBe(0.42);
+ });
+});
diff --git a/server/services/identity/markers.js b/server/services/identity/markers.js
index 75afbc3968..394aea3cae 100644
--- a/server/services/identity/markers.js
+++ b/server/services/identity/markers.js
@@ -145,6 +145,39 @@ export function extractCardiovascularMarkers(savedMarkers) {
return results;
}
+/**
+ * Time horizons for a birth date measured against an adjusted life expectancy.
+ *
+ * Date-dependent and therefore never trustworthy as a stored snapshot: every read
+ * path re-runs this so `yearsRemaining` is "as of now" rather than "as of the last
+ * derive" (#4122). It is cheap arithmetic with no I/O, so re-deriving on every read
+ * costs nothing.
+ *
+ * Returns `null` — not a zero-filled shape — when the birth date is missing or
+ * unparseable, or when no adjusted life expectancy has been derived yet. "We can't
+ * compute horizons" must stay distinguishable from "you have no time left"; callers
+ * gate on the null.
+ */
+export function computeTimeHorizons(birthDate, adjustedLifeExpectancy) {
+ if (!birthDate || typeof adjustedLifeExpectancy !== 'number') return null;
+
+ const birthMs = new Date(birthDate).getTime();
+ if (Number.isNaN(birthMs)) return null;
+
+ const ageYears = (Date.now() - birthMs) / (365.25 * 24 * 60 * 60 * 1000);
+ const yearsRemaining = Math.max(0, Math.round((adjustedLifeExpectancy - ageYears) * 10) / 10);
+ // Healthy years: estimate ~85% of remaining years are active/healthy
+ const healthyYearsRemaining = Math.round(yearsRemaining * 0.85 * 10) / 10;
+ const percentLifeComplete = Math.round((ageYears / adjustedLifeExpectancy) * 1000) / 10;
+
+ return {
+ ageYears: Math.round(ageYears * 10) / 10,
+ yearsRemaining,
+ healthyYearsRemaining,
+ percentLifeComplete: Math.min(100, percentLifeComplete)
+ };
+}
+
export function computeLifeExpectancy(longevityMarkers, cardiovascularMarkers, birthDate) {
// Longevity score: weighted average of signals (+1 beneficial, -1 concern)
let longevityScore = 0;
@@ -180,24 +213,9 @@ export function computeLifeExpectancy(longevityMarkers, cardiovascularMarkers, b
const coverage = (longevityCount + cardioCount) / (maxLongevity + maxCardio);
const confidence = Math.round(Math.min(1, coverage) * 100) / 100;
- // Time horizons if birth date provided
- let timeHorizons = null;
- if (birthDate) {
- const birth = new Date(birthDate);
- const now = new Date();
- const ageYears = (now - birth) / (365.25 * 24 * 60 * 60 * 1000);
- const yearsRemaining = Math.max(0, Math.round((adjusted - ageYears) * 10) / 10);
- // Healthy years: estimate ~85% of remaining years are active/healthy
- const healthyYearsRemaining = Math.round(yearsRemaining * 0.85 * 10) / 10;
- const percentLifeComplete = Math.round((ageYears / adjusted) * 1000) / 10;
-
- timeHorizons = {
- ageYears: Math.round(ageYears * 10) / 10,
- yearsRemaining,
- healthyYearsRemaining,
- percentLifeComplete: Math.min(100, percentLifeComplete)
- };
- }
+ // Time horizons if birth date provided — same helper the read paths call, so the
+ // persisted snapshot and a freshly re-derived one can never disagree on the math.
+ const timeHorizons = computeTimeHorizons(birthDate, adjusted);
return {
longevityScore: Math.round(longevityScore * 1000) / 1000,