Compare commits

...

4 Commits

Author SHA1 Message Date
qqqys
12f874d04c fix(hooks): restore main config behavior 2026-06-01 11:29:40 +08:00
qqqys
3fe3b2aed2 fix(hooks): remove stale branch regressions 2026-06-01 11:19:59 +08:00
qqqys
0769aebde3 fix(hooks): align InstructionsLoaded branch with main config 2026-06-01 11:12:32 +08:00
qqqys
c954b47837 feat(hooks): add InstructionsLoaded event 2026-06-01 10:57:23 +08:00
17 changed files with 691 additions and 9 deletions

View File

@ -12,6 +12,7 @@ import {
FileDiscoveryService,
getAllGeminiMdFilenames,
loadServerHierarchicalMemory,
type LoadServerHierarchicalMemoryOptions,
type LoadServerHierarchicalMemoryResponse,
setGeminiMdFilename as setServerGeminiMdFilename,
resolveTelemetrySettings,
@ -1130,6 +1131,7 @@ export async function loadHierarchicalGeminiMemory(
folderTrust: boolean,
memoryImportFormat: 'flat' | 'tree' = 'tree',
contextRuleExcludes: string[] = [],
options: LoadServerHierarchicalMemoryOptions = {},
): Promise<LoadServerHierarchicalMemoryResponse> {
// FIX: Use real, canonical paths for a reliable comparison to handle symlinks.
const realCwd = fs.realpathSync(path.resolve(currentWorkingDirectory));
@ -1149,6 +1151,7 @@ export async function loadHierarchicalGeminiMemory(
folderTrust,
memoryImportFormat,
contextRuleExcludes,
options,
);
}

View File

@ -1307,6 +1307,22 @@ export const AppContainer = (props: AppContainerProps) => {
config.isTrustedFolder(),
settings.merged.context?.importFormat || 'tree', // Use setting or default to 'tree'
config.getContextRuleExcludes(),
{
onInstructionsLoaded: async (notification) => {
await config
.getHookSystem()
?.fireInstructionsLoadedEvent(
notification.filePath,
notification.memoryType,
notification.loadReason,
{
globs: notification.globs,
triggerFilePath: notification.triggerFilePath,
parentFilePath: notification.parentFilePath,
},
);
},
},
);
config.setUserMemory(memoryContent);

View File

@ -241,6 +241,22 @@ export const directoryCommand: SlashCommand = {
context.services.settings.merged.context?.importFormat ||
'tree', // Use setting or default to 'tree'
config.getContextRuleExcludes(),
{
onInstructionsLoaded: async (notification) => {
await config
.getHookSystem()
?.fireInstructionsLoadedEvent(
notification.filePath,
notification.memoryType,
notification.loadReason,
{
globs: notification.globs,
triggerFilePath: notification.triggerFilePath,
parentFilePath: notification.parentFilePath,
},
);
},
},
);
config.setUserMemory(memoryContent);
config.setGeminiMdFileCount(fileCount);

View File

@ -83,6 +83,11 @@ describe('hooks constants', () => {
expect(exitCodes).toHaveLength(3);
});
it('should return exit codes for InstructionsLoaded event', () => {
const exitCodes = getHookExitCodes(HookEventName.InstructionsLoaded);
expect(exitCodes).toHaveLength(2);
});
it('should return empty array for unknown event', () => {
const exitCodes = getHookExitCodes('unknown_event' as HookEventName);
expect(exitCodes).toEqual([]);
@ -110,6 +115,11 @@ describe('hooks constants', () => {
expect(desc).toBe('When a new session is started');
});
it('should return description for InstructionsLoaded', () => {
const desc = getHookShortDescription(HookEventName.InstructionsLoaded);
expect(desc).toBe('When instruction files are loaded');
});
it('should return empty string for unknown event', () => {
const desc = getHookShortDescription('unknown_event' as HookEventName);
expect(desc).toBe('');
@ -133,6 +143,13 @@ describe('hooks constants', () => {
expect(desc).toBe('');
});
it('should return description for InstructionsLoaded', () => {
const desc = getHookDescription(HookEventName.InstructionsLoaded);
expect(desc).toContain('file_path');
expect(desc).toContain('memory_type');
expect(desc).toContain('load_reason');
});
it('should return empty string for unknown event', () => {
const desc = getHookDescription('unknown_event' as HookEventName);
expect(desc).toBe('');
@ -179,10 +196,11 @@ describe('hooks constants', () => {
expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.PermissionDenied);
expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.TodoCreated);
expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.TodoCompleted);
expect(DISPLAY_HOOK_EVENTS).toContain(HookEventName.InstructionsLoaded);
});
it('should have 17 events', () => {
expect(DISPLAY_HOOK_EVENTS).toHaveLength(17);
it('should have 18 events', () => {
expect(DISPLAY_HOOK_EVENTS).toHaveLength(18);
});
});
@ -242,5 +260,15 @@ describe('hooks constants', () => {
expect(info.exitCodes).toHaveLength(3);
expect(info.configs).toEqual([]);
});
it('should create empty info for InstructionsLoaded', () => {
const info = createEmptyHookEventInfo(HookEventName.InstructionsLoaded);
expect(info.event).toBe(HookEventName.InstructionsLoaded);
expect(info.shortDescription).toBe('When instruction files are loaded');
expect(info.description).toContain('file_path');
expect(info.exitCodes).toHaveLength(2);
expect(info.configs).toEqual([]);
});
});
});

View File

@ -43,6 +43,10 @@ export function getHookExitCodes(eventName: string): HookExitCode[] {
{ code: 0, description: t('stdout/stderr not shown') },
{ code: 'Other', description: t('show stderr to user only') },
],
[HookEventName.InstructionsLoaded]: [
{ code: 0, description: t('stdout/stderr not shown') },
{ code: 'Other', description: t('show stderr to user only') },
],
[HookEventName.UserPromptSubmit]: [
{ code: 0, description: t('stdout shown to Qwen') },
{
@ -127,6 +131,7 @@ export function getHookShortDescription(eventName: string): string {
[HookEventName.PostToolUse]: t('After tool execution'),
[HookEventName.PostToolUseFailure]: t('After tool execution fails'),
[HookEventName.Notification]: t('When notifications are sent'),
[HookEventName.InstructionsLoaded]: t('When instruction files are loaded'),
[HookEventName.UserPromptSubmit]: t('When the user submits a prompt'),
[HookEventName.SessionStart]: t('When a new session is started'),
[HookEventName.Stop]: t('Right before Qwen Code concludes its response'),
@ -168,6 +173,9 @@ export function getHookDescription(eventName: string): string {
[HookEventName.Notification]: t(
'Input to command is JSON with notification message and type.',
),
[HookEventName.InstructionsLoaded]: t(
'Input to command is JSON with file_path, memory_type, load_reason, and optional globs, trigger_file_path, and parent_file_path.',
),
[HookEventName.UserPromptSubmit]: t(
'Input to command is JSON with original user prompt text.',
),

View File

@ -49,6 +49,7 @@ import { ToolNames } from '../tools/tool-names.js';
import { fireNotificationHook } from '../core/toolHookTriggers.js';
import type { MessageBus } from '../confirmation-bus/message-bus.js';
import { loadServerHierarchicalMemory } from '../utils/memoryDiscovery.js';
import type { LoadServerHierarchicalMemoryOptions } from '../utils/memoryDiscovery.js';
import { readAutoMemoryIndex } from '../memory/store.js';
import { ExtensionManager } from '../extension/extensionManager.js';
import { SkillManager } from '../skills/skill-manager.js';
@ -1440,7 +1441,7 @@ describe('Server Config (config.ts)', () => {
await config.refreshHierarchicalMemory();
const lastCall = vi.mocked(loadServerHierarchicalMemory).mock.calls.at(-1);
expect(lastCall?.at(-1)).toEqual({ explicitOnly: true });
expect(lastCall?.at(-1)).toMatchObject({ explicitOnly: true });
expect(lastCall?.[1]).toEqual([]);
expect(readAutoMemoryIndex).not.toHaveBeenCalled();
expect(config.getUserMemory()).toContain('Project rules');
@ -1468,7 +1469,51 @@ describe('Server Config (config.ts)', () => {
const lastCall = vi.mocked(loadServerHierarchicalMemory).mock.calls.at(-1);
expect(lastCall?.[1]).toEqual([explicitDir]);
expect(lastCall?.at(-1)).toEqual({ explicitOnly: true });
expect(lastCall?.at(-1)).toMatchObject({ explicitOnly: true });
});
it('refreshHierarchicalMemory should fire InstructionsLoaded hooks from memory notifications', async () => {
const config = new Config(baseParams);
const fireInstructionsLoadedEvent = vi.fn().mockResolvedValue(undefined);
config['hookSystem'] = {
fireInstructionsLoadedEvent,
} as unknown as HookSystem;
vi.mocked(loadServerHierarchicalMemory).mockResolvedValue({
memoryContent: '--- Context from: QWEN.md ---\nProject rules',
fileCount: 1,
ruleCount: 0,
conditionalRules: [],
projectRoot: '/tmp',
});
await config.refreshHierarchicalMemory();
const lastCall = vi.mocked(loadServerHierarchicalMemory).mock.calls.at(-1);
const options = lastCall?.at(-1) as
| LoadServerHierarchicalMemoryOptions
| undefined;
expect(options?.onInstructionsLoaded).toEqual(expect.any(Function));
await options?.onInstructionsLoaded?.({
filePath: '/tmp/project/QWEN.md',
memoryType: 'project',
loadReason: 'include',
globs: ['**/*.ts'],
triggerFilePath: '/tmp/project/AGENTS.md',
parentFilePath: '/tmp/project/AGENTS.md',
});
expect(fireInstructionsLoadedEvent).toHaveBeenCalledWith(
'/tmp/project/QWEN.md',
'project',
'include',
{
globs: ['**/*.ts'],
triggerFilePath: '/tmp/project/AGENTS.md',
parentFilePath: '/tmp/project/AGENTS.md',
},
);
});
it('Config constructor should call setGeminiMdFilename with contextFileName if provided', () => {

View File

@ -1848,7 +1848,21 @@ export class Config {
this.isTrustedFolder(),
this.getImportFormat(),
this.contextRuleExcludes,
{ explicitOnly: this.getBareMode() },
{
explicitOnly: this.getBareMode(),
onInstructionsLoaded: async (notification) => {
await this.hookSystem?.fireInstructionsLoadedEvent(
notification.filePath,
notification.memoryType,
notification.loadReason,
{
globs: notification.globs,
triggerFilePath: notification.triggerFilePath,
parentFilePath: notification.parentFilePath,
},
);
},
},
);
if (this.getManagedAutoMemoryEnabled()) {
const managedAutoMemoryIndex = await readAutoMemoryIndex(

View File

@ -168,6 +168,52 @@ describe('HookEventHandler', () => {
});
});
describe('fireInstructionsLoadedEvent', () => {
it('should include instruction load metadata in hook input', async () => {
const mockPlan = createMockExecutionPlan([
{
type: HookType.Command,
command: 'echo test',
source: HooksConfigSource.Project,
},
]);
vi.mocked(mockHookPlanner.createExecutionPlan).mockReturnValue(mockPlan);
vi.mocked(mockHookRunner.executeHooksParallel).mockResolvedValue([]);
vi.mocked(mockHookAggregator.aggregateResults).mockReturnValue(
createMockAggregatedResult(true),
);
await hookEventHandler.fireInstructionsLoadedEvent(
'/repo/.qwen/QWEN.local.md',
'local',
'include',
{
parentFilePath: '/repo/QWEN.md',
},
);
expect(mockHookPlanner.createExecutionPlan).toHaveBeenCalledWith(
HookEventName.InstructionsLoaded,
{
filePath: '/repo/.qwen/QWEN.local.md',
},
);
const mockCalls = (mockHookRunner.executeHooksParallel as Mock).mock
.calls;
const input = mockCalls[0][2] as {
file_path: string;
memory_type: string;
load_reason: string;
parent_file_path?: string;
};
expect(input.file_path).toBe('/repo/.qwen/QWEN.local.md');
expect(input.memory_type).toBe('local');
expect(input.load_reason).toBe('include');
expect(input.parent_file_path).toBe('/repo/QWEN.md');
});
});
describe('fireStopEvent', () => {
it('should execute hooks for Stop event', async () => {
const mockPlan = createMockExecutionPlan([]);

View File

@ -45,6 +45,9 @@ import type {
TodoCompletedInput,
TodoItem,
TodoStatus,
InstructionsLoadedInput,
InstructionMemoryType,
InstructionLoadReason,
} from './types.js';
import { HookPhase, PermissionMode } from './types.js';
import { createDebugLogger } from '../utils/debugLogger.js';
@ -116,6 +119,37 @@ export class HookEventHandler {
);
}
async fireInstructionsLoadedEvent(
filePath: string,
memoryType: InstructionMemoryType,
loadReason: InstructionLoadReason,
options: {
globs?: string[];
triggerFilePath?: string;
parentFilePath?: string;
} = {},
signal?: AbortSignal,
): Promise<AggregatedHookResult> {
const input: InstructionsLoadedInput = {
...this.createBaseInput(HookEventName.InstructionsLoaded),
file_path: filePath,
memory_type: memoryType,
load_reason: loadReason,
globs: options.globs,
trigger_file_path: options.triggerFilePath,
parent_file_path: options.parentFilePath,
};
return this.executeHooks(
HookEventName.InstructionsLoaded,
input,
{
filePath,
},
signal,
);
}
/**
* Fire a Stop event
* Called by handleHookExecutionRequest - executes hooks directly

View File

@ -83,6 +83,17 @@ describe('HookPlanner', () => {
});
});
it('returns file path targets for instruction load events', () => {
expect(
getHookMatcherTarget(HookEventName.InstructionsLoaded, {
filePath: '/repo/.qwen/QWEN.local.md',
}),
).toEqual({
kind: 'filePath',
target: '/repo/.qwen/QWEN.local.md',
});
});
it('returns undefined for events without matcher semantics', () => {
expect(getHookMatcherTarget(HookEventName.UserPromptSubmit)).toBe(
undefined,
@ -518,6 +529,46 @@ describe('HookPlanner', () => {
expect(result).not.toBeNull();
});
it('should match instruction loaded file paths with regex', () => {
const entry: HookRegistryEntry = {
config: { type: HookType.Command, command: 'echo test' },
source: HooksConfigSource.Project,
eventName: HookEventName.InstructionsLoaded,
matcher: '\\.qwen/QWEN\\.local\\.md$',
enabled: true,
};
vi.mocked(mockRegistry.getHooksForEvent).mockReturnValue([entry]);
const result = planner.createExecutionPlan(
HookEventName.InstructionsLoaded,
{
filePath: '/repo/.qwen/QWEN.local.md',
},
);
expect(result).not.toBeNull();
});
it('should not match unrelated instruction loaded file paths', () => {
const entry: HookRegistryEntry = {
config: { type: HookType.Command, command: 'echo test' },
source: HooksConfigSource.Project,
eventName: HookEventName.InstructionsLoaded,
matcher: '\\.qwen/QWEN\\.local\\.md$',
enabled: true,
};
vi.mocked(mockRegistry.getHooksForEvent).mockReturnValue([entry]);
const result = planner.createExecutionPlan(
HookEventName.InstructionsLoaded,
{
filePath: '/repo/QWEN.md',
},
);
expect(result).toBeNull();
});
it('should match auth_success notification type', () => {
const entry: HookRegistryEntry = {
config: { type: HookType.Command, command: 'echo test' },

View File

@ -17,7 +17,8 @@ type HookMatcherTargetKind =
| 'trigger'
| 'sessionTrigger'
| 'error'
| 'notificationType';
| 'notificationType'
| 'filePath';
interface HookMatcherTarget {
kind: HookMatcherTargetKind;
@ -57,6 +58,9 @@ export function getHookMatcherTarget(
target: context?.notificationType ?? '',
};
case HookEventName.InstructionsLoaded:
return { kind: 'filePath', target: context?.filePath ?? '' };
case HookEventName.UserPromptSubmit:
case HookEventName.Stop:
case HookEventName.TodoCreated:
@ -162,6 +166,9 @@ export class HookPlanner {
case 'notificationType':
return this.matchesNotificationType(matcher, matcherTarget.target);
case 'filePath':
return this.matchesFilePath(matcher, matcherTarget.target);
case 'sessionTrigger':
return this.matchesSessionTrigger(matcher, matcherTarget.target);
@ -182,6 +189,21 @@ export class HookPlanner {
return matcher === notificationType;
}
/**
* Match loaded instruction file path against matcher pattern.
*/
private matchesFilePath(matcher: string, filePath: string): boolean {
try {
const regex = new RegExp(matcher);
return regex.test(filePath);
} catch (error) {
debugLogger.warn(
`Invalid regex in hook matcher "${matcher}" for file path "${filePath}", falling back to exact match: ${error}`,
);
return matcher === filePath;
}
}
/**
* Match session source or end reason against matcher pattern
*/
@ -270,4 +292,6 @@ export interface HookEventContext {
agentType?: string;
/** Error type for StopFailure matcher filtering (fieldToMatch: 'error') */
error?: string;
/** Loaded instruction/context file path for InstructionsLoaded matcher filtering */
filePath?: string;
}

View File

@ -34,6 +34,8 @@ import type {
StopFailureErrorType,
TodoItem,
TodoStatus,
InstructionMemoryType,
InstructionLoadReason,
} from './types.js';
import { SessionHooksManager } from './sessionHooksManager.js';
import type { AsyncHookRegistry } from './asyncHookRegistry.js';
@ -152,6 +154,29 @@ export class HookSystem {
: undefined;
}
async fireInstructionsLoadedEvent(
filePath: string,
memoryType: InstructionMemoryType,
loadReason: InstructionLoadReason,
options: {
globs?: string[];
triggerFilePath?: string;
parentFilePath?: string;
} = {},
signal?: AbortSignal,
): Promise<DefaultHookOutput | undefined> {
const result = await this.hookEventHandler.fireInstructionsLoadedEvent(
filePath,
memoryType,
loadReason,
options,
signal,
);
return result.finalOutput
? createHookOutput('InstructionsLoaded', result.finalOutput)
: undefined;
}
async fireStopEvent(
stopHookActive: boolean = false,
lastAssistantMessage: string = '',

View File

@ -54,6 +54,8 @@ export enum HookEventName {
TodoCreated = 'TodoCreated',
// TodoCompleted - When a todo item's status changes to 'completed' (Qwen Code specific)
TodoCompleted = 'TodoCompleted',
// InstructionsLoaded - When an instruction or context file is loaded
InstructionsLoaded = 'InstructionsLoaded',
}
/**
@ -253,6 +255,22 @@ export interface HookInput {
timestamp: string;
}
export type InstructionMemoryType = 'user' | 'project' | 'local' | 'extension';
export type InstructionLoadReason = 'session_start' | 'include';
/**
* Input for InstructionsLoaded hook events
*/
export interface InstructionsLoadedInput extends HookInput {
file_path: string;
memory_type: InstructionMemoryType;
load_reason: InstructionLoadReason;
globs?: string[];
trigger_file_path?: string;
parent_file_path?: string;
}
/**
* Base hook output - common fields for all events
*/

View File

@ -12,9 +12,11 @@ import { loadServerHierarchicalMemory } from './memoryDiscovery.js';
import {
setGeminiMdFilename,
DEFAULT_CONTEXT_FILENAME,
LOCAL_CONTEXT_FILENAME,
} from '../memory/const.js';
import { FileDiscoveryService } from '../services/fileDiscoveryService.js';
import { QWEN_DIR } from './paths.js';
import type { InstructionsLoadedNotification } from './memoryDiscovery.js';
vi.mock('os', async (importOriginal) => {
const actualOs = await importOriginal<typeof os>();
@ -438,6 +440,162 @@ describe('loadServerHierarchicalMemory', () => {
});
});
it('notifies when startup instruction files are loaded', async () => {
const globalFile = await createTestFile(
path.join(homedir, QWEN_DIR, DEFAULT_CONTEXT_FILENAME),
'global context',
);
const projectFile = await createTestFile(
path.join(projectRoot, DEFAULT_CONTEXT_FILENAME),
'project context',
);
const extensionFile = await createTestFile(
path.join(testRootDir, 'extensions/ext1/QWEN.md'),
'extension context',
);
const notifications: InstructionsLoadedNotification[] = [];
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
[extensionFile],
DEFAULT_FOLDER_TRUST,
'tree',
[],
{
onInstructionsLoaded: (notification) => {
notifications.push(notification);
},
},
);
expect(notifications).toEqual(
expect.arrayContaining([
{
filePath: globalFile,
memoryType: 'user',
loadReason: 'session_start',
},
{
filePath: projectFile,
memoryType: 'project',
loadReason: 'session_start',
},
{
filePath: extensionFile,
memoryType: 'extension',
loadReason: 'session_start',
},
]),
);
});
it('notifies when imported instruction files are loaded', async () => {
await createEmptyDir(path.join(projectRoot, '.git'));
const importedFile = await createTestFile(
path.join(projectRoot, 'included.md'),
'included content',
);
const projectFile = await createTestFile(
path.join(projectRoot, DEFAULT_CONTEXT_FILENAME),
'project context @./included.md',
);
const notifications: InstructionsLoadedNotification[] = [];
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
[],
DEFAULT_FOLDER_TRUST,
'tree',
[],
{
onInstructionsLoaded: (notification) => {
notifications.push(notification);
},
},
);
expect(notifications).toEqual(
expect.arrayContaining([
expect.objectContaining({
filePath: importedFile,
memoryType: 'project',
loadReason: 'include',
parentFilePath: projectFile,
}),
]),
);
});
it('classifies extension-owned imports as extension memory', async () => {
const extensionDir = path.join(testRootDir, 'extensions/ext1');
const importedFile = await createTestFile(
path.join(extensionDir, 'included.md'),
'extension included content',
);
const extensionFile = await createTestFile(
path.join(extensionDir, DEFAULT_CONTEXT_FILENAME),
'extension context @./included.md',
);
const notifications: InstructionsLoadedNotification[] = [];
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
[extensionFile],
DEFAULT_FOLDER_TRUST,
'tree',
[],
{
onInstructionsLoaded: (notification) => {
notifications.push(notification);
},
},
);
expect(notifications).toEqual(
expect.arrayContaining([
expect.objectContaining({
filePath: importedFile,
memoryType: 'extension',
loadReason: 'include',
parentFilePath: extensionFile,
}),
]),
);
});
it('still loads memory when instruction load notification fails', async () => {
const projectFile = await createTestFile(
path.join(projectRoot, DEFAULT_CONTEXT_FILENAME),
'project context',
);
const result = await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
[],
DEFAULT_FOLDER_TRUST,
'tree',
[],
{
onInstructionsLoaded: () => {
throw new Error('hook failed');
},
},
);
expect(result.fileCount).toBe(1);
expect(result.memoryContent).toContain(
`--- Context from: ${path.relative(cwd, projectFile)} ---\nproject context`,
);
});
it('should load memory from included directories', async () => {
const includedDir = await createEmptyDir(
path.join(testRootDir, 'included'),
@ -567,6 +725,39 @@ describe('loadServerHierarchicalMemory', () => {
);
});
it('notifies when QWEN.local.md is loaded', async () => {
const localFile = await createTestFile(
path.join(projectRoot, QWEN_DIR, LOCAL_CONTEXT_FILENAME),
'local context content',
);
const notifications: InstructionsLoadedNotification[] = [];
await loadServerHierarchicalMemory(
cwd,
[],
new FileDiscoveryService(projectRoot),
[],
DEFAULT_FOLDER_TRUST,
'tree',
[],
{
onInstructionsLoaded: (notification) => {
notifications.push(notification);
},
},
);
expect(notifications).toEqual(
expect.arrayContaining([
{
filePath: localFile,
memoryType: 'local',
loadReason: 'session_start',
},
]),
);
});
it('orders QWEN.local.md after the project-root QWEN.md', async () => {
const projectFile = await createTestFile(
path.join(projectRoot, DEFAULT_CONTEXT_FILENAME),

View File

@ -14,11 +14,15 @@ import {
} from '../memory/const.js';
import type { FileDiscoveryService } from '../services/fileDiscoveryService.js';
import { processImports } from './memoryImportProcessor.js';
import { QWEN_DIR } from './paths.js';
import { isSubpath, QWEN_DIR } from './paths.js';
import { Storage } from '../config/storage.js';
import { createDebugLogger } from './debugLogger.js';
import { findProjectRoot } from './projectRoot.js';
import { loadRules, type RuleFile } from './rulesDiscovery.js';
import type {
InstructionLoadReason,
InstructionMemoryType,
} from '../hooks/types.js';
const logger = createDebugLogger('MEMORY_DISCOVERY');
@ -27,6 +31,15 @@ interface GeminiFileContent {
content: string | null;
}
export interface InstructionsLoadedNotification {
filePath: string;
memoryType: InstructionMemoryType;
loadReason: InstructionLoadReason;
globs?: string[];
triggerFilePath?: string;
parentFilePath?: string;
}
async function getGeminiMdFilePathsInternal(
currentWorkingDirectory: string,
includeDirectoriesToReadGemini: readonly string[],
@ -203,10 +216,24 @@ async function getGeminiMdFilePathsInternalForEachDir(
async function readGeminiMdFiles(
filePaths: string[],
importFormat: 'flat' | 'tree' = 'tree',
getMemoryType: (filePath: string) => InstructionMemoryType,
onInstructionsLoaded?: (
notification: InstructionsLoadedNotification,
) => void | Promise<void>,
): Promise<GeminiFileContent[]> {
// Process files in parallel with concurrency limit to prevent EMFILE errors
const CONCURRENT_LIMIT = 20; // Higher limit for file reads as they're typically faster
const results: GeminiFileContent[] = [];
const notifyInstructionsLoaded = async (
notification: InstructionsLoadedNotification,
) => {
try {
await onInstructionsLoaded?.(notification);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
logger.warn(`InstructionsLoaded notification failed: ${message}`);
}
};
for (let i = 0; i < filePaths.length; i += CONCURRENT_LIMIT) {
const batch = filePaths.slice(i, i + CONCURRENT_LIMIT);
@ -219,13 +246,34 @@ async function readGeminiMdFiles(
const processedResult = await processImports(
content,
path.dirname(filePath),
undefined,
{
processedFiles: new Set([path.resolve(filePath)]),
maxDepth: 5,
currentDepth: 0,
currentFile: path.resolve(filePath),
},
undefined,
importFormat,
{
onFileImported: async (notification) => {
await notifyInstructionsLoaded({
filePath: notification.filePath,
memoryType: getMemoryType(notification.filePath),
loadReason: 'include',
triggerFilePath: notification.parentFilePath,
parentFilePath: notification.parentFilePath,
});
},
},
);
logger.debug(
`Successfully read and processed imports: ${filePath} (Length: ${processedResult.content.length})`,
);
await notifyInstructionsLoaded({
filePath,
memoryType: getMemoryType(filePath),
loadReason: 'session_start',
});
return { filePath, content: processedResult.content };
} catch (error: unknown) {
@ -296,6 +344,52 @@ export interface LoadServerHierarchicalMemoryResponse {
export interface LoadServerHierarchicalMemoryOptions {
explicitOnly?: boolean;
onInstructionsLoaded?: (
notification: InstructionsLoadedNotification,
) => void | Promise<void>;
}
function createMemoryTypeClassifier(
userHomePath: string,
foundRoot: string | null,
extensionContextFilePaths: string[],
): (filePath: string) => InstructionMemoryType {
const resolvedHome = path.resolve(userHomePath);
const globalQwenDir = path.resolve(Storage.getGlobalQwenDir());
const resolvedRoot = foundRoot ? path.resolve(foundRoot) : undefined;
const extensionPaths = new Set(
extensionContextFilePaths.map((filePath) => path.resolve(filePath)),
);
const extensionRoots = extensionContextFilePaths.map((filePath) =>
path.dirname(path.resolve(filePath)),
);
return (filePath) => {
const resolvedPath = path.resolve(filePath);
if (
extensionPaths.has(resolvedPath) ||
extensionRoots.some((root) => isSubpath(root, resolvedPath))
) {
return 'extension';
}
if (
resolvedRoot &&
resolvedPath === path.join(resolvedRoot, QWEN_DIR, LOCAL_CONTEXT_FILENAME)
) {
return 'local';
}
if (
resolvedPath.startsWith(`${globalQwenDir}${path.sep}`) ||
path.dirname(resolvedPath) === resolvedHome
) {
return 'user';
}
return 'project';
};
}
/**
@ -374,7 +468,16 @@ export async function loadServerHierarchicalMemory(
let fileCount = 0;
if (filePaths.length > 0) {
const contentsWithPaths = await readGeminiMdFiles(filePaths, importFormat);
const contentsWithPaths = await readGeminiMdFiles(
filePaths,
importFormat,
createMemoryTypeClassifier(
userHomePath,
foundRoot,
extensionContextFilePaths,
),
options.onInstructionsLoaded,
);
// Pass CWD for relative path display in concatenated content
combinedInstructions = concatenateInstructions(
contentsWithPaths,

View File

@ -144,6 +144,45 @@ describe('memoryImportProcessor', () => {
);
});
it('notifies after importing a file', async () => {
const content = 'Some content @./test.md more content';
const basePath = testPath('test', 'path');
const parentFile = path.resolve(basePath, 'QWEN.md');
const importedFile = path.resolve(basePath, 'test.md');
const importedFiles: Array<{
filePath: string;
parentFilePath: string;
}> = [];
mockedFs.access.mockResolvedValue(undefined);
mockedFs.readFile.mockResolvedValue('# Imported Content');
await processImports(
content,
basePath,
{
processedFiles: new Set(),
maxDepth: 5,
currentDepth: 0,
currentFile: parentFile,
},
undefined,
'tree',
{
onFileImported: (event) => {
importedFiles.push(event);
},
},
);
expect(importedFiles).toEqual([
{
filePath: importedFile,
parentFilePath: parentFile,
},
]);
});
it('should import non-md files just like md files', async () => {
const content = 'Some content @./instructions.txt more content';
const basePath = testPath('test', 'path');

View File

@ -39,6 +39,17 @@ export interface ProcessImportsResult {
importTree: MemoryFile;
}
export interface ImportedFileNotification {
filePath: string;
parentFilePath: string;
}
export interface ProcessImportsOptions {
onFileImported?: (
notification: ImportedFileNotification,
) => void | Promise<void>;
}
// `findProjectRoot` now lives in `./projectRoot.ts` and is shared with
// memoryDiscovery. It returns `string | null`; `processImports` below
// preserves the previous "fall back to startDir" contract at the call
@ -190,6 +201,7 @@ export async function processImports(
},
projectRoot?: string,
importFormat: 'flat' | 'tree' = 'tree',
options: ProcessImportsOptions = {},
): Promise<ProcessImportsResult> {
if (!projectRoot) {
// Preserve the previous local helper's contract: if no `.git`
@ -268,6 +280,10 @@ export async function processImports(
try {
await fs.access(fullPath);
const importedContent = await fs.readFile(fullPath, 'utf-8');
await options.onFileImported?.({
filePath: normalizedFullPath,
parentFilePath: normalizedPath,
});
// Process the imported file
await processFlat(
@ -339,6 +355,10 @@ export async function processImports(
try {
await fs.access(fullPath);
const fileContent = await fs.readFile(fullPath, 'utf-8');
await options.onFileImported?.({
filePath: fullPath,
parentFilePath: importState.currentFile ?? path.resolve(basePath),
});
// Mark this file as processed for this import chain
const newImportState: ImportState = {
...importState,
@ -353,6 +373,7 @@ export async function processImports(
newImportState,
projectRoot,
importFormat,
options,
);
result += `<!-- Imported from: ${importPath} -->\n${imported.content}\n<!-- End of import from: ${importPath} -->`;
imports.push(imported.importTree);