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
|
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { vi, describe, it, expect, beforeEach, Mocked } from 'vitest';
import * as fsPromises from 'fs/promises';
import * as fsSync from 'fs';
import { Stats, Dirent } from 'fs';
import * as os from 'os';
import * as path from 'path';
import { loadServerHierarchicalMemory } from './memoryDiscovery.js';
import {
GEMINI_CONFIG_DIR,
setGeminiMdFilename,
getCurrentGeminiMdFilename,
DEFAULT_CONTEXT_FILENAME,
} from '../tools/memoryTool.js';
const ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST = DEFAULT_CONTEXT_FILENAME;
// Mock the entire fs/promises module
vi.mock('fs/promises');
// Mock the parts of fsSync we might use (like constants or existsSync if needed)
vi.mock('fs', async (importOriginal) => {
const actual = await importOriginal<typeof fsSync>();
return {
...actual, // Spread actual to get all exports, including Stats and Dirent if they are classes/constructors
constants: { ...actual.constants }, // Preserve constants
};
});
vi.mock('os');
describe('loadServerHierarchicalMemory', () => {
const mockFs = fsPromises as Mocked<typeof fsPromises>;
const mockOs = os as Mocked<typeof os>;
const CWD = '/test/project/src';
const PROJECT_ROOT = '/test/project';
const USER_HOME = '/test/userhome';
let GLOBAL_GEMINI_DIR: string;
let GLOBAL_GEMINI_FILE: string; // Defined in beforeEach
beforeEach(() => {
vi.resetAllMocks();
// Set environment variables to indicate test environment
process.env.NODE_ENV = 'test';
process.env.VITEST = 'true';
setGeminiMdFilename(DEFAULT_CONTEXT_FILENAME); // Use defined const
mockOs.homedir.mockReturnValue(USER_HOME);
// Define these here to use potentially reset/updated values from imports
GLOBAL_GEMINI_DIR = path.join(USER_HOME, GEMINI_CONFIG_DIR);
GLOBAL_GEMINI_FILE = path.join(
GLOBAL_GEMINI_DIR,
getCurrentGeminiMdFilename(), // Use current filename
);
mockFs.stat.mockRejectedValue(new Error('File not found'));
mockFs.readdir.mockResolvedValue([]);
mockFs.readFile.mockRejectedValue(new Error('File not found'));
mockFs.access.mockRejectedValue(new Error('File not found'));
});
it('should return empty memory and count if no context files are found', async () => {
const { memoryContent, fileCount } = await loadServerHierarchicalMemory(
CWD,
false,
);
expect(memoryContent).toBe('');
expect(fileCount).toBe(0);
});
it('should load only the global context file if present and others are not (default filename)', async () => {
const globalDefaultFile = path.join(
GLOBAL_GEMINI_DIR,
DEFAULT_CONTEXT_FILENAME,
);
mockFs.access.mockImplementation(async (p) => {
if (p === globalDefaultFile) {
return undefined;
}
throw new Error('File not found');
});
mockFs.readFile.mockImplementation(async (p) => {
if (p === globalDefaultFile) {
return 'Global memory content';
}
throw new Error('File not found');
});
const { memoryContent, fileCount } = await loadServerHierarchicalMemory(
CWD,
false,
);
expect(memoryContent).toBe(
`--- Context from: ${path.relative(CWD, globalDefaultFile)} ---\nGlobal memory content\n--- End of Context from: ${path.relative(CWD, globalDefaultFile)} ---`,
);
expect(fileCount).toBe(1);
expect(mockFs.readFile).toHaveBeenCalledWith(globalDefaultFile, 'utf-8');
});
it('should load only the global custom context file if present and filename is changed', async () => {
const customFilename = 'CUSTOM_AGENTS.md';
setGeminiMdFilename(customFilename);
const globalCustomFile = path.join(GLOBAL_GEMINI_DIR, customFilename);
mockFs.access.mockImplementation(async (p) => {
if (p === globalCustomFile) {
return undefined;
}
throw new Error('File not found');
});
mockFs.readFile.mockImplementation(async (p) => {
if (p === globalCustomFile) {
return 'Global custom memory';
}
throw new Error('File not found');
});
const { memoryContent, fileCount } = await loadServerHierarchicalMemory(
CWD,
false,
);
expect(memoryContent).toBe(
`--- Context from: ${path.relative(CWD, globalCustomFile)} ---\nGlobal custom memory\n--- End of Context from: ${path.relative(CWD, globalCustomFile)} ---`,
);
expect(fileCount).toBe(1);
expect(mockFs.readFile).toHaveBeenCalledWith(globalCustomFile, 'utf-8');
});
it('should load context files by upward traversal with custom filename', async () => {
const customFilename = 'PROJECT_CONTEXT.md';
setGeminiMdFilename(customFilename);
const projectRootCustomFile = path.join(PROJECT_ROOT, customFilename);
const srcCustomFile = path.join(CWD, customFilename);
mockFs.stat.mockImplementation(async (p) => {
if (p === path.join(PROJECT_ROOT, '.git')) {
return { isDirectory: () => true } as Stats;
}
throw new Error('File not found');
});
mockFs.access.mockImplementation(async (p) => {
if (p === projectRootCustomFile || p === srcCustomFile) {
return undefined;
}
throw new Error('File not found');
});
mockFs.readFile.mockImplementation(async (p) => {
if (p === projectRootCustomFile) {
return 'Project root custom memory';
}
if (p === srcCustomFile) {
return 'Src directory custom memory';
}
throw new Error('File not found');
});
const { memoryContent, fileCount } = await loadServerHierarchicalMemory(
CWD,
false,
);
const expectedContent =
`--- Context from: ${path.relative(CWD, projectRootCustomFile)} ---\nProject root custom memory\n--- End of Context from: ${path.relative(CWD, projectRootCustomFile)} ---\n\n` +
`--- Context from: ${customFilename} ---\nSrc directory custom memory\n--- End of Context from: ${customFilename} ---`;
expect(memoryContent).toBe(expectedContent);
expect(fileCount).toBe(2);
expect(mockFs.readFile).toHaveBeenCalledWith(
projectRootCustomFile,
'utf-8',
);
expect(mockFs.readFile).toHaveBeenCalledWith(srcCustomFile, 'utf-8');
});
it('should load context files by downward traversal with custom filename', async () => {
const customFilename = 'LOCAL_CONTEXT.md';
setGeminiMdFilename(customFilename);
const subDir = path.join(CWD, 'subdir');
const subDirCustomFile = path.join(subDir, customFilename);
const cwdCustomFile = path.join(CWD, customFilename);
mockFs.access.mockImplementation(async (p) => {
if (p === cwdCustomFile || p === subDirCustomFile) return undefined;
throw new Error('File not found');
});
mockFs.readFile.mockImplementation(async (p) => {
if (p === cwdCustomFile) return 'CWD custom memory';
if (p === subDirCustomFile) return 'Subdir custom memory';
throw new Error('File not found');
});
mockFs.readdir.mockImplementation((async (
p: fsSync.PathLike,
): Promise<Dirent[]> => {
if (p === CWD) {
return [
{
name: customFilename,
isFile: () => true,
isDirectory: () => false,
} as Dirent,
{
name: 'subdir',
isFile: () => false,
isDirectory: () => true,
} as Dirent,
] as Dirent[];
}
if (p === subDir) {
return [
{
name: customFilename,
isFile: () => true,
isDirectory: () => false,
} as Dirent,
] as Dirent[];
}
return [] as Dirent[];
}) as unknown as typeof fsPromises.readdir);
const { memoryContent, fileCount } = await loadServerHierarchicalMemory(
CWD,
false,
);
const expectedContent =
`--- Context from: ${customFilename} ---\nCWD custom memory\n--- End of Context from: ${customFilename} ---\n\n` +
`--- Context from: ${path.join('subdir', customFilename)} ---\nSubdir custom memory\n--- End of Context from: ${path.join('subdir', customFilename)} ---`;
expect(memoryContent).toBe(expectedContent);
expect(fileCount).toBe(2);
});
it('should load ORIGINAL_GEMINI_MD_FILENAME files by upward traversal from CWD to project root', async () => {
const projectRootGeminiFile = path.join(
PROJECT_ROOT,
ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST,
);
const srcGeminiFile = path.join(
CWD,
ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST,
);
mockFs.stat.mockImplementation(async (p) => {
if (p === path.join(PROJECT_ROOT, '.git')) {
return { isDirectory: () => true } as Stats;
}
throw new Error('File not found');
});
mockFs.access.mockImplementation(async (p) => {
if (p === projectRootGeminiFile || p === srcGeminiFile) {
return undefined;
}
throw new Error('File not found');
});
mockFs.readFile.mockImplementation(async (p) => {
if (p === projectRootGeminiFile) {
return 'Project root memory';
}
if (p === srcGeminiFile) {
return 'Src directory memory';
}
throw new Error('File not found');
});
const { memoryContent, fileCount } = await loadServerHierarchicalMemory(
CWD,
false,
);
const expectedContent =
`--- Context from: ${path.relative(CWD, projectRootGeminiFile)} ---\nProject root memory\n--- End of Context from: ${path.relative(CWD, projectRootGeminiFile)} ---\n\n` +
`--- Context from: ${ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST} ---\nSrc directory memory\n--- End of Context from: ${ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST} ---`;
expect(memoryContent).toBe(expectedContent);
expect(fileCount).toBe(2);
expect(mockFs.readFile).toHaveBeenCalledWith(
projectRootGeminiFile,
'utf-8',
);
expect(mockFs.readFile).toHaveBeenCalledWith(srcGeminiFile, 'utf-8');
});
it('should load ORIGINAL_GEMINI_MD_FILENAME files by downward traversal from CWD', async () => {
const subDir = path.join(CWD, 'subdir');
const subDirGeminiFile = path.join(
subDir,
ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST,
);
const cwdGeminiFile = path.join(
CWD,
ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST,
);
mockFs.access.mockImplementation(async (p) => {
if (p === cwdGeminiFile || p === subDirGeminiFile) return undefined;
throw new Error('File not found');
});
mockFs.readFile.mockImplementation(async (p) => {
if (p === cwdGeminiFile) return 'CWD memory';
if (p === subDirGeminiFile) return 'Subdir memory';
throw new Error('File not found');
});
mockFs.readdir.mockImplementation((async (
p: fsSync.PathLike,
): Promise<Dirent[]> => {
if (p === CWD) {
return [
{
name: ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST,
isFile: () => true,
isDirectory: () => false,
} as Dirent,
{
name: 'subdir',
isFile: () => false,
isDirectory: () => true,
} as Dirent,
] as Dirent[];
}
if (p === subDir) {
return [
{
name: ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST,
isFile: () => true,
isDirectory: () => false,
} as Dirent,
] as Dirent[];
}
return [] as Dirent[];
}) as unknown as typeof fsPromises.readdir);
const { memoryContent, fileCount } = await loadServerHierarchicalMemory(
CWD,
false,
);
const expectedContent =
`--- Context from: ${ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST} ---\nCWD memory\n--- End of Context from: ${ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST} ---\n\n` +
`--- Context from: ${path.join('subdir', ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST)} ---\nSubdir memory\n--- End of Context from: ${path.join('subdir', ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST)} ---`;
expect(memoryContent).toBe(expectedContent);
expect(fileCount).toBe(2);
});
it('should load and correctly order global, upward, and downward ORIGINAL_GEMINI_MD_FILENAME files', async () => {
setGeminiMdFilename(ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST); // Explicitly set for this test
const globalFileToUse = path.join(
GLOBAL_GEMINI_DIR,
ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST,
);
const projectParentDir = path.dirname(PROJECT_ROOT);
const projectParentGeminiFile = path.join(
projectParentDir,
ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST,
);
const projectRootGeminiFile = path.join(
PROJECT_ROOT,
ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST,
);
const cwdGeminiFile = path.join(
CWD,
ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST,
);
const subDir = path.join(CWD, 'sub');
const subDirGeminiFile = path.join(
subDir,
ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST,
);
mockFs.stat.mockImplementation(async (p) => {
if (p === path.join(PROJECT_ROOT, '.git')) {
return { isDirectory: () => true } as Stats;
} else if (p === path.join(PROJECT_ROOT, '.gemini')) {
return { isDirectory: () => true } as Stats;
}
throw new Error('File not found');
});
mockFs.access.mockImplementation(async (p) => {
if (
p === globalFileToUse || // Use the dynamically set global file path
p === projectParentGeminiFile ||
p === projectRootGeminiFile ||
p === cwdGeminiFile ||
p === subDirGeminiFile
) {
return undefined;
}
throw new Error('File not found');
});
mockFs.readFile.mockImplementation(async (p) => {
if (p === globalFileToUse) return 'Global memory'; // Use the dynamically set global file path
if (p === projectParentGeminiFile) return 'Project parent memory';
if (p === projectRootGeminiFile) return 'Project root memory';
if (p === cwdGeminiFile) return 'CWD memory';
if (p === subDirGeminiFile) return 'Subdir memory';
throw new Error('File not found');
});
mockFs.readdir.mockImplementation((async (
p: fsSync.PathLike,
): Promise<Dirent[]> => {
if (p === CWD) {
return [
{
name: 'sub',
isFile: () => false,
isDirectory: () => true,
} as Dirent,
] as Dirent[];
}
if (p === subDir) {
return [
{
name: ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST,
isFile: () => true,
isDirectory: () => false,
} as Dirent,
] as Dirent[];
}
return [] as Dirent[];
}) as unknown as typeof fsPromises.readdir);
const { memoryContent, fileCount } = await loadServerHierarchicalMemory(
CWD,
false,
);
const relPathGlobal = path.relative(CWD, GLOBAL_GEMINI_FILE);
const relPathProjectParent = path.relative(CWD, projectParentGeminiFile);
const relPathProjectRoot = path.relative(CWD, projectRootGeminiFile);
const relPathCwd = ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST;
const relPathSubDir = path.join(
'sub',
ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST,
);
const expectedContent = [
`--- Context from: ${relPathGlobal} ---\nGlobal memory\n--- End of Context from: ${relPathGlobal} ---`,
`--- Context from: ${relPathProjectParent} ---\nProject parent memory\n--- End of Context from: ${relPathProjectParent} ---`,
`--- Context from: ${relPathProjectRoot} ---\nProject root memory\n--- End of Context from: ${relPathProjectRoot} ---`,
`--- Context from: ${relPathCwd} ---\nCWD memory\n--- End of Context from: ${relPathCwd} ---`,
`--- Context from: ${relPathSubDir} ---\nSubdir memory\n--- End of Context from: ${relPathSubDir} ---`,
].join('\n\n');
expect(memoryContent).toBe(expectedContent);
expect(fileCount).toBe(5);
});
it('should ignore specified directories during downward scan', async () => {
const ignoredDir = path.join(CWD, 'node_modules');
const ignoredDirGeminiFile = path.join(
ignoredDir,
ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST,
); // Corrected
const regularSubDir = path.join(CWD, 'my_code');
const regularSubDirGeminiFile = path.join(
regularSubDir,
ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST,
);
mockFs.access.mockImplementation(async (p) => {
if (p === regularSubDirGeminiFile) return undefined;
if (p === ignoredDirGeminiFile)
throw new Error('Should not access ignored file');
throw new Error('File not found');
});
mockFs.readFile.mockImplementation(async (p) => {
if (p === regularSubDirGeminiFile) return 'My code memory';
throw new Error('File not found');
});
mockFs.readdir.mockImplementation((async (
p: fsSync.PathLike,
): Promise<Dirent[]> => {
if (p === CWD) {
return [
{
name: 'node_modules',
isFile: () => false,
isDirectory: () => true,
} as Dirent,
{
name: 'my_code',
isFile: () => false,
isDirectory: () => true,
} as Dirent,
] as Dirent[];
}
if (p === regularSubDir) {
return [
{
name: ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST,
isFile: () => true,
isDirectory: () => false,
} as Dirent,
] as Dirent[];
}
if (p === ignoredDir) {
return [
{
name: ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST,
isFile: () => true,
isDirectory: () => false,
} as Dirent,
] as Dirent[];
}
return [] as Dirent[];
}) as unknown as typeof fsPromises.readdir);
const { memoryContent, fileCount } = await loadServerHierarchicalMemory(
CWD,
false,
);
const expectedContent = `--- Context from: ${path.join('my_code', ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST)} ---\nMy code memory\n--- End of Context from: ${path.join('my_code', ORIGINAL_GEMINI_MD_FILENAME_CONST_FOR_TEST)} ---`;
expect(memoryContent).toBe(expectedContent);
expect(fileCount).toBe(1);
expect(mockFs.readFile).not.toHaveBeenCalledWith(
ignoredDirGeminiFile,
'utf-8',
);
});
it('should respect MAX_DIRECTORIES_TO_SCAN_FOR_MEMORY during downward scan', async () => {
const consoleDebugSpy = vi
.spyOn(console, 'debug')
.mockImplementation(() => {});
const dirNames: Dirent[] = [];
for (let i = 0; i < 250; i++) {
dirNames.push({
name: `deep_dir_${i}`,
isFile: () => false,
isDirectory: () => true,
} as Dirent);
}
mockFs.readdir.mockImplementation((async (
p: fsSync.PathLike,
): Promise<Dirent[]> => {
if (p === CWD) return dirNames;
if (p.toString().startsWith(path.join(CWD, 'deep_dir_')))
return [] as Dirent[];
return [] as Dirent[];
}) as unknown as typeof fsPromises.readdir);
mockFs.access.mockRejectedValue(new Error('not found'));
await loadServerHierarchicalMemory(CWD, true);
expect(consoleDebugSpy).toHaveBeenCalledWith(
expect.stringContaining('[DEBUG] [MemoryDiscovery]'),
expect.stringContaining(
'Max directory scan limit (200) reached. Stopping downward scan at:',
),
);
consoleDebugSpy.mockRestore();
});
});
|