-
Notifications
You must be signed in to change notification settings - Fork 13.4k
Expand file tree
/
Copy pathmemoryDiscovery.test.ts
More file actions
1554 lines (1353 loc) · 49.2 KB
/
memoryDiscovery.test.ts
File metadata and controls
1554 lines (1353 loc) · 49.2 KB
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
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
import * as fsPromises from 'node:fs/promises';
import * as os from 'node:os';
import * as path from 'node:path';
import {
loadServerHierarchicalMemory,
getGlobalMemoryPaths,
getExtensionMemoryPaths,
getEnvironmentMemoryPaths,
loadJitSubdirectoryMemory,
refreshServerHierarchicalMemory,
readGeminiMdFiles,
} from './memoryDiscovery.js';
import {
setGeminiMdFilename,
DEFAULT_CONTEXT_FILENAME,
} from '../tools/memoryTool.js';
import { flattenMemory, type HierarchicalMemory } from '../config/memory.js';
import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
import { GEMINI_DIR, normalizePath, homedir as pathsHomedir } from './paths.js';
function flattenResult(result: {
memoryContent: HierarchicalMemory;
fileCount: number;
filePaths: string[];
}) {
return {
...result,
memoryContent: flattenMemory(result.memoryContent),
filePaths: result.filePaths.map((p) => normalizePath(p)),
};
}
import { Config, type GeminiCLIExtension } from '../config/config.js';
import { Storage } from '../config/storage.js';
import { SimpleExtensionLoader } from './extensionLoader.js';
import { CoreEvent, coreEvents } from './events.js';
vi.mock('os', async (importOriginal) => {
const actualOs = await importOriginal<typeof os>();
return {
...actualOs,
homedir: vi.fn(),
};
});
vi.mock('../utils/paths.js', async (importOriginal) => {
const actual = await importOriginal<typeof import('../utils/paths.js')>();
return {
...actual,
normalizePath: (p: string) => {
const resolved = path.resolve(p);
return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
},
homedir: vi.fn(),
};
});
describe('memoryDiscovery', () => {
const DEFAULT_FOLDER_TRUST = true;
let testRootDir: string;
let cwd: string;
let projectRoot: string;
let homedir: string;
async function createEmptyDir(fullPath: string) {
await fsPromises.mkdir(fullPath, { recursive: true });
return normalizePath(fullPath);
}
async function createTestFile(fullPath: string, fileContents: string) {
await fsPromises.mkdir(path.dirname(fullPath), { recursive: true });
await fsPromises.writeFile(fullPath, fileContents);
return normalizePath(path.resolve(testRootDir, fullPath));
}
beforeEach(async () => {
testRootDir = normalizePath(
await fsPromises.mkdtemp(
path.join(os.tmpdir(), 'folder-structure-test-'),
),
);
vi.resetAllMocks();
// Set environment variables to indicate test environment
vi.stubEnv('NODE_ENV', 'test');
vi.stubEnv('VITEST', 'true');
projectRoot = await createEmptyDir(path.join(testRootDir, 'project'));
cwd = await createEmptyDir(path.join(projectRoot, 'src'));
homedir = await createEmptyDir(path.join(testRootDir, 'userhome'));
vi.mocked(os.homedir).mockReturnValue(homedir);
vi.mocked(pathsHomedir).mockReturnValue(homedir);
});
const normMarker = (p: string) =>
process.platform === 'win32' ? p.toLowerCase() : p;
afterEach(async () => {
vi.unstubAllEnvs();
// Some tests set this to a different value.
setGeminiMdFilename(DEFAULT_CONTEXT_FILENAME);
// Clean up the temporary directory to prevent resource leaks.
// Use maxRetries option for robust cleanup without race conditions
await fsPromises.rm(testRootDir, {
recursive: true,
force: true,
maxRetries: 3,
retryDelay: 10,
});
});
describe('when untrusted', () => {
it('does not load context files from untrusted workspaces', async () => {
await createTestFile(
path.join(projectRoot, DEFAULT_CONTEXT_FILENAME),
'Project root memory',
);
await createTestFile(
path.join(cwd, DEFAULT_CONTEXT_FILENAME),
'Src directory memory',
);
const result = flattenResult(
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
false, // untrusted
),
);
expect(result).toEqual({
memoryContent: '',
fileCount: 0,
filePaths: [],
});
});
it('loads context from outside the untrusted workspace', async () => {
await createTestFile(
path.join(projectRoot, DEFAULT_CONTEXT_FILENAME),
'Project root memory', // Untrusted
);
await createTestFile(
path.join(cwd, DEFAULT_CONTEXT_FILENAME),
'Src directory memory', // Untrusted
);
const filepathInput = path.join(
homedir,
GEMINI_DIR,
DEFAULT_CONTEXT_FILENAME,
);
const filepath = await createTestFile(
filepathInput,
'default context content',
); // In user home dir (outside untrusted space).
const { fileCount, memoryContent, filePaths } = flattenResult(
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
false, // untrusted
),
);
expect(fileCount).toEqual(1);
expect(memoryContent).toContain(filepath);
expect(filePaths).toEqual([filepath]);
});
});
it('should return empty memory and count if no context files are found', async () => {
const result = flattenResult(
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
),
);
expect(result).toEqual({
memoryContent: '',
fileCount: 0,
filePaths: [],
});
});
it('should load only the global context file if present and others are not (default filename)', async () => {
const defaultContextFile = await createTestFile(
path.join(homedir, GEMINI_DIR, DEFAULT_CONTEXT_FILENAME),
'default context content',
);
const result = flattenResult(
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
),
);
expect({
...result,
memoryContent: flattenMemory(result.memoryContent),
}).toEqual({
memoryContent: `--- Global ---
--- Context from: ${defaultContextFile} ---
default context content
--- End of Context from: ${defaultContextFile} ---`,
fileCount: 1,
filePaths: [defaultContextFile],
});
});
it('should load only the global custom context file if present and filename is changed', async () => {
const customFilename = 'CUSTOM_AGENTS.md';
setGeminiMdFilename(customFilename);
const customContextFile = await createTestFile(
path.join(homedir, GEMINI_DIR, customFilename),
'custom context content',
);
const result = flattenResult(
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
),
);
expect(result).toEqual({
memoryContent: `--- Global ---
--- Context from: ${customContextFile} ---
custom context content
--- End of Context from: ${customContextFile} ---`,
fileCount: 1,
filePaths: [customContextFile],
});
});
it('should load context files by upward traversal with custom filename', async () => {
const customFilename = 'PROJECT_CONTEXT.md';
setGeminiMdFilename(customFilename);
const projectContextFile = await createTestFile(
path.join(projectRoot, customFilename),
'project context content',
);
const cwdContextFile = await createTestFile(
path.join(cwd, customFilename),
'cwd context content',
);
const result = flattenResult(
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
),
);
expect(result).toEqual({
memoryContent: `--- Project ---
--- Context from: ${projectContextFile} ---
project context content
--- End of Context from: ${projectContextFile} ---
--- Context from: ${cwdContextFile} ---
cwd context content
--- End of Context from: ${cwdContextFile} ---`,
fileCount: 2,
filePaths: [projectContextFile, cwdContextFile],
});
});
it('should load context files by downward traversal with custom filename', async () => {
const customFilename = 'LOCAL_CONTEXT.md';
setGeminiMdFilename(customFilename);
const subdirCustomFile = await createTestFile(
path.join(cwd, 'subdir', customFilename),
'Subdir custom memory',
);
const cwdCustomFile = await createTestFile(
path.join(cwd, customFilename),
'CWD custom memory',
);
const result = flattenResult(
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
),
);
expect(result).toEqual({
memoryContent: `--- Project ---
--- Context from: ${cwdCustomFile} ---
CWD custom memory
--- End of Context from: ${cwdCustomFile} ---
--- Context from: ${subdirCustomFile} ---
Subdir custom memory
--- End of Context from: ${subdirCustomFile} ---`,
fileCount: 2,
filePaths: [cwdCustomFile, subdirCustomFile],
});
});
it('should load ORIGINAL_GEMINI_MD_FILENAME files by upward traversal from CWD to project root', async () => {
const projectRootGeminiFile = await createTestFile(
path.join(projectRoot, DEFAULT_CONTEXT_FILENAME),
'Project root memory',
);
const srcGeminiFile = await createTestFile(
path.join(cwd, DEFAULT_CONTEXT_FILENAME),
'Src directory memory',
);
const result = flattenResult(
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
),
);
expect(result).toEqual({
memoryContent: `--- Project ---
--- Context from: ${projectRootGeminiFile} ---
Project root memory
--- End of Context from: ${projectRootGeminiFile} ---
--- Context from: ${srcGeminiFile} ---
Src directory memory
--- End of Context from: ${srcGeminiFile} ---`,
fileCount: 2,
filePaths: [projectRootGeminiFile, srcGeminiFile],
});
});
it('should load ORIGINAL_GEMINI_MD_FILENAME files by downward traversal from CWD', async () => {
const subDirGeminiFile = await createTestFile(
path.join(cwd, 'subdir', DEFAULT_CONTEXT_FILENAME),
'Subdir memory',
);
const cwdGeminiFile = await createTestFile(
path.join(cwd, DEFAULT_CONTEXT_FILENAME),
'CWD memory',
);
const result = flattenResult(
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
),
);
expect(result).toEqual({
memoryContent: `--- Project ---
--- Context from: ${cwdGeminiFile} ---
CWD memory
--- End of Context from: ${cwdGeminiFile} ---
--- Context from: ${subDirGeminiFile} ---
Subdir memory
--- End of Context from: ${subDirGeminiFile} ---`,
fileCount: 2,
filePaths: [cwdGeminiFile, subDirGeminiFile],
});
});
it('should load and correctly order global, upward, and downward ORIGINAL_GEMINI_MD_FILENAME files', async () => {
const defaultContextFile = await createTestFile(
path.join(homedir, GEMINI_DIR, DEFAULT_CONTEXT_FILENAME),
'default context content',
);
const rootGeminiFile = await createTestFile(
path.join(testRootDir, DEFAULT_CONTEXT_FILENAME),
'Project parent memory',
);
const projectRootGeminiFile = await createTestFile(
path.join(projectRoot, DEFAULT_CONTEXT_FILENAME),
'Project root memory',
);
const cwdGeminiFile = await createTestFile(
path.join(cwd, DEFAULT_CONTEXT_FILENAME),
'CWD memory',
);
const subDirGeminiFile = await createTestFile(
path.join(cwd, 'sub', DEFAULT_CONTEXT_FILENAME),
'Subdir memory',
);
const result = flattenResult(
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
),
);
expect(result).toEqual({
memoryContent: `--- Global ---
--- Context from: ${defaultContextFile} ---
default context content
--- End of Context from: ${defaultContextFile} ---
--- Project ---
--- Context from: ${rootGeminiFile} ---
Project parent memory
--- End of Context from: ${rootGeminiFile} ---
--- Context from: ${projectRootGeminiFile} ---
Project root memory
--- End of Context from: ${projectRootGeminiFile} ---
--- Context from: ${cwdGeminiFile} ---
CWD memory
--- End of Context from: ${cwdGeminiFile} ---
--- Context from: ${subDirGeminiFile} ---
Subdir memory
--- End of Context from: ${subDirGeminiFile} ---`,
fileCount: 5,
filePaths: [
defaultContextFile,
rootGeminiFile,
projectRootGeminiFile,
cwdGeminiFile,
subDirGeminiFile,
],
});
});
it('should ignore specified directories during downward scan', async () => {
await createEmptyDir(path.join(projectRoot, '.git'));
await createTestFile(path.join(projectRoot, '.gitignore'), 'node_modules');
await createTestFile(
path.join(cwd, 'node_modules', DEFAULT_CONTEXT_FILENAME),
'Ignored memory',
);
const regularSubDirGeminiFile = await createTestFile(
path.join(cwd, 'my_code', DEFAULT_CONTEXT_FILENAME),
'My code memory',
);
const result = flattenResult(
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
'tree',
{
respectGitIgnore: true,
respectGeminiIgnore: true,
customIgnoreFilePaths: [],
},
200, // maxDirs parameter
),
);
expect(result).toEqual({
memoryContent: `--- Project ---
--- Context from: ${regularSubDirGeminiFile} ---
My code memory
--- End of Context from: ${regularSubDirGeminiFile} ---`,
fileCount: 1,
filePaths: [regularSubDirGeminiFile],
});
});
it('should respect the maxDirs parameter during downward scan', async () => {
// Create directories in parallel for better performance
const dirPromises = Array.from({ length: 2 }, (_, i) =>
createEmptyDir(path.join(cwd, `deep_dir_${i}`)),
);
await Promise.all(dirPromises);
// Pass the custom limit directly to the function
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
'tree', // importFormat
{
respectGitIgnore: true,
respectGeminiIgnore: true,
customIgnoreFilePaths: [],
},
1, // maxDirs
);
// Note: bfsFileSearch debug logging is no longer controlled via debugMode parameter
// The test verifies maxDirs is respected by checking the result, not debug logs
const result = flattenResult(
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
),
);
expect(result).toEqual({
memoryContent: '',
fileCount: 0,
filePaths: [],
});
});
it('should load extension context file paths', async () => {
const extensionFilePath = await createTestFile(
path.join(testRootDir, 'extensions/ext1/GEMINI.md'),
'Extension memory content',
);
const result = flattenResult(
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([
{
contextFiles: [extensionFilePath],
isActive: true,
} as GeminiCLIExtension,
]),
DEFAULT_FOLDER_TRUST,
),
);
expect(result).toEqual({
memoryContent: `--- Extension ---
--- Context from: ${extensionFilePath} ---
Extension memory content
--- End of Context from: ${extensionFilePath} ---`,
fileCount: 1,
filePaths: [extensionFilePath],
});
});
it('should load memory from included directories', async () => {
const includedDir = await createEmptyDir(
path.join(testRootDir, 'included'),
);
const includedFile = await createTestFile(
path.join(includedDir, DEFAULT_CONTEXT_FILENAME),
'included directory memory',
);
const result = flattenResult(
await loadServerHierarchicalMemory(
cwd,
[includedDir],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
),
);
expect(result).toEqual({
memoryContent: `--- Project ---
--- Context from: ${includedFile} ---
included directory memory
--- End of Context from: ${includedFile} ---`,
fileCount: 1,
filePaths: [includedFile],
});
});
it('should handle multiple directories and files in parallel correctly', async () => {
// Create multiple test directories with GEMINI.md files
const numDirs = 5;
const createdFiles: string[] = [];
for (let i = 0; i < numDirs; i++) {
const dirPath = await createEmptyDir(
path.join(testRootDir, `project-${i}`),
);
const filePath = await createTestFile(
path.join(dirPath, DEFAULT_CONTEXT_FILENAME),
`Content from project ${i}`,
);
createdFiles.push(filePath);
}
// Load memory from all directories
const result = flattenResult(
await loadServerHierarchicalMemory(
cwd,
createdFiles.map((f) => path.dirname(f)),
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
),
);
// Should have loaded all files
expect(result.fileCount).toBe(numDirs);
expect(result.filePaths.length).toBe(numDirs);
expect(result.filePaths.sort()).toEqual(createdFiles.sort());
// Content should include all project contents
const flattenedMemory = flattenMemory(result.memoryContent);
for (let i = 0; i < numDirs; i++) {
expect(flattenedMemory).toContain(`Content from project ${i}`);
}
});
it('should preserve order and prevent duplicates when processing multiple directories', async () => {
// Create overlapping directory structure
const parentDir = await createEmptyDir(path.join(testRootDir, 'parent'));
const childDir = await createEmptyDir(path.join(parentDir, 'child'));
const parentFile = await createTestFile(
path.join(parentDir, DEFAULT_CONTEXT_FILENAME),
'Parent content',
);
const childFile = await createTestFile(
path.join(childDir, DEFAULT_CONTEXT_FILENAME),
'Child content',
);
// Include both parent and child directories
const result = flattenResult(
await loadServerHierarchicalMemory(
parentDir,
[childDir, parentDir], // Deliberately include duplicates
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
),
);
// Should have both files without duplicates
const flattenedMemory = flattenMemory(result.memoryContent);
expect(result.fileCount).toBe(2);
expect(flattenedMemory).toContain('Parent content');
expect(flattenedMemory).toContain('Child content');
expect(result.filePaths.sort()).toEqual([parentFile, childFile].sort());
// Check that files are not duplicated
const parentOccurrences = (flattenedMemory.match(/Parent content/g) || [])
.length;
const childOccurrences = (flattenedMemory.match(/Child content/g) || [])
.length;
expect(parentOccurrences).toBe(1);
expect(childOccurrences).toBe(1);
});
describe('EISDIR handling for GEMINI.md as a directory', () => {
it('readGeminiMdFiles returns null content (without throwing) when path is a directory', async () => {
const dirAsFilePath = await createEmptyDir(
path.join(cwd, DEFAULT_CONTEXT_FILENAME),
);
const results = await readGeminiMdFiles([dirAsFilePath]);
expect(results).toHaveLength(1);
expect(results[0].filePath).toBe(dirAsFilePath);
expect(results[0].content).toBeNull();
});
it('loadServerHierarchicalMemory ignores a GEMINI.md directory and returns empty memory', async () => {
// Create a directory named GEMINI.md where a regular file would be expected.
await createEmptyDir(path.join(cwd, DEFAULT_CONTEXT_FILENAME));
const result = flattenResult(
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
),
);
// EISDIR is silently skipped, so memory is empty (no readable file
// contents) and no exception propagates.
expect(result.memoryContent).toBe('');
});
it('falls back to a real GEMINI.md file at a higher level when a directory shadows the same name lower in the tree', async () => {
// Lower in the tree (cwd): a directory named GEMINI.md (invalid).
await createEmptyDir(path.join(cwd, DEFAULT_CONTEXT_FILENAME));
// Higher in the tree (projectRoot): a real GEMINI.md file (valid).
const projectContextFile = await createTestFile(
path.join(projectRoot, DEFAULT_CONTEXT_FILENAME),
'Project root memory content',
);
const result = flattenResult(
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
),
);
// The directory at cwd is silently skipped; the actual file at
// projectRoot is still discovered and loaded normally.
expect(result.memoryContent).toContain('Project root memory content');
expect(result.filePaths).toContain(projectContextFile);
});
it('silently skips a GEMINI.md symlink that points to a directory', async () => {
// Create a real directory elsewhere and symlink GEMINI.md to it.
const realDir = await createEmptyDir(path.join(cwd, '.geminimd-target'));
const symlinkPath = path.join(cwd, DEFAULT_CONTEXT_FILENAME);
try {
await fsPromises.symlink(realDir, symlinkPath, 'dir');
} catch (err) {
// Symlink creation may be unsupported on some Windows setups (no
// SeCreateSymbolicLinkPrivilege). Skip the test there rather than fail.
if (
err instanceof Error &&
(err as NodeJS.ErrnoException).code === 'EPERM'
) {
return;
}
throw err;
}
const result = flattenResult(
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
),
);
// A symlink resolving to a directory triggers EISDIR on read in the
// same way a plain directory does and must be skipped silently.
expect(result.memoryContent).toBe('');
});
});
describe('getGlobalMemoryPaths', () => {
it('should find global memory file if it exists', async () => {
const globalMemoryFile = await createTestFile(
path.join(homedir, GEMINI_DIR, DEFAULT_CONTEXT_FILENAME),
'Global memory content',
);
const result = await getGlobalMemoryPaths();
expect(result).toHaveLength(1);
expect(result[0]).toBe(globalMemoryFile);
});
it('should return empty array if global memory file does not exist', async () => {
const result = await getGlobalMemoryPaths();
expect(result).toHaveLength(0);
});
});
describe('getExtensionMemoryPaths', () => {
it('should return active extension context files', async () => {
const extFile = await createTestFile(
path.join(testRootDir, 'ext', 'GEMINI.md'),
'Extension content',
);
const loader = new SimpleExtensionLoader([
{
isActive: true,
contextFiles: [extFile],
} as GeminiCLIExtension,
]);
const result = getExtensionMemoryPaths(loader);
expect(result).toHaveLength(1);
expect(result[0]).toBe(extFile);
});
it('should ignore inactive extensions', async () => {
const extFile = await createTestFile(
path.join(testRootDir, 'ext', 'GEMINI.md'),
'Extension content',
);
const loader = new SimpleExtensionLoader([
{
isActive: false,
contextFiles: [extFile],
} as GeminiCLIExtension,
]);
const result = getExtensionMemoryPaths(loader);
expect(result).toHaveLength(0);
});
});
describe('getEnvironmentMemoryPaths', () => {
it('should traverse upward from trusted root to git root', async () => {
// Setup: /temp/parent/repo/.git
const parentDir = await createEmptyDir(path.join(testRootDir, 'parent'));
const repoDir = await createEmptyDir(path.join(parentDir, 'repo'));
await createEmptyDir(path.join(repoDir, '.git'));
const srcDir = await createEmptyDir(path.join(repoDir, 'src'));
await createTestFile(
path.join(parentDir, DEFAULT_CONTEXT_FILENAME),
'Parent content',
);
const repoFile = await createTestFile(
path.join(repoDir, DEFAULT_CONTEXT_FILENAME),
'Repo content',
);
const srcFile = await createTestFile(
path.join(srcDir, DEFAULT_CONTEXT_FILENAME),
'Src content',
);
// Trust srcDir. Should load srcFile AND repoFile (git root),
// but NOT parentFile (above git root).
const result = await getEnvironmentMemoryPaths([srcDir]);
expect(result).toHaveLength(2);
expect(result).toContain(repoFile);
expect(result).toContain(srcFile);
});
it('should fall back to trusted root as ceiling when no .git exists', async () => {
// Setup: /homedir/docs/notes (no .git anywhere)
const docsDir = await createEmptyDir(path.join(homedir, 'docs'));
const notesDir = await createEmptyDir(path.join(docsDir, 'notes'));
await createTestFile(
path.join(homedir, DEFAULT_CONTEXT_FILENAME),
'Home content',
);
const docsFile = await createTestFile(
path.join(docsDir, DEFAULT_CONTEXT_FILENAME),
'Docs content',
);
// No .git, so ceiling falls back to the trusted root itself.
// notesDir has no GEMINI.md and won't traverse up to docsDir.
const resultNotes = await getEnvironmentMemoryPaths([notesDir]);
expect(resultNotes).toHaveLength(0);
// docsDir has a GEMINI.md at the trusted root itself, so it's found.
const resultDocs = await getEnvironmentMemoryPaths([docsDir]);
expect(resultDocs).toHaveLength(1);
expect(resultDocs[0]).toBe(docsFile);
});
it('should deduplicate paths when same root is trusted multiple times', async () => {
const repoDir = await createEmptyDir(path.join(testRootDir, 'repo'));
await createEmptyDir(path.join(repoDir, '.git'));
const repoFile = await createTestFile(
path.join(repoDir, DEFAULT_CONTEXT_FILENAME),
'Repo content',
);
// Trust repoDir twice.
const result = await getEnvironmentMemoryPaths([repoDir, repoDir]);
expect(result).toHaveLength(1);
expect(result[0]).toBe(repoFile);
});
it('should recognize .git as a file (submodules/worktrees)', async () => {
const repoDir = await createEmptyDir(
path.join(testRootDir, 'worktree_repo'),
);
// .git as a file, like in submodules and worktrees
await createTestFile(
path.join(repoDir, '.git'),
'gitdir: /some/other/path/.git/worktrees/worktree_repo',
);
const srcDir = await createEmptyDir(path.join(repoDir, 'src'));
const repoFile = await createTestFile(
path.join(repoDir, DEFAULT_CONTEXT_FILENAME),
'Repo content',
);
const srcFile = await createTestFile(
path.join(srcDir, DEFAULT_CONTEXT_FILENAME),
'Src content',
);
// Trust srcDir. Should traverse up to repoDir (git root via .git file).
const result = await getEnvironmentMemoryPaths([srcDir]);
expect(result).toHaveLength(2);
expect(result).toContain(repoFile);
expect(result).toContain(srcFile);
});
it('should keep multiple memory files from the same directory adjacent and in order', async () => {
// Configure multiple memory filenames
setGeminiMdFilename(['PRIMARY.md', 'SECONDARY.md']);
const dir = await createEmptyDir(
path.join(testRootDir, 'multi_file_dir'),
);
await createEmptyDir(path.join(dir, '.git'));
const primaryFile = await createTestFile(
path.join(dir, 'PRIMARY.md'),
'Primary content',
);
const secondaryFile = await createTestFile(
path.join(dir, 'SECONDARY.md'),
'Secondary content',
);
const result = await getEnvironmentMemoryPaths([dir]);
expect(result).toHaveLength(2);
// Verify order: PRIMARY should come before SECONDARY because they are
// sorted by path and PRIMARY.md comes before SECONDARY.md alphabetically
// if in same dir.
expect(result[0]).toBe(primaryFile);
expect(result[1]).toBe(secondaryFile);
});
});
describe('case-insensitive filesystem deduplication', () => {
it('should deduplicate files that point to the same inode (same physical file)', async () => {
const geminiFile = await createTestFile(
path.join(projectRoot, 'gemini.md'),
'Project root memory',
);
// create hard link to simulate case-insensitive filesystem behavior
const geminiFileLink = path.join(projectRoot, 'GEMINI.md');
try {
await fsPromises.link(geminiFile, geminiFileLink);
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error);
if (
errorMessage.includes('cross-device') ||
errorMessage.includes('EXDEV') ||
errorMessage.includes('EEXIST')
) {
return;
}
throw error;
}
const stats1 = await fsPromises.lstat(geminiFile);
const stats2 = await fsPromises.lstat(geminiFileLink);
expect(stats1.ino).toBe(stats2.ino);
expect(stats1.dev).toBe(stats2.dev);
setGeminiMdFilename(['GEMINI.md', 'gemini.md']);
const result = flattenResult(
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
new SimpleExtensionLoader([]),
DEFAULT_FOLDER_TRUST,
),