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

test: stop re-implementing the code under test, and cover three blind spots

[._.]/ Adam Eivy44e12a8e93bf
diff --git a/client/src/hooks/useOpenClawStream.test.jsx b/client/src/hooks/useOpenClawStream.test.jsx
new file mode 100644
index 0000000000..d6429bfc69
--- /dev/null
+++ b/client/src/hooks/useOpenClawStream.test.jsx
@@ -0,0 +1,239 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { useState } from 'react';
+import { renderHook, act } from '@testing-library/react';
+import { useOpenClawStream } from './useOpenClawStream';
+import { getOpenClawMessages, streamOpenClawMessage } from '../services/apiOpenClaw';
+
+vi.mock('../services/apiOpenClaw', () => ({
+ getOpenClawMessages: vi.fn(),
+ streamOpenClawMessage: vi.fn()
+}));
+
+// The hook takes its composer/attachments/sending state as controlled props from
+// the owning component (see the hook's own header comment). Wrap it in a small
+// harness that owns that state the same way the real component does, so tests
+// can drive it through renderHook without reimplementing the component.
+function useHarness(overrides = {}) {
+ const [selectedSessionId, setSelectedSessionId] = useState(overrides.selectedSessionId ?? 'session-1');
+ const [attachments, setAttachments] = useState(overrides.attachments ?? []);
+ const [composer, setComposer] = useState(overrides.composer ?? 'hello');
+ const [sending, setSending] = useState(false);
+
+ const stream = useOpenClawStream({
+ selectedSessionId,
+ attachments,
+ setAttachments,
+ composer,
+ setComposer,
+ context: overrides.context ?? {},
+ apps: overrides.apps ?? [],
+ sending,
+ setSending,
+ onError: overrides.onError ?? (() => {}),
+ onSendComplete: overrides.onSendComplete ?? (() => {})
+ });
+
+ return { ...stream, setSelectedSessionId, setComposer, composer, sending };
+}
+
+const flushMicrotasks = () => new Promise(resolve => setTimeout(resolve, 0));
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+// =============================================================================
+// loadMessages — stale-response guard (loadingSessionRef)
+// =============================================================================
+
+describe('loadMessages stale-session guard', () => {
+ it('discards an in-flight load when a newer session load starts before it resolves', async () => {
+ let resolveA;
+ const promiseA = new Promise(resolve => { resolveA = resolve; });
+ let resolveB;
+ const promiseB = new Promise(resolve => { resolveB = resolve; });
+ getOpenClawMessages.mockImplementation(sessionId =>
+ sessionId === 'session-A' ? promiseA : promiseB
+ );
+
+ const { result } = renderHook(() => useHarness());
+
+ act(() => { result.current.loadMessages('session-A'); });
+ act(() => { result.current.loadMessages('session-B'); });
+
+ // Resolve the OLDER (session-A) request first — the user already moved on
+ // to session-B, so this response must be silently discarded.
+ await act(async () => {
+ resolveA({ messages: [{ id: 'stale', role: 'assistant', content: 'stale response' }] });
+ await flushMicrotasks();
+ });
+ expect(result.current.messages).toEqual([]);
+ expect(result.current.messagesLoading).toBe(true); // session-B still pending
+
+ // Now resolve the NEWER (session-B) request — this one should win.
+ await act(async () => {
+ resolveB({ messages: [{ id: 'fresh', role: 'assistant', content: 'fresh response' }] });
+ await flushMicrotasks();
+ });
+ expect(result.current.messages).toEqual([
+ { id: 'fresh', role: 'assistant', content: 'fresh response' }
+ ]);
+ expect(result.current.messagesLoading).toBe(false);
+ });
+
+ it('discards a stale rejection the same way it discards a stale success', async () => {
+ let rejectA;
+ const promiseA = new Promise((_resolve, reject) => { rejectA = reject; });
+ let resolveB;
+ const promiseB = new Promise(resolve => { resolveB = resolve; });
+ getOpenClawMessages.mockImplementation(sessionId =>
+ sessionId === 'session-A' ? promiseA : promiseB
+ );
+ const onError = vi.fn();
+
+ const { result } = renderHook(() => useHarness({ onError }));
+
+ act(() => { result.current.loadMessages('session-A'); });
+ act(() => { result.current.loadMessages('session-B'); });
+ onError.mockClear(); // clear the '' resets fired by the two loadMessages calls above
+
+ await act(async () => {
+ rejectA(new Error('session-A network error'));
+ await flushMicrotasks();
+ });
+ // The stale rejection must not surface an error for the abandoned session.
+ expect(onError).not.toHaveBeenCalled();
+
+ await act(async () => {
+ resolveB({ messages: [{ id: 'fresh', role: 'assistant', content: 'fresh' }] });
+ await flushMicrotasks();
+ });
+ expect(result.current.messages).toEqual([{ id: 'fresh', role: 'assistant', content: 'fresh' }]);
+ });
+
+ it('clears messages immediately when the session id is falsy', async () => {
+ getOpenClawMessages.mockResolvedValue({ messages: [{ id: 'x', role: 'user', content: 'x' }] });
+ const { result } = renderHook(() => useHarness());
+
+ await act(async () => { await result.current.loadMessages('session-1'); });
+ expect(result.current.messages).toHaveLength(1);
+
+ await act(async () => { await result.current.loadMessages(null); });
+ expect(result.current.messages).toEqual([]);
+ expect(result.current.messagesLoading).toBe(false);
+ expect(getOpenClawMessages).toHaveBeenCalledTimes(1); // no fetch for a null session
+ });
+
+ it('surfaces a load failure via onError and clears messages', async () => {
+ getOpenClawMessages.mockRejectedValue(new Error('boom'));
+ const onError = vi.fn();
+ const { result } = renderHook(() => useHarness({ onError }));
+
+ await act(async () => { await result.current.loadMessages('session-1'); });
+ expect(result.current.messages).toEqual([]);
+ expect(onError).toHaveBeenCalledWith('boom');
+ expect(result.current.messagesLoading).toBe(false);
+ });
+});
+
+// =============================================================================
+// handleSend — abort-on-unmount cleanup
+// =============================================================================
+
+describe('unmount cleanup', () => {
+ it('aborts the in-flight stream request when the hook unmounts', async () => {
+ let capturedSignal;
+ streamOpenClawMessage.mockImplementation((_sessionId, { signal }) => {
+ capturedSignal = signal;
+ return new Promise(() => {}); // never resolves — simulates an open stream
+ });
+
+ const { result, unmount } = renderHook(() => useHarness());
+
+ await act(async () => {
+ result.current.handleSend({ preventDefault: () => {} });
+ await flushMicrotasks();
+ });
+
+ expect(capturedSignal).toBeInstanceOf(AbortSignal);
+ expect(capturedSignal.aborted).toBe(false);
+
+ unmount();
+
+ expect(capturedSignal.aborted).toBe(true);
+ });
+
+ it('does nothing on unmount when no request is in flight', () => {
+ const { unmount } = renderHook(() => useHarness());
+ expect(() => unmount()).not.toThrow();
+ });
+});
+
+// =============================================================================
+// handleSend — streaming behavior
+// =============================================================================
+
+describe('handleSend', () => {
+ it('does not send when the composer is empty and there are no attachments', async () => {
+ const { result } = renderHook(() => useHarness({ composer: '' }));
+ await act(async () => {
+ await result.current.handleSend({ preventDefault: () => {} });
+ });
+ expect(streamOpenClawMessage).not.toHaveBeenCalled();
+ expect(result.current.messages).toEqual([]);
+ });
+
+ it('accumulates text deltas and marks the message completed on the done event', async () => {
+ streamOpenClawMessage.mockImplementation(async (_sessionId, { onEvent }) => {
+ onEvent({ event: 'response.output_text.delta', data: 'Hello ' });
+ onEvent({ event: 'response.output_text.delta', data: 'world' });
+ onEvent({ event: 'done' });
+ });
+ const onSendComplete = vi.fn();
+
+ const { result } = renderHook(() => useHarness({ onSendComplete }));
+
+ await act(async () => {
+ await result.current.handleSend({ preventDefault: () => {} });
+ });
+
+ const assistantMessage = result.current.messages.find(m => m.role === 'assistant');
+ expect(assistantMessage.content).toBe('Hello world');
+ expect(assistantMessage.status).toBe('completed');
+ expect(result.current.composer).toBe('');
+ expect(onSendComplete).toHaveBeenCalledWith({ sessionId: 'session-1' });
+ });
+
+ it('removes the assistant placeholder and reports the error on stream failure', async () => {
+ streamOpenClawMessage.mockRejectedValue(new Error('stream exploded'));
+ const onError = vi.fn();
+
+ const { result } = renderHook(() => useHarness({ onError }));
+
+ await act(async () => {
+ await result.current.handleSend({ preventDefault: () => {} });
+ });
+
+ expect(result.current.messages.some(m => m.role === 'assistant')).toBe(false);
+ expect(onError).toHaveBeenCalledWith('stream exploded');
+ });
+
+ it('keeps a partial response and marks it completed when the user stops the stream', async () => {
+ streamOpenClawMessage.mockImplementation(async (_sessionId, { onEvent, signal }) => {
+ onEvent({ event: 'response.output_text.delta', data: 'partial' });
+ const err = new Error('aborted');
+ err.name = 'AbortError';
+ throw err;
+ });
+
+ const { result } = renderHook(() => useHarness());
+
+ await act(async () => {
+ await result.current.handleSend({ preventDefault: () => {} });
+ });
+
+ const assistantMessage = result.current.messages.find(m => m.role === 'assistant');
+ expect(assistantMessage.status).toBe('completed');
+ expect(assistantMessage.content).toBe('partial');
+ });
+});
diff --git a/client/src/test/settledInput.js b/client/src/test/settledInput.js
index df83baabfb..3253b7ef4b 100644
--- a/client/src/test/settledInput.js
+++ b/client/src/test/settledInput.js
@@ -12,7 +12,13 @@ import { expect } from 'vitest';
// Pinning the settled input value in between turns a load-dependent flake into
// either a pass or an honest, immediately-legible failure.
-const settled = (input, value) => waitFor(() => expect(input).toHaveValue(value));
+// `waitFor` defaults to a 1000ms timeout (testing-library/dom, uncustomized here —
+// see setup.js). Under parallel test-worker CPU contention that's tight for a
+// `user.type()`/`user.clear()` + React re-render to settle, producing phantom
+// failures that have nothing to do with the component under test. Raise it
+// explicitly rather than relying on the tight default.
+const settled = (input, value) =>
+ waitFor(() => expect(input).toHaveValue(value), { timeout: 3000 });
// A `type="number"` input reads its value back coerced, and empty as `null`.
const readBack = (input, text) => (input.type === 'number' ? Number(text) : text);
diff --git a/server/services/appleHealthClinical.test.js b/server/services/appleHealthClinical.test.js
index 038a83d5ba..65702da2ef 100644
--- a/server/services/appleHealthClinical.test.js
+++ b/server/services/appleHealthClinical.test.js
@@ -1,117 +1,10 @@
import { describe, it, expect } from 'vitest';
-
-// Inline pure functions to avoid mocking file I/O (matches project test pattern)
-// These are copies of the functions from appleHealthClinical.js
-
-const LOINC_TO_KEY = {
- '2345-7': 'glucose',
- '3094-0': 'bun',
- '2160-0': 'creatinine',
- '48642-3': 'egfr',
- '2951-2': 'na',
- '2823-3': 'k',
- '2075-0': 'ci',
- '2028-9': 'co2',
- '2093-3': 'cholesterol',
- '2085-9': 'hdl',
- '2089-1': 'ldl',
- '2571-8': 'triglycerides',
- '6690-2': 'wbc',
- '789-8': 'rbc',
- '718-7': 'hemoglobin',
- '3016-3': 'tsh',
- '4548-4': 'hba1c',
-};
-
-function toSnakeCase(str) {
- if (!str) return '';
- return str
- .replace(/\[.*?\]/g, '')
- .replace(/\s+in\s+(Blood|Serum|Plasma).*$/i, '')
- .replace(/\s+by\s+.+$/i, '')
- .trim()
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, '_')
- .replace(/^_|_$/g, '')
- .replace(/_+/g, '_');
-}
-
-function parseFhirLabResult(jsonStr) {
- let resource;
- try { resource = JSON.parse(jsonStr); } catch { return null; }
- if (!resource) return null;
- if (resource.resourceType !== 'Observation') return null;
- const categories = resource.category || [];
- const isLab = categories.some(cat =>
- cat.coding?.some(c => c.code === 'laboratory')
- );
- if (!isLab) return null;
- if (resource.status === 'cancelled' || resource.status === 'entered-in-error') return null;
- const vq = resource.valueQuantity;
- if (!vq || typeof vq.value !== 'number') return null;
- const dateRaw = resource.effectiveDateTime || resource.issued;
- if (!dateRaw) return null;
- const date = dateRaw.substring(0, 10);
- const coding = resource.code?.coding || [];
- const loincEntry = coding.find(c => c.system?.includes('loinc'));
- const loincCode = loincEntry?.code;
- const displayName = resource.code?.text || loincEntry?.display || '';
- const key = (loincCode && LOINC_TO_KEY[loincCode]) || toSnakeCase(displayName);
- if (!key) return null;
- const refRange = resource.referenceRange?.[0];
- const refLow = refRange?.low?.value ?? null;
- const refHigh = refRange?.high?.value ?? null;
- return { date, key, value: vq.value, unit: vq.unit || vq.code || '', refLow, refHigh, label: displayName || key };
-}
-
-function processClinicalRecords(jsonStrings) {
- const byDate = {};
- const refRanges = {};
- let totalParsed = 0;
- let totalSkipped = 0;
- for (const jsonStr of jsonStrings) {
- const result = parseFhirLabResult(jsonStr);
- if (!result) { totalSkipped++; continue; }
- totalParsed++;
- const { date, key, value, unit, refLow, refHigh, label } = result;
- if (!byDate[date]) byDate[date] = {};
- byDate[date][key] = value;
- if ((refLow != null || refHigh != null) && !refRanges[key]) {
- refRanges[key] = {
- ...(refLow != null && { min: refLow }),
- ...(refHigh != null && { max: refHigh }),
- unit, label
- };
- }
- }
- const tests = Object.entries(byDate)
- .sort(([a], [b]) => a.localeCompare(b))
- .map(([date, values]) => ({ date, ...values }));
- return { tests, referenceRanges: refRanges, totalParsed, totalSkipped };
-}
-
-function mergeBloodTests(existing, fhirData) {
- const existingTests = [...(existing.tests || [])];
- const existingRanges = { ...(existing.referenceRanges || {}) };
- const existingByDate = new Map(existingTests.map(t => [t.date, t]));
- for (const fhirTest of fhirData.tests) {
- const { date, ...fhirValues } = fhirTest;
- const existingEntry = existingByDate.get(date);
- if (existingEntry) {
- for (const [key, value] of Object.entries(fhirValues)) {
- if (existingEntry[key] === undefined) existingEntry[key] = value;
- }
- } else {
- existingTests.push(fhirTest);
- existingByDate.set(date, fhirTest);
- }
- }
- for (const [key, range] of Object.entries(fhirData.referenceRanges)) {
- if (!existingRanges[key]) existingRanges[key] = range;
- }
- existingTests.sort((a, b) => a.date.localeCompare(b.date));
- return { tests: existingTests, referenceRanges: existingRanges };
-}
+import {
+ toSnakeCase,
+ parseFhirLabResult,
+ processClinicalRecords,
+ mergeBloodTests
+} from './appleHealthClinical.js';
// === Test Helpers ===
diff --git a/server/services/eventScheduler.test.js b/server/services/eventScheduler.test.js
new file mode 100644
index 0000000000..0482b60302
--- /dev/null
+++ b/server/services/eventScheduler.test.js
@@ -0,0 +1,362 @@
+import { describe, it, expect, vi, beforeEach, afterEach, beforeAll, afterAll } from 'vitest';
+import {
+ schedule,
+ cancel,
+ pause,
+ resume,
+ getScheduledEvents,
+ getEvent,
+ getHistory,
+ getStats,
+ cancelAll,
+ triggerNow,
+ parseCronToNextRun,
+ parseCronToPrevRun,
+ isValidCron
+} from './eventScheduler.js';
+
+// eventScheduler.js's "UTC" branch (the default, and what every consumer below
+// uses unless it passes an explicit IANA timezone) reads local Date methods
+// (getMonth/getDate/getDay/getHours/getMinutes), not getUTC*. Production always
+// runs under PM2 with TZ=UTC (see ecosystem.config.cjs), which makes that local
+// time UTC. Pin the same env here so cron matches are deterministic regardless
+// of the machine running the tests.
+let originalTZ;
+beforeAll(() => {
+ originalTZ = process.env.TZ;
+ process.env.TZ = 'UTC';
+});
+afterAll(() => {
+ if (originalTZ === undefined) delete process.env.TZ;
+ else process.env.TZ = originalTZ;
+});
+
+// 2024-01-01T00:00:00.000Z is a Monday (getUTCDay()/getDay() under TZ=UTC === 1).
+const FIXED_NOW = new Date('2024-01-01T00:00:00.000Z');
+
+// The scheduler's Maps (scheduledEvents/activeTimers) are module-level singleton
+// state shared across every test in this file — clear it between tests so cases
+// don't leak into each other.
+beforeEach(() => {
+ cancelAll();
+});
+
+// =============================================================================
+// isValidCron
+// =============================================================================
+
+describe('isValidCron', () => {
+ it('accepts a plain 5-field expression', () => {
+ expect(isValidCron('5 0 * * *')).toBe(true);
+ });
+
+ it('accepts step syntax', () => {
+ expect(isValidCron('*/15 * * * *')).toBe(true);
+ });
+
+ it('accepts range syntax', () => {
+ expect(isValidCron('0 9-17 * * *')).toBe(true);
+ });
+
+ it('accepts list syntax', () => {
+ expect(isValidCron('0 9,13,17 * * *')).toBe(true);
+ });
+
+ it('rejects a minute value of 60 (out of range)', () => {
+ expect(isValidCron('60 0 * * *')).toBe(false);
+ });
+
+ it('rejects an hour value of 24 (out of range)', () => {
+ expect(isValidCron('0 24 * * *')).toBe(false);
+ });
+
+ it('rejects a month value of 13 (out of range)', () => {
+ expect(isValidCron('0 0 * 13 *')).toBe(false);
+ });
+
+ it('rejects a day-of-month value of 0 (below range)', () => {
+ expect(isValidCron('0 0 0 * *')).toBe(false);
+ });
+
+ it('rejects a malformed field count', () => {
+ expect(isValidCron('* * *')).toBe(false);
+ expect(isValidCron('* * * * * *')).toBe(false);
+ });
+
+ it('rejects non-string and empty input', () => {
+ expect(isValidCron('')).toBe(false);
+ expect(isValidCron(' ')).toBe(false);
+ expect(isValidCron(null)).toBe(false);
+ expect(isValidCron(undefined)).toBe(false);
+ expect(isValidCron(123)).toBe(false);
+ });
+});
+
+// =============================================================================
+// parseCronToNextRun
+// =============================================================================
+
+describe('parseCronToNextRun', () => {
+ it('finds the next matching minute later the same day', () => {
+ const next = parseCronToNextRun('5 0 * * *', FIXED_NOW);
+ expect(next.toISOString()).toBe('2024-01-01T00:05:00.000Z');
+ });
+
+ it('throws for a malformed field count', () => {
+ expect(() => parseCronToNextRun('* * *', FIXED_NOW)).toThrow(/Invalid cron expression/);
+ });
+
+ it('returns null for an out-of-range field instead of throwing', () => {
+ expect(parseCronToNextRun('60 * * * *', FIXED_NOW)).toBeNull();
+ });
+
+ it('resolves step syntax to the next step boundary', () => {
+ const next = parseCronToNextRun('*/15 * * * *', FIXED_NOW);
+ expect(next.toISOString()).toBe('2024-01-01T00:15:00.000Z');
+ });
+
+ it('resolves range syntax to the first hour in range', () => {
+ const next = parseCronToNextRun('0 9-17 * * *', FIXED_NOW);
+ expect(next.toISOString()).toBe('2024-01-01T09:00:00.000Z');
+ });
+
+ it('resolves list syntax to the next listed minute', () => {
+ const next = parseCronToNextRun('0,30 * * * *', FIXED_NOW);
+ expect(next.toISOString()).toBe('2024-01-01T00:30:00.000Z');
+ });
+
+ it('treats day-of-week 7 the same as 0 (Sunday)', () => {
+ const asZero = parseCronToNextRun('0 0 * * 0', FIXED_NOW);
+ const asSeven = parseCronToNextRun('0 0 * * 7', FIXED_NOW);
+ expect(asZero.toISOString()).toBe('2024-01-07T00:00:00.000Z');
+ expect(asSeven.toISOString()).toBe(asZero.toISOString());
+ });
+
+ it('respects an explicit IANA timezone rather than the process TZ', () => {
+ // 09:00 America/New_York on 2024-01-01 (EST, UTC-5) is 14:00 UTC.
+ const next = parseCronToNextRun('0 9 * * *', FIXED_NOW, 'America/New_York');
+ expect(next.toISOString()).toBe('2024-01-01T14:00:00.000Z');
+ });
+
+ it('returns null quickly for an impossible date within a tight until bound', () => {
+ // Feb 31st never occurs; bound the search to a few days so it returns null
+ // fast instead of scanning the full 2-year window.
+ const until = new Date('2024-01-05T00:00:00.000Z');
+ expect(parseCronToNextRun('0 0 31 2 *', FIXED_NOW, 'UTC', until)).toBeNull();
+ });
+});
+
+// =============================================================================
+// parseCronToPrevRun
+// =============================================================================
+
+describe('parseCronToPrevRun', () => {
+ it('finds the most recent matching minute at or before `from`', () => {
+ const from = new Date('2024-01-01T00:10:00.000Z');
+ const prev = parseCronToPrevRun('5 0 * * *', from);
+ expect(prev.toISOString()).toBe('2024-01-01T00:05:00.000Z');
+ });
+
+ it('returns the exact minute when `from` lands on a match', () => {
+ const from = new Date('2024-01-01T00:05:00.000Z');
+ const prev = parseCronToPrevRun('5 0 * * *', from);
+ expect(prev.toISOString()).toBe('2024-01-01T00:05:00.000Z');
+ });
+
+ it('throws for a malformed field count', () => {
+ expect(() => parseCronToPrevRun('* * *', FIXED_NOW)).toThrow(/Invalid cron expression/);
+ });
+
+ it('returns null for an out-of-range field instead of throwing', () => {
+ expect(parseCronToPrevRun('0 25 * * *', FIXED_NOW)).toBeNull();
+ });
+
+ it('treats day-of-week 7 the same as 0 (Sunday) walking backward', () => {
+ // 2024-01-08 is a Monday; the prior Sunday midnight is 2024-01-07.
+ const from = new Date('2024-01-08T12:00:00.000Z');
+ const asZero = parseCronToPrevRun('0 0 * * 0', from);
+ const asSeven = parseCronToPrevRun('0 0 * * 7', from);
+ expect(asZero.toISOString()).toBe('2024-01-07T00:00:00.000Z');
+ expect(asSeven.toISOString()).toBe(asZero.toISOString());
+ });
+});
+
+// =============================================================================
+// schedule / cancel / pause / resume lifecycle
+// =============================================================================
+
+describe('schedule() validation', () => {
+ it('throws when id is missing', () => {
+ expect(() => schedule({ type: 'once', delayMs: 1000, handler: () => {} }))
+ .toThrow(/requires id, type, and handler/);
+ });
+
+ it('throws when handler is missing', () => {
+ expect(() => schedule({ id: 'e1', type: 'once', delayMs: 1000 }))
+ .toThrow(/requires id, type, and handler/);
+ });
+
+ it('throws for an unknown event type', () => {
+ expect(() => schedule({ id: 'e1', type: 'bogus', handler: () => {} }))
+ .toThrow(/Unknown event type/);
+ });
+
+ it('throws when cron type is missing its cron expression', () => {
+ expect(() => schedule({ id: 'e1', type: 'cron', handler: () => {} }))
+ .toThrow(/requires cron expression/);
+ });
+
+ it('throws when interval type is missing intervalMs', () => {
+ expect(() => schedule({ id: 'e1', type: 'interval', handler: () => {} }))
+ .toThrow(/requires intervalMs/);
+ });
+
+ it('throws when once type is missing delayMs', () => {
+ expect(() => schedule({ id: 'e1', type: 'once', handler: () => {} }))
+ .toThrow(/requires delayMs/);
+ });
+});
+
+describe('schedule() lifecycle with fake timers', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.setSystemTime(FIXED_NOW);
+ });
+
+ afterEach(() => {
+ cancelAll();
+ vi.useRealTimers();
+ });
+
+ it('fires an interval handler on the configured cadence and updates runCount', async () => {
+ const handler = vi.fn();
+ schedule({ id: 'iv-1', type: 'interval', intervalMs: 5000, handler });
+
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(handler).toHaveBeenCalledTimes(1);
+ expect(getEvent('iv-1').runCount).toBe(1);
+
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(handler).toHaveBeenCalledTimes(2);
+ expect(getEvent('iv-1').runCount).toBe(2);
+ });
+
+ it('fires a once event exactly once and then deactivates it', async () => {
+ const handler = vi.fn();
+ schedule({ id: 'once-1', type: 'once', delayMs: 1000, handler });
+
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(handler).toHaveBeenCalledTimes(1);
+ expect(getEvent('once-1').active).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(10000);
+ expect(handler).toHaveBeenCalledTimes(1); // no further runs
+ });
+
+ it('fires a cron event at the next matching minute', async () => {
+ const handler = vi.fn();
+ schedule({ id: 'cron-1', type: 'cron', cron: '* * * * *', handler });
+
+ const event = getEvent('cron-1');
+ expect(event.nextRunAt).toBe(new Date('2024-01-01T00:01:00.000Z').getTime());
+
+ await vi.advanceTimersByTimeAsync(60 * 1000);
+ expect(handler).toHaveBeenCalledTimes(1);
+ });
+
+ it('cancel() removes the event and its pending timer stops firing', async () => {
+ const handler = vi.fn();
+ schedule({ id: 'cancel-1', type: 'once', delayMs: 1000, handler });
+
+ expect(cancel('cancel-1')).toBe(true);
+ expect(getEvent('cancel-1')).toBeNull();
+
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(handler).not.toHaveBeenCalled();
+ });
+
+ it('cancel() returns false for an unknown id', () => {
+ expect(cancel('does-not-exist')).toBe(false);
+ });
+
+ it('pause() stops the timer without removing the event, resume() restarts it', async () => {
+ const handler = vi.fn();
+ schedule({ id: 'pause-1', type: 'interval', intervalMs: 5000, handler });
+
+ expect(pause('pause-1')).toBe(true);
+ expect(getEvent('pause-1').active).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(20000);
+ expect(handler).not.toHaveBeenCalled(); // paused — no runs
+
+ expect(resume('pause-1')).toBe(true);
+ expect(getEvent('pause-1').active).toBe(true);
+
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(handler).toHaveBeenCalledTimes(1);
+ });
+
+ it('pause() and resume() return false for an unknown id', () => {
+ expect(pause('does-not-exist')).toBe(false);
+ expect(resume('does-not-exist')).toBe(false);
+ });
+
+ it('triggerNow() runs the handler immediately regardless of nextRunAt', async () => {
+ const handler = vi.fn();
+ schedule({ id: 'trigger-1', type: 'interval', intervalMs: 60000, handler });
+
+ expect(await triggerNow('trigger-1')).toBe(true);
+ expect(handler).toHaveBeenCalledTimes(1);
+ });
+
+ it('triggerNow() returns false for an unknown id', async () => {
+ expect(await triggerNow('does-not-exist')).toBe(false);
+ });
+
+ it('records a failed handler in history without deactivating a recurring event', async () => {
+ const handler = vi.fn().mockRejectedValue(new Error('boom'));
+ schedule({ id: 'fail-1', type: 'interval', intervalMs: 5000, handler });
+
+ await vi.advanceTimersByTimeAsync(5000);
+
+ const [entry] = getHistory({ eventId: 'fail-1' });
+ expect(entry.success).toBe(false);
+ expect(entry.error).toBe('boom');
+ expect(getEvent('fail-1').active).toBe(true); // still scheduled for next run
+
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(handler).toHaveBeenCalledTimes(2); // recurring run still happened
+ });
+
+ it('records a successful run in history with a non-negative duration', async () => {
+ const handler = vi.fn().mockResolvedValue(undefined);
+ schedule({ id: 'success-1', type: 'once', delayMs: 1000, handler });
+
+ await vi.advanceTimersByTimeAsync(1000);
+
+ const [entry] = getHistory({ eventId: 'success-1' });
+ expect(entry.success).toBe(true);
+ expect(entry.error).toBeNull();
+ expect(entry.duration).toBeGreaterThanOrEqual(0);
+ });
+
+ it('cancelAll() removes every scheduled event and reports the count removed', () => {
+ schedule({ id: 'a', type: 'once', delayMs: 1000, handler: () => {} });
+ schedule({ id: 'b', type: 'once', delayMs: 1000, handler: () => {} });
+
+ expect(getScheduledEvents()).toHaveLength(2);
+ expect(cancelAll()).toBe(2);
+ expect(getScheduledEvents()).toHaveLength(0);
+ });
+
+ it('getStats() reports totals broken down by type', () => {
+ schedule({ id: 'stat-a', type: 'once', delayMs: 1000, handler: () => {} });
+ schedule({ id: 'stat-b', type: 'interval', intervalMs: 5000, handler: () => {} });
+ pause('stat-b');
+
+ const stats = getStats();
+ expect(stats.totalEvents).toBe(2);
+ expect(stats.activeEvents).toBe(1); // stat-b paused
+ expect(stats.byType).toEqual({ once: 1, interval: 1 });
+ });
+});
diff --git a/server/services/featureAgents.js b/server/services/featureAgents.js
index 98e32d3fb4..b68257a5f4 100644
--- a/server/services/featureAgents.js
+++ b/server/services/featureAgents.js
@@ -27,6 +27,18 @@ const EVT = 'feature-agent';
const MIN_BACKOFF_MS = 60 * 60 * 1000; // 1 hour
const MAX_BACKOFF_MS = 24 * 60 * 60 * 1000; // 24 hours
+/**
+ * Exponential idle backoff, doubling per consecutive idle run and capped at
+ * MAX_BACKOFF_MS. `consecutiveIdles` is 1-indexed (the first idle run yields
+ * MIN_BACKOFF_MS, not half of it).
+ */
+export function calculateBackoff(consecutiveIdles) {
+ return Math.min(
+ MIN_BACKOFF_MS * Math.pow(2, consecutiveIdles - 1),
+ MAX_BACKOFF_MS
+ );
+}
+
/**
* Read the feature agents data file
*/
@@ -370,10 +382,7 @@ export async function recordRunCompletion(id, runData) {
// Handle idle detection for backoff
if (runData.status === 'idle-no-work') {
const consecutiveIdles = (agent.backoff?.consecutiveIdles || 0) + 1;
- const currentDelayMs = Math.min(
- MIN_BACKOFF_MS * Math.pow(2, consecutiveIdles - 1),
- MAX_BACKOFF_MS
- );
+ const currentDelayMs = calculateBackoff(consecutiveIdles);
agent.backoff = {
currentDelayMs,
consecutiveIdles,
diff --git a/server/services/featureAgents.test.js b/server/services/featureAgents.test.js
index a30f173b08..cab4c8eaad 100644
--- a/server/services/featureAgents.test.js
+++ b/server/services/featureAgents.test.js
@@ -1,21 +1,14 @@
import { describe, it, expect } from 'vitest';
+import { calculateBackoff } from './featureAgents.js';
/**
* Tests for feature agents pure logic.
- * Uses inline function copies to avoid complex mocking (same pattern as subAgentSpawner.test.js).
*/
const MIN_BACKOFF_MS = 60 * 60 * 1000;
const MAX_BACKOFF_MS = 24 * 60 * 60 * 1000;
describe('Feature Agent Backoff Calculation', () => {
- function calculateBackoff(consecutiveIdles) {
- return Math.min(
- MIN_BACKOFF_MS * Math.pow(2, consecutiveIdles - 1),
- MAX_BACKOFF_MS
- );
- }
-
it('should start at 1 hour for first idle', () => {
expect(calculateBackoff(1)).toBe(60 * 60 * 1000);
});
diff --git a/server/services/identity.test.js b/server/services/identity.test.js
index 1bd778b830..9136c9f6a6 100644
--- a/server/services/identity.test.js
+++ b/server/services/identity.test.js
@@ -1,4 +1,14 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import {
+ extractSleepMarkers,
+ extractCaffeineMarkers,
+ extractLongevityMarkers,
+ extractCardiovascularMarkers,
+ computeLifeExpectancy,
+ computeChronotype,
+ computeRecommendations,
+ computeGoalUrgency
+} from './identity.js';
// identity/store.js now persists via the canonical atomicWrite (#1837), which
// writes to a temp file then renames it over the target (with unlink cleanup on
@@ -33,181 +43,6 @@ function makeFsPromisesStore() {
};
}
-// === Pure function copies for unit testing (avoids complex mocking) ===
-
-const SLEEP_MARKERS = {
- rs1801260: 'clockGene',
- rs57875989: 'dec2',
- rs35333999: 'per2',
- rs2287161: 'cry1',
- rs4753426: 'mtnr1b'
-};
-
-const CAFFEINE_MARKERS = {
- rs762551: 'cyp1a2',
- rs73598374: 'ada'
-};
-
-const MARKER_WEIGHTS = {
- cry1: 0.30,
- clockGene: 0.25,
- per2: 0.20,
- mtnr1b: 0.15,
- dec2: 0.10
-};
-
-const SIGNAL_MAP = {
- clockGene: { beneficial: -1, typical: 0, concern: 1 },
- dec2: { beneficial: -1, typical: 0, concern: 1 },
- per2: { beneficial: -1, typical: 0, concern: 1 },
- cry1: { beneficial: 1, typical: 0, concern: -1 },
- mtnr1b: { beneficial: 0, typical: 0, concern: 1 }
-};
-
-const SCHEDULE_TEMPLATES = {
- morning: {
- wakeTime: '06:00', sleepTime: '22:00',
- peakFocusStart: '08:00', peakFocusEnd: '12:00',
- exerciseWindow: '06:30-08:00', windDownStart: '20:30'
- },
- intermediate: {
- wakeTime: '07:00', sleepTime: '23:00',
- peakFocusStart: '09:30', peakFocusEnd: '13:00',
- exerciseWindow: '07:30-09:00', windDownStart: '21:30'
- },
- evening: {
- wakeTime: '08:30', sleepTime: '00:30',
- peakFocusStart: '11:00', peakFocusEnd: '15:00',
- exerciseWindow: '10:00-12:00', windDownStart: '23:00'
- }
-};
-
-function extractSleepMarkers(savedMarkers) {
- const results = {};
- const markerValues = Object.values(savedMarkers || {});
- for (const [rsid, name] of Object.entries(SLEEP_MARKERS)) {
- const found = markerValues.find(m => m.rsid === rsid);
- if (found) {
- const signalMap = SIGNAL_MAP[name];
- const signal = signalMap?.[found.status] ?? 0;
- results[name] = { rsid, genotype: found.genotype, status: found.status, signal };
- }
- }
- return results;
-}
-
-function extractCaffeineMarkers(savedMarkers) {
- const results = {};
- const markerValues = Object.values(savedMarkers || {});
- for (const [rsid, name] of Object.entries(CAFFEINE_MARKERS)) {
- const found = markerValues.find(m => m.rsid === rsid);
- if (found) {
- results[name] = { rsid, genotype: found.genotype, status: found.status };
- }
- }
- return results;
-}
-
-function computeChronotype(geneticMarkers, behavioralData) {
- const markerNames = Object.keys(geneticMarkers);
- const hasGenetic = markerNames.length > 0;
- const hasBehavioral = behavioralData?.preferredWakeTime || behavioralData?.preferredSleepTime;
-
- let geneticScore = 0;
- let totalWeight = 0;
- for (const name of markerNames) {
- const weight = MARKER_WEIGHTS[name] ?? 0;
- geneticScore += geneticMarkers[name].signal * weight;
- totalWeight += weight;
- }
- if (totalWeight > 0) geneticScore /= totalWeight;
-
- let behavioralScore = 0;
- if (hasBehavioral) {
- const scores = [];
- if (behavioralData.preferredWakeTime) {
- const [h] = behavioralData.preferredWakeTime.split(':').map(Number);
- scores.push(Math.max(-1, Math.min(1, (h - 8) / 2)));
- }
- if (behavioralData.preferredSleepTime) {
- const [h] = behavioralData.preferredSleepTime.split(':').map(Number);
- const normalizedH = h < 6 ? h + 24 : h;
- scores.push(Math.max(-1, Math.min(1, (normalizedH - 23) / 2)));
- }
- if (scores.length > 0) {
- behavioralScore = scores.reduce((a, b) => a + b, 0) / scores.length;
- }
- }
-
- let composite;
- if (hasGenetic && hasBehavioral) {
- composite = (geneticScore + behavioralScore) / 2;
- } else if (hasGenetic) {
- composite = geneticScore;
- } else if (hasBehavioral) {
- composite = behavioralScore;
- } else {
- composite = 0;
- }
-
- let type;
- if (composite < -0.25) type = 'morning';
- else if (composite > 0.25) type = 'evening';
- else type = 'intermediate';
-
- const markerCount = markerNames.length;
- const maxMarkers = Object.keys(MARKER_WEIGHTS).length;
- const markerConfidence = Math.min(0.5, (markerCount / maxMarkers) * 0.5);
- const behavioralConfidence = hasBehavioral ? 0.3 : 0;
-
- let agreementBonus = 0;
- if (hasGenetic && hasBehavioral) {
- const sameDirection = Math.sign(geneticScore) === Math.sign(behavioralScore) &&
- Math.sign(geneticScore) !== 0;
- agreementBonus = sameDirection ? 0.2 : -0.1;
- }
-
- const confidence = Math.max(0, Math.min(1,
- markerConfidence + behavioralConfidence + agreementBonus
- ));
-
- return {
- type,
- confidence: Math.round(confidence * 100) / 100,
- scores: {
- genetic: Math.round(geneticScore * 1000) / 1000,
- behavioral: Math.round(behavioralScore * 1000) / 1000,
- composite: Math.round(composite * 1000) / 1000
- }
- };
-}
-
-function computeRecommendations(type, caffeineMarkers, mtnr1bStatus) {
- const schedule = { ...SCHEDULE_TEMPLATES[type] };
-
- const cyp1a2 = caffeineMarkers?.cyp1a2;
- if (cyp1a2?.status === 'beneficial') {
- schedule.caffeineCutoff = '16:00';
- schedule.caffeineNote = 'Fast metabolizer — caffeine clears quickly';
- } else if (cyp1a2?.status === 'concern' || cyp1a2?.status === 'major_concern') {
- schedule.caffeineCutoff = '12:00';
- schedule.caffeineNote = 'Slow metabolizer — limit afternoon caffeine';
- } else {
- schedule.caffeineCutoff = '14:00';
- schedule.caffeineNote = 'Typical metabolism — moderate afternoon cutoff';
- }
-
- if (mtnr1bStatus === 'concern' || mtnr1bStatus === 'major_concern') {
- schedule.lastMealCutoff = '19:00';
- schedule.mealNote = 'MTNR1B variant — earlier meals may improve glucose response';
- } else {
- schedule.lastMealCutoff = '20:30';
- schedule.mealNote = 'Standard meal timing recommendation';
- }
-
- return schedule;
-}
-
// === Helper: build savedMarkers map from rsid/status pairs ===
function buildSavedMarkers(entries) {
@@ -530,135 +365,6 @@ describe('computeRecommendations', () => {
});
});
-// === Longevity & Goal pure function copies ===
-
-const LONGEVITY_MARKERS = {
- rs2802292: { name: 'foxo3a', gene: 'FOXO3A', weight: 0.25, label: 'Longevity / FOXO3A' },
- rs2229765: { name: 'igf1r', gene: 'IGF1R', weight: 0.20, label: 'Growth Factor Receptor' },
- rs5882: { name: 'cetp', gene: 'CETP', weight: 0.20, label: 'HDL Cholesterol' },
- rs12366: { name: 'ipmk', gene: 'IPMK', weight: 0.15, label: 'Nutrient Sensing' },
- rs10936599: { name: 'terc', gene: 'TERC', weight: 0.20, label: 'Telomere Length' }
-};
-
-const CARDIOVASCULAR_MARKERS = {
- rs6025: { name: 'factorV', gene: 'F5', weight: 0.20, label: 'Factor V Leiden' },
- rs1333049: { name: 'cad9p21', gene: '9p21.3', weight: 0.20, label: 'Coronary Artery Disease' },
- rs10455872: { name: 'lpa', gene: 'LPA', weight: 0.15, label: 'Lipoprotein(a)' },
- rs1799963: { name: 'prothrombin', gene: 'F2', weight: 0.15, label: 'Prothrombin Thrombophilia' },
- rs1800795: { name: 'il6', gene: 'IL-6', weight: 0.15, label: 'Inflammation / IL-6' },
- rs1800629: { name: 'tnfa', gene: 'TNF-alpha', weight: 0.15, label: 'Inflammation / TNF-alpha' }
-};
-
-const LONGEVITY_SIGNAL = { beneficial: 1, typical: 0, concern: -1 };
-const CARDIO_SIGNAL = { beneficial: -1, typical: 0, concern: 1, major_concern: 1.5 };
-const SSA_BASELINE_LIFE_EXPECTANCY = 78.5;
-
-function extractLongevityMarkers(savedMarkers) {
- const results = {};
- const markerValues = Object.values(savedMarkers || {});
- for (const [rsid, def] of Object.entries(LONGEVITY_MARKERS)) {
- const found = markerValues.find(m => m.rsid === rsid);
- if (found) {
- const signal = LONGEVITY_SIGNAL[found.status] ?? 0;
- results[def.name] = {
- rsid, gene: def.gene, label: def.label,
- genotype: found.genotype, status: found.status,
- weight: def.weight, signal
- };
- }
- }
- return results;
-}
-
-function extractCardiovascularMarkers(savedMarkers) {
- const results = {};
- const markerValues = Object.values(savedMarkers || {});
- for (const [rsid, def] of Object.entries(CARDIOVASCULAR_MARKERS)) {
- const found = markerValues.find(m => m.rsid === rsid);
- if (found) {
- const signal = CARDIO_SIGNAL[found.status] ?? 0;
- results[def.name] = {
- rsid, gene: def.gene, label: def.label,
- genotype: found.genotype, status: found.status,
- weight: def.weight, signal
- };
- }
- }
- return results;
-}
-
-function computeLifeExpectancy(longevityMarkers, cardiovascularMarkers, birthDate) {
- let longevityScore = 0;
- let longevityWeight = 0;
- for (const marker of Object.values(longevityMarkers)) {
- longevityScore += marker.signal * marker.weight;
- longevityWeight += marker.weight;
- }
- if (longevityWeight > 0) longevityScore /= longevityWeight;
-
- let cardioRisk = 0;
- let cardioWeight = 0;
- for (const marker of Object.values(cardiovascularMarkers)) {
- cardioRisk += marker.signal * marker.weight;
- cardioWeight += marker.weight;
- }
- if (cardioWeight > 0) cardioRisk /= cardioWeight;
-
- const longevityAdjustment = Math.round(longevityScore * 5 * 100) / 100 || 0;
- const cardiovascularAdjustment = Math.round(-cardioRisk * 4 * 100) / 100 || 0;
- const adjusted = Math.round((SSA_BASELINE_LIFE_EXPECTANCY + longevityAdjustment + cardiovascularAdjustment) * 10) / 10;
-
- const longevityCount = Object.keys(longevityMarkers).length;
- const cardioCount = Object.keys(cardiovascularMarkers).length;
- const maxLongevity = Object.keys(LONGEVITY_MARKERS).length;
- const maxCardio = Object.keys(CARDIOVASCULAR_MARKERS).length;
- const coverage = (longevityCount + cardioCount) / (maxLongevity + maxCardio);
- const confidence = Math.round(Math.min(1, coverage) * 100) / 100;
-
- 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);
- 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)
- };
- }
-
- return {
- longevityScore: Math.round(longevityScore * 1000) / 1000,
- cardiovascularRisk: Math.round(cardioRisk * 1000) / 1000,
- lifeExpectancy: {
- baseline: SSA_BASELINE_LIFE_EXPECTANCY,
- adjusted,
- longevityAdjustment,
- cardiovascularAdjustment
- },
- timeHorizons,
- confidence
- };
-}
-
-function computeGoalUrgency(goal, timeHorizons) {
- if (!timeHorizons || !goal.horizon) return null;
- const horizonMap = {
- '1-year': 1, '3-year': 3, '5-year': 5,
- '10-year': 10, '20-year': 20, 'lifetime': timeHorizons.yearsRemaining
- };
- const horizonYears = horizonMap[goal.horizon] ?? 5;
- const yearsRemaining = timeHorizons.yearsRemaining;
- const rawUrgency = 1 - Math.min(1, yearsRemaining / (horizonYears * 2));
- const healthPressure = horizonYears > timeHorizons.healthyYearsRemaining ? 0.2 : 0;
- return Math.min(1, Math.round((rawUrgency + healthPressure) * 100) / 100);
-}
-
// ============================================================
// Longevity Tests
// ============================================================
@@ -870,6 +576,19 @@ describe('computeGoalUrgency', () => {
const urgency = computeGoalUrgency({ horizon: '20-year' }, tightHorizons);
expect(urgency).toBeLessThanOrEqual(1);
});
+
+ it('returns max urgency instead of NaN for a lifetime goal with zero years remaining', () => {
+ // horizonYears for 'lifetime' is derived from timeHorizons.yearsRemaining, so
+ // when that's 0 the old formula divided 0/0 and produced NaN. The real
+ // implementation short-circuits to max urgency (1) whenever horizonYears or
+ // yearsRemaining is non-positive — this case is reachable in production for
+ // a user whose computed life expectancy has already elapsed.
+ const urgency = computeGoalUrgency(
+ { horizon: 'lifetime' },
+ { yearsRemaining: 0, healthyYearsRemaining: 0 }
+ );
+ expect(urgency).toBe(1);
+ });
});
// === Integration tests (mock fs + genome service) ===
diff --git a/server/services/localThinking.test.js b/server/services/localThinking.test.js
new file mode 100644
index 0000000000..c97ecb13ca
--- /dev/null
+++ b/server/services/localThinking.test.js
@@ -0,0 +1,270 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+vi.mock('./lmStudioManager.js', () => ({
+ checkLMStudioAvailable: vi.fn(),
+ quickCompletion: vi.fn()
+}));
+
+import { checkLMStudioAvailable, quickCompletion } from './lmStudioManager.js';
+import { analyzeTask, classifyMemory, getStats, resetStats, COMPLEXITY_THRESHOLDS } from './localThinking.js';
+
+// getStats()/resetStats() operate on module-level singleton state that
+// analyzeTask()/classifyMemory() mutate as a side effect — reset between
+// tests so counts from one case don't leak into the next.
+beforeEach(() => {
+ vi.clearAllMocks();
+ resetStats();
+});
+
+// =============================================================================
+// analyzeTask — LM Studio unavailable (keyword-only fallback)
+// =============================================================================
+
+describe('analyzeTask (LM Studio unavailable)', () => {
+ beforeEach(() => {
+ checkLMStudioAvailable.mockResolvedValue(false);
+ });
+
+ it('scores a high-complexity keyword description above the escalation threshold', async () => {
+ const result = await analyzeTask({ description: 'refactor the entire codebase for security' });
+ expect(result.complexity).toBeGreaterThanOrEqual(0.8);
+ expect(result.escalateToCloud).toBe(true);
+ expect(result.localAnalysis).toBe(false);
+ expect(result.reason).toBe('LM Studio unavailable, using keyword analysis');
+ });
+
+ it('scores a low-complexity keyword description below the escalation threshold', async () => {
+ const result = await analyzeTask({ description: 'fix a typo in the readme' });
+ expect(result.complexity).toBe(0.3);
+ expect(result.escalateToCloud).toBe(false);
+ });
+
+ it('scores a medium-complexity keyword description at the default midpoint', async () => {
+ const result = await analyzeTask({ description: 'implement a new feature' });
+ expect(result.complexity).toBe(0.5);
+ expect(result.escalateToCloud).toBe(false);
+ });
+
+ it('defaults to medium complexity for an empty/missing description', async () => {
+ const result = await analyzeTask({});
+ expect(result.complexity).toBe(0.5);
+ expect(result.escalateToCloud).toBe(false);
+ });
+
+ it('boosts complexity for a long description with no matching keywords', async () => {
+ const filler = 'lorem ipsum dolor sit amet consectetur adipiscing elit '.repeat(20); // > 1000 chars, no keyword hits
+ expect(filler.length).toBeGreaterThan(1000);
+ const result = await analyzeTask({ description: filler });
+ // base 0.5 + 0.1 (>500 chars) + 0.1 (>1000 chars) = 0.7
+ expect(result.complexity).toBeCloseTo(0.7, 5);
+ });
+
+ it('caps the length boost at 1.0 even when combined with a high-complexity keyword', async () => {
+ const filler = 'refactor ' + 'x'.repeat(1200);
+ const result = await analyzeTask({ description: filler });
+ expect(result.complexity).toBeLessThanOrEqual(1);
+ });
+});
+
+// =============================================================================
+// analyzeTask — LM Studio available (local-model analysis)
+// =============================================================================
+
+describe('analyzeTask (LM Studio available)', () => {
+ beforeEach(() => {
+ checkLMStudioAvailable.mockResolvedValue(true);
+ });
+
+ it('escalates when the local model reports complexity above the complex threshold', async () => {
+ quickCompletion.mockResolvedValue({
+ success: true,
+ content: JSON.stringify({ complexity: COMPLEXITY_THRESHOLDS.complex + 0.05, requiresArchitecturalDecisions: false })
+ });
+ const result = await analyzeTask({ description: 'do something' });
+ expect(result.escalateToCloud).toBe(true);
+ expect(result.localAnalysis).toBe(true);
+ expect(result.reason).toBe('Task requires advanced reasoning');
+ });
+
+ it('escalates when the local model flags an architectural decision, even at low complexity', async () => {
+ quickCompletion.mockResolvedValue({
+ success: true,
+ content: JSON.stringify({ complexity: 0.1, requiresArchitecturalDecisions: true })
+ });
+ const result = await analyzeTask({ description: 'do something' });
+ expect(result.escalateToCloud).toBe(true);
+ });
+
+ it('escalates for multi-file changes only when complexity also exceeds the medium threshold', async () => {
+ const belowMedium = await (async () => {
+ quickCompletion.mockResolvedValue({
+ success: true,
+ content: JSON.stringify({ complexity: COMPLEXITY_THRESHOLDS.medium - 0.1, requiresMultiFileChanges: true })
+ });
+ return analyzeTask({ description: 'do something' });
+ })();
+ expect(belowMedium.escalateToCloud).toBe(false);
+
+ const aboveMedium = await (async () => {
+ quickCompletion.mockResolvedValue({
+ success: true,
+ content: JSON.stringify({ complexity: COMPLEXITY_THRESHOLDS.medium + 0.1, requiresMultiFileChanges: true })
+ });
+ return analyzeTask({ description: 'do something' });
+ })();
+ expect(aboveMedium.escalateToCloud).toBe(true);
+ });
+
+ it('does not escalate a low-complexity task with no risk flags', async () => {
+ quickCompletion.mockResolvedValue({
+ success: true,
+ content: JSON.stringify({ complexity: 0.2, requiresArchitecturalDecisions: false, requiresMultiFileChanges: false })
+ });
+ const result = await analyzeTask({ description: 'do something' });
+ expect(result.escalateToCloud).toBe(false);
+ expect(result.reason).toBe('Task suitable for local execution');
+ });
+
+ it('surfaces the suggested approach and risks from the local model', async () => {
+ quickCompletion.mockResolvedValue({
+ success: true,
+ content: JSON.stringify({
+ complexity: 0.4,
+ suggestedApproach: 'Write a helper function',
+ potentialRisks: ['may break existing callers']
+ })
+ });
+ const result = await analyzeTask({ description: 'do something' });
+ expect(result.suggestedApproach).toBe('Write a helper function');
+ expect(result.potentialRisks).toEqual(['may break existing callers']);
+ expect(result.suggestions).toEqual(['may break existing callers']);
+ });
+
+ it('falls back to keyword complexity when the local completion call fails', async () => {
+ quickCompletion.mockResolvedValue({ success: false, error: 'model not loaded' });
+ const result = await analyzeTask({ description: 'refactor everything' });
+ expect(result.localAnalysis).toBe(false);
+ expect(result.reason).toBe('Local analysis failed: model not loaded');
+ expect(result.complexity).toBeGreaterThanOrEqual(0.8); // keyword fallback still applies
+ });
+
+ it('falls back to keyword complexity when the local model response has no parseable JSON', async () => {
+ quickCompletion.mockResolvedValue({ success: true, content: 'not json at all' });
+ const result = await analyzeTask({ description: 'refactor everything' });
+ expect(result.localAnalysis).toBe(true);
+ expect(result.reason).toBe('Could not parse local analysis');
+ expect(result.rawResponse).toBe('not json at all');
+ expect(result.complexity).toBeGreaterThanOrEqual(0.8);
+ });
+
+ it('falls back to keyword complexity when the local model response is malformed JSON', async () => {
+ quickCompletion.mockResolvedValue({ success: true, content: '{ complexity: 0.9,, }' });
+ const result = await analyzeTask({ description: 'fix a typo' });
+ expect(result.localAnalysis).toBe(true);
+ expect(result.complexity).toBe(0.3); // keyword fallback for "typo"
+ });
+});
+
+// =============================================================================
+// classifyMemory
+// =============================================================================
+
+describe('classifyMemory', () => {
+ it('reports unavailable when LM Studio cannot be reached', async () => {
+ checkLMStudioAvailable.mockResolvedValue(false);
+ const result = await classifyMemory('The user prefers dark mode.');
+ expect(result).toEqual({ success: false, error: 'LM Studio unavailable' });
+ });
+
+ it('returns the parsed classification on success', async () => {
+ checkLMStudioAvailable.mockResolvedValue(true);
+ quickCompletion.mockResolvedValue({
+ success: true,
+ content: JSON.stringify({ type: 'preference', category: 'other', tags: ['ui'], importance: 0.4 })
+ });
+ const result = await classifyMemory('The user prefers dark mode.');
+ expect(result).toEqual({
+ success: true,
+ type: 'preference',
+ category: 'other',
+ tags: ['ui'],
+ importance: 0.4
+ });
+ });
+
+ it('propagates the completion error when the local call fails', async () => {
+ checkLMStudioAvailable.mockResolvedValue(true);
+ quickCompletion.mockResolvedValue({ success: false, error: 'timeout' });
+ const result = await classifyMemory('some memory');
+ expect(result).toEqual({ success: false, error: 'timeout' });
+ });
+
+ it('returns a bare success with no fields when the response has no JSON braces at all', async () => {
+ // No `{...}` substring means the regex match is null; spreading `null` into
+ // the return object is a JS no-op (not an error), so this short-circuits to
+ // `{ success: true }` WITHOUT hitting the catch/parse-failure branch below.
+ checkLMStudioAvailable.mockResolvedValue(true);
+ quickCompletion.mockResolvedValue({ success: true, content: 'nonsense response' });
+ const result = await classifyMemory('some memory');
+ expect(result).toEqual({ success: true });
+ });
+
+ it('reports a parse failure with the raw response when the matched braces are invalid JSON', async () => {
+ checkLMStudioAvailable.mockResolvedValue(true);
+ quickCompletion.mockResolvedValue({ success: true, content: '{ type: unquoted-key }' });
+ const result = await classifyMemory('some memory');
+ expect(result).toEqual({
+ success: false,
+ error: 'Could not parse classification',
+ rawResponse: '{ type: unquoted-key }'
+ });
+ });
+});
+
+// =============================================================================
+// getStats / resetStats
+// =============================================================================
+
+describe('getStats', () => {
+ it('reports zero rates with no analyses recorded', () => {
+ const stats = getStats();
+ expect(stats).toEqual({
+ localAnalyses: 0,
+ cloudEscalations: 0,
+ localSuccesses: 0,
+ localFailures: 0,
+ localSuccessRate: '0%',
+ escalationRate: '0%'
+ });
+ });
+
+ it('tracks success and escalation rates across multiple analyses', async () => {
+ checkLMStudioAvailable.mockResolvedValue(true);
+
+ // One successful, non-escalating analysis
+ quickCompletion.mockResolvedValueOnce({
+ success: true,
+ content: JSON.stringify({ complexity: 0.1 })
+ });
+ await analyzeTask({ description: 'do something' });
+
+ // One successful, escalating analysis
+ quickCompletion.mockResolvedValueOnce({
+ success: true,
+ content: JSON.stringify({ complexity: 0.95 })
+ });
+ await analyzeTask({ description: 'do something else' });
+
+ // One failed local completion
+ quickCompletion.mockResolvedValueOnce({ success: false, error: 'down' });
+ await analyzeTask({ description: 'a third task' });
+
+ const stats = getStats();
+ expect(stats.localAnalyses).toBe(3);
+ expect(stats.localSuccesses).toBe(2);
+ expect(stats.localFailures).toBe(1);
+ expect(stats.cloudEscalations).toBe(1);
+ expect(stats.localSuccessRate).toBe('66.7%');
+ expect(stats.escalationRate).toBe('33.3%');
+ });
+});
diff --git a/server/services/meatspace.test.js b/server/services/meatspace.test.js
index 050fda6a00..41fe512dc5 100644
--- a/server/services/meatspace.test.js
+++ b/server/services/meatspace.test.js
@@ -1,109 +1,5 @@
import { describe, it, expect } from 'vitest';
-
-// Inline copies of pure functions to avoid complex mocking
-// (follows existing test pattern in subAgentSpawner.test.js)
-
-function computeLifestyleAdjustment(lifestyle) {
- if (!lifestyle) return 0;
- let adj = 0;
-
- const smoking = lifestyle.smokingStatus || 'never';
- if (smoking === 'never') adj += 0;
- else if (smoking === 'former') adj -= 2;
- else if (smoking === 'current') adj -= 10;
-
- const drinks = lifestyle.alcoholDrinksPerDay;
- if (drinks != null) {
- if (drinks <= 2) adj += 0.5;
- else if (drinks > 3) adj -= 5;
- }
-
- const exercise = lifestyle.exerciseMinutesPerWeek ?? 150;
- if (exercise > 150) adj += 2;
- else if (exercise >= 75) adj += 0.5;
- else adj -= 2;
-
- const sleep = lifestyle.sleepHoursPerNight ?? 7.5;
- if (sleep >= 7 && sleep <= 9) adj += 1;
- else if (sleep >= 6 && sleep < 7) adj += 0;
- else adj -= 1.5;
-
- const diet = lifestyle.dietQuality || 'good';
- if (diet === 'excellent') adj += 2;
- else if (diet === 'good') adj += 0.5;
- else if (diet === 'fair') adj += 0;
- else adj -= 3;
-
- const stress = lifestyle.stressLevel || 'moderate';
- if (stress === 'low') adj += 1;
- else if (stress === 'moderate') adj += 0;
- else adj -= 2;
-
- const bmi = lifestyle.bmi;
- if (bmi != null) {
- if (bmi >= 18.5 && bmi < 25) adj += 0.5;
- else if (bmi >= 25 && bmi < 30) adj -= 0.5;
- else if (bmi >= 30) adj -= 3;
- }
-
- return Math.round(adj * 100) / 100;
-}
-
-function computeDeathClock(birthDate, genomeAdjustedLE, lifestyleAdj) {
- const SSA_BASELINE = 78.5;
- const baseline = genomeAdjustedLE ?? SSA_BASELINE;
- const totalLE = baseline + lifestyleAdj;
-
- const birth = new Date(birthDate);
- const deathDate = new Date(birth);
- deathDate.setFullYear(deathDate.getFullYear() + Math.floor(totalLE));
- deathDate.setMonth(deathDate.getMonth() + Math.round((totalLE % 1) * 12));
-
- const now = new Date();
- const msRemaining = deathDate.getTime() - now.getTime();
- const ageYears = (now - birth) / (365.25 * 24 * 60 * 60 * 1000);
- const yearsRemaining = Math.max(0, totalLE - ageYears);
- const healthyYearsRemaining = Math.round(yearsRemaining * 0.85 * 10) / 10;
- const percentComplete = Math.min(100, Math.round((ageYears / totalLE) * 1000) / 10);
-
- return {
- birthDate,
- deathDate: deathDate.toISOString(),
- msRemaining: Math.max(0, msRemaining),
- lifeExpectancy: {
- baseline: SSA_BASELINE,
- genomeAdjusted: genomeAdjustedLE ?? SSA_BASELINE,
- lifestyleAdjustment: lifestyleAdj,
- total: Math.round(totalLE * 10) / 10
- },
- ageYears: Math.round(ageYears * 100) / 100,
- yearsRemaining: Math.round(yearsRemaining * 100) / 100,
- healthyYearsRemaining,
- percentComplete
- };
-}
-
-function computeLEV(birthDate, adjustedLE) {
- const LEV_TARGET_YEAR = 2045;
- const LEV_START_YEAR = 2000;
- const birthYear = new Date(birthDate).getFullYear();
-
- const now = new Date();
- const currentYear = now.getFullYear() + now.getMonth() / 12;
- const ageAtLEV = LEV_TARGET_YEAR - birthYear;
- const yearsToLEV = LEV_TARGET_YEAR - currentYear;
- const researchProgress = Math.round(((currentYear - LEV_START_YEAR) / (LEV_TARGET_YEAR - LEV_START_YEAR)) * 1000) / 10;
- const onTrack = adjustedLE > ageAtLEV;
-
- return {
- targetYear: LEV_TARGET_YEAR,
- ageAtLEV,
- yearsToLEV: Math.round(yearsToLEV * 10) / 10,
- researchProgress: Math.min(100, researchProgress),
- onTrack,
- adjustedLifeExpectancy: adjustedLE
- };
-}
+import { computeLifestyleAdjustment, computeDeathClock, computeLEV } from './meatspace.js';
// =============================================================================
// LIFESTYLE ADJUSTMENT TESTS
diff --git a/server/services/meatspaceAlcohol.test.js b/server/services/meatspaceAlcohol.test.js
index 9ffd4e7d08..5701516bb0 100644
--- a/server/services/meatspaceAlcohol.test.js
+++ b/server/services/meatspaceAlcohol.test.js
@@ -1,72 +1,6 @@
import { describe, it, expect } from 'vitest';
-
-// Inline pure functions to avoid mocking file I/O
-
-function computeStandardDrinks(oz, abv) {
- const pureAlcoholOz = oz * (abv / 100);
- return Math.round((pureAlcoholOz / 0.6) * 100) / 100;
-}
-
-function computeRollingAverages(entries, sex = 'male') {
- const now = new Date();
- const today = now.toISOString().split('T')[0];
-
- const alcoholEntries = entries
- .filter(e => e.alcohol?.standardDrinks > 0)
- .sort((a, b) => a.date.localeCompare(b.date));
-
- const allEntries = entries.sort((a, b) => a.date.localeCompare(b.date));
-
- const todayEntry = allEntries.find(e => e.date === today);
- const todayDrinks = todayEntry?.alcohol?.standardDrinks || 0;
-
- const rollingAverage = (days) => {
- const cutoff = new Date(now);
- cutoff.setDate(cutoff.getDate() - days);
- const cutoffStr = cutoff.toISOString().split('T')[0];
-
- let totalDrinks = 0;
- let dayCount = 0;
-
- for (const entry of allEntries) {
- if (entry.date >= cutoffStr && entry.date <= today) {
- totalDrinks += entry.alcohol?.standardDrinks || 0;
- dayCount++;
- }
- }
-
- return dayCount > 0 ? Math.round((totalDrinks / days) * 100) / 100 : 0;
- };
-
- let allTimeAvg = 0;
- if (allEntries.length > 0) {
- const firstDate = new Date(allEntries[0].date);
- const totalDays = Math.max(1, Math.ceil((now - firstDate) / (24 * 60 * 60 * 1000)));
- const totalDrinks = allEntries.reduce((sum, e) => sum + (e.alcohol?.standardDrinks || 0), 0);
- allTimeAvg = Math.round((totalDrinks / totalDays) * 100) / 100;
- }
-
- const thresholds = sex === 'female'
- ? { dailyMax: 1, weeklyMax: 7 }
- : { dailyMax: 2, weeklyMax: 14 };
-
- const avg7day = rollingAverage(7);
- const weeklyTotal = Math.round(avg7day * 7 * 100) / 100;
-
- return {
- today: todayDrinks,
- avg7day,
- avg30day: rollingAverage(30),
- allTimeAvg,
- weeklyTotal,
- thresholds,
- riskLevel: weeklyTotal > thresholds.weeklyMax ? 'high'
- : weeklyTotal > thresholds.weeklyMax * 0.7 ? 'moderate'
- : 'low',
- drinkingDays: alcoholEntries.length,
- totalEntries: allEntries.length
- };
-}
+import { computeStandardDrinks, computeRollingAverages } from './meatspaceAlcohol.js';
+import { getDateString } from '../lib/fileUtils.js';
// =============================================================================
// STANDARD DRINKS TESTS
@@ -173,11 +107,14 @@ describe('updateDrink logic', () => {
// =============================================================================
describe('computeRollingAverages', () => {
- // Helper to make dates relative to today
+ // Helper to make dates relative to today. computeRollingAverages derives "today"
+ // from getDateString (local calendar date), NOT a UTC toISOString() split — a
+ // UTC-based fixture here would drift by a day from the function's own "today"
+ // near local midnight in any timezone west of UTC. Match the real semantics.
const daysAgo = (n) => {
const d = new Date();
d.setDate(d.getDate() - n);
- return d.toISOString().split('T')[0];
+ return getDateString(d);
};
it('returns zeros for empty entries', () => {
@@ -190,7 +127,7 @@ describe('computeRollingAverages', () => {
});
it('computes today drinks from matching entry', () => {
- const today = new Date().toISOString().split('T')[0];
+ const today = getDateString();
const entries = [
{ date: today, alcohol: { standardDrinks: 2.5, drinks: [{ name: 'Beer', oz: 12, abv: 5 }] } }
];
diff --git a/server/services/meatspaceHealth.test.js b/server/services/meatspaceHealth.test.js
index 8b76cfb4ae..559c058268 100644
--- a/server/services/meatspaceHealth.test.js
+++ b/server/services/meatspaceHealth.test.js
@@ -1,228 +1,234 @@
-import { describe, it, expect } from 'vitest';
-
-// Inline pure functions to avoid mocking file I/O
-
-function extractBodyHistory(entries) {
- return entries
- .filter(e => e.body && Object.keys(e.body).length > 0)
- .map(e => ({ date: e.date, ...e.body }))
- .sort((a, b) => a.date.localeCompare(b.date));
-}
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// classifyBP is pure and lives in the client bundle (client/src/components/meatspace/
+// bpClassification.js) — "ported from MortalLoom's CardioFitnessEngine so PortOS and
+// the iOS/macOS companion app report identical categories for the same reading" per
+// its own header comment. It has no server-side counterpart to reimplement: import
+// the real, shared source of truth directly rather than keeping a second inline copy
+// that could silently drift from what the UI actually classifies.
+import { classifyBP } from '../../client/src/components/meatspace/bpClassification.js';
+
+// getBodyHistory / addBodyEntry / getBloodPressureHistory / addBloodPressureReading
+// in meatspaceHealth.js do NOT expose their filter/sort/merge logic as standalone
+// pure functions — it's inlined in each async service function. Rather than keep
+// reimplementing that logic locally (the anti-pattern this file used to have),
+// exercise the real exported functions with fs/promises + mortalLoomStore mocked
+// at the I/O boundary, mirroring meatspaceCustomDrinks.test.js's established
+// pattern for this same service directory.
+
+vi.mock('fs/promises', () => ({
+ writeFile: vi.fn().mockResolvedValue(undefined)
+}));
+
+vi.mock('../lib/fileUtils.js', () => ({
+ tryReadFile: vi.fn().mockResolvedValue(null),
+ readJSONFile: vi.fn(),
+ getDateString: vi.fn(() => '2024-06-01'),
+ PATHS: {
+ root: '/mock',
+ data: '/mock/data',
+ meatspace: '/mock/data/meatspace'
+ },
+ ensureDir: vi.fn().mockResolvedValue(undefined),
+ atomicWrite: vi.fn(async (filePath, data) => {
+ const payload = (typeof data === 'string' || Buffer.isBuffer(data)) ? data : JSON.stringify(data, null, 2);
+ const { writeFile } = await import('fs/promises');
+ return writeFile(filePath, payload);
+ })
+}));
+
+vi.mock('./mortalLoomStore.js', () => ({
+ isMortalLoomEnabled: vi.fn().mockResolvedValue(false),
+ mlArrayIfEnabled: vi.fn().mockResolvedValue(null),
+ mlPush: vi.fn(),
+ mlPatchById: vi.fn(),
+ mlRemoveById: vi.fn(),
+ mlUpsertHealthMetricByDate: vi.fn()
+}));
+
+import { writeFile } from 'fs/promises';
+import { readJSONFile, getDateString } from '../lib/fileUtils.js';
+import {
+ getBodyHistory,
+ addBodyEntry,
+ getBloodPressureHistory,
+ addBloodPressureReading
+} from './meatspaceHealth.js';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ getDateString.mockReturnValue('2024-06-01');
+});
-function mergeBodyEntry(existingBody, newBody) {
- return { ...(existingBody || {}), ...newBody };
-}
+// =============================================================================
+// BP CLASSIFICATION TESTS (AHA/ACC 2017, ported from MortalLoom CardioFitnessEngine)
+// =============================================================================
-function sortByDate(items) {
- return [...items].sort((a, b) => a.date.localeCompare(b.date));
-}
+describe('classifyBP', () => {
+ it.each([
+ [110, 70, 'normal'],
+ [119, 79, 'normal'],
+ [120, 79, 'elevated'],
+ [125, 75, 'elevated'],
+ [130, 75, 'highStage1'],
+ [115, 82, 'highStage1'],
+ [140, 85, 'highStage2'],
+ [135, 92, 'highStage2'],
+ [185, 95, 'crisis'],
+ [150, 125, 'crisis']
+ ])('classifies %d/%d as %s', (sys, dia, expected) => {
+ expect(classifyBP(sys, dia)).toBe(expected);
+ });
+});
// =============================================================================
-// BODY HISTORY TESTS
+// BODY HISTORY TESTS (real getBodyHistory, fs mocked)
// =============================================================================
-describe('extractBodyHistory', () => {
- it('returns empty array for no body entries', () => {
- const entries = [
- { date: '2024-01-01', nutrition: { calories: 2000 } }
- ];
- expect(extractBodyHistory(entries)).toEqual([]);
+describe('getBodyHistory', () => {
+ it('returns empty array for no body entries', async () => {
+ readJSONFile.mockResolvedValue({
+ entries: [{ date: '2024-01-01', nutrition: { calories: 2000 } }]
+ });
+ expect(await getBodyHistory()).toEqual([]);
});
- it('extracts and sorts body entries', () => {
- const entries = [
- { date: '2024-03-01', body: { weightLbs: 160 } },
- { date: '2024-01-01', body: { weightLbs: 165 } },
- { date: '2024-02-01', body: { weightLbs: 162 } }
- ];
- const result = extractBodyHistory(entries);
+ it('extracts and sorts body entries chronologically', async () => {
+ readJSONFile.mockResolvedValue({
+ entries: [
+ { date: '2024-03-01', body: { weightLbs: 160 } },
+ { date: '2024-01-01', body: { weightLbs: 165 } },
+ { date: '2024-02-01', body: { weightLbs: 162 } }
+ ]
+ });
+ const result = await getBodyHistory();
expect(result).toHaveLength(3);
- expect(result[0].date).toBe('2024-01-01');
- expect(result[0].weightLbs).toBe(165);
+ expect(result[0]).toEqual({ date: '2024-01-01', weightLbs: 165 });
expect(result[2].date).toBe('2024-03-01');
});
- it('filters out entries with empty body objects', () => {
- const entries = [
- { date: '2024-01-01', body: {} },
- { date: '2024-01-02', body: { weightLbs: 160 } }
- ];
- const result = extractBodyHistory(entries);
+ it('filters out entries with empty body objects', async () => {
+ readJSONFile.mockResolvedValue({
+ entries: [
+ { date: '2024-01-01', body: {} },
+ { date: '2024-01-02', body: { weightLbs: 160 } }
+ ]
+ });
+ const result = await getBodyHistory();
expect(result).toHaveLength(1);
expect(result[0].date).toBe('2024-01-02');
});
});
// =============================================================================
-// BODY ENTRY MERGE TESTS
+// BODY ENTRY MERGE TESTS (real addBodyEntry, fs mocked)
// =============================================================================
-describe('mergeBodyEntry', () => {
- it('creates body from scratch when no existing data', () => {
- const result = mergeBodyEntry(null, { weightLbs: 160 });
- expect(result).toEqual({ weightLbs: 160 });
- });
-
- it('merges new fields into existing body', () => {
- const existing = { weightLbs: 160 };
- const result = mergeBodyEntry(existing, { fatPct: 15 });
- expect(result).toEqual({ weightLbs: 160, fatPct: 15 });
+describe('addBodyEntry', () => {
+ it('creates a body entry from scratch when the date is unseen', async () => {
+ readJSONFile.mockResolvedValue({ entries: [], lastEntryDate: null });
+ const result = await addBodyEntry({ date: '2024-01-01', weightLbs: 160 });
+ expect(result).toEqual({ date: '2024-01-01', weightLbs: 160 });
+ expect(writeFile).toHaveBeenCalledTimes(1);
});
- it('overwrites existing fields', () => {
- const existing = { weightLbs: 160, fatPct: 15 };
- const result = mergeBodyEntry(existing, { weightLbs: 158 });
- expect(result).toEqual({ weightLbs: 158, fatPct: 15 });
+ it('merges new fields into an existing body entry for the same date', async () => {
+ readJSONFile.mockResolvedValue({
+ entries: [{ date: '2024-01-01', body: { weightLbs: 160 } }],
+ lastEntryDate: '2024-01-01'
+ });
+ const result = await addBodyEntry({ date: '2024-01-01', fatPct: 15 });
+ expect(result).toEqual({ date: '2024-01-01', weightLbs: 160, fatPct: 15 });
});
-});
-
-// =============================================================================
-// SORT TESTS
-// =============================================================================
-describe('sortByDate', () => {
- it('sorts chronologically', () => {
- const items = [
- { date: '2024-12-01' },
- { date: '2024-01-15' },
- { date: '2024-06-20' }
- ];
- const result = sortByDate(items);
- expect(result[0].date).toBe('2024-01-15');
- expect(result[1].date).toBe('2024-06-20');
- expect(result[2].date).toBe('2024-12-01');
+ it('overwrites an existing field on a repeat entry for the same date', async () => {
+ readJSONFile.mockResolvedValue({
+ entries: [{ date: '2024-01-01', body: { weightLbs: 160, fatPct: 15 } }],
+ lastEntryDate: '2024-01-01'
+ });
+ const result = await addBodyEntry({ date: '2024-01-01', weightLbs: 158 });
+ expect(result).toEqual({ date: '2024-01-01', weightLbs: 158, fatPct: 15 });
});
- it('does not mutate original array', () => {
- const items = [{ date: '2024-12-01' }, { date: '2024-01-01' }];
- sortByDate(items);
- expect(items[0].date).toBe('2024-12-01');
+ it('defaults to the local calendar day when no date is given', async () => {
+ readJSONFile.mockResolvedValue({ entries: [], lastEntryDate: null });
+ getDateString.mockReturnValue('2024-06-01');
+ const result = await addBodyEntry({ weightLbs: 170 });
+ expect(result.date).toBe('2024-06-01');
});
});
// =============================================================================
-// BLOOD PRESSURE TESTS
+// BLOOD PRESSURE HISTORY TESTS (real getBloodPressureHistory, fs mocked)
// =============================================================================
-// Pure versions of the BP logic in meatspaceHealth.js / mortalLoomStore.js,
-// copied here per project convention (see BODY HISTORY TESTS above).
-
-function extractBloodPressureHistory(healthMetrics) {
- return healthMetrics
- .filter(m => m?.bloodPressureSystolic != null && m?.bloodPressureDiastolic != null)
- .map(m => ({ date: m.date, systolic: m.bloodPressureSystolic, diastolic: m.bloodPressureDiastolic }))
- .sort((a, b) => a.date.localeCompare(b.date));
-}
-
-function upsertHealthMetricByDate(healthMetrics, date, patch) {
- const existing = healthMetrics.find(m => m.date === date);
- if (existing) {
- for (const [k, v] of Object.entries(patch)) {
- if (v !== undefined && v !== null) existing[k] = v;
- }
- return { metrics: healthMetrics, entry: existing };
- }
- const created = { date, ...patch };
- return { metrics: [...healthMetrics, created], entry: created };
-}
-
-describe('extractBloodPressureHistory', () => {
- it('filters entries missing either systolic or diastolic', () => {
- const metrics = [
- { date: '2024-01-01', bloodPressureSystolic: 118, bloodPressureDiastolic: 78 },
- { date: '2024-01-02', bloodPressureSystolic: 125 },
- { date: '2024-01-03', bloodPressureDiastolic: 82 },
- { date: '2024-01-04', heartRate: 60 }
- ];
- const result = extractBloodPressureHistory(metrics);
+describe('getBloodPressureHistory', () => {
+ it('filters entries missing either systolic or diastolic', async () => {
+ readJSONFile.mockResolvedValue({
+ entries: [
+ { date: '2024-01-01', bloodPressureSystolic: 118, bloodPressureDiastolic: 78 },
+ { date: '2024-01-02', bloodPressureSystolic: 125 },
+ { date: '2024-01-03', bloodPressureDiastolic: 82 },
+ { date: '2024-01-04', heartRate: 60 }
+ ]
+ });
+ const result = await getBloodPressureHistory();
expect(result).toHaveLength(1);
expect(result[0]).toEqual({ date: '2024-01-01', systolic: 118, diastolic: 78 });
});
- it('sorts ascending by date', () => {
- const metrics = [
- { date: '2024-03-01', bloodPressureSystolic: 130, bloodPressureDiastolic: 85 },
- { date: '2024-01-01', bloodPressureSystolic: 120, bloodPressureDiastolic: 80 },
- { date: '2024-02-01', bloodPressureSystolic: 125, bloodPressureDiastolic: 82 }
- ];
- const result = extractBloodPressureHistory(metrics);
+ it('sorts ascending by date', async () => {
+ readJSONFile.mockResolvedValue({
+ entries: [
+ { date: '2024-03-01', bloodPressureSystolic: 130, bloodPressureDiastolic: 85 },
+ { date: '2024-01-01', bloodPressureSystolic: 120, bloodPressureDiastolic: 80 },
+ { date: '2024-02-01', bloodPressureSystolic: 125, bloodPressureDiastolic: 82 }
+ ]
+ });
+ const result = await getBloodPressureHistory();
expect(result.map(r => r.date)).toEqual(['2024-01-01', '2024-02-01', '2024-03-01']);
});
});
-describe('upsertHealthMetricByDate', () => {
- it('appends a new entry when the date is unseen', () => {
- const { metrics, entry } = upsertHealthMetricByDate(
- [{ date: '2024-01-01', heartRate: 60 }],
- '2024-02-01',
- { bloodPressureSystolic: 120, bloodPressureDiastolic: 80 }
- );
- expect(metrics).toHaveLength(2);
- expect(entry).toMatchObject({ date: '2024-02-01', bloodPressureSystolic: 120, bloodPressureDiastolic: 80 });
+// =============================================================================
+// BLOOD PRESSURE UPSERT TESTS (real addBloodPressureReading, fs mocked)
+// =============================================================================
+
+describe('addBloodPressureReading', () => {
+ it('appends a new entry when the date is unseen', async () => {
+ readJSONFile.mockResolvedValue({
+ entries: [{ date: '2024-01-01', heartRate: 60 }]
+ });
+ const result = await addBloodPressureReading({ date: '2024-02-01', systolic: 120, diastolic: 80 });
+ expect(result).toEqual({ date: '2024-02-01', systolic: 120, diastolic: 80 });
+ const written = JSON.parse(writeFile.mock.calls[0][1]);
+ expect(written.entries).toHaveLength(2);
});
- it('merges new BP fields into the existing entry for the same date', () => {
- const metrics = [{ date: '2024-01-01', heartRate: 62, hrv: 50 }];
- const { metrics: next, entry } = upsertHealthMetricByDate(
- metrics,
- '2024-01-01',
- { bloodPressureSystolic: 118, bloodPressureDiastolic: 78 }
- );
- expect(next).toHaveLength(1);
- expect(entry).toMatchObject({
+ it('merges BP fields into the existing entry, preserving unrelated fields', async () => {
+ readJSONFile.mockResolvedValue({
+ entries: [{ date: '2024-01-01', heartRate: 62, hrv: 50 }]
+ });
+ await addBloodPressureReading({ date: '2024-01-01', systolic: 118, diastolic: 78 });
+ const written = JSON.parse(writeFile.mock.calls[0][1]);
+ expect(written.entries[0]).toEqual({
date: '2024-01-01', heartRate: 62, hrv: 50,
bloodPressureSystolic: 118, bloodPressureDiastolic: 78
});
});
- it('overwrites the BP fields on a repeat reading for the same date', () => {
- const metrics = [{ date: '2024-01-01', bloodPressureSystolic: 140, bloodPressureDiastolic: 90 }];
- const { entry } = upsertHealthMetricByDate(
- metrics,
- '2024-01-01',
- { bloodPressureSystolic: 122, bloodPressureDiastolic: 81 }
- );
- expect(entry.bloodPressureSystolic).toBe(122);
- expect(entry.bloodPressureDiastolic).toBe(81);
- });
-
- it('ignores null/undefined patch fields so partial updates do not wipe data', () => {
- const metrics = [{ date: '2024-01-01', bloodPressureSystolic: 120, bloodPressureDiastolic: 80 }];
- const { entry } = upsertHealthMetricByDate(
- metrics,
- '2024-01-01',
- { bloodPressureSystolic: 125, bloodPressureDiastolic: null }
- );
- expect(entry.bloodPressureSystolic).toBe(125);
- expect(entry.bloodPressureDiastolic).toBe(80);
+ it('overwrites the BP fields on a repeat reading for the same date', async () => {
+ readJSONFile.mockResolvedValue({
+ entries: [{ date: '2024-01-01', bloodPressureSystolic: 140, bloodPressureDiastolic: 90 }]
+ });
+ const result = await addBloodPressureReading({ date: '2024-01-01', systolic: 122, diastolic: 81 });
+ expect(result).toEqual({ date: '2024-01-01', systolic: 122, diastolic: 81 });
});
-});
-
-// =============================================================================
-// BP CLASSIFICATION TESTS (AHA/ACC 2017, ported from MortalLoom CardioFitnessEngine)
-// =============================================================================
-function classifyBP(systolic, diastolic) {
- if (systolic > 180 || diastolic > 120) return 'crisis';
- if (systolic >= 140 || diastolic >= 90) return 'highStage2';
- if (systolic >= 130 || diastolic >= 80) return 'highStage1';
- if (systolic >= 120) return 'elevated';
- return 'normal';
-}
-
-describe('classifyBP', () => {
- it.each([
- [110, 70, 'normal'],
- [119, 79, 'normal'],
- [120, 79, 'elevated'],
- [125, 75, 'elevated'],
- [130, 75, 'highStage1'],
- [115, 82, 'highStage1'],
- [140, 85, 'highStage2'],
- [135, 92, 'highStage2'],
- [185, 95, 'crisis'],
- [150, 125, 'crisis']
- ])('classifies %d/%d as %s', (sys, dia, expected) => {
- expect(classifyBP(sys, dia)).toBe(expected);
+ it('defaults to the local calendar day when no date is given', async () => {
+ readJSONFile.mockResolvedValue({ entries: [] });
+ getDateString.mockReturnValue('2024-06-01');
+ const result = await addBloodPressureReading({ systolic: 118, diastolic: 76 });
+ expect(result.date).toBe('2024-06-01');
});
});
diff --git a/server/services/taskConflict.test.js b/server/services/taskConflict.test.js
index 658869666c..a0f2c9677f 100644
--- a/server/services/taskConflict.test.js
+++ b/server/services/taskConflict.test.js
@@ -1,26 +1,15 @@
import { describe, it, expect } from 'vitest';
+import { extractKeywords } from './taskConflict.js';
/**
* Tests for the task conflict detection service.
- * We test the pure logic inline to avoid complex mocking of child_process/fs.
+ * extractKeywords is imported from the real module (pure, no I/O). The
+ * conflict-recommendation branching below (`analyzeConflict`) has no standalone
+ * exported counterpart — it's inlined inside the async detectConflicts(), which
+ * shells out to git via getModifiedFiles/isGitRepo. It stays a local copy here
+ * to test the recommendation branching without mocking child_process/fs.
*/
-// Inline extractKeywords logic for unit testing
-function extractKeywords(text) {
- const stopWords = new Set([
- 'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for',
- 'of', 'with', 'by', 'from', 'is', 'it', 'this', 'that', 'be', 'as',
- 'are', 'was', 'were', 'been', 'has', 'have', 'had', 'do', 'does',
- 'not', 'no', 'can', 'will', 'should', 'may', 'task', 'fix', 'add',
- 'update', 'change', 'make', 'use', 'new', 'all', 'any', 'each'
- ]);
-
- return text
- .replace(/[^a-z0-9\s-_/.]/g, ' ')
- .split(/\s+/)
- .filter(w => w.length > 2 && !stopWords.has(w));
-}
-
// Inline conflict analysis logic for testing without git/fs dependencies
function analyzeConflict(task, workspacePath, activeAgents, options = {}) {
const { isGitRepo = true, modifiedFiles = [] } = options;