File size: 22,212 Bytes
7a1ad33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { beforeEach, describe, it, expect, vi, afterEach } from 'vitest';

vi.unmock('./storage.js');
vi.unmock('./projectRegistry.js');
vi.unmock('./storageMigration.js');

import * as os from 'node:os';
import * as path from 'node:path';
import * as fs from 'node:fs';

vi.mock('fs', async (importOriginal) => {
  const actual = await importOriginal<typeof import('fs')>();
  const mockedRealpath = vi.fn(actual.realpathSync);
  Object.defineProperty(mockedRealpath, 'native', {
    value: (p: fs.PathLike) => mockedRealpath(p),
    writable: true,
  });
  return {
    ...actual,
    mkdirSync: vi.fn(),
    realpathSync: mockedRealpath,
  };
});

import { Storage } from './storage.js';
import { GEMINI_DIR, homedir, resolveToRealPath } from '../utils/paths.js';
import { ProjectRegistry } from './projectRegistry.js';
import { StorageMigration } from './storageMigration.js';

const PROJECT_SLUG = 'project-slug';

vi.mock('./projectRegistry.js');
vi.mock('./storageMigration.js');

describe('Storage – initialize', () => {
  const projectRoot = '/tmp/project';
  let storage: Storage;

  beforeEach(() => {
    ProjectRegistry.prototype.initialize = vi.fn().mockResolvedValue(undefined);
    ProjectRegistry.prototype.getShortId = vi
      .fn()
      .mockReturnValue(PROJECT_SLUG);
    storage = new Storage(projectRoot);
    vi.clearAllMocks();

    // Mock StorageMigration.migrateDirectory
    vi.mocked(StorageMigration.migrateDirectory).mockResolvedValue(undefined);
  });

  it('sets up the registry and performs migration if `getProjectTempDir` is called', async () => {
    await storage.initialize();
    expect(storage.getProjectTempDir()).toBe(
      path.join(os.homedir(), GEMINI_DIR, 'tmp', PROJECT_SLUG),
    );

    // Verify registry initialization
    expect(ProjectRegistry).toHaveBeenCalled();
    expect(vi.mocked(ProjectRegistry).prototype.initialize).toHaveBeenCalled();
    expect(
      vi.mocked(ProjectRegistry).prototype.getShortId,
    ).toHaveBeenCalledWith(projectRoot);

    // Verify migration calls
    // We can't easily get the hash here without repeating logic, but we can verify it's called twice
    expect(StorageMigration.migrateDirectory).toHaveBeenCalledTimes(2);

    // Verify identifier is set by checking a path
    expect(storage.getProjectTempDir()).toContain(PROJECT_SLUG);
  });
});

vi.mock('../utils/paths.js', async (importOriginal) => {
  const actual = await importOriginal<typeof import('../utils/paths.js')>();
  return {
    ...actual,
    homedir: vi.fn(actual.homedir),
  };
});

describe('Storage – getGlobalSettingsPath', () => {
  it('returns path to ~/.gemini/settings.json', () => {
    const expected = path.join(os.homedir(), GEMINI_DIR, 'settings.json');
    expect(Storage.getGlobalSettingsPath()).toBe(expected);
  });
});

describe('Storage - Security', () => {
  it('falls back to tmp for gemini but returns empty for agents if the home directory cannot be determined', () => {
    vi.mocked(homedir).mockReturnValue('');

    // .gemini falls back for backward compatibility
    expect(Storage.getGlobalGeminiDir()).toBe(
      path.join(os.tmpdir(), GEMINI_DIR),
    );

    // .agents returns empty to avoid insecure fallback WITHOUT throwing error
    expect(Storage.getGlobalAgentsDir()).toBe('');

    vi.mocked(homedir).mockReturnValue(os.homedir());
  });
});

describe('Storage – additional helpers', () => {
  const projectRoot = resolveToRealPath(path.resolve('/tmp/project'));
  const storage = new Storage(projectRoot);

  beforeEach(() => {
    ProjectRegistry.prototype.getShortId = vi
      .fn()
      .mockReturnValue(PROJECT_SLUG);
  });

  it('getWorkspaceSettingsPath returns project/.gemini/settings.json', () => {
    const expected = path.join(projectRoot, GEMINI_DIR, 'settings.json');
    expect(storage.getWorkspaceSettingsPath()).toBe(expected);
  });

  it('getUserCommandsDir returns ~/.gemini/commands', () => {
    const expected = path.join(os.homedir(), GEMINI_DIR, 'commands');
    expect(Storage.getUserCommandsDir()).toBe(expected);
  });

  it('getProjectCommandsDir returns project/.gemini/commands', () => {
    const expected = path.join(projectRoot, GEMINI_DIR, 'commands');
    expect(storage.getProjectCommandsDir()).toBe(expected);
  });

  it('getUserSkillsDir returns ~/.gemini/skills', () => {
    const expected = path.join(os.homedir(), GEMINI_DIR, 'skills');
    expect(Storage.getUserSkillsDir()).toBe(expected);
  });

  it('getProjectSkillsDir returns project/.gemini/skills', () => {
    const expected = path.join(projectRoot, GEMINI_DIR, 'skills');
    expect(storage.getProjectSkillsDir()).toBe(expected);
  });

  it('getUserAgentsDir returns ~/.gemini/agents', () => {
    const expected = path.join(os.homedir(), GEMINI_DIR, 'agents');
    expect(Storage.getUserAgentsDir()).toBe(expected);
  });

  it('getProjectAgentsDir returns project/.gemini/agents', () => {
    const expected = path.join(projectRoot, GEMINI_DIR, 'agents');
    expect(storage.getProjectAgentsDir()).toBe(expected);
  });

  it('getProjectMemoryDir returns ~/.gemini/tmp/<identifier>/memory', async () => {
    await storage.initialize();
    const expected = path.join(
      os.homedir(),
      GEMINI_DIR,
      'tmp',
      PROJECT_SLUG,
      'memory',
    );
    expect(storage.getProjectMemoryDir()).toBe(expected);
  });

  it('getMcpOAuthTokensPath returns ~/.gemini/mcp-oauth-tokens.json', () => {
    const expected = path.join(
      os.homedir(),
      GEMINI_DIR,
      'mcp-oauth-tokens.json',
    );
    expect(Storage.getMcpOAuthTokensPath()).toBe(expected);
  });

  it('getGlobalBinDir returns ~/.gemini/tmp/bin', () => {
    const expected = path.join(os.homedir(), GEMINI_DIR, 'tmp', 'bin');
    expect(Storage.getGlobalBinDir()).toBe(expected);
  });

  it('getProjectTempPlansDir returns ~/.gemini/tmp/<identifier>/plans when no sessionId is provided', async () => {
    await storage.initialize();
    const tempDir = storage.getProjectTempDir();
    const expected = path.join(tempDir, 'plans');
    expect(storage.getProjectTempPlansDir()).toBe(expected);
  });

  it('getProjectTempPlansDir returns ~/.gemini/tmp/<identifier>/<sessionId>/plans when sessionId is provided', async () => {
    const sessionId = 'test-session-id';
    const storageWithSession = new Storage(projectRoot, sessionId);
    ProjectRegistry.prototype.getShortId = vi
      .fn()
      .mockReturnValue(PROJECT_SLUG);
    await storageWithSession.initialize();
    const tempDir = storageWithSession.getProjectTempDir();
    const expected = path.join(tempDir, sessionId, 'plans');
    expect(storageWithSession.getProjectTempPlansDir()).toBe(expected);
  });

  it('getProjectTempTrackerDir returns ~/.gemini/tmp/<identifier>/tracker when no sessionId is provided', async () => {
    await storage.initialize();
    const tempDir = storage.getProjectTempDir();
    const expected = path.join(tempDir, 'tracker');
    expect(storage.getProjectTempTrackerDir()).toBe(expected);
  });

  it('getProjectTempTrackerDir returns ~/.gemini/tmp/<identifier>/<sessionId>/tracker when sessionId is provided', async () => {
    const sessionId = 'test-session-id';
    const storageWithSession = new Storage(projectRoot, sessionId);
    ProjectRegistry.prototype.getShortId = vi
      .fn()
      .mockReturnValue(PROJECT_SLUG);
    await storageWithSession.initialize();
    const tempDir = storageWithSession.getProjectTempDir();
    const expected = path.join(tempDir, sessionId, 'tracker');
    expect(storageWithSession.getProjectTempTrackerDir()).toBe(expected);
  });

  it('updates session-scoped directories when the sessionId changes', async () => {
    const storageWithSession = new Storage(projectRoot, 'session-one');
    ProjectRegistry.prototype.getShortId = vi
      .fn()
      .mockReturnValue(PROJECT_SLUG);
    await storageWithSession.initialize();
    const tempDir = storageWithSession.getProjectTempDir();

    storageWithSession.setSessionId('session-two');

    expect(storageWithSession.getProjectTempPlansDir()).toBe(
      path.join(tempDir, 'session-two', 'plans'),
    );
    expect(storageWithSession.getProjectTempTrackerDir()).toBe(
      path.join(tempDir, 'session-two', 'tracker'),
    );
    expect(storageWithSession.getProjectTempTasksDir()).toBe(
      path.join(tempDir, 'session-two', 'tasks'),
    );
  });

  describe('Session and JSON Loading', () => {
    beforeEach(async () => {
      await storage.initialize();
    });

    it('listProjectChatFiles returns sorted sessions from chats directory', async () => {
      const readdirSpy = vi
        .spyOn(fs.promises, 'readdir')
        /* eslint-disable @typescript-eslint/no-explicit-any */
        .mockResolvedValue([
          'session-1.json',
          'session-2.json',
          'not-a-session.txt',
        ] as any);

      const statSpy = vi
        .spyOn(fs.promises, 'stat')
        .mockImplementation(async (p: any) => {
          if (p.toString().endsWith('session-1.json')) {
            return {
              mtime: new Date('2026-02-01'),
              mtimeMs: 1000,
            } as any;
          }
          return {
            mtime: new Date('2026-02-02'),
            mtimeMs: 2000,
          } as any;
        });
      /* eslint-enable @typescript-eslint/no-explicit-any */

      const sessions = await storage.listProjectChatFiles();

      expect(readdirSpy).toHaveBeenCalledWith(expect.stringContaining('chats'));
      expect(sessions).toHaveLength(2);
      // Sorted by mtime desc
      expect(sessions[0].filePath).toBe(path.join('chats', 'session-2.json'));
      expect(sessions[1].filePath).toBe(path.join('chats', 'session-1.json'));
      expect(sessions[0].lastUpdated).toBe(
        new Date('2026-02-02').toISOString(),
      );

      readdirSpy.mockRestore();
      statSpy.mockRestore();
    });

    it('loadProjectTempFile loads and parses JSON from relative path', async () => {
      const readFileSpy = vi
        .spyOn(fs.promises, 'readFile')
        .mockResolvedValue(JSON.stringify({ hello: 'world' }));

      const result = await storage.loadProjectTempFile<{ hello: string }>(
        'some/file.json',
      );

      expect(readFileSpy).toHaveBeenCalledWith(
        expect.stringContaining(path.join(PROJECT_SLUG, 'some/file.json')),
        'utf8',
      );
      expect(result).toEqual({ hello: 'world' });

      readFileSpy.mockRestore();
    });

    it('loadProjectTempFile returns null if file does not exist', async () => {
      const error = new Error('File not found');
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      (error as any).code = 'ENOENT';
      const readFileSpy = vi
        .spyOn(fs.promises, 'readFile')
        .mockRejectedValue(error);

      const result = await storage.loadProjectTempFile('missing.json');

      expect(result).toBeNull();

      readFileSpy.mockRestore();
    });
  });

  describe('getPlansDir', () => {
    interface TestCase {
      name: string;
      customDir: string | undefined;
      expected: string | (() => string);
      expectedError?: string;
      setup?: () => () => void;
    }

    const testCases: TestCase[] = [
      {
        name: 'custom relative path',
        customDir: '.my-plans',
        expected: path.resolve(projectRoot, '.my-plans'),
      },
      {
        name: 'custom absolute path outside throws',
        customDir: path.resolve('/absolute/path/to/plans'),
        expected: '',
        expectedError: `Custom plans directory '${path.resolve('/absolute/path/to/plans')}' resolves to '${path.resolve('/absolute/path/to/plans')}', which is outside the project root '${resolveToRealPath(projectRoot)}'.`,
      },
      {
        name: 'absolute path that happens to be inside project root',
        customDir: path.join(projectRoot, 'internal-plans'),
        expected: path.join(projectRoot, 'internal-plans'),
      },
      {
        name: 'relative path that stays within project root',
        customDir: 'subdir/../plans',
        expected: path.resolve(projectRoot, 'plans'),
      },
      {
        name: 'dot path',
        customDir: '.',
        expected: projectRoot,
      },
      {
        name: 'default behavior when customDir is undefined',
        customDir: undefined,
        expected: () => storage.getProjectTempPlansDir(),
      },
      {
        name: 'escaping relative path throws',
        customDir: '../escaped-plans',
        expected: '',
        expectedError: `Custom plans directory '../escaped-plans' resolves to '${resolveToRealPath(path.resolve(projectRoot, '../escaped-plans'))}', which is outside the project root '${resolveToRealPath(projectRoot)}'.`,
      },
      {
        name: 'hidden directory starting with ..',
        customDir: '..plans',
        expected: path.resolve(projectRoot, '..plans'),
      },
      {
        name: 'security escape via symbolic link throws',
        customDir: 'symlink-to-outside',
        setup: () => {
          vi.mocked(fs.realpathSync).mockImplementation((p: fs.PathLike) => {
            if (p.toString().includes('symlink-to-outside')) {
              return path.resolve('/outside/project/root');
            }
            return p.toString();
          });
          return () => vi.mocked(fs.realpathSync).mockRestore();
        },
        expected: '',
        expectedError: `Custom plans directory 'symlink-to-outside' resolves to '${path.resolve('/outside/project/root')}', which is outside the project root '${resolveToRealPath(projectRoot)}'.`,
      },
    ];

    testCases.forEach(({ name, customDir, expected, expectedError, setup }) => {
      it(`should handle ${name}`, async () => {
        const cleanup = setup?.();
        try {
          if (name.includes('default behavior')) {
            await storage.initialize();
          }

          storage.setCustomPlansDir(customDir);
          if (expectedError) {
            expect(() => storage.getPlansDir()).toThrow(expectedError);
          } else {
            const expectedValue =
              typeof expected === 'function' ? expected() : expected;
            expect(storage.getPlansDir()).toBe(expectedValue);
          }
        } finally {
          cleanup?.();
        }
      });
    });
  });
});

describe('Storage - System Paths', () => {
  const originalEnv = process.env['GEMINI_CLI_SYSTEM_SETTINGS_PATH'];

  afterEach(() => {
    if (originalEnv !== undefined) {
      process.env['GEMINI_CLI_SYSTEM_SETTINGS_PATH'] = originalEnv;
    } else {
      delete process.env['GEMINI_CLI_SYSTEM_SETTINGS_PATH'];
    }
  });

  it('getSystemSettingsPath returns correct path based on platform (default)', () => {
    delete process.env['GEMINI_CLI_SYSTEM_SETTINGS_PATH'];

    const platform = os.platform();
    const result = Storage.getSystemSettingsPath();

    if (platform === 'darwin') {
      expect(result).toBe(
        '/Library/Application Support/GeminiCli/settings.json',
      );
    } else if (platform === 'win32') {
      expect(result).toBe('C:\\ProgramData\\gemini-cli\\settings.json');
    } else {
      expect(result).toBe('/etc/gemini-cli/settings.json');
    }
  });

  it('getSystemSettingsPath follows GEMINI_CLI_SYSTEM_SETTINGS_PATH if set', () => {
    const customPath = '/custom/path/settings.json';
    process.env['GEMINI_CLI_SYSTEM_SETTINGS_PATH'] = customPath;
    expect(Storage.getSystemSettingsPath()).toBe(customPath);
  });

  it('getSystemPoliciesDir returns correct path based on platform and ignores env var', () => {
    process.env['GEMINI_CLI_SYSTEM_SETTINGS_PATH'] =
      '/custom/path/settings.json';
    const platform = os.platform();
    const result = Storage.getSystemPoliciesDir();

    expect(result).not.toContain('/custom/path');

    if (platform === 'darwin') {
      expect(result).toBe('/Library/Application Support/GeminiCli/policies');
    } else if (platform === 'win32') {
      expect(result).toBe('C:\\ProgramData\\gemini-cli\\policies');
    } else {
      expect(result).toBe('/etc/gemini-cli/policies');
    }
  });

  describe('Storage - Runtime Directory Resolution', () => {
    afterEach(() => {
      vi.unstubAllEnvs();
    });

    it('identifies sandbox mode when SANDBOX environment variable is set', () => {
      vi.stubEnv('SANDBOX', '');
      expect(Storage.isSandbox()).toBe(false);

      vi.stubEnv('SANDBOX', 'docker');
      expect(Storage.isSandbox()).toBe(true);
    });

    it('consistently resolves getGlobalRuntimeDir to getGlobalGeminiDir in both normal and sandbox mode', () => {
      vi.stubEnv('SANDBOX', '');
      expect(Storage.getGlobalRuntimeDir()).toBe(Storage.getGlobalGeminiDir());
      expect(Storage.getGoogleAccountsPath()).toBe(
        path.join(Storage.getGlobalGeminiDir(), 'google_accounts.json'),
      );
      expect(Storage.getMcpOAuthTokensPath()).toBe(
        path.join(Storage.getGlobalGeminiDir(), 'mcp-oauth-tokens.json'),
      );
      expect(Storage.getA2AOAuthTokensPath()).toBe(
        path.join(Storage.getGlobalGeminiDir(), 'a2a-oauth-tokens.json'),
      );
      expect(Storage.getTrustedFoldersPath()).toBe(
        path.join(Storage.getGlobalGeminiDir(), 'trustedFolders.json'),
      );
      expect(Storage.getPolicyIntegrityStoragePath()).toBe(
        path.join(Storage.getGlobalGeminiDir(), 'policy_integrity.json'),
      );

      vi.stubEnv('SANDBOX', 'docker');
      expect(Storage.getGlobalRuntimeDir()).toBe(Storage.getGlobalGeminiDir());
      expect(Storage.getGoogleAccountsPath()).toBe(
        path.join(Storage.getGlobalGeminiDir(), 'google_accounts.json'),
      );
      expect(Storage.getMcpOAuthTokensPath()).toBe(
        path.join(Storage.getGlobalGeminiDir(), 'mcp-oauth-tokens.json'),
      );
      expect(Storage.getA2AOAuthTokensPath()).toBe(
        path.join(Storage.getGlobalGeminiDir(), 'a2a-oauth-tokens.json'),
      );
      expect(Storage.getTrustedFoldersPath()).toBe(
        path.join(Storage.getGlobalGeminiDir(), 'trustedFolders.json'),
      );
      expect(Storage.getPolicyIntegrityStoragePath()).toBe(
        path.join(Storage.getGlobalGeminiDir(), 'policy_integrity.json'),
      );
    });

    it('routes getGlobalRuntimeDir to ~/.cache/.gemini under macOS Seatbelt (sandbox-exec)', () => {
      vi.stubEnv('SANDBOX', 'sandbox-exec');

      const expectedDir = path.join(os.homedir(), '.cache', GEMINI_DIR);
      expect(Storage.getGlobalRuntimeDir()).toBe(expectedDir);
      expect(Storage.getGoogleAccountsPath()).toBe(
        path.join(expectedDir, 'google_accounts.json'),
      );
      expect(Storage.getMcpOAuthTokensPath()).toBe(
        path.join(expectedDir, 'mcp-oauth-tokens.json'),
      );
      expect(Storage.getA2AOAuthTokensPath()).toBe(
        path.join(expectedDir, 'a2a-oauth-tokens.json'),
      );
      expect(Storage.getTrustedFoldersPath()).toBe(
        path.join(expectedDir, 'trustedFolders.json'),
      );
      expect(Storage.getPolicyIntegrityStoragePath()).toBe(
        path.join(expectedDir, 'policy_integrity.json'),
      );
    });

    it('falls back to getGlobalGeminiDir under sandbox-exec if homedir is empty', () => {
      vi.stubEnv('SANDBOX', 'sandbox-exec');
      vi.mocked(homedir).mockReturnValue('');

      expect(Storage.getGlobalRuntimeDir()).toBe(Storage.getGlobalGeminiDir());

      vi.mocked(homedir).mockReturnValue(os.homedir());
    });

    it('asynchronously creates runtime directory recursively in ensureGlobalRuntimeDirExists', async () => {
      vi.stubEnv('SANDBOX', 'sandbox-exec');
      const expectedDir = path.join(os.homedir(), '.cache', GEMINI_DIR);
      const mkdirSpy = vi
        .spyOn(fs.promises, 'mkdir')
        .mockResolvedValue(undefined);

      const result = await Storage.ensureGlobalRuntimeDirExists();

      expect(result).toBe(expectedDir);
      expect(mkdirSpy).toHaveBeenCalledWith(expectedDir, {
        recursive: true,
      });
      mkdirSpy.mockRestore();
    });

    it('silently ignores directory creation errors in ensureGlobalRuntimeDirExists', async () => {
      vi.stubEnv('SANDBOX', 'sandbox-exec');
      const expectedDir = path.join(os.homedir(), '.cache', GEMINI_DIR);
      const mkdirSpy = vi
        .spyOn(fs.promises, 'mkdir')
        .mockRejectedValue(new Error('EACCES: permission denied'));

      await expect(Storage.ensureGlobalRuntimeDirExists()).resolves.toBe(
        expectedDir,
      );
      mkdirSpy.mockRestore();
    });

    it('does not perform synchronous filesystem operations in getGlobalRuntimeDir', () => {
      vi.stubEnv('SANDBOX', 'sandbox-exec');
      const expectedDir = path.join(os.homedir(), '.cache', GEMINI_DIR);
      const existsSyncSpy = vi.spyOn(fs, 'existsSync');
      const mkdirSyncSpy = vi.spyOn(fs, 'mkdirSync');

      const result = Storage.getGlobalRuntimeDir();

      expect(result).toBe(expectedDir);
      expect(existsSyncSpy).not.toHaveBeenCalled();
      expect(mkdirSyncSpy).not.toHaveBeenCalled();
      existsSyncSpy.mockRestore();
      mkdirSyncSpy.mockRestore();
    });
  });

  describe('isWorkspaceHomeDir', () => {
    it('returns false when homedir is empty without throwing', () => {
      vi.mocked(homedir).mockReturnValue('');
      const storage = new Storage('/some/workspace');
      expect(storage.isWorkspaceHomeDir()).toBe(false);
      vi.mocked(homedir).mockReturnValue(os.homedir());
    });

    it('returns true when targetDir is the home directory', () => {
      vi.mocked(homedir).mockReturnValue(os.homedir());
      const storage = new Storage(os.homedir());
      expect(storage.isWorkspaceHomeDir()).toBe(true);
    });

    it('returns false when targetDir is not the home directory', () => {
      vi.mocked(homedir).mockReturnValue(os.homedir());
      const storage = new Storage(
        path.join(os.homedir(), 'projects', 'my-project'),
      );
      expect(storage.isWorkspaceHomeDir()).toBe(false);
    });

    it('returns false when targetDir is empty', () => {
      vi.mocked(homedir).mockReturnValue(os.homedir());
      const storage = new Storage('');
      expect(storage.isWorkspaceHomeDir()).toBe(false);
    });
  });
});