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: add coverage for untested utilities and services

[._.]/ Adam Eivy8ba3e9a8bd3c
diff --git a/server/lib/asyncMutex.test.js b/server/lib/asyncMutex.test.js
new file mode 100644
index 0000000000..524579f6c3
--- /dev/null
+++ b/server/lib/asyncMutex.test.js
@@ -0,0 +1,122 @@
+import { describe, it, expect } from 'vitest';
+import { createMutex } from './asyncMutex.js';
+
+describe('asyncMutex.js', () => {
+ describe('createMutex', () => {
+ it('should serialize concurrent operations', async () => {
+ const withLock = createMutex();
+ const results = [];
+
+ // Start multiple operations concurrently
+ const p1 = withLock(async () => {
+ await new Promise(r => setTimeout(r, 20));
+ results.push('first');
+ return 'first';
+ });
+
+ const p2 = withLock(async () => {
+ results.push('second');
+ return 'second';
+ });
+
+ const p3 = withLock(async () => {
+ results.push('third');
+ return 'third';
+ });
+
+ await Promise.all([p1, p2, p3]);
+
+ // Operations should complete in order despite first one being slow
+ expect(results).toEqual(['first', 'second', 'third']);
+ });
+
+ it('should return the result of the wrapped function', async () => {
+ const withLock = createMutex();
+
+ const result = await withLock(async () => {
+ return { value: 42, message: 'success' };
+ });
+
+ expect(result).toEqual({ value: 42, message: 'success' });
+ });
+
+ it('should propagate errors from the wrapped function', async () => {
+ const withLock = createMutex();
+
+ await expect(
+ withLock(async () => {
+ throw new Error('test error');
+ })
+ ).rejects.toThrow('test error');
+ });
+
+ it('should release lock even when function throws', async () => {
+ const withLock = createMutex();
+ const results = [];
+
+ // First operation throws
+ await withLock(async () => {
+ throw new Error('first fails');
+ }).catch(() => {
+ results.push('first caught');
+ });
+
+ // Second operation should still run
+ await withLock(async () => {
+ results.push('second succeeds');
+ });
+
+ expect(results).toEqual(['first caught', 'second succeeds']);
+ });
+
+ it('should allow synchronous functions', async () => {
+ const withLock = createMutex();
+
+ const result = await withLock(() => 'sync result');
+
+ expect(result).toBe('sync result');
+ });
+
+ it('should handle rapid sequential calls', async () => {
+ const withLock = createMutex();
+ let counter = 0;
+
+ const promises = [];
+ for (let i = 0; i < 10; i++) {
+ promises.push(withLock(async () => {
+ const current = counter;
+ await new Promise(r => setTimeout(r, 1));
+ counter = current + 1;
+ }));
+ }
+
+ await Promise.all(promises);
+
+ // Without serialization, counter would likely be less than 10
+ // due to race conditions
+ expect(counter).toBe(10);
+ });
+
+ it('should create independent mutexes', async () => {
+ const withLock1 = createMutex();
+ const withLock2 = createMutex();
+ const results = [];
+
+ // Both locks should run concurrently
+ const p1 = withLock1(async () => {
+ await new Promise(r => setTimeout(r, 20));
+ results.push('lock1');
+ });
+
+ const p2 = withLock2(async () => {
+ results.push('lock2');
+ });
+
+ await Promise.all([p1, p2]);
+
+ // lock2 should finish first since locks are independent
+ expect(results[0]).toBe('lock2');
+ expect(results[1]).toBe('lock1');
+ });
+ });
+});
diff --git a/server/lib/brainValidation.test.js b/server/lib/brainValidation.test.js
new file mode 100644
index 0000000000..b71969a502
--- /dev/null
+++ b/server/lib/brainValidation.test.js
@@ -0,0 +1,522 @@
+import { describe, it, expect } from 'vitest';
+import {
+ destinationEnum,
+ projectStatusEnum,
+ ideaStatusEnum,
+ adminStatusEnum,
+ inboxStatusEnum,
+ aiConfigSchema,
+ classificationSchema,
+ filedSchema,
+ correctionSchema,
+ inboxLogRecordSchema,
+ peopleRecordSchema,
+ projectRecordSchema,
+ ideaRecordSchema,
+ adminRecordSchema,
+ brainSettingsSchema,
+ captureInputSchema,
+ resolveReviewInputSchema,
+ fixInputSchema,
+ updateInboxInputSchema,
+ peopleInputSchema,
+ projectInputSchema,
+ ideaInputSchema,
+ adminInputSchema,
+ inboxQuerySchema,
+ linkRecordSchema,
+ linkInputSchema,
+ linksQuerySchema
+} from './brainValidation.js';
+
+describe('brainValidation.js', () => {
+ describe('destinationEnum', () => {
+ it('should accept valid destinations', () => {
+ expect(destinationEnum.safeParse('people').success).toBe(true);
+ expect(destinationEnum.safeParse('projects').success).toBe(true);
+ expect(destinationEnum.safeParse('ideas').success).toBe(true);
+ expect(destinationEnum.safeParse('admin').success).toBe(true);
+ expect(destinationEnum.safeParse('unknown').success).toBe(true);
+ });
+
+ it('should reject invalid destinations', () => {
+ expect(destinationEnum.safeParse('invalid').success).toBe(false);
+ expect(destinationEnum.safeParse('').success).toBe(false);
+ });
+ });
+
+ describe('projectStatusEnum', () => {
+ it('should accept valid statuses', () => {
+ expect(projectStatusEnum.safeParse('active').success).toBe(true);
+ expect(projectStatusEnum.safeParse('waiting').success).toBe(true);
+ expect(projectStatusEnum.safeParse('blocked').success).toBe(true);
+ expect(projectStatusEnum.safeParse('someday').success).toBe(true);
+ expect(projectStatusEnum.safeParse('done').success).toBe(true);
+ });
+
+ it('should reject invalid statuses', () => {
+ expect(projectStatusEnum.safeParse('invalid').success).toBe(false);
+ });
+ });
+
+ describe('aiConfigSchema', () => {
+ it('should validate a complete AI config', () => {
+ const config = {
+ providerId: 'openai',
+ modelId: 'gpt-4',
+ promptTemplateId: 'classify-v1',
+ temperature: 0.7,
+ maxTokens: 1000
+ };
+ const result = aiConfigSchema.safeParse(config);
+ expect(result.success).toBe(true);
+ });
+
+ it('should validate with minimal required fields', () => {
+ const config = {
+ providerId: 'openai',
+ modelId: 'gpt-4',
+ promptTemplateId: 'classify-v1'
+ };
+ const result = aiConfigSchema.safeParse(config);
+ expect(result.success).toBe(true);
+ });
+
+ it('should reject temperature outside 0-2 range', () => {
+ const config = {
+ providerId: 'test',
+ modelId: 'test',
+ promptTemplateId: 'test',
+ temperature: 3
+ };
+ expect(aiConfigSchema.safeParse(config).success).toBe(false);
+ });
+
+ it('should reject negative maxTokens', () => {
+ const config = {
+ providerId: 'test',
+ modelId: 'test',
+ promptTemplateId: 'test',
+ maxTokens: -1
+ };
+ expect(aiConfigSchema.safeParse(config).success).toBe(false);
+ });
+ });
+
+ describe('classificationSchema', () => {
+ it('should validate a classification result', () => {
+ const classification = {
+ destination: 'projects',
+ confidence: 0.85,
+ title: 'New project idea',
+ extracted: { name: 'Test Project' },
+ reasons: ['Has clear next actions']
+ };
+ const result = classificationSchema.safeParse(classification);
+ expect(result.success).toBe(true);
+ });
+
+ it('should reject confidence outside 0-1 range', () => {
+ const classification = {
+ destination: 'projects',
+ confidence: 1.5,
+ title: 'Test',
+ extracted: {}
+ };
+ expect(classificationSchema.safeParse(classification).success).toBe(false);
+ });
+
+ it('should reject empty title', () => {
+ const classification = {
+ destination: 'projects',
+ confidence: 0.8,
+ title: '',
+ extracted: {}
+ };
+ expect(classificationSchema.safeParse(classification).success).toBe(false);
+ });
+
+ it('should reject title over 200 characters', () => {
+ const classification = {
+ destination: 'projects',
+ confidence: 0.8,
+ title: 'a'.repeat(201),
+ extracted: {}
+ };
+ expect(classificationSchema.safeParse(classification).success).toBe(false);
+ });
+
+ it('should reject more than 5 reasons', () => {
+ const classification = {
+ destination: 'projects',
+ confidence: 0.8,
+ title: 'Test',
+ extracted: {},
+ reasons: ['1', '2', '3', '4', '5', '6']
+ };
+ expect(classificationSchema.safeParse(classification).success).toBe(false);
+ });
+ });
+
+ describe('filedSchema', () => {
+ it('should validate filed info with valid destination', () => {
+ const filed = {
+ destination: 'projects',
+ destinationId: '550e8400-e29b-41d4-a716-446655440000'
+ };
+ const result = filedSchema.safeParse(filed);
+ expect(result.success).toBe(true);
+ });
+
+ it('should reject unknown destination', () => {
+ const filed = {
+ destination: 'unknown',
+ destinationId: '550e8400-e29b-41d4-a716-446655440000'
+ };
+ expect(filedSchema.safeParse(filed).success).toBe(false);
+ });
+
+ it('should reject invalid UUID', () => {
+ const filed = {
+ destination: 'projects',
+ destinationId: 'not-a-uuid'
+ };
+ expect(filedSchema.safeParse(filed).success).toBe(false);
+ });
+ });
+
+ describe('correctionSchema', () => {
+ it('should validate a correction', () => {
+ const correction = {
+ correctedAt: '2026-01-01T00:00:00.000Z',
+ previousDestination: 'ideas',
+ newDestination: 'projects',
+ note: 'Actually a concrete project'
+ };
+ const result = correctionSchema.safeParse(correction);
+ expect(result.success).toBe(true);
+ });
+
+ it('should reject unknown as newDestination', () => {
+ const correction = {
+ correctedAt: '2026-01-01T00:00:00.000Z',
+ previousDestination: 'ideas',
+ newDestination: 'unknown'
+ };
+ expect(correctionSchema.safeParse(correction).success).toBe(false);
+ });
+
+ it('should reject note over 500 characters', () => {
+ const correction = {
+ correctedAt: '2026-01-01T00:00:00.000Z',
+ previousDestination: 'ideas',
+ newDestination: 'projects',
+ note: 'a'.repeat(501)
+ };
+ expect(correctionSchema.safeParse(correction).success).toBe(false);
+ });
+ });
+
+ describe('peopleRecordSchema', () => {
+ it('should validate a complete people record', () => {
+ const record = {
+ id: '550e8400-e29b-41d4-a716-446655440000',
+ name: 'John Doe',
+ context: 'Met at conference',
+ followUps: ['Send article', 'Schedule call'],
+ lastTouched: '2026-01-15T10:00:00.000Z',
+ tags: ['work', 'networking'],
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-15T10:00:00.000Z'
+ };
+ const result = peopleRecordSchema.safeParse(record);
+ expect(result.success).toBe(true);
+ });
+
+ it('should reject empty name', () => {
+ const record = {
+ id: '550e8400-e29b-41d4-a716-446655440000',
+ name: '',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z'
+ };
+ expect(peopleRecordSchema.safeParse(record).success).toBe(false);
+ });
+
+ it('should reject name over 200 characters', () => {
+ const record = {
+ id: '550e8400-e29b-41d4-a716-446655440000',
+ name: 'a'.repeat(201),
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z'
+ };
+ expect(peopleRecordSchema.safeParse(record).success).toBe(false);
+ });
+ });
+
+ describe('projectRecordSchema', () => {
+ it('should validate a complete project record', () => {
+ const record = {
+ id: '550e8400-e29b-41d4-a716-446655440000',
+ name: 'New Project',
+ status: 'active',
+ nextAction: 'Review requirements',
+ notes: 'Project notes here',
+ tags: ['priority'],
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z'
+ };
+ const result = projectRecordSchema.safeParse(record);
+ expect(result.success).toBe(true);
+ });
+
+ it('should require nextAction', () => {
+ const record = {
+ id: '550e8400-e29b-41d4-a716-446655440000',
+ name: 'Test Project',
+ status: 'active',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z'
+ };
+ expect(projectRecordSchema.safeParse(record).success).toBe(false);
+ });
+
+ it('should reject empty nextAction', () => {
+ const record = {
+ id: '550e8400-e29b-41d4-a716-446655440000',
+ name: 'Test Project',
+ status: 'active',
+ nextAction: '',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z'
+ };
+ expect(projectRecordSchema.safeParse(record).success).toBe(false);
+ });
+ });
+
+ describe('ideaRecordSchema', () => {
+ it('should validate an idea record', () => {
+ const record = {
+ id: '550e8400-e29b-41d4-a716-446655440000',
+ title: 'Great Idea',
+ status: 'active',
+ oneLiner: 'A brief description of the idea',
+ notes: 'Extended notes',
+ tags: ['brainstorm'],
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z'
+ };
+ const result = ideaRecordSchema.safeParse(record);
+ expect(result.success).toBe(true);
+ });
+
+ it('should require oneLiner', () => {
+ const record = {
+ id: '550e8400-e29b-41d4-a716-446655440000',
+ title: 'Test Idea',
+ status: 'active',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z'
+ };
+ expect(ideaRecordSchema.safeParse(record).success).toBe(false);
+ });
+ });
+
+ describe('adminRecordSchema', () => {
+ it('should validate an admin record', () => {
+ const record = {
+ id: '550e8400-e29b-41d4-a716-446655440000',
+ title: 'Admin Task',
+ status: 'open',
+ dueDate: '2026-02-01T00:00:00.000Z',
+ nextAction: 'Complete paperwork',
+ notes: 'Important deadline',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z'
+ };
+ const result = adminRecordSchema.safeParse(record);
+ expect(result.success).toBe(true);
+ });
+
+ it('should allow optional fields', () => {
+ const record = {
+ id: '550e8400-e29b-41d4-a716-446655440000',
+ title: 'Simple Admin',
+ status: 'done',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z'
+ };
+ const result = adminRecordSchema.safeParse(record);
+ expect(result.success).toBe(true);
+ });
+ });
+
+ describe('brainSettingsSchema', () => {
+ it('should apply defaults', () => {
+ const result = brainSettingsSchema.safeParse({});
+ expect(result.success).toBe(true);
+ expect(result.data.version).toBe(1);
+ expect(result.data.confidenceThreshold).toBe(0.6);
+ expect(result.data.dailyDigestTime).toBe('09:00');
+ expect(result.data.weeklyReviewDay).toBe('sunday');
+ });
+
+ it('should validate custom settings', () => {
+ const settings = {
+ version: 2,
+ confidenceThreshold: 0.8,
+ dailyDigestTime: '08:30',
+ weeklyReviewTime: '17:00',
+ weeklyReviewDay: 'friday',
+ defaultProvider: 'anthropic',
+ defaultModel: 'claude-3'
+ };
+ const result = brainSettingsSchema.safeParse(settings);
+ expect(result.success).toBe(true);
+ });
+
+ it('should reject invalid time format', () => {
+ const settings = { dailyDigestTime: '9:00' };
+ expect(brainSettingsSchema.safeParse(settings).success).toBe(false);
+ });
+
+ it('should reject confidenceThreshold outside 0-1', () => {
+ expect(brainSettingsSchema.safeParse({ confidenceThreshold: -0.1 }).success).toBe(false);
+ expect(brainSettingsSchema.safeParse({ confidenceThreshold: 1.1 }).success).toBe(false);
+ });
+ });
+
+ describe('captureInputSchema', () => {
+ it('should validate capture input', () => {
+ const input = { text: 'New thought to capture' };
+ const result = captureInputSchema.safeParse(input);
+ expect(result.success).toBe(true);
+ });
+
+ it('should allow overrides', () => {
+ const input = {
+ text: 'Capture this',
+ providerOverride: 'openai',
+ modelOverride: 'gpt-4'
+ };
+ const result = captureInputSchema.safeParse(input);
+ expect(result.success).toBe(true);
+ });
+
+ it('should reject empty text', () => {
+ expect(captureInputSchema.safeParse({ text: '' }).success).toBe(false);
+ });
+
+ it('should reject text over 10000 characters', () => {
+ expect(captureInputSchema.safeParse({ text: 'a'.repeat(10001) }).success).toBe(false);
+ });
+ });
+
+ describe('inboxQuerySchema', () => {
+ it('should apply defaults', () => {
+ const result = inboxQuerySchema.safeParse({});
+ expect(result.success).toBe(true);
+ expect(result.data.limit).toBe(50);
+ expect(result.data.offset).toBe(0);
+ });
+
+ it('should coerce string numbers', () => {
+ const result = inboxQuerySchema.safeParse({ limit: '25', offset: '10' });
+ expect(result.success).toBe(true);
+ expect(result.data.limit).toBe(25);
+ expect(result.data.offset).toBe(10);
+ });
+
+ it('should reject limit over 100', () => {
+ expect(inboxQuerySchema.safeParse({ limit: 101 }).success).toBe(false);
+ });
+
+ it('should reject negative offset', () => {
+ expect(inboxQuerySchema.safeParse({ offset: -1 }).success).toBe(false);
+ });
+ });
+
+ describe('linkRecordSchema', () => {
+ it('should validate a complete link record', () => {
+ const record = {
+ id: '550e8400-e29b-41d4-a716-446655440000',
+ url: 'https://github.com/example/repo',
+ title: 'Example Repository',
+ description: 'A great example repo',
+ linkType: 'github',
+ tags: ['reference'],
+ isGitHubRepo: true,
+ gitHubOwner: 'example',
+ gitHubRepo: 'repo',
+ cloneStatus: 'cloned',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z'
+ };
+ const result = linkRecordSchema.safeParse(record);
+ expect(result.success).toBe(true);
+ });
+
+ it('should reject invalid URL', () => {
+ const record = {
+ id: '550e8400-e29b-41d4-a716-446655440000',
+ url: 'not-a-url',
+ title: 'Test',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z'
+ };
+ expect(linkRecordSchema.safeParse(record).success).toBe(false);
+ });
+
+ it('should reject invalid cloneStatus', () => {
+ const record = {
+ id: '550e8400-e29b-41d4-a716-446655440000',
+ url: 'https://example.com',
+ title: 'Test',
+ cloneStatus: 'invalid',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z'
+ };
+ expect(linkRecordSchema.safeParse(record).success).toBe(false);
+ });
+ });
+
+ describe('linkInputSchema', () => {
+ it('should validate minimal input', () => {
+ const input = { url: 'https://example.com' };
+ const result = linkInputSchema.safeParse(input);
+ expect(result.success).toBe(true);
+ });
+
+ it('should apply autoClone default', () => {
+ const input = { url: 'https://example.com' };
+ const result = linkInputSchema.safeParse(input);
+ expect(result.success).toBe(true);
+ expect(result.data.autoClone).toBe(true);
+ });
+
+ it('should reject invalid URL', () => {
+ expect(linkInputSchema.safeParse({ url: 'not-valid' }).success).toBe(false);
+ });
+ });
+
+ describe('linksQuerySchema', () => {
+ it('should apply defaults', () => {
+ const result = linksQuerySchema.safeParse({});
+ expect(result.success).toBe(true);
+ expect(result.data.limit).toBe(50);
+ expect(result.data.offset).toBe(0);
+ });
+
+ it('should coerce isGitHubRepo boolean', () => {
+ const result = linksQuerySchema.safeParse({ isGitHubRepo: 'true' });
+ expect(result.success).toBe(true);
+ expect(result.data.isGitHubRepo).toBe(true);
+ });
+
+ it('should filter by linkType', () => {
+ const result = linksQuerySchema.safeParse({ linkType: 'documentation' });
+ expect(result.success).toBe(true);
+ expect(result.data.linkType).toBe('documentation');
+ });
+ });
+});
diff --git a/server/lib/memoryValidation.test.js b/server/lib/memoryValidation.test.js
new file mode 100644
index 0000000000..af94793dfb
--- /dev/null
+++ b/server/lib/memoryValidation.test.js
@@ -0,0 +1,409 @@
+import { describe, it, expect } from 'vitest';
+import {
+ memoryTypeEnum,
+ memoryStatusEnum,
+ memoryCategoryEnum,
+ memoryCreateSchema,
+ memorySchema,
+ memoryUpdateSchema,
+ memorySearchSchema,
+ memoryListSchema,
+ memoryTimelineSchema,
+ memoryExtractSchema,
+ memoryConsolidateSchema,
+ memoryLinkSchema
+} from './memoryValidation.js';
+
+describe('memoryValidation.js', () => {
+ describe('memoryTypeEnum', () => {
+ it('should accept valid memory types', () => {
+ expect(memoryTypeEnum.safeParse('fact').success).toBe(true);
+ expect(memoryTypeEnum.safeParse('learning').success).toBe(true);
+ expect(memoryTypeEnum.safeParse('observation').success).toBe(true);
+ expect(memoryTypeEnum.safeParse('decision').success).toBe(true);
+ expect(memoryTypeEnum.safeParse('preference').success).toBe(true);
+ expect(memoryTypeEnum.safeParse('context').success).toBe(true);
+ });
+
+ it('should reject invalid types', () => {
+ expect(memoryTypeEnum.safeParse('invalid').success).toBe(false);
+ expect(memoryTypeEnum.safeParse('').success).toBe(false);
+ });
+ });
+
+ describe('memoryStatusEnum', () => {
+ it('should accept valid statuses', () => {
+ expect(memoryStatusEnum.safeParse('active').success).toBe(true);
+ expect(memoryStatusEnum.safeParse('archived').success).toBe(true);
+ expect(memoryStatusEnum.safeParse('expired').success).toBe(true);
+ expect(memoryStatusEnum.safeParse('pending_approval').success).toBe(true);
+ });
+
+ it('should reject invalid statuses', () => {
+ expect(memoryStatusEnum.safeParse('deleted').success).toBe(false);
+ });
+ });
+
+ describe('memoryCategoryEnum', () => {
+ it('should accept valid categories', () => {
+ expect(memoryCategoryEnum.safeParse('codebase').success).toBe(true);
+ expect(memoryCategoryEnum.safeParse('workflow').success).toBe(true);
+ expect(memoryCategoryEnum.safeParse('tools').success).toBe(true);
+ expect(memoryCategoryEnum.safeParse('architecture').success).toBe(true);
+ expect(memoryCategoryEnum.safeParse('patterns').success).toBe(true);
+ expect(memoryCategoryEnum.safeParse('conventions').success).toBe(true);
+ expect(memoryCategoryEnum.safeParse('preferences').success).toBe(true);
+ expect(memoryCategoryEnum.safeParse('system').success).toBe(true);
+ expect(memoryCategoryEnum.safeParse('project').success).toBe(true);
+ expect(memoryCategoryEnum.safeParse('other').success).toBe(true);
+ });
+ });
+
+ describe('memoryCreateSchema', () => {
+ it('should validate minimal memory creation', () => {
+ const memory = {
+ type: 'fact',
+ content: 'The sky is blue'
+ };
+ const result = memoryCreateSchema.safeParse(memory);
+ expect(result.success).toBe(true);
+ expect(result.data.category).toBe('other');
+ expect(result.data.confidence).toBe(0.8);
+ expect(result.data.importance).toBe(0.5);
+ });
+
+ it('should validate complete memory creation', () => {
+ const memory = {
+ type: 'learning',
+ content: 'React hooks are easier than class components',
+ summary: 'React hooks preferred',
+ category: 'patterns',
+ tags: ['react', 'frontend'],
+ confidence: 0.95,
+ importance: 0.8,
+ relatedMemories: ['550e8400-e29b-41d4-a716-446655440000'],
+ sourceTaskId: 'task-123',
+ sourceAgentId: 'agent-456',
+ sourceAppId: 'app-789'
+ };
+ const result = memoryCreateSchema.safeParse(memory);
+ expect(result.success).toBe(true);
+ });
+
+ it('should reject empty content', () => {
+ const memory = { type: 'fact', content: '' };
+ expect(memoryCreateSchema.safeParse(memory).success).toBe(false);
+ });
+
+ it('should reject content over 10240 characters', () => {
+ const memory = { type: 'fact', content: 'a'.repeat(10241) };
+ expect(memoryCreateSchema.safeParse(memory).success).toBe(false);
+ });
+
+ it('should reject summary over 500 characters', () => {
+ const memory = {
+ type: 'fact',
+ content: 'test',
+ summary: 'a'.repeat(501)
+ };
+ expect(memoryCreateSchema.safeParse(memory).success).toBe(false);
+ });
+
+ it('should reject more than 20 tags', () => {
+ const memory = {
+ type: 'fact',
+ content: 'test',
+ tags: Array(21).fill('tag')
+ };
+ expect(memoryCreateSchema.safeParse(memory).success).toBe(false);
+ });
+
+ it('should reject tag over 50 characters', () => {
+ const memory = {
+ type: 'fact',
+ content: 'test',
+ tags: ['a'.repeat(51)]
+ };
+ expect(memoryCreateSchema.safeParse(memory).success).toBe(false);
+ });
+
+ it('should reject confidence outside 0-1', () => {
+ expect(memoryCreateSchema.safeParse({
+ type: 'fact', content: 'test', confidence: -0.1
+ }).success).toBe(false);
+ expect(memoryCreateSchema.safeParse({
+ type: 'fact', content: 'test', confidence: 1.1
+ }).success).toBe(false);
+ });
+
+ it('should reject importance outside 0-1', () => {
+ expect(memoryCreateSchema.safeParse({
+ type: 'fact', content: 'test', importance: -0.1
+ }).success).toBe(false);
+ expect(memoryCreateSchema.safeParse({
+ type: 'fact', content: 'test', importance: 1.1
+ }).success).toBe(false);
+ });
+
+ it('should reject invalid UUIDs in relatedMemories', () => {
+ const memory = {
+ type: 'fact',
+ content: 'test',
+ relatedMemories: ['not-a-uuid']
+ };
+ expect(memoryCreateSchema.safeParse(memory).success).toBe(false);
+ });
+
+ it('should allow null sourceAppId', () => {
+ const memory = {
+ type: 'fact',
+ content: 'test',
+ sourceAppId: null
+ };
+ const result = memoryCreateSchema.safeParse(memory);
+ expect(result.success).toBe(true);
+ });
+ });
+
+ describe('memorySchema', () => {
+ it('should validate a complete memory with system fields', () => {
+ const memory = {
+ id: '550e8400-e29b-41d4-a716-446655440000',
+ type: 'fact',
+ content: 'Test content',
+ embedding: [0.1, 0.2, 0.3],
+ embeddingModel: 'text-embedding-3-small',
+ accessCount: 5,
+ lastAccessed: '2026-01-15T10:00:00.000Z',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-15T10:00:00.000Z',
+ expiresAt: null,
+ status: 'active'
+ };
+ const result = memorySchema.safeParse(memory);
+ expect(result.success).toBe(true);
+ });
+
+ it('should apply default status', () => {
+ const memory = {
+ id: '550e8400-e29b-41d4-a716-446655440000',
+ type: 'fact',
+ content: 'Test',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z'
+ };
+ const result = memorySchema.safeParse(memory);
+ expect(result.success).toBe(true);
+ expect(result.data.status).toBe('active');
+ });
+
+ it('should reject negative accessCount', () => {
+ const memory = {
+ id: '550e8400-e29b-41d4-a716-446655440000',
+ type: 'fact',
+ content: 'Test',
+ accessCount: -1,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z'
+ };
+ expect(memorySchema.safeParse(memory).success).toBe(false);
+ });
+ });
+
+ describe('memoryUpdateSchema', () => {
+ it('should allow partial updates', () => {
+ const update = { content: 'Updated content' };
+ const result = memoryUpdateSchema.safeParse(update);
+ expect(result.success).toBe(true);
+ });
+
+ it('should allow empty object', () => {
+ const result = memoryUpdateSchema.safeParse({});
+ expect(result.success).toBe(true);
+ });
+
+ it('should allow status update', () => {
+ const update = { status: 'archived' };
+ const result = memoryUpdateSchema.safeParse(update);
+ expect(result.success).toBe(true);
+ });
+
+ it('should validate provided fields', () => {
+ const update = { content: '' };
+ expect(memoryUpdateSchema.safeParse(update).success).toBe(false);
+ });
+ });
+
+ describe('memorySearchSchema', () => {
+ it('should validate search query', () => {
+ const search = { query: 'react hooks' };
+ const result = memorySearchSchema.safeParse(search);
+ expect(result.success).toBe(true);
+ expect(result.data.status).toBe('active');
+ expect(result.data.minRelevance).toBe(0.7);
+ expect(result.data.limit).toBe(20);
+ });
+
+ it('should validate full search options', () => {
+ const search = {
+ query: 'react patterns',
+ types: ['learning', 'fact'],
+ categories: ['patterns', 'codebase'],
+ tags: ['react'],
+ status: 'active',
+ minRelevance: 0.8,
+ limit: 50,
+ offset: 10
+ };
+ const result = memorySearchSchema.safeParse(search);
+ expect(result.success).toBe(true);
+ });
+
+ it('should reject empty query', () => {
+ expect(memorySearchSchema.safeParse({ query: '' }).success).toBe(false);
+ });
+
+ it('should reject query over 1000 characters', () => {
+ expect(memorySearchSchema.safeParse({ query: 'a'.repeat(1001) }).success).toBe(false);
+ });
+
+ it('should reject minRelevance outside 0-1', () => {
+ expect(memorySearchSchema.safeParse({
+ query: 'test', minRelevance: 1.5
+ }).success).toBe(false);
+ });
+
+ it('should reject limit over 100', () => {
+ expect(memorySearchSchema.safeParse({
+ query: 'test', limit: 101
+ }).success).toBe(false);
+ });
+ });
+
+ describe('memoryListSchema', () => {
+ it('should apply defaults', () => {
+ const result = memoryListSchema.safeParse({});
+ expect(result.success).toBe(true);
+ expect(result.data.status).toBe('active');
+ expect(result.data.limit).toBe(50);
+ expect(result.data.offset).toBe(0);
+ expect(result.data.sortBy).toBe('createdAt');
+ expect(result.data.sortOrder).toBe('desc');
+ });
+
+ it('should validate custom sorting', () => {
+ const list = {
+ sortBy: 'importance',
+ sortOrder: 'asc'
+ };
+ const result = memoryListSchema.safeParse(list);
+ expect(result.success).toBe(true);
+ });
+
+ it('should reject invalid sortBy', () => {
+ expect(memoryListSchema.safeParse({ sortBy: 'invalid' }).success).toBe(false);
+ });
+
+ it('should reject invalid sortOrder', () => {
+ expect(memoryListSchema.safeParse({ sortOrder: 'random' }).success).toBe(false);
+ });
+ });
+
+ describe('memoryTimelineSchema', () => {
+ it('should apply default limit', () => {
+ const result = memoryTimelineSchema.safeParse({});
+ expect(result.success).toBe(true);
+ expect(result.data.limit).toBe(100);
+ });
+
+ it('should validate date range', () => {
+ const timeline = {
+ startDate: '2026-01-01T00:00:00.000Z',
+ endDate: '2026-01-31T23:59:59.000Z',
+ types: ['fact', 'learning']
+ };
+ const result = memoryTimelineSchema.safeParse(timeline);
+ expect(result.success).toBe(true);
+ });
+
+ it('should reject limit over 500', () => {
+ expect(memoryTimelineSchema.safeParse({ limit: 501 }).success).toBe(false);
+ });
+ });
+
+ describe('memoryExtractSchema', () => {
+ it('should validate extraction request', () => {
+ const extract = {
+ agentId: 'agent-123',
+ taskId: 'task-456',
+ output: 'Agent completed the task with these findings...'
+ };
+ const result = memoryExtractSchema.safeParse(extract);
+ expect(result.success).toBe(true);
+ });
+
+ it('should require all fields', () => {
+ expect(memoryExtractSchema.safeParse({ agentId: 'test' }).success).toBe(false);
+ expect(memoryExtractSchema.safeParse({ taskId: 'test' }).success).toBe(false);
+ expect(memoryExtractSchema.safeParse({ output: 'test' }).success).toBe(false);
+ });
+
+ it('should reject empty output', () => {
+ const extract = {
+ agentId: 'agent-123',
+ taskId: 'task-456',
+ output: ''
+ };
+ expect(memoryExtractSchema.safeParse(extract).success).toBe(false);
+ });
+ });
+
+ describe('memoryConsolidateSchema', () => {
+ it('should apply defaults', () => {
+ const result = memoryConsolidateSchema.safeParse({});
+ expect(result.success).toBe(true);
+ expect(result.data.similarityThreshold).toBe(0.9);
+ expect(result.data.dryRun).toBe(false);
+ });
+
+ it('should validate custom threshold', () => {
+ const consolidate = { similarityThreshold: 0.85, dryRun: true };
+ const result = memoryConsolidateSchema.safeParse(consolidate);
+ expect(result.success).toBe(true);
+ });
+
+ it('should reject threshold below 0.5', () => {
+ expect(memoryConsolidateSchema.safeParse({ similarityThreshold: 0.4 }).success).toBe(false);
+ });
+
+ it('should reject threshold above 1', () => {
+ expect(memoryConsolidateSchema.safeParse({ similarityThreshold: 1.1 }).success).toBe(false);
+ });
+ });
+
+ describe('memoryLinkSchema', () => {
+ it('should validate link request', () => {
+ const link = {
+ sourceId: '550e8400-e29b-41d4-a716-446655440000',
+ targetId: '550e8400-e29b-41d4-a716-446655440001'
+ };
+ const result = memoryLinkSchema.safeParse(link);
+ expect(result.success).toBe(true);
+ });
+
+ it('should reject invalid UUIDs', () => {
+ expect(memoryLinkSchema.safeParse({
+ sourceId: 'not-uuid', targetId: '550e8400-e29b-41d4-a716-446655440000'
+ }).success).toBe(false);
+ expect(memoryLinkSchema.safeParse({
+ sourceId: '550e8400-e29b-41d4-a716-446655440000', targetId: 'not-uuid'
+ }).success).toBe(false);
+ });
+
+ it('should require both fields', () => {
+ expect(memoryLinkSchema.safeParse({
+ sourceId: '550e8400-e29b-41d4-a716-446655440000'
+ }).success).toBe(false);
+ });
+ });
+});
diff --git a/server/services/decisionLog.test.js b/server/services/decisionLog.test.js
new file mode 100644
index 0000000000..a28a95ed93
--- /dev/null
+++ b/server/services/decisionLog.test.js
@@ -0,0 +1,441 @@
+import { describe, it, expect, vi, beforeEach, beforeAll } from 'vitest';
+
+// Mock dependencies before importing the module
+vi.mock('fs/promises', () => ({
+ writeFile: vi.fn(),
+ mkdir: vi.fn()
+}));
+
+vi.mock('fs', () => ({
+ existsSync: vi.fn(() => true)
+}));
+
+vi.mock('./cosEvents.js', () => ({
+ cosEvents: { emit: vi.fn(), on: vi.fn() }
+}));
+
+vi.mock('../lib/fileUtils.js', () => ({
+ readJSONFile: vi.fn()
+}));
+
+// Helper to create mock decision data
+const makeDecisionData = (overrides = {}) => ({
+ version: 1,
+ decisions: [],
+ stats: {
+ totalDecisions: 0,
+ byType: {}
+ },
+ ...overrides
+});
+
+describe('decisionLog.js', () => {
+ let savedData;
+ let writeFile;
+ let readJSONFile;
+ let cosEvents;
+ let recordDecision;
+ let getRecentDecisions;
+ let getDecisionSummary;
+ let getDecisionPatterns;
+ let cleanupOldDecisions;
+ let DECISION_TYPES;
+
+ beforeAll(async () => {
+ // Import mocks after they're set up
+ const fsPromises = await import('fs/promises');
+ writeFile = fsPromises.writeFile;
+ const fileUtils = await import('../lib/fileUtils.js');
+ readJSONFile = fileUtils.readJSONFile;
+ const cosEventsModule = await import('./cosEvents.js');
+ cosEvents = cosEventsModule.cosEvents;
+ });
+
+ beforeEach(async () => {
+ // Reset modules to clear the in-memory cache between tests
+ vi.resetModules();
+
+ // Re-mock after reset
+ vi.doMock('fs/promises', () => ({
+ writeFile: vi.fn(),
+ mkdir: vi.fn()
+ }));
+ vi.doMock('fs', () => ({
+ existsSync: vi.fn(() => true)
+ }));
+ vi.doMock('./cosEvents.js', () => ({
+ cosEvents: { emit: vi.fn(), on: vi.fn() }
+ }));
+ vi.doMock('../lib/fileUtils.js', () => ({
+ readJSONFile: vi.fn()
+ }));
+
+ // Re-import fresh module instances
+ const fsPromises = await import('fs/promises');
+ writeFile = fsPromises.writeFile;
+ const fileUtils = await import('../lib/fileUtils.js');
+ readJSONFile = fileUtils.readJSONFile;
+ const cosEventsModule = await import('./cosEvents.js');
+ cosEvents = cosEventsModule.cosEvents;
+ const decisionLogModule = await import('./decisionLog.js');
+ recordDecision = decisionLogModule.recordDecision;
+ getRecentDecisions = decisionLogModule.getRecentDecisions;
+ getDecisionSummary = decisionLogModule.getDecisionSummary;
+ getDecisionPatterns = decisionLogModule.getDecisionPatterns;
+ cleanupOldDecisions = decisionLogModule.cleanupOldDecisions;
+ DECISION_TYPES = decisionLogModule.DECISION_TYPES;
+
+ savedData = null;
+ writeFile.mockImplementation(async (_path, content) => {
+ savedData = JSON.parse(content);
+ });
+ });
+
+ describe('DECISION_TYPES', () => {
+ it('should define all decision types', () => {
+ expect(DECISION_TYPES.TASK_SKIPPED).toBe('task_skipped');
+ expect(DECISION_TYPES.TASK_SWITCHED).toBe('task_switched');
+ expect(DECISION_TYPES.INTERVAL_ADJUSTED).toBe('interval_adjusted');
+ expect(DECISION_TYPES.COOLDOWN_ACTIVE).toBe('cooldown_active');
+ expect(DECISION_TYPES.NOT_DUE).toBe('not_due');
+ expect(DECISION_TYPES.QUEUE_FULL).toBe('queue_full');
+ expect(DECISION_TYPES.CAPACITY_FULL).toBe('capacity_full');
+ expect(DECISION_TYPES.TASK_SELECTED).toBe('task_selected');
+ expect(DECISION_TYPES.REHABILITATION).toBe('rehabilitation');
+ expect(DECISION_TYPES.IDLE).toBe('idle');
+ });
+ });
+
+ describe('recordDecision', () => {
+ it('should record a new decision', async () => {
+ readJSONFile.mockResolvedValue(makeDecisionData());
+
+ const result = await recordDecision(
+ DECISION_TYPES.TASK_SELECTED,
+ 'Selected high-priority user task',
+ { taskType: 'user-task', priority: 'high' }
+ );
+
+ expect(result.type).toBe(DECISION_TYPES.TASK_SELECTED);
+ expect(result.reason).toBe('Selected high-priority user task');
+ expect(result.context.taskType).toBe('user-task');
+ expect(result.id).toMatch(/^dec-/);
+ expect(result.timestamp).toBeDefined();
+ });
+
+ it('should add decision to beginning of list', async () => {
+ const existing = makeDecisionData({
+ decisions: [
+ { id: 'dec-old', type: DECISION_TYPES.IDLE, reason: 'Old decision', timestamp: '2026-01-01T00:00:00.000Z' }
+ ]
+ });
+ readJSONFile.mockResolvedValue(existing);
+
+ await recordDecision(DECISION_TYPES.TASK_SELECTED, 'New decision', {});
+
+ expect(savedData.decisions[0].reason).toBe('New decision');
+ expect(savedData.decisions[1].id).toBe('dec-old');
+ });
+
+ it('should collapse consecutive identical decisions', async () => {
+ const existing = makeDecisionData({
+ decisions: [
+ {
+ id: 'dec-existing',
+ type: DECISION_TYPES.IDLE,
+ reason: 'No work available',
+ count: 1,
+ timestamp: '2026-01-25T10:00:00.000Z'
+ }
+ ]
+ });
+ readJSONFile.mockResolvedValue(existing);
+
+ const result = await recordDecision(DECISION_TYPES.IDLE, 'No work available', {});
+
+ expect(result.count).toBe(2);
+ expect(result.lastTimestamp).toBeDefined();
+ expect(savedData.decisions).toHaveLength(1);
+ });
+
+ it('should not collapse different decision types', async () => {
+ const existing = makeDecisionData({
+ decisions: [
+ { id: 'dec-1', type: DECISION_TYPES.IDLE, reason: 'No work', timestamp: '2026-01-25T10:00:00.000Z' }
+ ]
+ });
+ readJSONFile.mockResolvedValue(existing);
+
+ await recordDecision(DECISION_TYPES.TASK_SELECTED, 'Task picked', {});
+
+ expect(savedData.decisions).toHaveLength(2);
+ });
+
+ it('should not collapse different reasons', async () => {
+ const existing = makeDecisionData({
+ decisions: [
+ { id: 'dec-1', type: DECISION_TYPES.TASK_SKIPPED, reason: 'Reason A', timestamp: '2026-01-25T10:00:00.000Z' }
+ ]
+ });
+ readJSONFile.mockResolvedValue(existing);
+
+ await recordDecision(DECISION_TYPES.TASK_SKIPPED, 'Reason B', {});
+
+ expect(savedData.decisions).toHaveLength(2);
+ });
+
+ it('should trim decisions to max size (200)', async () => {
+ const decisions = Array(200).fill(null).map((_, i) => ({
+ id: `dec-${i}`,
+ type: DECISION_TYPES.IDLE,
+ reason: `Decision ${i}`,
+ timestamp: '2026-01-25T10:00:00.000Z'
+ }));
+ readJSONFile.mockResolvedValue(makeDecisionData({ decisions }));
+
+ await recordDecision(DECISION_TYPES.TASK_SELECTED, 'New one', {});
+
+ expect(savedData.decisions).toHaveLength(200);
+ expect(savedData.decisions[0].reason).toBe('New one');
+ });
+
+ it('should update stats', async () => {
+ readJSONFile.mockResolvedValue(makeDecisionData());
+
+ await recordDecision(DECISION_TYPES.TASK_SKIPPED, 'Poor success rate', {});
+
+ expect(savedData.stats.totalDecisions).toBe(1);
+ expect(savedData.stats.byType[DECISION_TYPES.TASK_SKIPPED]).toBe(1);
+ });
+
+ it('should emit decision event', async () => {
+ readJSONFile.mockResolvedValue(makeDecisionData());
+
+ await recordDecision(DECISION_TYPES.TASK_SELECTED, 'Test', {});
+
+ expect(cosEvents.emit).toHaveBeenCalledWith('decision', expect.objectContaining({
+ type: DECISION_TYPES.TASK_SELECTED,
+ reason: 'Test'
+ }));
+ });
+ });
+
+ describe('getRecentDecisions', () => {
+ it('should return decisions up to limit', async () => {
+ const decisions = Array(50).fill(null).map((_, i) => ({
+ id: `dec-${i}`,
+ type: DECISION_TYPES.IDLE,
+ reason: `Decision ${i}`,
+ timestamp: '2026-01-25T10:00:00.000Z'
+ }));
+ readJSONFile.mockResolvedValue(makeDecisionData({ decisions }));
+
+ const result = await getRecentDecisions(10);
+
+ expect(result).toHaveLength(10);
+ });
+
+ it('should filter by type', async () => {
+ const decisions = [
+ { id: 'dec-1', type: DECISION_TYPES.TASK_SELECTED, reason: 'A', timestamp: '2026-01-25T10:00:00.000Z' },
+ { id: 'dec-2', type: DECISION_TYPES.IDLE, reason: 'B', timestamp: '2026-01-25T10:00:00.000Z' },
+ { id: 'dec-3', type: DECISION_TYPES.TASK_SELECTED, reason: 'C', timestamp: '2026-01-25T10:00:00.000Z' }
+ ];
+ readJSONFile.mockResolvedValue(makeDecisionData({ decisions }));
+
+ const result = await getRecentDecisions(20, DECISION_TYPES.TASK_SELECTED);
+
+ expect(result).toHaveLength(2);
+ expect(result.every(d => d.type === DECISION_TYPES.TASK_SELECTED)).toBe(true);
+ });
+
+ it('should use default limit of 20', async () => {
+ const decisions = Array(30).fill(null).map((_, i) => ({
+ id: `dec-${i}`,
+ type: DECISION_TYPES.IDLE,
+ reason: `Decision ${i}`,
+ timestamp: '2026-01-25T10:00:00.000Z'
+ }));
+ readJSONFile.mockResolvedValue(makeDecisionData({ decisions }));
+
+ const result = await getRecentDecisions();
+
+ expect(result).toHaveLength(20);
+ });
+ });
+
+ describe('getDecisionSummary', () => {
+ it('should return summary for last 24 hours', async () => {
+ const now = new Date();
+ const recentTimestamp = new Date(now.getTime() - 1000 * 60 * 60).toISOString(); // 1 hour ago
+ const oldTimestamp = new Date(now.getTime() - 1000 * 60 * 60 * 30).toISOString(); // 30 hours ago
+
+ const decisions = [
+ { id: 'dec-1', type: DECISION_TYPES.TASK_SELECTED, reason: 'A', timestamp: recentTimestamp },
+ { id: 'dec-2', type: DECISION_TYPES.IDLE, reason: 'B', timestamp: recentTimestamp },
+ { id: 'dec-3', type: DECISION_TYPES.TASK_SELECTED, reason: 'C', timestamp: oldTimestamp }
+ ];
+ readJSONFile.mockResolvedValue(makeDecisionData({ decisions }));
+
+ const result = await getDecisionSummary();
+
+ expect(result.last24Hours.total).toBe(2);
+ });
+
+ it('should count collapsed decisions correctly', async () => {
+ const now = new Date();
+ const recentTimestamp = now.toISOString();
+
+ const decisions = [
+ {
+ id: 'dec-1',
+ type: DECISION_TYPES.IDLE,
+ reason: 'No work',
+ count: 10,
+ timestamp: recentTimestamp,
+ lastTimestamp: recentTimestamp
+ }
+ ];
+ readJSONFile.mockResolvedValue(makeDecisionData({ decisions }));
+
+ const result = await getDecisionSummary();
+
+ expect(result.last24Hours.total).toBe(10);
+ expect(result.last24Hours.idle).toBe(10);
+ });
+
+ it('should identify impactful decisions', async () => {
+ const now = new Date();
+ const recentTimestamp = now.toISOString();
+
+ const decisions = [
+ { id: 'dec-1', type: DECISION_TYPES.TASK_SKIPPED, reason: 'Poor rate', timestamp: recentTimestamp, context: { taskType: 'test' } },
+ { id: 'dec-2', type: DECISION_TYPES.CAPACITY_FULL, reason: 'Max agents', timestamp: recentTimestamp, context: {} },
+ { id: 'dec-3', type: DECISION_TYPES.IDLE, reason: 'No work', timestamp: recentTimestamp }
+ ];
+ readJSONFile.mockResolvedValue(makeDecisionData({ decisions }));
+
+ const result = await getDecisionSummary();
+
+ expect(result.impactfulDecisions).toHaveLength(2);
+ expect(result.hasImpactfulDecisions).toBe(true);
+ });
+
+ it('should calculate transparency score', async () => {
+ const now = new Date();
+ const recentTimestamp = now.toISOString();
+
+ const decisions = [
+ { id: 'dec-1', type: DECISION_TYPES.IDLE, reason: 'Has reason', timestamp: recentTimestamp },
+ { id: 'dec-2', type: DECISION_TYPES.IDLE, reason: '', timestamp: recentTimestamp },
+ { id: 'dec-3', type: DECISION_TYPES.IDLE, reason: 'Has reason too', timestamp: recentTimestamp }
+ ];
+ readJSONFile.mockResolvedValue(makeDecisionData({ decisions }));
+
+ const result = await getDecisionSummary();
+
+ // 2 out of 3 have reasons = 67%
+ expect(result.transparencyScore).toBe(67);
+ });
+
+ it('should return 100 transparency when no decisions', async () => {
+ readJSONFile.mockResolvedValue(makeDecisionData());
+
+ const result = await getDecisionSummary();
+
+ expect(result.transparencyScore).toBe(100);
+ });
+ });
+
+ describe('getDecisionPatterns', () => {
+ it('should identify frequently skipped task types', async () => {
+ const decisions = [
+ { id: 'dec-1', type: DECISION_TYPES.TASK_SKIPPED, reason: 'A', context: { taskType: 'self-improve:ui' }, timestamp: '2026-01-25T10:00:00.000Z' },
+ { id: 'dec-2', type: DECISION_TYPES.TASK_SKIPPED, reason: 'B', context: { taskType: 'self-improve:ui' }, timestamp: '2026-01-25T10:00:00.000Z' },
+ { id: 'dec-3', type: DECISION_TYPES.TASK_SKIPPED, reason: 'C', context: { taskType: 'user-task' }, timestamp: '2026-01-25T10:00:00.000Z' }
+ ];
+ readJSONFile.mockResolvedValue(makeDecisionData({ decisions }));
+
+ const result = await getDecisionPatterns();
+
+ expect(result.frequentlySkipped[0].taskType).toBe('self-improve:ui');
+ expect(result.frequentlySkipped[0].count).toBe(2);
+ expect(result.totalSkips).toBe(3);
+ });
+
+ it('should track switched tasks', async () => {
+ const decisions = [
+ { id: 'dec-1', type: DECISION_TYPES.TASK_SWITCHED, reason: 'A', context: { fromTask: 'task-a' }, timestamp: '2026-01-25T10:00:00.000Z' },
+ { id: 'dec-2', type: DECISION_TYPES.TASK_SWITCHED, reason: 'B', context: { fromTask: 'task-a' }, timestamp: '2026-01-25T10:00:00.000Z' }
+ ];
+ readJSONFile.mockResolvedValue(makeDecisionData({ decisions }));
+
+ const result = await getDecisionPatterns();
+
+ expect(result.totalSwitches).toBe(2);
+ });
+
+ it('should return empty patterns when no data', async () => {
+ readJSONFile.mockResolvedValue(makeDecisionData());
+
+ const result = await getDecisionPatterns();
+
+ expect(result.frequentlySkipped).toHaveLength(0);
+ expect(result.totalSkips).toBe(0);
+ expect(result.totalSwitches).toBe(0);
+ });
+ });
+
+ describe('cleanupOldDecisions', () => {
+ it('should remove decisions older than specified days', async () => {
+ const now = Date.now();
+ const recentTimestamp = new Date(now - 1000 * 60 * 60 * 24).toISOString(); // 1 day ago
+ const oldTimestamp = new Date(now - 1000 * 60 * 60 * 24 * 10).toISOString(); // 10 days ago
+
+ const decisions = [
+ { id: 'dec-1', type: DECISION_TYPES.IDLE, reason: 'Recent', timestamp: recentTimestamp },
+ { id: 'dec-2', type: DECISION_TYPES.IDLE, reason: 'Old', timestamp: oldTimestamp }
+ ];
+ readJSONFile.mockResolvedValue(makeDecisionData({ decisions }));
+
+ const result = await cleanupOldDecisions(7);
+
+ expect(result.removed).toBe(1);
+ expect(result.remaining).toBe(1);
+ expect(savedData.decisions).toHaveLength(1);
+ expect(savedData.decisions[0].reason).toBe('Recent');
+ });
+
+ it('should not save when nothing to remove', async () => {
+ const now = Date.now();
+ const recentTimestamp = new Date(now - 1000 * 60 * 60).toISOString(); // 1 hour ago
+
+ const decisions = [
+ { id: 'dec-1', type: DECISION_TYPES.IDLE, reason: 'Recent', timestamp: recentTimestamp }
+ ];
+ readJSONFile.mockResolvedValue(makeDecisionData({ decisions }));
+
+ const result = await cleanupOldDecisions(7);
+
+ expect(result.removed).toBe(0);
+ expect(writeFile).not.toHaveBeenCalled();
+ });
+
+ it('should use default of 7 days', async () => {
+ const now = Date.now();
+ const recentTimestamp = new Date(now - 1000 * 60 * 60 * 24 * 5).toISOString(); // 5 days ago
+ const oldTimestamp = new Date(now - 1000 * 60 * 60 * 24 * 10).toISOString(); // 10 days ago
+
+ const decisions = [
+ { id: 'dec-1', type: DECISION_TYPES.IDLE, reason: 'Recent', timestamp: recentTimestamp },
+ { id: 'dec-2', type: DECISION_TYPES.IDLE, reason: 'Old', timestamp: oldTimestamp }
+ ];
+ readJSONFile.mockResolvedValue(makeDecisionData({ decisions }));
+
+ const result = await cleanupOldDecisions();
+
+ expect(result.removed).toBe(1);
+ expect(result.remaining).toBe(1);
+ });
+ });
+});
diff --git a/server/services/goalProgress.test.js b/server/services/goalProgress.test.js
new file mode 100644
index 0000000000..0c73bbdc02
--- /dev/null
+++ b/server/services/goalProgress.test.js
@@ -0,0 +1,414 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock dependencies before importing the module
+vi.mock('fs/promises', () => ({
+ readFile: vi.fn()
+}));
+
+vi.mock('../lib/fileUtils.js', () => ({
+ readJSONFile: vi.fn(),
+ PATHS: {
+ data: '/mock/data',
+ cos: '/mock/data/cos'
+ }
+}));
+
+import { readFile } from 'fs/promises';
+import { readJSONFile } from '../lib/fileUtils.js';
+import {
+ getGoalProgress,
+ getGoalProgressSummary,
+ parseGoalsFile,
+ GOAL_MAPPINGS
+} from './goalProgress.js';
+
+describe('goalProgress.js', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('GOAL_MAPPINGS', () => {
+ it('should define mappings for standard goals', () => {
+ expect(GOAL_MAPPINGS['Codebase Quality']).toBeDefined();
+ expect(GOAL_MAPPINGS['Self-Improvement']).toBeDefined();
+ expect(GOAL_MAPPINGS['Documentation']).toBeDefined();
+ expect(GOAL_MAPPINGS['User Engagement']).toBeDefined();
+ expect(GOAL_MAPPINGS['System Health']).toBeDefined();
+ });
+
+ it('should have icons and colors for each mapping', () => {
+ for (const mapping of Object.values(GOAL_MAPPINGS)) {
+ expect(mapping.icon).toBeDefined();
+ expect(mapping.color).toBeDefined();
+ expect(mapping.keywords).toBeDefined();
+ expect(mapping.taskTypes).toBeDefined();
+ }
+ });
+ });
+
+ describe('parseGoalsFile', () => {
+ it('should parse goals from markdown', async () => {
+ const goalsMarkdown = `
+# COS Goals
+
+## Active Goals
+
+### Goal 1: Codebase Quality
+- Improve test coverage
+- Fix security issues
+
+### Goal 2: Documentation
+- Update README
+- Add API docs
+
+## Completed Goals
+### Goal 3: Old Goal
+- This should not be parsed
+`;
+ readFile.mockResolvedValue(goalsMarkdown);
+
+ const result = await parseGoalsFile();
+
+ expect(result).toHaveLength(2);
+ expect(result[0].name).toBe('Codebase Quality');
+ expect(result[0].items).toEqual(['Improve test coverage', 'Fix security issues']);
+ expect(result[1].name).toBe('Documentation');
+ expect(result[1].items).toEqual(['Update README', 'Add API docs']);
+ });
+
+ it('should return empty array when file does not exist', async () => {
+ readFile.mockRejectedValue(new Error('ENOENT'));
+
+ const result = await parseGoalsFile();
+
+ expect(result).toEqual([]);
+ });
+
+ it('should assign correct mappings to known goals', async () => {
+ const goalsMarkdown = `
+## Active Goals
+
+### Goal 1: Codebase Quality
+- Test item
+`;
+ readFile.mockResolvedValue(goalsMarkdown);
+
+ const result = await parseGoalsFile();
+
+ expect(result[0].mapping.icon).toBe(GOAL_MAPPINGS['Codebase Quality'].icon);
+ expect(result[0].mapping.color).toBe(GOAL_MAPPINGS['Codebase Quality'].color);
+ });
+
+ it('should use default mapping for unknown goals', async () => {
+ const goalsMarkdown = `
+## Active Goals
+
+### Goal 1: Unknown Goal Type
+- Test item
+`;
+ readFile.mockResolvedValue(goalsMarkdown);
+
+ const result = await parseGoalsFile();
+
+ expect(result[0].mapping.icon).toBe('🎯');
+ expect(result[0].mapping.color).toBe('gray');
+ });
+
+ it('should handle empty Active Goals section', async () => {
+ const goalsMarkdown = `
+## Active Goals
+
+## Other Section
+### Goal 1: Other
+- Item
+`;
+ readFile.mockResolvedValue(goalsMarkdown);
+
+ const result = await parseGoalsFile();
+
+ expect(result).toEqual([]);
+ });
+ });
+
+ describe('getGoalProgress', () => {
+ it('should calculate progress from task stats', async () => {
+ const goalsMarkdown = `
+## Active Goals
+
+### Goal 1: User Engagement
+- Respond to feedback
+`;
+ readFile.mockResolvedValue(goalsMarkdown);
+
+ const learningData = {
+ byTaskType: {
+ 'user-task': {
+ completed: 20,
+ succeeded: 15,
+ failed: 5
+ }
+ }
+ };
+ readJSONFile.mockResolvedValue(learningData);
+
+ const result = await getGoalProgress();
+
+ expect(result.goals).toHaveLength(1);
+ expect(result.goals[0].metrics.totalTasks).toBe(20);
+ expect(result.goals[0].metrics.succeededTasks).toBe(15);
+ expect(result.goals[0].metrics.successRate).toBe(75);
+ });
+
+ it('should determine engagement level based on task count', async () => {
+ const goalsMarkdown = `
+## Active Goals
+
+### Goal 1: User Engagement
+- Item
+`;
+ readFile.mockResolvedValue(goalsMarkdown);
+
+ // Test low engagement (< 5 tasks)
+ readJSONFile.mockResolvedValue({
+ byTaskType: { 'user-task': { completed: 2, succeeded: 2 } }
+ });
+ let result = await getGoalProgress();
+ expect(result.goals[0].metrics.engagement).toBe('low');
+
+ // Test medium engagement (5-19 tasks)
+ readJSONFile.mockResolvedValue({
+ byTaskType: { 'user-task': { completed: 10, succeeded: 8 } }
+ });
+ result = await getGoalProgress();
+ expect(result.goals[0].metrics.engagement).toBe('medium');
+
+ // Test high engagement (>= 20 tasks)
+ readJSONFile.mockResolvedValue({
+ byTaskType: { 'user-task': { completed: 25, succeeded: 20 } }
+ });
+ result = await getGoalProgress();
+ expect(result.goals[0].metrics.engagement).toBe('high');
+ });
+
+ it('should match tasks by keywords', async () => {
+ const goalsMarkdown = `
+## Active Goals
+
+### Goal 1: Codebase Quality
+- Fix security issues
+`;
+ readFile.mockResolvedValue(goalsMarkdown);
+
+ const learningData = {
+ byTaskType: {
+ // This should match by keyword 'security'
+ 'custom-security-check': {
+ completed: 5,
+ succeeded: 4
+ }
+ }
+ };
+ readJSONFile.mockResolvedValue(learningData);
+
+ const result = await getGoalProgress();
+
+ expect(result.goals[0].metrics.totalTasks).toBe(5);
+ });
+
+ it('should calculate summary statistics', async () => {
+ const goalsMarkdown = `
+## Active Goals
+
+### Goal 1: User Engagement
+- Item
+
+### Goal 2: Documentation
+- Item
+`;
+ readFile.mockResolvedValue(goalsMarkdown);
+
+ readJSONFile.mockResolvedValue({
+ byTaskType: {
+ 'user-task': { completed: 30, succeeded: 25 },
+ 'self-improve:documentation': { completed: 10, succeeded: 8 }
+ }
+ });
+
+ const result = await getGoalProgress();
+
+ expect(result.summary.totalGoals).toBe(2);
+ expect(result.summary.totalTasks).toBe(40);
+ expect(result.summary.totalSucceeded).toBe(33);
+ expect(result.summary.overallSuccessRate).toBe(83);
+ });
+
+ it('should identify most and least active goals', async () => {
+ const goalsMarkdown = `
+## Active Goals
+
+### Goal 1: User Engagement
+- Item
+
+### Goal 2: Documentation
+- Item
+`;
+ readFile.mockResolvedValue(goalsMarkdown);
+
+ readJSONFile.mockResolvedValue({
+ byTaskType: {
+ 'user-task': { completed: 50, succeeded: 40 },
+ 'self-improve:documentation': { completed: 5, succeeded: 4 }
+ }
+ });
+
+ const result = await getGoalProgress();
+
+ expect(result.summary.mostActive).toBe('User Engagement');
+ expect(result.summary.leastActive).toBe('Documentation');
+ });
+
+ it('should handle null for leastActive when same as mostActive', async () => {
+ const goalsMarkdown = `
+## Active Goals
+
+### Goal 1: User Engagement
+- Item
+`;
+ readFile.mockResolvedValue(goalsMarkdown);
+
+ readJSONFile.mockResolvedValue({
+ byTaskType: { 'user-task': { completed: 10, succeeded: 8 } }
+ });
+
+ const result = await getGoalProgress();
+
+ expect(result.summary.leastActive).toBeNull();
+ });
+
+ it('should return null successRate when no tasks', async () => {
+ const goalsMarkdown = `
+## Active Goals
+
+### Goal 1: Unknown Goal
+- Item
+`;
+ readFile.mockResolvedValue(goalsMarkdown);
+ readJSONFile.mockResolvedValue({ byTaskType: {} });
+
+ const result = await getGoalProgress();
+
+ expect(result.goals[0].metrics.successRate).toBeNull();
+ });
+
+ it('should include updatedAt timestamp', async () => {
+ readFile.mockResolvedValue('## Active Goals');
+ readJSONFile.mockResolvedValue({});
+
+ const result = await getGoalProgress();
+
+ expect(result.updatedAt).toBeDefined();
+ expect(new Date(result.updatedAt)).toBeInstanceOf(Date);
+ });
+ });
+
+ describe('getGoalProgressSummary', () => {
+ it('should return top 5 goals', async () => {
+ const goalsMarkdown = `
+## Active Goals
+
+### Goal 1: Codebase Quality
+- Item
+
+### Goal 2: Self-Improvement
+- Item
+
+### Goal 3: Documentation
+- Item
+
+### Goal 4: User Engagement
+- Item
+
+### Goal 5: System Health
+- Item
+
+### Goal 6: Extra Goal
+- Item
+`;
+ readFile.mockResolvedValue(goalsMarkdown);
+
+ readJSONFile.mockResolvedValue({
+ byTaskType: {
+ 'self-improve:security-audit': { completed: 50, succeeded: 45 },
+ 'self-improve:general': { completed: 40, succeeded: 35 },
+ 'self-improve:documentation': { completed: 30, succeeded: 25 },
+ 'user-task': { completed: 20, succeeded: 15 },
+ 'auto-fix': { completed: 10, succeeded: 8 }
+ }
+ });
+
+ const result = await getGoalProgressSummary();
+
+ expect(result.goals.length).toBeLessThanOrEqual(5);
+ });
+
+ it('should return compact goal format', async () => {
+ const goalsMarkdown = `
+## Active Goals
+
+### Goal 1: User Engagement
+- Item
+`;
+ readFile.mockResolvedValue(goalsMarkdown);
+
+ readJSONFile.mockResolvedValue({
+ byTaskType: { 'user-task': { completed: 10, succeeded: 8 } }
+ });
+
+ const result = await getGoalProgressSummary();
+
+ expect(result.goals[0]).toHaveProperty('name');
+ expect(result.goals[0]).toHaveProperty('icon');
+ expect(result.goals[0]).toHaveProperty('color');
+ expect(result.goals[0]).toHaveProperty('tasks');
+ expect(result.goals[0]).toHaveProperty('successRate');
+ expect(result.goals[0]).toHaveProperty('engagement');
+ // Should not have full metrics object
+ expect(result.goals[0]).not.toHaveProperty('metrics');
+ });
+
+ it('should sort goals by task count descending', async () => {
+ const goalsMarkdown = `
+## Active Goals
+
+### Goal 1: Documentation
+- Item
+
+### Goal 2: User Engagement
+- Item
+`;
+ readFile.mockResolvedValue(goalsMarkdown);
+
+ readJSONFile.mockResolvedValue({
+ byTaskType: {
+ 'user-task': { completed: 100, succeeded: 90 },
+ 'self-improve:documentation': { completed: 10, succeeded: 8 }
+ }
+ });
+
+ const result = await getGoalProgressSummary();
+
+ expect(result.goals[0].name).toBe('User Engagement');
+ expect(result.goals[0].tasks).toBe(100);
+ });
+
+ it('should include summary in response', async () => {
+ readFile.mockResolvedValue('## Active Goals');
+ readJSONFile.mockResolvedValue({});
+
+ const result = await getGoalProgressSummary();
+
+ expect(result.summary).toBeDefined();
+ expect(result.updatedAt).toBeDefined();
+ });
+ });
+});
diff --git a/server/services/settings.test.js b/server/services/settings.test.js
new file mode 100644
index 0000000000..9f9dfbed41
--- /dev/null
+++ b/server/services/settings.test.js
@@ -0,0 +1,151 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+// Mock fs/promises before importing the module
+vi.mock('fs/promises', () => ({
+ readFile: vi.fn(),
+ writeFile: vi.fn()
+}));
+
+import { readFile, writeFile } from 'fs/promises';
+import { getSettings, updateSettings } from './settings.js';
+
+describe('settings.js', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ describe('getSettings', () => {
+ it('should return parsed settings from file', async () => {
+ const mockSettings = { theme: 'dark', notifications: true };
+ readFile.mockResolvedValue(JSON.stringify(mockSettings));
+
+ const result = await getSettings();
+
+ expect(result).toEqual(mockSettings);
+ expect(readFile).toHaveBeenCalledTimes(1);
+ });
+
+ it('should return empty object when file does not exist', async () => {
+ readFile.mockRejectedValue(new Error('ENOENT'));
+
+ const result = await getSettings();
+
+ expect(result).toEqual({});
+ });
+
+ it('should throw on invalid JSON in file', async () => {
+ // The code doesn't handle empty/invalid JSON - it will throw
+ // This tests that behavior
+ readFile.mockResolvedValue('');
+
+ await expect(getSettings()).rejects.toThrow();
+ });
+
+ it('should handle complex nested settings', async () => {
+ const mockSettings = {
+ display: {
+ theme: 'dark',
+ fontSize: 14
+ },
+ features: ['notifications', 'autoSave'],
+ version: 2
+ };
+ readFile.mockResolvedValue(JSON.stringify(mockSettings));
+
+ const result = await getSettings();
+
+ expect(result).toEqual(mockSettings);
+ });
+ });
+
+ describe('updateSettings', () => {
+ it('should merge patch with existing settings', async () => {
+ const existingSettings = { theme: 'light', notifications: true };
+ readFile.mockResolvedValue(JSON.stringify(existingSettings));
+ writeFile.mockResolvedValue();
+
+ const result = await updateSettings({ theme: 'dark' });
+
+ expect(result).toEqual({ theme: 'dark', notifications: true });
+ });
+
+ it('should add new keys when patching', async () => {
+ const existingSettings = { theme: 'light' };
+ readFile.mockResolvedValue(JSON.stringify(existingSettings));
+ writeFile.mockResolvedValue();
+
+ const result = await updateSettings({ newSetting: 'value' });
+
+ expect(result).toEqual({ theme: 'light', newSetting: 'value' });
+ });
+
+ it('should write formatted JSON to file', async () => {
+ readFile.mockResolvedValue('{}');
+ writeFile.mockResolvedValue();
+
+ await updateSettings({ test: true });
+
+ expect(writeFile).toHaveBeenCalledTimes(1);
+ const [, content] = writeFile.mock.calls[0];
+ // Should be formatted with 2-space indent and trailing newline
+ expect(content).toBe('{\n "test": true\n}\n');
+ });
+
+ it('should create settings from empty when file does not exist', async () => {
+ readFile.mockRejectedValue(new Error('ENOENT'));
+ writeFile.mockResolvedValue();
+
+ const result = await updateSettings({ firstSetting: 'value' });
+
+ expect(result).toEqual({ firstSetting: 'value' });
+ });
+
+ it('should overwrite nested values with shallow merge', async () => {
+ const existingSettings = {
+ display: { theme: 'light', fontSize: 12 }
+ };
+ readFile.mockResolvedValue(JSON.stringify(existingSettings));
+ writeFile.mockResolvedValue();
+
+ // Shallow merge replaces the entire display object
+ const result = await updateSettings({ display: { theme: 'dark' } });
+
+ expect(result).toEqual({ display: { theme: 'dark' } });
+ // Note: fontSize is lost because it's a shallow merge
+ });
+
+ it('should preserve unmodified settings', async () => {
+ const existingSettings = {
+ a: 1,
+ b: 2,
+ c: 3
+ };
+ readFile.mockResolvedValue(JSON.stringify(existingSettings));
+ writeFile.mockResolvedValue();
+
+ const result = await updateSettings({ b: 20 });
+
+ expect(result).toEqual({ a: 1, b: 20, c: 3 });
+ });
+
+ it('should handle null values in patch', async () => {
+ const existingSettings = { feature: true };
+ readFile.mockResolvedValue(JSON.stringify(existingSettings));
+ writeFile.mockResolvedValue();
+
+ const result = await updateSettings({ feature: null });
+
+ expect(result).toEqual({ feature: null });
+ });
+
+ it('should handle empty patch object', async () => {
+ const existingSettings = { theme: 'dark' };
+ readFile.mockResolvedValue(JSON.stringify(existingSettings));
+ writeFile.mockResolvedValue();
+
+ const result = await updateSettings({});
+
+ expect(result).toEqual({ theme: 'dark' });
+ });
+ });
+});