import { liveWatcher } from './src/liveWatcher'; import assert from 'assert'; console.log('๐Ÿงช Starting LiveWatcher Unit & RAM Retention Tests...\n'); // 1. Initial State console.log('1. Testing initial state (inactive and empty)...'); assert.strictEqual(liveWatcher.isActive(), false, 'Watcher should initially be inactive'); assert.strictEqual(liveWatcher.getState().bufferCount, 0, 'Buffer should initially be empty'); console.log(' โœ“ Watcher starts inactive with 0 items in RAM.'); // 2. Toggling ON console.log('\n2. Testing toggleWatcher(true)...'); const toggleOnRes = liveWatcher.toggleWatcher(true); assert.strictEqual(toggleOnRes.active, true, 'Watcher active should be true'); assert.strictEqual(liveWatcher.isActive(), true); console.log(' โœ“ Watcher toggled ON.'); // 3. Capturing incoming requests console.log('\n3. Testing request start, chunk accumulation, candidate step, and completion...'); const reqId = 'test-req-001'; liveWatcher.startRequest({ requestId: reqId, method: 'POST', path: '/v1/chat/completions', clientIp: '192.168.1.100', userAgent: 'TestClient/1.0', isStreaming: true, body: { model: 'custom-pipeline', messages: [ { role: 'system', content: 'You are helpful.' }, { role: 'user', content: 'What is 2+2?' } ], temperature: 0.7, max_tokens: 100 } }); let entries = liveWatcher.getEntries(); assert.strictEqual(entries.length, 1, 'Should have 1 entry in RAM'); assert.strictEqual(entries[0].id, reqId); assert.strictEqual(entries[0].status, 'streaming'); assert.strictEqual(entries[0].input.messages.length, 2); // Append stream chunks liveWatcher.appendStreamChunk(reqId, 'The answer '); liveWatcher.appendStreamChunk(reqId, 'is 4.'); assert.strictEqual(entries[0].output.completionText, 'The answer is 4.'); // Record candidate step liveWatcher.recordCandidateStep(reqId, { stepIndex: 1, timestamp: new Date().toISOString(), tierIndex: 0, tierName: 'Main Tier', providerId: 'prov-1', providerName: 'Google AI Studio', providerType: 'gemini', model: 'gemini-1.5-flash', keyIndex: 0, maskedKey: 'AIzaSy...abc', durationMs: 150, status: 'success', statusCode: 200, nextAction: 'Served successfully' }); // Record keepalive liveWatcher.recordKeepAlive(reqId, 'sse_comment'); assert.strictEqual(entries[0].debug.keepAlivePingsCount, 1); // Complete request liveWatcher.completeRequest({ requestId: reqId, statusCode: 200, tokens: { promptTokens: 12, completionTokens: 5, totalTokens: 17 }, finishReason: 'stop' }); assert.strictEqual(entries[0].status, 'completed'); assert.strictEqual(entries[0].output.tokens?.totalTokens, 17); assert.strictEqual(entries[0].output.finishReason, 'stop'); assert.strictEqual(entries[0].debug.stepTraces.length, 1); console.log(' โœ“ Request lifecycle, streaming chunks, tokens, and debug step traces captured in RAM.'); // 4. Filtering and Search console.log('\n4. Testing search and filtering...'); // Add second failed request liveWatcher.startRequest({ requestId: 'test-req-002', method: 'POST', path: '/v1/chat/completions', isStreaming: false, body: { model: 'groq-model', messages: [{ role: 'user', content: 'Say hello in French' }] } }); liveWatcher.failRequest({ requestId: 'test-req-002', statusCode: 503, error: new Error('Upstream timeout') }); const completedOnly = liveWatcher.getEntries({ status: 'completed' }); assert.strictEqual(completedOnly.length, 1); assert.strictEqual(completedOnly[0].id, 'test-req-001'); const failedOnly = liveWatcher.getEntries({ status: 'failed' }); assert.strictEqual(failedOnly.length, 1); assert.strictEqual(failedOnly[0].id, 'test-req-002'); const searchFrench = liveWatcher.getEntries({ search: 'french' }); assert.strictEqual(searchFrench.length, 1); assert.strictEqual(searchFrench[0].id, 'test-req-002'); const searchAnswer = liveWatcher.getEntries({ search: 'answer is 4' }); assert.strictEqual(searchAnswer.length, 1); assert.strictEqual(searchAnswer[0].id, 'test-req-001'); console.log(' โœ“ Status filtering and full-text prompt/response search verified.'); // 5. FIFO Limit of 250 items console.log('\n5. Testing 250 items FIFO cap...'); for (let i = 0; i < 300; i++) { liveWatcher.startRequest({ requestId: `bulk-req-${i}`, method: 'POST', path: '/v1/chat/completions', isStreaming: false, body: { model: 'cap-test', messages: [] } }); } const stateAfterBulk = liveWatcher.getState(); assert.strictEqual(stateAfterBulk.bufferCount, 250, 'Buffer must be capped at maxCapacity 250'); const entriesAfterBulk = liveWatcher.getEntries(); assert.strictEqual(entriesAfterBulk.length, 250); // Newest should be bulk-req-299 assert.strictEqual(entriesAfterBulk[0].id, 'bulk-req-299'); console.log(' โœ“ 250-item FIFO safety cap verified without memory overflow.'); // 6. Toggling OFF flushes all RAM console.log('\n6. Testing toggleWatcher(false) flushes RAM...'); const toggleOffRes = liveWatcher.toggleWatcher(false); assert.strictEqual(toggleOffRes.active, false); assert.strictEqual(toggleOffRes.bufferCount, 0, 'Buffer count must be 0 after toggle off'); assert.strictEqual(liveWatcher.getEntries().length, 0, 'Buffer entries must be empty'); assert.strictEqual(liveWatcher.getState().bufferCount, 0); console.log(' โœ“ Toggling OFF immediately flushes RAM buffer and stops recording.'); // 7. Incoming requests while OFF are ignored console.log('\n7. Testing incoming requests while OFF are not recorded in RAM...'); liveWatcher.startRequest({ requestId: 'ignored-req', method: 'POST', path: '/v1/chat/completions', isStreaming: false, body: { messages: [] } }); assert.strictEqual(liveWatcher.getEntries().length, 0, 'Ignored request should not enter buffer'); console.log(' โœ“ Zero RAM overhead when watcher is OFF.'); console.log('\n๐ŸŽ‰ ALL LIVE WATCHER UNIT TESTS PASSED SUCCESSFULLY!\n');