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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: add tests for 7 untested modules (commandSecurity, httpClient, platform, memoryBM25, notifications, search, taskSchedule)
Adam Eivyeaa0d77bda43
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3ba42987a8..8f6eab80ac 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,6 @@## Added+- **Test coverage** for 7 previously untested modules: `commandSecurity`, `httpClient`, `platform`, `memoryBM25`, `notifications`, `search`, and `taskSchedule` — 171 new tests covering command validation, output redaction, HTTP client factory, BM25 memory indexing, notification CRUD, fan-out search, and task scheduling logic- **Xcode Multi-Platform template** — new "Xcode Multi-Platform" app template scaffolds a SwiftUI project with iOS, macOS, and watchOS targets via XcodeGen- Generic `deploy.sh` with `--ios`, `--macos`, `--watch`, `--all` flags for TestFlight deployment- Generic `take_screenshots.sh` and `take_screenshots_macos.sh` for App Store screenshot automationdiff --git a/server/lib/commandSecurity.test.js b/server/lib/commandSecurity.test.jsnew file mode 100644index 0000000000..8ddcd8c6ec--- /dev/null+++ b/server/lib/commandSecurity.test.js@@ -0,0 +1,201 @@+import { describe, it, expect } from 'vitest'+import {+ ALLOWED_COMMANDS,+ ALLOWED_COMMANDS_SORTED,+ DANGEROUS_SHELL_CHARS,+ validateCommand,+ redactOutput+} from './commandSecurity.js'++describe('commandSecurity', () => {+ describe('ALLOWED_COMMANDS', () => {+ it('should be a Set containing expected base commands', () => {+ expect(ALLOWED_COMMANDS).toBeInstanceOf(Set)+ expect(ALLOWED_COMMANDS.has('npm')).toBe(true)+ expect(ALLOWED_COMMANDS.has('git')).toBe(true)+ expect(ALLOWED_COMMANDS.has('node')).toBe(true)+ expect(ALLOWED_COMMANDS.has('docker')).toBe(true)+ expect(ALLOWED_COMMANDS.has('pm2')).toBe(true)+ })++ it('should not contain dangerous commands', () => {+ expect(ALLOWED_COMMANDS.has('rm')).toBe(false)+ expect(ALLOWED_COMMANDS.has('sudo')).toBe(false)+ expect(ALLOWED_COMMANDS.has('chmod')).toBe(false)+ expect(ALLOWED_COMMANDS.has('chown')).toBe(false)+ expect(ALLOWED_COMMANDS.has('kill')).toBe(false)+ })+ })++ describe('ALLOWED_COMMANDS_SORTED', () => {+ it('should be a sorted array', () => {+ const sorted = [...ALLOWED_COMMANDS_SORTED].sort()+ expect(ALLOWED_COMMANDS_SORTED).toEqual(sorted)+ })++ it('should contain same entries as the Set', () => {+ expect(ALLOWED_COMMANDS_SORTED.length).toBe(ALLOWED_COMMANDS.size)+ for (const cmd of ALLOWED_COMMANDS_SORTED) {+ expect(ALLOWED_COMMANDS.has(cmd)).toBe(true)+ }+ })+ })++ describe('DANGEROUS_SHELL_CHARS', () => {+ it.each([+ ['pipe', 'ls | grep foo'],+ ['semicolons', 'ls; rm -rf /'],+ ['ampersands', 'cmd && cmd2'],+ ['backticks', 'echo `whoami`'],+ ['dollar signs', 'echo $PATH'],+ ['parentheses', '$(command)'],+ ['redirect >', 'echo foo > file'],+ ['redirect <', 'cat < file']+ ])('should match %s', (_label, input) => {+ expect(DANGEROUS_SHELL_CHARS.test(input)).toBe(true)+ })++ it.each([+ ['npm install express'],+ ['git commit -m "hello"']+ ])('should not match safe string: %s', (input) => {+ expect(DANGEROUS_SHELL_CHARS.test(input)).toBe(false)+ })+ })++ describe('validateCommand', () => {+ it('should accept a valid simple command', () => {+ const result = validateCommand('npm install')+ expect(result).toEqual({+ valid: true,+ baseCommand: 'npm',+ args: ['install']+ })+ })++ it('should accept commands with multiple args', () => {+ const result = validateCommand('git commit -m "test message"')+ expect(result).toEqual({+ valid: true,+ baseCommand: 'git',+ args: ['commit', '-m', 'test message']+ })+ })++ it('should accept commands with single-quoted args', () => {+ const result = validateCommand("git log --format='%H %s'")+ expect(result).toEqual({+ valid: true,+ baseCommand: 'git',+ args: ['log', "--format=%H %s"]+ })+ })++ it('should accept a bare allowed command', () => {+ const result = validateCommand('pwd')+ expect(result).toEqual({+ valid: true,+ baseCommand: 'pwd',+ args: []+ })+ })++ it.each([+ ['null', null, 'Command is required'],+ ['undefined', undefined, 'Command is required'],+ ['empty string', '', 'Command is required'],+ ['non-string (number)', 123, 'Command is required'],+ ['whitespace-only', ' ', 'Command cannot be empty']+ ])('should reject %s input', (_label, input, expectedError) => {+ const result = validateCommand(input)+ expect(result.valid).toBe(false)+ expect(result.error).toBe(expectedError)+ })++ it('should reject commands with pipe operator', () => {+ const result = validateCommand('npm list | grep express')+ expect(result.valid).toBe(false)+ expect(result.error).toBe('Command contains disallowed shell characters')+ })++ it('should reject commands with semicolons', () => {+ const result = validateCommand('npm test; rm -rf /')+ expect(result.valid).toBe(false)+ expect(result.error).toBe('Command contains disallowed shell characters')+ })++ it('should reject commands with command substitution', () => {+ const result = validateCommand('npm install $(cat packages.txt)')+ expect(result.valid).toBe(false)+ expect(result.error).toBe('Command contains disallowed shell characters')+ })++ it('should reject commands not in allowlist', () => {+ const result = validateCommand('rm -rf /')+ expect(result.valid).toBe(false)+ expect(result.error).toContain("Command 'rm' is not in the allowlist")+ expect(result.error).toContain('Allowed:')+ })++ it('should reject unknown commands', () => {+ const result = validateCommand('malware execute')+ expect(result.valid).toBe(false)+ expect(result.error).toContain("Command 'malware' is not in the allowlist")+ })++ it('should handle leading/trailing whitespace', () => {+ const result = validateCommand(' npm install ')+ expect(result.valid).toBe(true)+ expect(result.baseCommand).toBe('npm')+ })++ it('should handle empty quoted strings in args', () => {+ const result = validateCommand('git commit -m ""')+ expect(result.valid).toBe(true)+ expect(result.args).toContain('')+ })+ })++ describe('redactOutput', () => {+ it.each([+ ['SECRET_KEY', '{"SECRET_KEY": "my-secret-123", "name": "test"}', '{"SECRET_KEY": "[REDACTED]", "name": "test"}'],+ ['TOKEN', '{"API_TOKEN": "abc123"}', '{"API_TOKEN": "[REDACTED]"}'],+ ['PASSWORD', '{"DB_PASSWORD": "hunter2"}', '{"DB_PASSWORD": "[REDACTED]"}'],+ ['AUTH', '{"GITHUB_AUTH": "ghp_abc123"}', '{"GITHUB_AUTH": "[REDACTED]"}'],+ ['CREDENTIAL', '{"SERVICE_CREDENTIAL": "cred-xyz"}', '{"SERVICE_CREDENTIAL": "[REDACTED]"}']+ ])('should redact %s values', (_label, input, expected) => {+ expect(redactOutput(input)).toBe(expected)+ })++ it('should not redact non-sensitive keys', () => {+ const input = '{"name": "test", "port": "3000"}'+ const result = redactOutput(input)+ expect(result).toBe(input)+ })++ it('should handle null input', () => {+ expect(redactOutput(null)).toBe(null)+ })++ it('should handle undefined input', () => {+ expect(redactOutput(undefined)).toBe(undefined)+ })++ it('should handle empty string', () => {+ expect(redactOutput('')).toBe('')+ })++ it('should handle plain text without JSON', () => {+ const input = 'Server started on port 3000'+ expect(redactOutput(input)).toBe(input)+ })++ it('should redact multiple sensitive values', () => {+ const input = '{"API_KEY": "key1", "SECRET_TOKEN": "tok2", "name": "app"}'+ const result = redactOutput(input)+ expect(result).toContain('"API_KEY": "[REDACTED]"')+ expect(result).toContain('"SECRET_TOKEN": "[REDACTED]"')+ expect(result).toContain('"name": "app"')+ })+ })+})diff --git a/server/lib/httpClient.test.js b/server/lib/httpClient.test.jsnew file mode 100644index 0000000000..2d6256d044--- /dev/null+++ b/server/lib/httpClient.test.js@@ -0,0 +1,223 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { createHttpClient } from './httpClient.js'++// Mock global fetch+const mockFetch = vi.fn()+vi.stubGlobal('fetch', mockFetch)++describe('httpClient', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ function mockJsonResponse(data, status = 200) {+ return {+ ok: status >= 200 && status < 300,+ status,+ headers: { get: (name) => name.toLowerCase() === 'content-type' ? 'application/json' : null },+ json: () => Promise.resolve(data),+ text: () => Promise.resolve(JSON.stringify(data))+ }+ }++ function mockTextResponse(text, status = 200) {+ return {+ ok: status >= 200 && status < 300,+ status,+ headers: { get: () => 'text/plain' },+ json: () => Promise.resolve(text),+ text: () => Promise.resolve(text)+ }+ }++ describe('createHttpClient', () => {+ it('should return an object with get, post, put, delete methods', () => {+ const client = createHttpClient()+ expect(typeof client.get).toBe('function')+ expect(typeof client.post).toBe('function')+ expect(typeof client.put).toBe('function')+ expect(typeof client.delete).toBe('function')+ })+ })++ describe('GET requests', () => {+ it('should make a GET request with baseURL', async () => {+ mockFetch.mockResolvedValueOnce(mockJsonResponse({ ok: true }))+ const client = createHttpClient({ baseURL: 'http://localhost:3000' })++ const result = await client.get('/api/test')++ expect(mockFetch).toHaveBeenCalledWith(+ 'http://localhost:3000/api/test',+ expect.objectContaining({ method: 'GET' })+ )+ expect(result.data).toEqual({ ok: true })+ expect(result.status).toBe(200)+ })++ it('should append query params', async () => {+ mockFetch.mockResolvedValueOnce(mockJsonResponse([]))+ const client = createHttpClient({ baseURL: 'http://localhost:3000' })++ await client.get('/items', { params: { page: 1, limit: 10 } })++ const calledUrl = mockFetch.mock.calls[0][0]+ expect(calledUrl).toContain('page=1')+ expect(calledUrl).toContain('limit=10')+ })++ it('should filter out null/undefined params', async () => {+ mockFetch.mockResolvedValueOnce(mockJsonResponse([]))+ const client = createHttpClient({ baseURL: 'http://localhost:3000' })++ await client.get('/items', { params: { page: 1, filter: null, sort: undefined } })++ const calledUrl = mockFetch.mock.calls[0][0]+ expect(calledUrl).toContain('page=1')+ expect(calledUrl).not.toContain('filter')+ expect(calledUrl).not.toContain('sort')+ })++ it('should include default headers', async () => {+ mockFetch.mockResolvedValueOnce(mockJsonResponse({}))+ const client = createHttpClient({+ baseURL: 'http://localhost:3000',+ headers: { 'Authorization': 'Bearer token123' }+ })++ await client.get('/secure')++ const calledOptions = mockFetch.mock.calls[0][1]+ expect(calledOptions.headers['Authorization']).toBe('Bearer token123')+ })++ it('should merge extra headers with default headers', async () => {+ mockFetch.mockResolvedValueOnce(mockJsonResponse({}))+ const client = createHttpClient({+ baseURL: 'http://localhost:3000',+ headers: { 'Authorization': 'Bearer token123' }+ })++ await client.get('/secure', { headers: { 'X-Custom': 'value' } })++ const calledOptions = mockFetch.mock.calls[0][1]+ expect(calledOptions.headers['Authorization']).toBe('Bearer token123')+ expect(calledOptions.headers['X-Custom']).toBe('value')+ })++ it('should handle text responses', async () => {+ mockFetch.mockResolvedValueOnce(mockTextResponse('Hello World'))+ const client = createHttpClient()++ const result = await client.get('/text')+ expect(result.data).toBe('Hello World')+ })+ })++ describe('POST requests', () => {+ it('should send JSON body', async () => {+ mockFetch.mockResolvedValueOnce(mockJsonResponse({ id: 1 }, 201))+ const client = createHttpClient({ baseURL: 'http://localhost:3000' })++ const result = await client.post('/items', { name: 'test' })++ const calledOptions = mockFetch.mock.calls[0][1]+ expect(calledOptions.method).toBe('POST')+ expect(calledOptions.body).toBe(JSON.stringify({ name: 'test' }))+ expect(calledOptions.headers['Content-Type']).toBe('application/json')+ })++ it('should not override existing Content-Type header', async () => {+ mockFetch.mockResolvedValueOnce(mockJsonResponse({}))+ const client = createHttpClient({+ headers: { 'Content-Type': 'application/xml' }+ })++ await client.post('/items', { name: 'test' })++ const calledOptions = mockFetch.mock.calls[0][1]+ expect(calledOptions.headers['Content-Type']).toBe('application/xml')+ })++ it('should not set Content-Type when no data provided', async () => {+ mockFetch.mockResolvedValueOnce(mockJsonResponse({}))+ const client = createHttpClient()++ await client.post('/items')++ const calledOptions = mockFetch.mock.calls[0][1]+ expect(calledOptions.body).toBeUndefined()+ })+ })++ describe('PUT requests', () => {+ it('should make PUT request with body', async () => {+ mockFetch.mockResolvedValueOnce(mockJsonResponse({ updated: true }))+ const client = createHttpClient({ baseURL: 'http://localhost:3000' })++ const result = await client.put('/items/1', { name: 'updated' })++ const calledOptions = mockFetch.mock.calls[0][1]+ expect(calledOptions.method).toBe('PUT')+ expect(calledOptions.body).toBe(JSON.stringify({ name: 'updated' }))+ expect(result.data).toEqual({ updated: true })+ })+ })++ describe('DELETE requests', () => {+ it('should make DELETE request', async () => {+ mockFetch.mockResolvedValueOnce(mockJsonResponse({ deleted: true }))+ const client = createHttpClient({ baseURL: 'http://localhost:3000' })++ const result = await client.delete('/items/1')++ const calledOptions = mockFetch.mock.calls[0][1]+ expect(calledOptions.method).toBe('DELETE')+ expect(result.data).toEqual({ deleted: true })+ })+ })++ describe('error handling', () => {+ it('should throw on non-ok response', async () => {+ mockFetch.mockResolvedValueOnce(mockJsonResponse({ error: 'Not found' }, 404))+ const client = createHttpClient()++ await expect(client.get('/missing')).rejects.toThrow('HTTP 404')+ })++ it('should include status and response data on error', async () => {+ mockFetch.mockResolvedValueOnce(mockJsonResponse({ error: 'Forbidden' }, 403))+ const client = createHttpClient()++ try {+ await client.get('/forbidden')+ expect.unreachable('should have thrown')+ } catch (err) {+ expect(err.status).toBe(403)+ expect(err.response.data).toEqual({ error: 'Forbidden' })+ expect(err.response.status).toBe(403)+ }+ })++ it('should throw on 500 server error', async () => {+ mockFetch.mockResolvedValueOnce(mockJsonResponse({ error: 'Internal error' }, 500))+ const client = createHttpClient()++ await expect(client.get('/error')).rejects.toThrow('HTTP 500')+ })+ })++ describe('no baseURL', () => {+ it('should work without baseURL', async () => {+ mockFetch.mockResolvedValueOnce(mockJsonResponse({ ok: true }))+ const client = createHttpClient()++ await client.get('/api/test')++ expect(mockFetch).toHaveBeenCalledWith(+ '/api/test',+ expect.any(Object)+ )+ })+ })+})diff --git a/server/lib/platform.test.js b/server/lib/platform.test.jsnew file mode 100644index 0000000000..f1fe526be9--- /dev/null+++ b/server/lib/platform.test.js@@ -0,0 +1,65 @@+import { describe, it, expect } from 'vitest'+import { platform, getListeningPorts, isPortInUse, findAvailablePorts } from './platform.js'++describe('platform module', () => {+ describe('platform constant', () => {+ it('should export the current platform', () => {+ expect(typeof platform).toBe('string')+ expect(platform).toBe(process.platform)+ })+ })++ describe('getListeningPorts', () => {+ it('should return an array of numbers', async () => {+ const ports = await getListeningPorts()+ expect(Array.isArray(ports)).toBe(true)+ for (const port of ports) {+ expect(typeof port).toBe('number')+ expect(Number.isInteger(port)).toBe(true)+ }+ })++ it('should return ports in sorted order', async () => {+ const ports = await getListeningPorts()+ for (let i = 1; i < ports.length; i++) {+ expect(ports[i]).toBeGreaterThanOrEqual(ports[i - 1])+ }+ })++ it('should return unique ports', async () => {+ const ports = await getListeningPorts()+ const unique = new Set(ports)+ expect(unique.size).toBe(ports.length)+ })+ })++ describe('isPortInUse', () => {+ it('should return a boolean', async () => {+ const result = await isPortInUse(59999)+ expect(typeof result).toBe('boolean')+ })+ })++ describe('findAvailablePorts', () => {+ it('should return available ports within range', async () => {+ const ports = await findAvailablePorts(49000, 49100, 3)+ expect(Array.isArray(ports)).toBe(true)+ expect(ports.length).toBeLessThanOrEqual(3)+ for (const port of ports) {+ expect(port).toBeGreaterThanOrEqual(49000)+ expect(port).toBeLessThanOrEqual(49100)+ }+ })++ it('should default to finding 1 port', async () => {+ const ports = await findAvailablePorts(49200, 49300)+ expect(ports.length).toBeLessThanOrEqual(1)+ })++ it('should return empty array when range is exhausted', async () => {+ // Range of 0 ports+ const ports = await findAvailablePorts(49400, 49399, 1)+ expect(ports).toEqual([])+ })+ })+})diff --git a/server/services/memoryBM25.test.js b/server/services/memoryBM25.test.jsnew file mode 100644index 0000000000..3c01c40f61--- /dev/null+++ b/server/services/memoryBM25.test.js@@ -0,0 +1,234 @@+import { describe, it, expect, beforeEach, vi } from 'vitest'++vi.mock('fs', () => ({+ promises: {+ access: vi.fn(),+ readFile: vi.fn(),+ writeFile: vi.fn().mockResolvedValue()+ }+}))++vi.mock('../lib/fileUtils.js', () => ({+ ensureDir: vi.fn().mockResolvedValue(),+ PATHS: { memory: '/mock/data/memory' }+}))++vi.mock('../lib/bm25.js', () => ({+ buildInvertedIndex: vi.fn((docs) => ({+ terms: {},+ docIds: new Set(docs.map(d => d.id)),+ totalDocs: docs.length,+ docLengths: {},+ avgDocLength: 0+ })),+ addDocument: vi.fn((index, id) => {+ index.docIds.add(id)+ index.totalDocs+++ }),+ removeDocument: vi.fn((index, id) => {+ index.docIds.delete(id)+ index.totalDocs--+ }),+ search: vi.fn(() => []),+ createEmptyIndex: vi.fn(() => ({+ terms: {},+ docIds: new Set(),+ totalDocs: 0,+ docLengths: {},+ avgDocLength: 0+ })),+ serializeIndex: vi.fn((idx) => ({+ terms: {},+ docIds: [...idx.docIds],+ totalDocs: idx.totalDocs,+ docLengths: {},+ avgDocLength: 0+ })),+ deserializeIndex: vi.fn((parsed) => ({+ ...parsed,+ docIds: new Set(parsed.docIds || [])+ })),+ getIndexStats: vi.fn((idx) => ({+ totalDocs: idx.totalDocs,+ totalTerms: Object.keys(idx.terms).length+ }))+}))++import {+ loadIndex,+ rebuildIndex,+ indexMemory,+ removeMemoryFromIndex,+ searchBM25,+ getStats,+ flush,+ clearIndex,+ hasMemory,+ batchIndex,+ buildIndexableText+} from './memoryBM25.js'++import { promises as fs } from 'fs'+import { search, createEmptyIndex, buildInvertedIndex } from '../lib/bm25.js'++describe('memoryBM25', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ // Reset the module's internal cache by clearing the index+ clearIndex()+ })++ describe('buildIndexableText', () => {+ it('should combine content, type, tags, and source', () => {+ const memory = {+ content: 'Hello world',+ type: 'fact',+ tags: ['greeting', 'test'],+ source: 'manual'+ }+ const text = buildIndexableText(memory)+ expect(text).toBe('Hello world fact greeting test manual')+ })++ it('should handle missing fields', () => {+ const text = buildIndexableText({})+ expect(text).toBe('')+ })++ it('should handle content only', () => {+ const text = buildIndexableText({ content: 'just content' })+ expect(text).toBe('just content')+ })++ it('should handle non-array tags gracefully', () => {+ const text = buildIndexableText({ content: 'test', tags: 'not-array' })+ expect(text).toBe('test')+ })++ it('should handle empty tags array', () => {+ const text = buildIndexableText({ content: 'test', tags: [] })+ // empty array still pushes empty string to parts, resulting in trailing space+ expect(text).toBe('test ')+ })+ })++ describe('loadIndex', () => {+ it('should return an index with expected shape', async () => {+ const index = await loadIndex()+ expect(index).toHaveProperty('totalDocs')+ expect(index).toHaveProperty('terms')+ expect(index).toHaveProperty('docIds')+ })++ it('should return cached index on subsequent calls', async () => {+ const index1 = await loadIndex()+ const index2 = await loadIndex()+ expect(index1).toBe(index2)+ })+ })++ describe('rebuildIndex', () => {+ it('should rebuild index from memories', async () => {+ const memories = [+ { id: 'm1', content: 'First memory', type: 'fact', tags: ['test'] },+ { id: 'm2', content: 'Second memory', type: 'event', tags: [] }+ ]++ const stats = await rebuildIndex(memories)+ expect(buildInvertedIndex).toHaveBeenCalledWith([+ { id: 'm1', text: 'First memory fact test' },+ { id: 'm2', text: 'Second memory event ' }+ ])+ expect(stats).toHaveProperty('totalDocs')+ })+ })++ describe('indexMemory', () => {+ it('should add a memory to the index', async () => {+ const memory = { id: 'new-1', content: 'New memory', type: 'fact', tags: ['new'] }+ await indexMemory(memory)++ const exists = await hasMemory('new-1')+ expect(exists).toBe(true)+ })+ })++ describe('removeMemoryFromIndex', () => {+ it('should remove a memory from the index', async () => {+ const memory = { id: 'rm-1', content: 'To remove', type: 'fact', tags: [] }+ await indexMemory(memory)+ await removeMemoryFromIndex('rm-1')++ const exists = await hasMemory('rm-1')+ expect(exists).toBe(false)+ })+ })++ describe('searchBM25', () => {+ it('should search with default options', async () => {+ search.mockReturnValueOnce([+ { docId: 'doc1', score: 1.5 },+ { docId: 'doc2', score: 0.8 }+ ])++ const results = await searchBM25('test query')+ expect(results).toEqual([+ { id: 'doc1', score: 1.5 },+ { id: 'doc2', score: 0.8 }+ ])+ expect(search).toHaveBeenCalledWith('test query', expect.any(Object), { limit: 20, threshold: 0.1 })+ })++ it('should pass custom options', async () => {+ search.mockReturnValueOnce([])++ await searchBM25('query', { limit: 5, threshold: 0.5 })+ expect(search).toHaveBeenCalledWith('query', expect.any(Object), { limit: 5, threshold: 0.5 })+ })++ it('should return empty array when no matches', async () => {+ search.mockReturnValueOnce([])+ const results = await searchBM25('no match')+ expect(results).toEqual([])+ })+ })++ describe('getStats', () => {+ it('should return index stats with isDirty and indexFile', async () => {+ const stats = await getStats()+ expect(stats).toHaveProperty('isDirty')+ expect(stats).toHaveProperty('indexFile')+ expect(stats.indexFile).toContain('bm25-index.json')+ })+ })++ describe('clearIndex', () => {+ it('should reset the index to empty', async () => {+ await indexMemory({ id: 'temp', content: 'temp', type: 'fact', tags: [] })+ await clearIndex()++ const exists = await hasMemory('temp')+ expect(exists).toBe(false)+ })+ })++ describe('batchIndex', () => {+ it('should index multiple memories', async () => {+ const memories = [+ { id: 'b1', content: 'Batch 1', type: 'fact', tags: [] },+ { id: 'b2', content: 'Batch 2', type: 'fact', tags: [] },+ { id: 'b3', content: 'Batch 3', type: 'fact', tags: [] }+ ]++ const count = await batchIndex(memories)+ expect(count).toBe(3)+ })+ })++ describe('hasMemory', () => {+ it('should return false for non-existent memory', async () => {+ const exists = await hasMemory('nonexistent')+ expect(exists).toBe(false)+ })+ })+})diff --git a/server/services/notifications.test.js b/server/services/notifications.test.jsnew file mode 100644index 0000000000..d28551e252--- /dev/null+++ b/server/services/notifications.test.js@@ -0,0 +1,358 @@+import { describe, it, expect, beforeEach, vi } from 'vitest'++vi.mock('../lib/fileUtils.js', () => ({+ ensureDir: vi.fn().mockResolvedValue(),+ readJSONFile: vi.fn(),+ PATHS: { data: '/mock/data' }+}))++vi.mock('fs/promises', () => ({+ writeFile: vi.fn().mockResolvedValue(),+ rename: vi.fn().mockResolvedValue()+}))++vi.mock('../lib/uuid.js', () => ({+ v4: vi.fn(() => 'test-uuid-1234')+}))++vi.mock('../lib/asyncMutex.js', () => ({+ createMutex: () => (fn) => fn()+}))++import {+ getNotifications,+ getUnreadCount,+ getCountsByType,+ addNotification,+ removeNotification,+ removeByMetadata,+ markAsRead,+ markAllAsRead,+ clearAll,+ exists,+ invalidateCache,+ NOTIFICATION_TYPES,+ PRIORITY_LEVELS,+ notificationEvents+} from './notifications.js'+import { readJSONFile } from '../lib/fileUtils.js'++describe('notifications', () => {+ const baseNotifications = {+ version: 1,+ notifications: [+ {+ id: 'n1',+ type: NOTIFICATION_TYPES.MEMORY_APPROVAL,+ title: 'Memory needs review',+ description: 'Classify this memory',+ priority: PRIORITY_LEVELS.MEDIUM,+ timestamp: '2025-01-02T00:00:00.000Z',+ link: '/brain/memory',+ read: false,+ metadata: { memoryId: 'mem-1' }+ },+ {+ id: 'n2',+ type: NOTIFICATION_TYPES.CODE_REVIEW,+ title: 'Review PR #42',+ description: 'Code review needed',+ priority: PRIORITY_LEVELS.HIGH,+ timestamp: '2025-01-01T00:00:00.000Z',+ link: '/cos/agents',+ read: true,+ metadata: { prNumber: 42 }+ },+ {+ id: 'n3',+ type: NOTIFICATION_TYPES.HEALTH_ISSUE,+ title: 'High heart rate detected',+ description: 'HR exceeded threshold',+ priority: PRIORITY_LEVELS.CRITICAL,+ timestamp: '2025-01-03T00:00:00.000Z',+ link: '/meatspace/health',+ read: false,+ metadata: {}+ }+ ]+ }++ beforeEach(() => {+ vi.clearAllMocks()+ invalidateCache()+ readJSONFile.mockResolvedValue(JSON.parse(JSON.stringify(baseNotifications)))+ })++ describe('NOTIFICATION_TYPES', () => {+ it('should define expected notification types', () => {+ expect(NOTIFICATION_TYPES.MEMORY_APPROVAL).toBe('memory_approval')+ expect(NOTIFICATION_TYPES.TASK_APPROVAL).toBe('task_approval')+ expect(NOTIFICATION_TYPES.CODE_REVIEW).toBe('code_review')+ expect(NOTIFICATION_TYPES.HEALTH_ISSUE).toBe('health_issue')+ expect(NOTIFICATION_TYPES.BRIEFING_READY).toBe('briefing_ready')+ expect(NOTIFICATION_TYPES.AGENT_WARNING).toBe('agent_warning')+ })+ })++ describe('PRIORITY_LEVELS', () => {+ it('should define expected priority levels', () => {+ expect(PRIORITY_LEVELS.LOW).toBe('low')+ expect(PRIORITY_LEVELS.MEDIUM).toBe('medium')+ expect(PRIORITY_LEVELS.HIGH).toBe('high')+ expect(PRIORITY_LEVELS.CRITICAL).toBe('critical')+ })+ })++ describe('getNotifications', () => {+ it('should return all notifications sorted by timestamp descending', async () => {+ const notifications = await getNotifications()+ expect(notifications).toHaveLength(3)+ // Newest first+ expect(notifications[0].id).toBe('n3')+ expect(notifications[1].id).toBe('n1')+ expect(notifications[2].id).toBe('n2')+ })++ it('should filter by type', async () => {+ const notifications = await getNotifications({ type: NOTIFICATION_TYPES.CODE_REVIEW })+ expect(notifications).toHaveLength(1)+ expect(notifications[0].id).toBe('n2')+ })++ it('should filter unread only', async () => {+ const notifications = await getNotifications({ unreadOnly: true })+ expect(notifications).toHaveLength(2)+ notifications.forEach(n => expect(n.read).toBe(false))+ })++ it('should apply limit', async () => {+ const notifications = await getNotifications({ limit: 1 })+ expect(notifications).toHaveLength(1)+ expect(notifications[0].id).toBe('n3')+ })++ it('should combine filters', async () => {+ const notifications = await getNotifications({+ unreadOnly: true,+ limit: 1+ })+ expect(notifications).toHaveLength(1)+ expect(notifications[0].read).toBe(false)+ })+ })++ describe('getUnreadCount', () => {+ it('should count unread notifications', async () => {+ const count = await getUnreadCount()+ expect(count).toBe(2)+ })++ it('should return 0 when all read', async () => {+ readJSONFile.mockResolvedValue({+ version: 1,+ notifications: [+ { id: 'n1', read: true, type: 'test' }+ ]+ })+ invalidateCache()+ const count = await getUnreadCount()+ expect(count).toBe(0)+ })+ })++ describe('getCountsByType', () => {+ it('should return counts grouped by type', async () => {+ const counts = await getCountsByType()+ expect(counts.total).toBe(3)+ expect(counts.unread).toBe(2)+ expect(counts.byType[NOTIFICATION_TYPES.MEMORY_APPROVAL]).toBe(1)+ expect(counts.byType[NOTIFICATION_TYPES.CODE_REVIEW]).toBe(1)+ expect(counts.byType[NOTIFICATION_TYPES.HEALTH_ISSUE]).toBe(1)+ })+ })++ describe('addNotification', () => {+ it('should add a notification with generated fields', async () => {+ const result = await addNotification({+ type: NOTIFICATION_TYPES.TASK_APPROVAL,+ title: 'New task pending',+ description: 'Review this task',+ priority: PRIORITY_LEVELS.LOW,+ link: '/cos/tasks',+ metadata: { taskId: 't1' }+ })++ expect(result.id).toBe('test-uuid-1234')+ expect(result.type).toBe(NOTIFICATION_TYPES.TASK_APPROVAL)+ expect(result.title).toBe('New task pending')+ expect(result.read).toBe(false)+ expect(result.timestamp).toBeDefined()+ expect(result.metadata.taskId).toBe('t1')+ })++ it('should use default priority when not specified', async () => {+ const result = await addNotification({+ type: NOTIFICATION_TYPES.BRIEFING_READY,+ title: 'Briefing ready'+ })++ expect(result.priority).toBe(PRIORITY_LEVELS.MEDIUM)+ })++ it('should handle missing optional fields', async () => {+ const result = await addNotification({+ type: NOTIFICATION_TYPES.BRIEFING_READY,+ title: 'Test'+ })++ expect(result.description).toBe('')+ expect(result.link).toBeNull()+ expect(result.metadata).toEqual({})+ })++ it('should emit events when notification added', async () => {+ const addedSpy = vi.fn()+ const countSpy = vi.fn()+ notificationEvents.on('added', addedSpy)+ notificationEvents.on('count-changed', countSpy)++ await addNotification({+ type: NOTIFICATION_TYPES.TASK_APPROVAL,+ title: 'Test'+ })++ expect(addedSpy).toHaveBeenCalledOnce()+ expect(countSpy).toHaveBeenCalled()++ notificationEvents.off('added', addedSpy)+ notificationEvents.off('count-changed', countSpy)+ })+ })++ describe('removeNotification', () => {+ it('should remove an existing notification', async () => {+ const result = await removeNotification('n1')+ expect(result.success).toBe(true)+ expect(result.notification.id).toBe('n1')+ })++ it('should return error for non-existent notification', async () => {+ const result = await removeNotification('nonexistent')+ expect(result.success).toBe(false)+ expect(result.error).toBe('Notification not found')+ })+ })++ describe('removeByMetadata', () => {+ it('should remove notifications matching metadata field/value', async () => {+ const result = await removeByMetadata('memoryId', 'mem-1')+ expect(result.success).toBe(true)+ expect(result.removed).toBe(1)+ })++ it('should return 0 removed when no matches', async () => {+ const result = await removeByMetadata('memoryId', 'nonexistent')+ expect(result.success).toBe(true)+ expect(result.removed).toBe(0)+ })+ })++ describe('markAsRead', () => {+ it('should mark an unread notification as read', async () => {+ const result = await markAsRead('n1')+ expect(result.success).toBe(true)+ expect(result.notification.read).toBe(true)+ })++ it('should handle already-read notification', async () => {+ const result = await markAsRead('n2')+ expect(result.success).toBe(true)+ expect(result.notification.read).toBe(true)+ })++ it('should return error for non-existent notification', async () => {+ const result = await markAsRead('nonexistent')+ expect(result.success).toBe(false)+ expect(result.error).toBe('Notification not found')+ })+ })++ describe('markAllAsRead', () => {+ it('should mark all notifications as read', async () => {+ const result = await markAllAsRead()+ expect(result.success).toBe(true)+ expect(result.updated).toBe(2)+ })++ it('should return 0 updated when all already read', async () => {+ readJSONFile.mockResolvedValue({+ version: 1,+ notifications: [+ { id: 'n1', read: true, type: 'test' },+ { id: 'n2', read: true, type: 'test' }+ ]+ })+ invalidateCache()++ const result = await markAllAsRead()+ expect(result.success).toBe(true)+ expect(result.updated).toBe(0)+ })+ })++ describe('clearAll', () => {+ it('should remove all notifications', async () => {+ const result = await clearAll()+ expect(result.success).toBe(true)+ expect(result.cleared).toBe(3)+ })++ it('should emit cleared and count-changed events', async () => {+ const clearedSpy = vi.fn()+ const countSpy = vi.fn()+ notificationEvents.on('cleared', clearedSpy)+ notificationEvents.on('count-changed', countSpy)++ await clearAll()++ expect(clearedSpy).toHaveBeenCalledOnce()+ expect(countSpy).toHaveBeenCalledWith(0)++ notificationEvents.off('cleared', clearedSpy)+ notificationEvents.off('count-changed', countSpy)+ })+ })++ describe('exists', () => {+ it('should return true when notification of type exists', async () => {+ const result = await exists(NOTIFICATION_TYPES.MEMORY_APPROVAL)+ expect(result).toBe(true)+ })++ it('should return false when notification of type does not exist', async () => {+ const result = await exists(NOTIFICATION_TYPES.PLAN_QUESTION)+ expect(result).toBe(false)+ })++ it('should check metadata field/value when provided', async () => {+ const result = await exists(NOTIFICATION_TYPES.MEMORY_APPROVAL, 'memoryId', 'mem-1')+ expect(result).toBe(true)+ })++ it('should return false when metadata does not match', async () => {+ const result = await exists(NOTIFICATION_TYPES.MEMORY_APPROVAL, 'memoryId', 'mem-999')+ expect(result).toBe(false)+ })+ })++ describe('invalidateCache', () => {+ it('should force reload on next access', async () => {+ await getNotifications()+ expect(readJSONFile).toHaveBeenCalledTimes(1)++ invalidateCache()+ await getNotifications()+ expect(readJSONFile).toHaveBeenCalledTimes(2)+ })+ })+})diff --git a/server/services/search.test.js b/server/services/search.test.jsnew file mode 100644index 0000000000..0136f554eb--- /dev/null+++ b/server/services/search.test.js@@ -0,0 +1,261 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'++// Mock all dependencies+vi.mock('./brainStorage.js', () => ({+ getInboxLog: vi.fn().mockResolvedValue([]),+ getPeople: vi.fn().mockResolvedValue([]),+ getProjects: vi.fn().mockResolvedValue([]),+ getIdeas: vi.fn().mockResolvedValue([]),+ getAdminItems: vi.fn().mockResolvedValue([]),+ getMemoryEntries: vi.fn().mockResolvedValue([]),+ getLinks: vi.fn().mockResolvedValue([])+}))++vi.mock('./memoryBM25.js', () => ({+ searchBM25: vi.fn().mockResolvedValue([])+}))++vi.mock('./memoryBackend.js', () => ({+ getMemories: vi.fn().mockResolvedValue({ memories: [] }),+ ensureBackend: vi.fn().mockResolvedValue('file'),+ hybridSearchMemories: vi.fn().mockResolvedValue({ memories: [] })+}))++vi.mock('./apps.js', () => ({+ getAllApps: vi.fn().mockResolvedValue([])+}))++vi.mock('./history.js', () => ({+ getHistory: vi.fn().mockResolvedValue({ entries: [] })+}))++import { fanOutSearch } from './search.js'+import { getInboxLog, getPeople, getProjects, getIdeas, getAdminItems, getMemoryEntries, getLinks } from './brainStorage.js'+import { searchBM25 } from './memoryBM25.js'+import { getMemories, ensureBackend, hybridSearchMemories } from './memoryBackend.js'+import { getAllApps } from './apps.js'+import { getHistory } from './history.js'++describe('search service', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ ensureBackend.mockResolvedValue('file')+ })++ describe('fanOutSearch', () => {+ it('should return empty array when no sources match', async () => {+ const results = await fanOutSearch('nonexistent')+ expect(results).toEqual([])+ })++ it('should search across brain inbox entries', async () => {+ getInboxLog.mockResolvedValue([+ { id: 'i1', capturedText: 'Hello world from inbox' },+ { id: 'i2', capturedText: 'Another thought' }+ ])++ const results = await fanOutSearch('hello')+ const brainSource = results.find(s => s.id === 'brain')+ expect(brainSource).toBeDefined()+ expect(brainSource.results).toHaveLength(1)+ expect(brainSource.results[0].id).toBe('i1')+ expect(brainSource.results[0].type).toBe('inbox')+ })++ it('should search across people', async () => {+ getPeople.mockResolvedValue([+ { id: 'p1', name: 'John Doe', context: 'Friend from school' },+ { id: 'p2', name: 'Jane Smith', context: 'Colleague at work' }+ ])++ const results = await fanOutSearch('john')+ const brainSource = results.find(s => s.id === 'brain')+ expect(brainSource).toBeDefined()+ const personResult = brainSource.results.find(r => r.id === 'p1')+ expect(personResult).toBeDefined()+ expect(personResult.type).toBe('person')+ expect(personResult.title).toBe('John Doe')+ })++ it('should search across projects', async () => {+ getProjects.mockResolvedValue([+ { id: 'pr1', name: 'PortOS', notes: 'Personal operating system' }+ ])++ const results = await fanOutSearch('portos')+ const brainSource = results.find(s => s.id === 'brain')+ expect(brainSource).toBeDefined()+ const projectResult = brainSource.results.find(r => r.id === 'pr1')+ expect(projectResult).toBeDefined()+ expect(projectResult.type).toBe('project')+ })++ it('should search across ideas', async () => {+ getIdeas.mockResolvedValue([+ { id: 'id1', title: 'AI assistant', oneLiner: 'Build a smart agent', notes: 'Use LLMs' }+ ])++ const results = await fanOutSearch('agent')+ const brainSource = results.find(s => s.id === 'brain')+ expect(brainSource).toBeDefined()+ const ideaResult = brainSource.results.find(r => r.id === 'id1')+ expect(ideaResult).toBeDefined()+ expect(ideaResult.type).toBe('idea')+ })++ it('should search across links', async () => {+ getLinks.mockResolvedValue([+ { id: 'l1', title: 'GitHub', url: 'https://github.com', description: 'Code hosting platform' }+ ])++ const results = await fanOutSearch('github')+ const brainSource = results.find(s => s.id === 'brain')+ expect(brainSource).toBeDefined()+ const linkResult = brainSource.results.find(r => r.id === 'l1')+ expect(linkResult).toBeDefined()+ expect(linkResult.type).toBe('link')+ })++ it('should search apps', async () => {+ getAllApps.mockResolvedValue([+ { id: 'a1', name: 'MortalLoom', description: 'Longevity tracker app' },+ { id: 'a2', name: 'PortOS', description: 'Personal OS' }+ ])++ const results = await fanOutSearch('mortal')+ const appsSource = results.find(s => s.id === 'apps')+ expect(appsSource).toBeDefined()+ expect(appsSource.results).toHaveLength(1)+ expect(appsSource.results[0].id).toBe('a1')+ expect(appsSource.results[0].type).toBe('app')+ })++ it('should search history', async () => {+ getHistory.mockResolvedValue({+ entries: [+ { id: 'h1', targetName: 'deploy', action: 'deployed app to production' },+ { id: 'h2', targetName: 'test', action: 'ran test suite' }+ ]+ })++ const results = await fanOutSearch('deploy')+ const historySource = results.find(s => s.id === 'history')+ expect(historySource).toBeDefined()+ expect(historySource.results).toHaveLength(1)+ expect(historySource.results[0].id).toBe('h1')+ expect(historySource.results[0].type).toBe('history')+ })++ it('should search health metrics', async () => {+ const results = await fanOutSearch('heart')+ const healthSource = results.find(s => s.id === 'health')+ expect(healthSource).toBeDefined()+ expect(healthSource.results.length).toBeGreaterThan(0)+ expect(healthSource.results[0].type).toBe('health-metric')+ })++ it('should match health metrics by display name', async () => {+ const results = await fanOutSearch('steps')+ const healthSource = results.find(s => s.id === 'health')+ expect(healthSource).toBeDefined()+ const stepsResult = healthSource.results.find(r => r.id === 'step_count')+ expect(stepsResult).toBeDefined()+ expect(stepsResult.title).toBe('Steps')+ })++ it('should match health metrics by key name', async () => {+ const results = await fanOutSearch('hrv')+ const healthSource = results.find(s => s.id === 'health')+ expect(healthSource).toBeDefined()+ const hrvResult = healthSource.results.find(r => r.id === 'hrv')+ expect(hrvResult).toBeDefined()+ })++ it('should use BM25 search for file-based memory backend', async () => {+ ensureBackend.mockResolvedValue('file')+ searchBM25.mockResolvedValue([+ { id: 'mem1', score: 1.5 }+ ])+ getMemories.mockResolvedValue({+ memories: [+ { id: 'mem1', summary: 'Test memory about coding' }+ ]+ })++ const results = await fanOutSearch('coding')+ const memorySource = results.find(s => s.id === 'memory')+ expect(memorySource).toBeDefined()+ expect(memorySource.results).toHaveLength(1)+ expect(memorySource.results[0].type).toBe('memory')+ })++ it('should use hybrid search for postgres backend', async () => {+ ensureBackend.mockResolvedValue('postgres')+ hybridSearchMemories.mockResolvedValue({+ memories: [+ { id: 'pgm1', summary: 'Postgres memory result' }+ ]+ })++ const results = await fanOutSearch('postgres')+ const memorySource = results.find(s => s.id === 'memory')+ expect(memorySource).toBeDefined()+ expect(memorySource.results).toHaveLength(1)+ expect(hybridSearchMemories).toHaveBeenCalledWith('postgres', null, { limit: 10 })+ })++ it('should handle failing adapters gracefully', async () => {+ getInboxLog.mockRejectedValue(new Error('DB error'))+ getPeople.mockRejectedValue(new Error('DB error'))+ getProjects.mockRejectedValue(new Error('DB error'))+ getIdeas.mockRejectedValue(new Error('DB error'))+ getAdminItems.mockRejectedValue(new Error('DB error'))+ getMemoryEntries.mockRejectedValue(new Error('DB error'))+ getLinks.mockRejectedValue(new Error('DB error'))+ searchBM25.mockRejectedValue(new Error('Index error'))+ getAllApps.mockRejectedValue(new Error('App error'))+ getHistory.mockRejectedValue(new Error('History error'))++ // Should not throw, should return health results at minimum+ const results = await fanOutSearch('test')+ // Only health (synchronous) should have results, others fall back+ expect(Array.isArray(results)).toBe(true)+ })++ it('should limit brain results to 8', async () => {+ getInboxLog.mockResolvedValue(+ Array.from({ length: 20 }, (_, i) => ({+ id: `inbox-${i}`,+ capturedText: `test entry ${i}`+ }))+ )++ const results = await fanOutSearch('test')+ const brainSource = results.find(s => s.id === 'brain')+ expect(brainSource.results.length).toBeLessThanOrEqual(8)+ })++ it('should only return non-empty sources', async () => {+ // Only apps have results+ getAllApps.mockResolvedValue([+ { id: 'a1', name: 'TestApp', description: 'A test app' }+ ])++ const results = await fanOutSearch('testapp')+ for (const source of results) {+ expect(source.results.length).toBeGreaterThan(0)+ }+ })++ it('should be case-insensitive', async () => {+ getAllApps.mockResolvedValue([+ { id: 'a1', name: 'PortOS', description: 'Personal OS' }+ ])++ const results = await fanOutSearch('PORTOS')+ const appsSource = results.find(s => s.id === 'apps')+ expect(appsSource).toBeDefined()+ expect(appsSource.results).toHaveLength(1)+ })+ })+})diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.jsnew file mode 100644index 0000000000..7b7f57e622--- /dev/null+++ b/server/services/taskSchedule.test.js@@ -0,0 +1,492 @@+import { describe, it, expect, beforeEach, vi } from 'vitest'++vi.mock('./cosEvents.js', () => ({+ cosEvents: { emit: vi.fn() },+ emitLog: vi.fn()+}))++vi.mock('../lib/fileUtils.js', () => ({+ ensureDir: vi.fn().mockResolvedValue(),+ readJSONFile: vi.fn(),+ loadSlashdoFile: vi.fn().mockResolvedValue(''),+ PATHS: { cos: '/mock/data/cos' },+ HOUR: 60 * 60 * 1000,+ DAY: 24 * 60 * 60 * 1000,+ safeDate: (d) => d ? new Date(d).getTime() : 0+}))++vi.mock('fs/promises', () => ({+ writeFile: vi.fn().mockResolvedValue()+}))++vi.mock('fs', () => ({+ existsSync: vi.fn(() => true)+}))++vi.mock('./taskLearning.js', () => ({+ getAdaptiveCooldownMultiplier: vi.fn().mockResolvedValue({+ multiplier: 1.0,+ reason: 'insufficient-data',+ skip: false,+ successRate: null,+ completed: 0+ })+}))++vi.mock('./apps.js', () => ({+ isTaskTypeEnabledForApp: vi.fn().mockResolvedValue(true),+ getAppTaskTypeInterval: vi.fn().mockResolvedValue(null),+ getActiveApps: vi.fn().mockResolvedValue([]),+ getAppTaskTypeOverrides: vi.fn().mockResolvedValue({})+}))++vi.mock('../lib/ports.js', () => ({+ PORTOS_UI_URL: 'http://localhost:5554',+ PORTOS_API_URL: 'http://localhost:5555'+}))++vi.mock('../lib/timezone.js', () => ({+ getUserTimezone: vi.fn().mockResolvedValue('America/Los_Angeles'),+ getLocalParts: vi.fn(() => ({ dayOfWeek: 3 }))+}))++vi.mock('./eventScheduler.js', () => ({+ parseCronToNextRun: vi.fn()+}))++import {+ INTERVAL_TYPES,+ SELF_IMPROVEMENT_TASK_TYPES,+ loadSchedule,+ getTaskInterval,+ updateTaskInterval,+ recordExecution,+ getExecutionHistory,+ shouldRunTask,+ getDueTasks,+ getNextTaskType,+ addTemplateTask,+ getTemplateTasks,+ deleteTemplateTask,+ getDefaultPrompt,+ getTaskPrompt,+ resetExecutionHistory+} from './taskSchedule.js'++import { readJSONFile } from '../lib/fileUtils.js'+import { isTaskTypeEnabledForApp, getAppTaskTypeInterval } from './apps.js'+import { getLocalParts } from '../lib/timezone.js'+import { getAdaptiveCooldownMultiplier } from './taskLearning.js'++const mockSchedule = ({ tasks = {}, executions = {}, templates = [] } = {}) => {+ readJSONFile.mockResolvedValue({ version: 2, tasks, executions, templates })+}++describe('taskSchedule', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ // Default: no saved schedule → use defaults+ readJSONFile.mockResolvedValue(null)+ })++ describe('INTERVAL_TYPES', () => {+ it('should define all expected interval types', () => {+ expect(INTERVAL_TYPES.ROTATION).toBe('rotation')+ expect(INTERVAL_TYPES.DAILY).toBe('daily')+ expect(INTERVAL_TYPES.WEEKLY).toBe('weekly')+ expect(INTERVAL_TYPES.ONCE).toBe('once')+ expect(INTERVAL_TYPES.ON_DEMAND).toBe('on-demand')+ expect(INTERVAL_TYPES.CUSTOM).toBe('custom')+ expect(INTERVAL_TYPES.CRON).toBe('cron')+ })+ })++ describe('SELF_IMPROVEMENT_TASK_TYPES', () => {+ it('should be an array of strings', () => {+ expect(Array.isArray(SELF_IMPROVEMENT_TASK_TYPES)).toBe(true)+ expect(SELF_IMPROVEMENT_TASK_TYPES.length).toBeGreaterThan(0)+ for (const t of SELF_IMPROVEMENT_TASK_TYPES) {+ expect(typeof t).toBe('string')+ }+ })++ it('should include core task types', () => {+ expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('security')+ expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('code-quality')+ expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('test-coverage')+ expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('performance')+ expect(SELF_IMPROVEMENT_TASK_TYPES).toContain('dependency-updates')+ })+ })++ describe('loadSchedule', () => {+ it('should return default schedule when no file exists', async () => {+ readJSONFile.mockResolvedValue(null)+ const schedule = await loadSchedule()+ expect(schedule.version).toBe(2)+ expect(schedule.tasks).toBeDefined()+ expect(schedule.executions).toBeDefined()+ })++ it('should load and return existing v2 schedule', async () => {+ mockSchedule({+ tasks: { 'security': { type: 'weekly', enabled: true, providerId: 'p1', model: 'm1', prompt: null } }+ })++ const schedule = await loadSchedule()+ expect(schedule.version).toBe(2)+ expect(schedule.tasks['security'].enabled).toBe(true)+ expect(schedule.tasks['security'].providerId).toBe('p1')+ })++ it('should merge defaults for missing task types', async () => {+ mockSchedule({+ tasks: { 'security': { type: 'weekly', enabled: true, providerId: null, model: null, prompt: null } }+ })++ const schedule = await loadSchedule()+ // Should have all default task types even though only security was saved+ expect(schedule.tasks['code-quality']).toBeDefined()+ expect(schedule.tasks['test-coverage']).toBeDefined()+ })+ })++ describe('getTaskInterval', () => {+ it('should return interval for known task type', async () => {+ const interval = await getTaskInterval('security')+ expect(interval.type).toBe('weekly')+ })++ it('should return disabled defaults for unknown task type', async () => {+ const interval = await getTaskInterval('unknown-task')+ expect(interval.enabled).toBe(false)+ })+ })++ describe('updateTaskInterval', () => {+ it('should update and persist task interval settings', async () => {+ const result = await updateTaskInterval('security', {+ enabled: true,+ providerId: 'provider-1',+ model: 'claude-3'+ })++ expect(result.enabled).toBe(true)+ expect(result.providerId).toBe('provider-1')+ expect(result.model).toBe('claude-3')+ })++ it('should normalize empty prompt to null', async () => {+ const result = await updateTaskInterval('security', {+ prompt: ' '+ })+ expect(result.prompt).toBeNull()+ })++ it('should set promptCustomized when custom prompt provided', async () => {+ const result = await updateTaskInterval('security', {+ prompt: 'Custom security audit prompt'+ })+ expect(result.promptCustomized).toBe(true)+ })++ it('should clear promptCustomized when prompt set to null', async () => {+ const result = await updateTaskInterval('security', {+ prompt: null+ })+ expect(result.promptCustomized).toBe(false)+ })++ it('should create new task entry for unknown type', async () => {+ const result = await updateTaskInterval('custom-type', {+ type: 'daily',+ enabled: true+ })+ expect(result.type).toBe('daily')+ expect(result.enabled).toBe(true)+ })+ })++ describe('recordExecution', () => {+ it('should record global execution', async () => {+ mockSchedule()+ const result = await recordExecution('test-record-global')+ expect(result.lastRun).toBeDefined()+ expect(result.count).toBe(1)+ })++ it('should record per-app execution', async () => {+ mockSchedule()+ const result = await recordExecution('test-record-app', 'app-1')+ expect(result.perApp['app-1']).toBeDefined()+ expect(result.perApp['app-1'].count).toBe(1)+ expect(result.perApp['app-1'].lastRun).toBeDefined()+ })++ it('should increment count on repeated execution', async () => {+ mockSchedule({+ executions: { 'task:test-incr': { lastRun: '2025-01-01T00:00:00Z', count: 5, perApp: {} } }+ })+ const result = await recordExecution('test-incr')+ expect(result.count).toBe(6)+ })+ })++ describe('getExecutionHistory', () => {+ it('should return empty history for unexecuted task', async () => {+ mockSchedule()+ const history = await getExecutionHistory('never-ran-task')+ expect(history.lastRun).toBeNull()+ expect(history.count).toBe(0)+ expect(history.perApp).toEqual({})+ })++ it('should return existing execution data', async () => {+ mockSchedule({+ executions: { 'task:my-task': { lastRun: '2025-06-01T00:00:00Z', count: 3, perApp: {} } }+ })+ const history = await getExecutionHistory('my-task')+ expect(history.lastRun).toBe('2025-06-01T00:00:00Z')+ expect(history.count).toBe(3)+ })+ })++ describe('shouldRunTask', () => {+ it('should not run disabled task', async () => {+ mockSchedule({+ tasks: { 'disabled-task': { type: 'weekly', enabled: false, providerId: null, model: null, prompt: null } }+ })+ const result = await shouldRunTask('disabled-task')+ expect(result.shouldRun).toBe(false)+ expect(result.reason).toBe('disabled')+ })++ it('should run rotation tasks immediately', async () => {+ readJSONFile.mockResolvedValue({+ version: 2,+ tasks: {+ 'code-quality': { type: 'rotation', enabled: true, providerId: null, model: null, prompt: null }+ },+ executions: {}+ })++ const result = await shouldRunTask('code-quality')+ expect(result.shouldRun).toBe(true)+ expect(result.reason).toBe('rotation')+ })++ it('should not run on-demand tasks automatically', async () => {+ mockSchedule({+ tasks: { 'ui-bugs': { type: 'on-demand', enabled: true, providerId: null, model: null, prompt: null } }+ })++ const result = await shouldRunTask('ui-bugs')+ expect(result.shouldRun).toBe(false)+ expect(result.reason).toBe('on-demand-only')+ })++ it('should run once-type task on first run', async () => {+ mockSchedule({+ tasks: { 'accessibility': { type: 'once', enabled: true, providerId: null, model: null, prompt: null } }+ })++ const result = await shouldRunTask('accessibility')+ expect(result.shouldRun).toBe(true)+ expect(result.reason).toBe('once-first-run')+ })++ it('should not run once-type task after completion', async () => {+ mockSchedule({+ tasks: { 'accessibility': { type: 'once', enabled: true, providerId: null, model: null, prompt: null } },+ executions: { 'task:accessibility': { lastRun: '2025-01-01T00:00:00Z', count: 1, perApp: {} } }+ })++ const result = await shouldRunTask('accessibility')+ expect(result.shouldRun).toBe(false)+ expect(result.reason).toBe('once-completed')+ })++ it('should skip weekday-only tasks on weekends', async () => {+ getLocalParts.mockReturnValue({ dayOfWeek: 0 }) // Sunday++ mockSchedule({+ tasks: { 'pr-reviewer': { type: 'custom', intervalMs: 7200000, enabled: true, weekdaysOnly: true, providerId: null, model: null, prompt: null } }+ })++ const result = await shouldRunTask('pr-reviewer')+ expect(result.shouldRun).toBe(false)+ expect(result.reason).toBe('weekday-only')+ })++ it('should not run when disabled for specific app', async () => {+ isTaskTypeEnabledForApp.mockResolvedValue(false)++ mockSchedule({+ tasks: { 'security': { type: 'weekly', enabled: true, providerId: null, model: null, prompt: null } }+ })++ const result = await shouldRunTask('security', 'app-1')+ expect(result.shouldRun).toBe(false)+ expect(result.reason).toBe('disabled-for-app')+ })++ it('should run daily task when enough time has passed', async () => {+ const twoDaysAgo = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString()++ mockSchedule({+ tasks: { 'feature-ideas': { type: 'daily', enabled: true, providerId: null, model: null, prompt: null } },+ executions: { 'task:feature-ideas': { lastRun: twoDaysAgo, count: 1, perApp: {} } }+ })++ const result = await shouldRunTask('feature-ideas')+ expect(result.shouldRun).toBe(true)+ expect(result.reason).toContain('daily-due')+ })++ it('should not run daily task when in cooldown', async () => {+ const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000).toISOString()++ mockSchedule({+ tasks: { 'feature-ideas': { type: 'daily', enabled: true, providerId: null, model: null, prompt: null } },+ executions: { 'task:feature-ideas': { lastRun: oneHourAgo, count: 5, perApp: {} } }+ })++ const result = await shouldRunTask('feature-ideas')+ expect(result.shouldRun).toBe(false)+ expect(result.reason).toContain('daily-cooldown')+ })+ })++ describe('getDueTasks', () => {+ it('should return empty array when no tasks are enabled', async () => {+ mockSchedule({+ tasks: { 'security': { type: 'weekly', enabled: false, providerId: null, model: null, prompt: null } }+ })+ const due = await getDueTasks()+ expect(due).toEqual([])+ })++ it('should return enabled rotation tasks', async () => {+ mockSchedule({+ tasks: {+ 'code-quality': { type: 'rotation', enabled: true, providerId: null, model: null, prompt: null },+ 'security': { type: 'weekly', enabled: false, providerId: null, model: null, prompt: null }+ }+ })++ const due = await getDueTasks()+ expect(due.length).toBe(1)+ expect(due[0].taskType).toBe('code-quality')+ })+ })++ describe('getNextTaskType', () => {+ it('should return null when no tasks are enabled', async () => {+ mockSchedule({+ tasks: { 'security': { type: 'weekly', enabled: false, providerId: null, model: null, prompt: null } }+ })+ const result = await getNextTaskType()+ expect(result).toBeNull()+ })++ it('should return rotation task', async () => {+ mockSchedule({+ tasks: {+ 'code-quality': { type: 'rotation', enabled: true, providerId: null, model: null, prompt: null },+ 'error-handling': { type: 'rotation', enabled: true, providerId: null, model: null, prompt: null }+ }+ })++ const result = await getNextTaskType()+ expect(result).toBeDefined()+ expect(result.reason).toBe('rotation')+ })++ it('should rotate to next task after last type', async () => {+ mockSchedule({+ tasks: {+ 'code-quality': { type: 'rotation', enabled: true, providerId: null, model: null, prompt: null },+ 'error-handling': { type: 'rotation', enabled: true, providerId: null, model: null, prompt: null }+ }+ })++ const result = await getNextTaskType(null, 'code-quality')+ expect(result.taskType).toBe('error-handling')+ })+ })++ describe('templates', () => {+ it('should add a template task', async () => {+ const template = {+ name: 'Custom audit',+ prompt: 'Run custom audit',+ priority: 'HIGH'+ }++ const result = await addTemplateTask(template)+ expect(result.id).toBeDefined()+ expect(result.name).toBe('Custom audit')+ })++ it('should get template tasks', async () => {+ const templates = await getTemplateTasks()+ expect(Array.isArray(templates)).toBe(true)+ })++ it('should delete template task', async () => {+ const template = await addTemplateTask({ name: 'To delete', prompt: 'test' })+ const result = await deleteTemplateTask(template.id)+ expect(result.success).toBe(true)+ })+ })++ describe('getDefaultPrompt', () => {+ it('should return prompt for known task type', () => {+ const prompt = getDefaultPrompt('security')+ expect(prompt).toBeDefined()+ expect(prompt).toContain('Security')+ })++ it('should return null for unknown task type', () => {+ const prompt = getDefaultPrompt('nonexistent')+ expect(prompt).toBeNull()+ })+ })++ describe('getTaskPrompt', () => {+ it('should return default prompt when no custom prompt set', async () => {+ const prompt = await getTaskPrompt('security')+ expect(prompt).toBeDefined()+ expect(prompt).toContain('Security')+ })++ it('should return fallback prompt for unknown task type', async () => {+ const prompt = await getTaskPrompt('unknown-type')+ expect(prompt).toContain('unknown-type')+ expect(prompt).toContain('{repoPath}')+ })+ })++ describe('resetExecutionHistory', () => {+ it('should reset global execution history', async () => {+ mockSchedule({+ executions: { 'task:reset-test': { lastRun: '2025-01-01T00:00:00Z', count: 5, perApp: {} } }+ })+ const result = await resetExecutionHistory('reset-test')+ expect(result.success).toBe(true)+ })++ it('should reset per-app execution history', async () => {+ mockSchedule({+ executions: {+ 'task:reset-app-test': {+ lastRun: '2025-01-01T00:00:00Z', count: 3,+ perApp: { 'app-1': { lastRun: '2025-01-01T00:00:00Z', count: 2 } }+ }+ }+ })+ const result = await resetExecutionHistory('reset-app-test', 'app-1')+ expect(result.success).toBe(true)+ })+ })+})