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85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { StartupProfiler } from './startupProfiler.js';
import type { Config } from '../config/config.js';
import { debugLogger } from '../utils/debugLogger.js';

// Mock the metrics module
vi.mock('./metrics.js', () => ({
  recordStartupPerformance: vi.fn(),
}));

// Mock loggers module
vi.mock('./loggers.js', () => ({
  logStartupStats: vi.fn(),
}));

// Mock os module
vi.mock('node:os', () => ({
  platform: vi.fn(() => 'darwin'),
  arch: vi.fn(() => 'x64'),
  release: vi.fn(() => '22.6.0'),
}));

// Mock fs module
vi.mock('node:fs', () => ({
  existsSync: vi.fn(() => false),
  createWriteStream: vi.fn(() => ({
    write: vi.fn(),
    on: vi.fn(),
  })),
}));

describe('StartupProfiler', () => {
  let profiler: StartupProfiler;
  let mockConfig: Config;
  let recordStartupPerformance: ReturnType<typeof vi.fn>;
  let logStartupStats: ReturnType<typeof vi.fn>;

  beforeEach(async () => {
    vi.resetAllMocks();

    // Get the mocked function
    const metricsModule = await import('./metrics.js');
    recordStartupPerformance =
      metricsModule.recordStartupPerformance as ReturnType<typeof vi.fn>;

    const loggersModule = await import('./loggers.js');
    logStartupStats = loggersModule.logStartupStats as ReturnType<typeof vi.fn>;

    // Create a fresh profiler instance
    profiler = StartupProfiler.getInstance();

    // Clear any existing phases and performance entries
    profiler['phases'].clear();
    performance.clearMarks();
    performance.clearMeasures();

    mockConfig = {
      getSessionId: () => 'test-session-id',
      getTelemetryEnabled: () => true,
    } as unknown as Config;
  });

  afterEach(() => {
    vi.restoreAllMocks();
  });

  describe('getInstance', () => {
    it('should return a singleton instance', () => {
      const instance1 = StartupProfiler.getInstance();
      const instance2 = StartupProfiler.getInstance();
      expect(instance1).toBe(instance2);
    });
  });

  describe('start', () => {
    it('should create a performance mark for a phase', () => {
      profiler.start('test_phase');

      const phase = profiler['phases'].get('test_phase');
      expect(phase).toBeDefined();
      expect(phase?.name).toBe('test_phase');

      // Verify performance mark was created
      const marks = performance.getEntriesByType('mark');
      const startMark = marks.find(
        (m) => m.name === 'startup:test_phase:start',
      );
      expect(startMark).toBeDefined();
    });

    it('should record start time with details', () => {
      const details = { key: 'value', count: 42 };
      profiler.start('test_phase', details);

      const phase = profiler['phases'].get('test_phase');
      expect(phase?.details).toEqual(details);
    });

    it('should return undefined when starting a phase that is already active', () => {
      profiler.start('test_phase');
      const handle = profiler.start('test_phase');
      expect(handle).toBeUndefined();
    });
  });

  describe('end', () => {
    it('should create a performance measure for a started phase', () => {
      const handle = profiler.start('test_phase');
      handle?.end();

      // Verify performance measure was created
      const measures = performance.getEntriesByType('measure');
      const measure = measures.find((m) => m.name === 'test_phase');
      expect(measure).toBeDefined();
      expect(measure?.duration).toBeGreaterThan(0);
    });

    it('should merge details when ending a phase', () => {
      const handle = profiler.start('test_phase', { initial: 'value' });
      handle?.end({ additional: 'data' });

      const phase = profiler['phases'].get('test_phase');
      expect(phase?.details).toEqual({
        initial: 'value',
        additional: 'data',
      });
    });

    it('should overwrite details with same key', () => {
      const handle = profiler.start('test_phase', { key: 'original' });
      handle?.end({ key: 'updated' });

      const phase = profiler['phases'].get('test_phase');
      expect(phase?.details).toEqual({ key: 'updated' });
    });
  });

  describe('flush', () => {
    it('should call recordStartupPerformance for each completed phase', () => {
      const handle1 = profiler.start('phase1');
      handle1?.end();

      const handle2 = profiler.start('phase2');
      handle2?.end();

      profiler.flush(mockConfig);

      expect(recordStartupPerformance).toHaveBeenCalledTimes(2);
    });

    it('should not record phases without duration', () => {
      profiler.start('incomplete_phase');
      profiler.flush(mockConfig);

      expect(recordStartupPerformance).not.toHaveBeenCalled();
    });

    it('should include common details in all metrics', () => {
      const handle = profiler.start('test_phase');
      handle?.end();

      profiler.flush(mockConfig);

      expect(recordStartupPerformance).toHaveBeenCalledWith(
        mockConfig,
        expect.any(Number),
        expect.objectContaining({
          phase: 'test_phase',
          details: expect.objectContaining({
            os_platform: 'darwin',
            os_arch: 'x64',
            os_release: '22.6.0',
            is_docker: false,
            cpu_usage_user: expect.any(Number),
            cpu_usage_system: expect.any(Number),
          }),
        }),
      );
    });

    it('should merge phase-specific details with common details', () => {
      const handle = profiler.start('test_phase', { custom: 'value' });
      handle?.end();

      profiler.flush(mockConfig);

      expect(recordStartupPerformance).toHaveBeenCalledWith(
        mockConfig,
        expect.any(Number),
        expect.objectContaining({
          phase: 'test_phase',
          details: expect.objectContaining({
            custom: 'value',
            os_platform: 'darwin',
          }),
        }),
      );
    });

    it('should clear phases after flushing', () => {
      const handle = profiler.start('test_phase');
      handle?.end();

      profiler.flush(mockConfig);

      expect(profiler['phases'].size).toBe(0);
    });

    it('should detect Docker environment', async () => {
      const fs = await import('node:fs');
      (fs.existsSync as ReturnType<typeof vi.fn>).mockReturnValue(true);

      const handle = profiler.start('test_phase');
      handle?.end();

      profiler.flush(mockConfig);

      expect(recordStartupPerformance).toHaveBeenCalledWith(
        mockConfig,
        expect.any(Number),
        expect.objectContaining({
          details: expect.objectContaining({
            is_docker: true,
          }),
        }),
      );
    });

    it('should calculate CPU usage correctly', () => {
      const cpuUsageSpy = vi.spyOn(process, 'cpuUsage');
      // Mock start usage
      cpuUsageSpy.mockReturnValueOnce({ user: 1000, system: 500 });
      // Mock diff usage (this is what process.cpuUsage(startUsage) returns)
      cpuUsageSpy.mockReturnValueOnce({ user: 100, system: 50 });

      const handle = profiler.start('cpu_test_phase');
      handle?.end();

      profiler.flush(mockConfig);

      expect(recordStartupPerformance).toHaveBeenCalledWith(
        mockConfig,
        expect.any(Number),
        expect.objectContaining({
          phase: 'cpu_test_phase',
          details: expect.objectContaining({
            cpu_usage_user: 100,
            cpu_usage_system: 50,
          }),
        }),
      );
    });

    it('should use debug logging instead of standard logging', () => {
      const logSpy = vi.spyOn(debugLogger, 'log');
      const debugSpy = vi.spyOn(debugLogger, 'debug');

      const handle = profiler.start('test_phase');
      handle?.end();

      profiler.flush(mockConfig);

      expect(logSpy).not.toHaveBeenCalled();
      expect(debugSpy).toHaveBeenCalled();
    });
  });

  describe('integration scenarios', () => {
    it('should handle a complete startup profiling workflow', () => {
      // Simulate startup sequence
      const totalHandle = profiler.start('total_startup');

      const settingsHandle = profiler.start('load_settings');
      settingsHandle?.end();

      const argsHandle = profiler.start('parse_arguments');
      argsHandle?.end();

      const appHandle = profiler.start('initialize_app');
      appHandle?.end();

      totalHandle?.end();

      profiler.flush(mockConfig);

      expect(recordStartupPerformance).toHaveBeenCalledTimes(4);
      expect(recordStartupPerformance).toHaveBeenCalledWith(
        mockConfig,
        expect.any(Number),
        expect.objectContaining({ phase: 'total_startup' }),
      );
    });

    it('should handle nested timing correctly', () => {
      const outerHandle = profiler.start('outer');
      const innerHandle = profiler.start('inner');
      innerHandle?.end();
      outerHandle?.end();

      profiler.flush(mockConfig);

      const calls = recordStartupPerformance.mock.calls;
      const outerCall = calls.find((call) => call[2].phase === 'outer');
      const innerCall = calls.find((call) => call[2].phase === 'inner');

      expect(outerCall).toBeDefined();
      expect(innerCall).toBeDefined();
      // Outer duration should be >= inner duration
      expect(outerCall![1]).toBeGreaterThanOrEqual(innerCall![1]);
    });
  });

  describe('sanity checking', () => {
    it('should return undefined when starting a phase that is already active', () => {
      profiler.start('test_phase');
      const handle = profiler.start('test_phase');
      expect(handle).toBeUndefined();
    });

    it('should allow restarting a phase after it has ended', () => {
      const handle1 = profiler.start('test_phase');
      handle1?.end();

      // Should not throw
      expect(() => profiler.start('test_phase')).not.toThrow();
    });

    it('should not throw error when ending a phase that is already ended', () => {
      const handle = profiler.start('test_phase');
      handle?.end();

      // Calling end() again on the same handle should not throw
      expect(() => handle?.end()).not.toThrow();
    });

    it('should not record metrics for incomplete phases', () => {
      profiler.start('incomplete_phase');
      // Never call end()

      profiler.flush(mockConfig);

      expect(recordStartupPerformance).not.toHaveBeenCalled();
    });

    it('should handle mix of complete and incomplete phases', () => {
      const completeHandle = profiler.start('complete_phase');
      completeHandle?.end();

      profiler.start('incomplete_phase');
      // Never call end()

      profiler.flush(mockConfig);

      // Should only record the complete phase
      expect(recordStartupPerformance).toHaveBeenCalledTimes(1);
      expect(recordStartupPerformance).toHaveBeenCalledWith(
        mockConfig,
        expect.any(Number),
        expect.objectContaining({ phase: 'complete_phase' }),
      );
    });
    it('should log startup stats event', () => {
      const handle = profiler.start('test_phase');
      handle?.end();

      profiler.flush(mockConfig);

      expect(logStartupStats).toHaveBeenCalledWith(
        mockConfig,
        expect.objectContaining({
          phases: expect.arrayContaining([
            expect.objectContaining({
              name: 'test_phase',
              duration_ms: expect.any(Number),
              start_time_usec: expect.any(Number),
              end_time_usec: expect.any(Number),
            }),
          ]),
          os_platform: 'darwin',
          os_release: '22.6.0',
          is_docker: false,
        }),
      );
    });

    it('should log startup stats timestamps as rounded integers', () => {
      const handle = profiler.start('test_phase');
      handle?.end();

      profiler.flush(mockConfig);

      const statsEvent = logStartupStats.mock.calls[0][1];
      const phase = statsEvent.phases[0];

      // Verify they are integers
      expect(Number.isInteger(phase.start_time_usec)).toBe(true);
      expect(Number.isInteger(phase.end_time_usec)).toBe(true);
    });

    it('should log startup stats duration as rounded integers', () => {
      const handle = profiler.start('test_phase');
      handle?.end();

      profiler.flush(mockConfig);

      const statsEvent = logStartupStats.mock.calls[0][1];
      const phase = statsEvent.phases[0];

      // Verify they are integers
      expect(Number.isInteger(phase.duration_ms)).toBe(true);
    });
  });
});