Compare commits
15 Commits
main
...
worktree-c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
58d2041590 | ||
|
|
a99cd0be28 | ||
|
|
2ca07e8917 | ||
|
|
28c5fe7b28 | ||
|
|
c29ab1afb8 | ||
|
|
74ce3eef0c | ||
|
|
08ae3ff9b8 | ||
|
|
fd8cfad6f9 | ||
|
|
073ecc1d4c | ||
|
|
b9d987b08d | ||
|
|
8abe822ba1 | ||
|
|
0c63c05c45 | ||
|
|
18f999a30d | ||
|
|
15aa924932 | ||
|
|
2c4d03a843 |
@ -297,13 +297,13 @@ describe('plan_mode', () => {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
evalTest('ALWAYS_PASSES', {
|
evalTest('USUALLY_PASSES', {
|
||||||
name: 'should transition from plan mode to normal execution and create a plan file from scratch',
|
name: 'should transition from plan mode to normal execution and create a plan file from scratch',
|
||||||
params: {
|
params: {
|
||||||
settings,
|
settings,
|
||||||
},
|
},
|
||||||
prompt:
|
prompt:
|
||||||
'Enter plan mode and plan to create a new module called foo. The plan should be saved as foo-plan.md. Then, exit plan mode.',
|
'Enter plan mode and plan to create a new module called foo. The plan should be saved as foo-plan.md. I agree with the strategy, so please create a detailed implementation plan and then execute it.',
|
||||||
assert: async (rig, result) => {
|
assert: async (rig, result) => {
|
||||||
const enterPlanCalled = await rig.waitForToolCall('enter_plan_mode');
|
const enterPlanCalled = await rig.waitForToolCall('enter_plan_mode');
|
||||||
expect(
|
expect(
|
||||||
|
|||||||
@ -3796,7 +3796,8 @@ describe('loadCliConfig mcpEnabled', () => {
|
|||||||
]);
|
]);
|
||||||
|
|
||||||
const config = await loadCliConfig(settings, 'test-session', argv);
|
const config = await loadCliConfig(settings, 'test-session', argv);
|
||||||
expect(config.storage.getPlansDir()).toContain('ext-plans-dir');
|
config.setActiveExtensionContext('ext-plan');
|
||||||
|
expect(config.getPlansDir()).toContain('ext-plans-dir');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT use plan directory from active extension when user has specified one', async () => {
|
it('should NOT use plan directory from active extension when user has specified one', async () => {
|
||||||
|
|||||||
@ -610,9 +610,12 @@ export async function loadCliConfig(
|
|||||||
});
|
});
|
||||||
await extensionManager.loadExtensions();
|
await extensionManager.loadExtensions();
|
||||||
|
|
||||||
const extensionPlanSettings = extensionManager
|
const extensionPlanDirs: Record<string, string> = {};
|
||||||
.getExtensions()
|
for (const ext of extensionManager.getExtensions()) {
|
||||||
.find((ext) => ext.isActive && ext.plan?.directory)?.plan;
|
if (ext.isActive && ext.plan?.directory) {
|
||||||
|
extensionPlanDirs[ext.name] = ext.plan.directory;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const experimentalJitContext = settings.experimental.jitContext;
|
const experimentalJitContext = settings.experimental.jitContext;
|
||||||
|
|
||||||
@ -982,9 +985,8 @@ export async function loadCliConfig(
|
|||||||
plan: settings.general?.plan?.enabled ?? true,
|
plan: settings.general?.plan?.enabled ?? true,
|
||||||
tracker: settings.experimental?.taskTracker,
|
tracker: settings.experimental?.taskTracker,
|
||||||
directWebFetch: settings.experimental?.directWebFetch,
|
directWebFetch: settings.experimental?.directWebFetch,
|
||||||
planSettings: settings.general?.plan?.directory
|
planSettings: settings.general?.plan,
|
||||||
? settings.general.plan
|
extensionPlanDirs,
|
||||||
: (extensionPlanSettings ?? settings.general?.plan),
|
|
||||||
enableEventDrivenScheduler: true,
|
enableEventDrivenScheduler: true,
|
||||||
skillsSupport: settings.skills?.enabled ?? true,
|
skillsSupport: settings.skills?.enabled ?? true,
|
||||||
disabledSkills: settings.skills?.disabled,
|
disabledSkills: settings.skills?.disabled,
|
||||||
|
|||||||
@ -23,6 +23,8 @@ export const createMockConfig = (overrides: Partial<Config> = {}): Config =>
|
|||||||
isInteractive: vi.fn(() => false),
|
isInteractive: vi.fn(() => false),
|
||||||
isInitialized: vi.fn(() => true),
|
isInitialized: vi.fn(() => true),
|
||||||
setTerminalBackground: vi.fn(),
|
setTerminalBackground: vi.fn(),
|
||||||
|
setActiveExtensionContext: vi.fn(),
|
||||||
|
hasExtensionPlanDir: vi.fn(() => true),
|
||||||
storage: {
|
storage: {
|
||||||
getProjectTempDir: vi.fn().mockReturnValue('/tmp/gemini-test'),
|
getProjectTempDir: vi.fn().mockReturnValue('/tmp/gemini-test'),
|
||||||
initialize: vi.fn().mockResolvedValue(undefined),
|
initialize: vi.fn().mockResolvedValue(undefined),
|
||||||
|
|||||||
@ -3195,6 +3195,157 @@ describe('AppContainer State Management', () => {
|
|||||||
);
|
);
|
||||||
unmount();
|
unmount();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('sets activeExtensionContext when an extension command WITH a plan dir is executed', async () => {
|
||||||
|
const { checkPermissions } = await import(
|
||||||
|
'./hooks/atCommandProcessor.js'
|
||||||
|
);
|
||||||
|
vi.mocked(checkPermissions).mockResolvedValue([]);
|
||||||
|
|
||||||
|
mockedUseSlashCommandProcessor.mockReturnValue({
|
||||||
|
handleSlashCommand: vi.fn(),
|
||||||
|
slashCommands: [
|
||||||
|
{
|
||||||
|
name: 'conductor:setup',
|
||||||
|
extensionName: 'conductor',
|
||||||
|
description: 'test',
|
||||||
|
action: vi.fn(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
pendingHistoryItems: [],
|
||||||
|
commandContext: {},
|
||||||
|
shellConfirmationRequest: null,
|
||||||
|
confirmationRequest: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
const spyHasExtensionPlanDir = vi
|
||||||
|
.spyOn(mockConfig, 'hasExtensionPlanDir')
|
||||||
|
.mockReturnValue(true);
|
||||||
|
const spySetActiveExtensionContext = vi.spyOn(
|
||||||
|
mockConfig,
|
||||||
|
'setActiveExtensionContext',
|
||||||
|
);
|
||||||
|
|
||||||
|
const { unmount } = await act(async () => renderAppContainer());
|
||||||
|
|
||||||
|
expect(capturedUIActions).toBeTruthy();
|
||||||
|
|
||||||
|
await act(async () =>
|
||||||
|
capturedUIActions.handleFinalSubmit('/conductor:setup'),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(spyHasExtensionPlanDir).toHaveBeenCalledWith('conductor');
|
||||||
|
expect(spySetActiveExtensionContext).toHaveBeenCalledWith('conductor');
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears activeExtensionContext when an extension command WITHOUT a plan dir is executed', async () => {
|
||||||
|
const { checkPermissions } = await import(
|
||||||
|
'./hooks/atCommandProcessor.js'
|
||||||
|
);
|
||||||
|
vi.mocked(checkPermissions).mockResolvedValue([]);
|
||||||
|
|
||||||
|
mockedUseSlashCommandProcessor.mockReturnValue({
|
||||||
|
handleSlashCommand: vi.fn(),
|
||||||
|
slashCommands: [
|
||||||
|
{
|
||||||
|
name: 'other:cmd',
|
||||||
|
extensionName: 'other',
|
||||||
|
description: 'test',
|
||||||
|
action: vi.fn(),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
pendingHistoryItems: [],
|
||||||
|
commandContext: {},
|
||||||
|
shellConfirmationRequest: null,
|
||||||
|
confirmationRequest: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
const spyHasExtensionPlanDir = vi
|
||||||
|
.spyOn(mockConfig, 'hasExtensionPlanDir')
|
||||||
|
.mockReturnValue(false);
|
||||||
|
const spySetActiveExtensionContext = vi.spyOn(
|
||||||
|
mockConfig,
|
||||||
|
'setActiveExtensionContext',
|
||||||
|
);
|
||||||
|
|
||||||
|
const { unmount } = await act(async () => renderAppContainer());
|
||||||
|
|
||||||
|
expect(capturedUIActions).toBeTruthy();
|
||||||
|
|
||||||
|
await act(async () => capturedUIActions.handleFinalSubmit('/other:cmd'));
|
||||||
|
|
||||||
|
expect(spyHasExtensionPlanDir).toHaveBeenCalledWith('other');
|
||||||
|
expect(spySetActiveExtensionContext).toHaveBeenCalledWith(undefined);
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('clears activeExtensionContext when /plan is explicitly executed', async () => {
|
||||||
|
const { checkPermissions } = await import(
|
||||||
|
'./hooks/atCommandProcessor.js'
|
||||||
|
);
|
||||||
|
vi.mocked(checkPermissions).mockResolvedValue([]);
|
||||||
|
|
||||||
|
mockedUseSlashCommandProcessor.mockReturnValue({
|
||||||
|
handleSlashCommand: vi.fn(),
|
||||||
|
slashCommands: [{ name: 'plan', description: 'test', action: vi.fn() }],
|
||||||
|
pendingHistoryItems: [],
|
||||||
|
commandContext: {},
|
||||||
|
shellConfirmationRequest: null,
|
||||||
|
confirmationRequest: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
const spySetActiveExtensionContext = vi.spyOn(
|
||||||
|
mockConfig,
|
||||||
|
'setActiveExtensionContext',
|
||||||
|
);
|
||||||
|
|
||||||
|
const { unmount } = await act(async () => renderAppContainer());
|
||||||
|
|
||||||
|
expect(capturedUIActions).toBeTruthy();
|
||||||
|
|
||||||
|
await act(async () =>
|
||||||
|
capturedUIActions.handleFinalSubmit('/plan my task'),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(spySetActiveExtensionContext).toHaveBeenCalledWith(undefined);
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does NOT clear activeExtensionContext when a standard non-plan command is executed', async () => {
|
||||||
|
const { checkPermissions } = await import(
|
||||||
|
'./hooks/atCommandProcessor.js'
|
||||||
|
);
|
||||||
|
vi.mocked(checkPermissions).mockResolvedValue([]);
|
||||||
|
|
||||||
|
mockedUseSlashCommandProcessor.mockReturnValue({
|
||||||
|
handleSlashCommand: vi.fn(),
|
||||||
|
slashCommands: [{ name: 'help', description: 'test', action: vi.fn() }],
|
||||||
|
pendingHistoryItems: [],
|
||||||
|
commandContext: {},
|
||||||
|
shellConfirmationRequest: null,
|
||||||
|
confirmationRequest: null,
|
||||||
|
});
|
||||||
|
|
||||||
|
const spySetActiveExtensionContext = vi.spyOn(
|
||||||
|
mockConfig,
|
||||||
|
'setActiveExtensionContext',
|
||||||
|
);
|
||||||
|
|
||||||
|
const { unmount } = await act(async () => renderAppContainer());
|
||||||
|
|
||||||
|
expect(capturedUIActions).toBeTruthy();
|
||||||
|
|
||||||
|
await act(async () => capturedUIActions.handleFinalSubmit('/help'));
|
||||||
|
|
||||||
|
// It should not touch the context at all
|
||||||
|
expect(spySetActiveExtensionContext).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
unmount();
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('Overflow Hint Handling', () => {
|
describe('Overflow Hint Handling', () => {
|
||||||
|
|||||||
@ -1377,6 +1377,30 @@ Logging in with Google... Restarting Gemini CLI to continue.
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const parsedCommand = parseSlashCommand(
|
||||||
|
submittedValue,
|
||||||
|
slashCommands ?? [],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (config) {
|
||||||
|
if (parsedCommand.extensionContext) {
|
||||||
|
// Explicit extension invocation sets the "sticky" context to that extension,
|
||||||
|
// allowing subsequent multi-turn conversational replies (e.g. "yes, do that")
|
||||||
|
// to continue interacting with the extension's isolated plan directory.
|
||||||
|
if (config.hasExtensionPlanDir(parsedCommand.extensionContext)) {
|
||||||
|
config.setActiveExtensionContext(parsedCommand.extensionContext);
|
||||||
|
} else {
|
||||||
|
// Extension doesn't have a plan dir registered, so fallback to default workspace context
|
||||||
|
config.setActiveExtensionContext(undefined);
|
||||||
|
}
|
||||||
|
} else if (parsedCommand.commandToExecute?.name === 'plan') {
|
||||||
|
// If the user explicitly runs the native global /plan command (e.g., "/plan copy"),
|
||||||
|
// they are signaling an intent to manage their standard workspace plans,
|
||||||
|
// so we clear the sticky extension context to avoid misdirecting the operation.
|
||||||
|
config.setActiveExtensionContext(undefined);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const isSlash = isSlashCommand(submittedValue.trim());
|
const isSlash = isSlashCommand(submittedValue.trim());
|
||||||
const isIdle = streamingState === StreamingState.Idle;
|
const isIdle = streamingState === StreamingState.Idle;
|
||||||
const isAgentRunning =
|
const isAgentRunning =
|
||||||
@ -1384,10 +1408,7 @@ Logging in with Google... Restarting Gemini CLI to continue.
|
|||||||
isToolExecuting(pendingHistoryItems);
|
isToolExecuting(pendingHistoryItems);
|
||||||
|
|
||||||
if (isSlash && isAgentRunning) {
|
if (isSlash && isAgentRunning) {
|
||||||
const { commandToExecute } = parseSlashCommand(
|
const commandToExecute = parsedCommand.commandToExecute;
|
||||||
submittedValue,
|
|
||||||
slashCommands ?? [],
|
|
||||||
);
|
|
||||||
if (commandToExecute?.isSafeConcurrent) {
|
if (commandToExecute?.isSafeConcurrent) {
|
||||||
void handleSlashCommand(submittedValue);
|
void handleSlashCommand(submittedValue);
|
||||||
addInput(submittedValue);
|
addInput(submittedValue);
|
||||||
|
|||||||
@ -45,6 +45,7 @@ describe('clearCommand', () => {
|
|||||||
fireSessionEndEvent: vi.fn().mockResolvedValue(undefined),
|
fireSessionEndEvent: vi.fn().mockResolvedValue(undefined),
|
||||||
fireSessionStartEvent: vi.fn().mockResolvedValue(undefined),
|
fireSessionStartEvent: vi.fn().mockResolvedValue(undefined),
|
||||||
}),
|
}),
|
||||||
|
setActiveExtensionContext: vi.fn(),
|
||||||
injectionService: {
|
injectionService: {
|
||||||
clear: mockHintClear,
|
clear: mockHintClear,
|
||||||
},
|
},
|
||||||
|
|||||||
@ -30,8 +30,9 @@ export const clearCommand: SlashCommand = {
|
|||||||
await hookSystem.fireSessionEndEvent(SessionEndReason.Clear);
|
await hookSystem.fireSessionEndEvent(SessionEndReason.Clear);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reset user steering hints
|
// Reset user steering hints and extension context
|
||||||
config?.injectionService.clear();
|
config?.injectionService.clear();
|
||||||
|
config?.setActiveExtensionContext(undefined);
|
||||||
|
|
||||||
// Start a new conversation recording with a new session ID
|
// Start a new conversation recording with a new session ID
|
||||||
// We MUST do this before calling resetChat() so the new ChatRecordingService
|
// We MUST do this before calling resetChat() so the new ChatRecordingService
|
||||||
|
|||||||
@ -10,6 +10,7 @@ export type ParsedSlashCommand = {
|
|||||||
commandToExecute: SlashCommand | undefined;
|
commandToExecute: SlashCommand | undefined;
|
||||||
args: string;
|
args: string;
|
||||||
canonicalPath: string[];
|
canonicalPath: string[];
|
||||||
|
extensionContext?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -69,6 +70,8 @@ export const parseSlashCommand = (
|
|||||||
|
|
||||||
const args = parts.slice(pathIndex).join(' ');
|
const args = parts.slice(pathIndex).join(' ');
|
||||||
|
|
||||||
|
const extensionContext = commandToExecute?.extensionName;
|
||||||
|
|
||||||
// Backtrack if the matched (sub)command doesn't take arguments but some were provided,
|
// Backtrack if the matched (sub)command doesn't take arguments but some were provided,
|
||||||
// AND the parent command is capable of handling them.
|
// AND the parent command is capable of handling them.
|
||||||
if (
|
if (
|
||||||
@ -82,8 +85,9 @@ export const parseSlashCommand = (
|
|||||||
commandToExecute: parentCommand,
|
commandToExecute: parentCommand,
|
||||||
args: parts.slice(pathIndex - 1).join(' '),
|
args: parts.slice(pathIndex - 1).join(' '),
|
||||||
canonicalPath: canonicalPath.slice(0, -1),
|
canonicalPath: canonicalPath.slice(0, -1),
|
||||||
|
extensionContext: parentCommand.extensionName,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
return { commandToExecute, args, canonicalPath };
|
return { commandToExecute, args, canonicalPath, extensionContext };
|
||||||
};
|
};
|
||||||
|
|||||||
@ -3357,11 +3357,12 @@ describe('Plans Directory Initialization', () => {
|
|||||||
|
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
vi.mocked(fs.promises.mkdir).mockRestore();
|
vi.mocked(fs.promises.mkdir).mockRestore();
|
||||||
vi.mocked(fs.promises.access).mockRestore?.();
|
vi.mocked(fs.mkdirSync).mockRestore?.();
|
||||||
|
vi.mocked(fs.existsSync).mockReturnValue(true); // Reset to default mock behavior
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should add plans directory to workspace context if it exists', async () => {
|
it('should not eagerly create plans directory during initialization', async () => {
|
||||||
vi.spyOn(fs.promises, 'access').mockResolvedValue(undefined);
|
vi.spyOn(fs, 'mkdirSync').mockReturnValue(undefined);
|
||||||
const config = new Config({
|
const config = new Config({
|
||||||
...baseParams,
|
...baseParams,
|
||||||
plan: true,
|
plan: true,
|
||||||
@ -3369,34 +3370,123 @@ describe('Plans Directory Initialization', () => {
|
|||||||
|
|
||||||
await config.initialize();
|
await config.initialize();
|
||||||
|
|
||||||
const plansDir = config.storage.getPlansDir();
|
|
||||||
// Should NOT create the directory eagerly
|
// Should NOT create the directory eagerly
|
||||||
expect(fs.promises.mkdir).not.toHaveBeenCalled();
|
expect(fs.mkdirSync).not.toHaveBeenCalled();
|
||||||
// Should check if it exists
|
|
||||||
expect(fs.promises.access).toHaveBeenCalledWith(plansDir);
|
// Using storage directly to avoid triggering creation
|
||||||
|
const plansDir = config.storage.getPlansDir();
|
||||||
|
const context = config.getWorkspaceContext();
|
||||||
|
expect(context.getDirectories()).not.toContain(plansDir);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create plans directory and add it to workspace context when getPlansDir is called and ApprovalMode.PLAN is active', async () => {
|
||||||
|
vi.spyOn(fs, 'mkdirSync').mockReturnValue(undefined);
|
||||||
|
const config = new Config({
|
||||||
|
...baseParams,
|
||||||
|
plan: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await config.initialize();
|
||||||
|
config.setApprovalMode(ApprovalMode.PLAN);
|
||||||
|
const plansDir = config.getPlansDir();
|
||||||
|
|
||||||
|
expect(fs.mkdirSync).toHaveBeenCalledWith(plansDir, {
|
||||||
|
recursive: true,
|
||||||
|
});
|
||||||
|
|
||||||
const context = config.getWorkspaceContext();
|
const context = config.getWorkspaceContext();
|
||||||
expect(context.getDirectories()).toContain(plansDir);
|
expect(context.getDirectories()).toContain(plansDir);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should NOT add plans directory to workspace context if it does not exist', async () => {
|
it('should NOT create plans directory if ApprovalMode is not PLAN even if plan is enabled', async () => {
|
||||||
vi.spyOn(fs.promises, 'access').mockRejectedValue({ code: 'ENOENT' });
|
vi.spyOn(fs, 'mkdirSync').mockReturnValue(undefined);
|
||||||
const config = new Config({
|
const config = new Config({
|
||||||
...baseParams,
|
...baseParams,
|
||||||
plan: true,
|
plan: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
await config.initialize();
|
await config.initialize();
|
||||||
|
// Default mode is DEFAULT, not PLAN
|
||||||
|
const plansDir = config.getPlansDir();
|
||||||
|
|
||||||
const plansDir = config.storage.getPlansDir();
|
expect(fs.mkdirSync).not.toHaveBeenCalled();
|
||||||
expect(fs.promises.mkdir).not.toHaveBeenCalled();
|
|
||||||
expect(fs.promises.access).toHaveBeenCalledWith(plansDir);
|
|
||||||
|
|
||||||
const context = config.getWorkspaceContext();
|
const context = config.getWorkspaceContext();
|
||||||
expect(context.getDirectories()).not.toContain(plansDir);
|
expect(context.getDirectories()).not.toContain(plansDir);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('should gracefully handle existing directories by relying on mkdirSync recursive: true when in PLAN mode', async () => {
|
||||||
|
vi.spyOn(fs, 'mkdirSync').mockReturnValue(undefined);
|
||||||
|
const config = new Config({
|
||||||
|
...baseParams,
|
||||||
|
plan: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await config.initialize();
|
||||||
|
config.setApprovalMode(ApprovalMode.PLAN);
|
||||||
|
const plansDir = config.getPlansDir();
|
||||||
|
|
||||||
|
// mkdirSync should be called unconditionally
|
||||||
|
expect(fs.mkdirSync).toHaveBeenCalledWith(plansDir, { recursive: true });
|
||||||
|
|
||||||
|
// It MUST still register the directory
|
||||||
|
const context = config.getWorkspaceContext();
|
||||||
|
expect(context.getDirectories()).toContain(plansDir);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should log a warning if the plan directory path is blocked by an existing file (EEXIST) in PLAN mode', async () => {
|
||||||
|
const writeSpy = vi
|
||||||
|
.spyOn(debugLogger, 'error')
|
||||||
|
.mockImplementation(() => {});
|
||||||
|
vi.spyOn(fs, 'mkdirSync').mockImplementation(() => {
|
||||||
|
const err = new Error('File exists') as NodeJS.ErrnoException;
|
||||||
|
err.code = 'EEXIST';
|
||||||
|
throw err;
|
||||||
|
});
|
||||||
|
const config = new Config({
|
||||||
|
...baseParams,
|
||||||
|
plan: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await config.initialize();
|
||||||
|
config.setApprovalMode(ApprovalMode.PLAN);
|
||||||
|
config.getPlansDir();
|
||||||
|
|
||||||
|
expect(writeSpy).toHaveBeenCalledWith(
|
||||||
|
expect.stringMatching(
|
||||||
|
/Failed to initialize active plan directory.*File exists/,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
writeSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should log a warning if mkdirSync fails during getPlansDir (e.g. EACCES) in PLAN mode', async () => {
|
||||||
|
const writeSpy = vi
|
||||||
|
.spyOn(debugLogger, 'error')
|
||||||
|
.mockImplementation(() => {});
|
||||||
|
vi.spyOn(fs, 'mkdirSync').mockImplementation(() => {
|
||||||
|
const err = new Error('Permission denied') as NodeJS.ErrnoException;
|
||||||
|
err.code = 'EACCES';
|
||||||
|
throw err;
|
||||||
|
});
|
||||||
|
const config = new Config({
|
||||||
|
...baseParams,
|
||||||
|
plan: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
await config.initialize();
|
||||||
|
config.setApprovalMode(ApprovalMode.PLAN);
|
||||||
|
config.getPlansDir();
|
||||||
|
|
||||||
|
expect(writeSpy).toHaveBeenCalledWith(
|
||||||
|
expect.stringMatching(
|
||||||
|
/Failed to initialize active plan directory.*Permission denied/,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
writeSpy.mockRestore();
|
||||||
|
});
|
||||||
|
|
||||||
it('should NOT create plans directory or add it to workspace context when plan is disabled', async () => {
|
it('should NOT create plans directory or add it to workspace context when plan is disabled', async () => {
|
||||||
|
vi.spyOn(fs, 'mkdirSync').mockReturnValue(undefined);
|
||||||
const config = new Config({
|
const config = new Config({
|
||||||
...baseParams,
|
...baseParams,
|
||||||
plan: false,
|
plan: false,
|
||||||
@ -3405,9 +3495,10 @@ describe('Plans Directory Initialization', () => {
|
|||||||
await config.initialize();
|
await config.initialize();
|
||||||
|
|
||||||
const plansDir = config.storage.getPlansDir();
|
const plansDir = config.storage.getPlansDir();
|
||||||
expect(fs.promises.mkdir).not.toHaveBeenCalledWith(plansDir, {
|
expect(fs.mkdirSync).not.toHaveBeenCalled();
|
||||||
recursive: true,
|
expect(config.getWorkspaceContext().getDirectories()).not.toContain(
|
||||||
});
|
plansDir,
|
||||||
|
);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@ -6,6 +6,7 @@
|
|||||||
|
|
||||||
import * as fs from 'node:fs';
|
import * as fs from 'node:fs';
|
||||||
import * as path from 'node:path';
|
import * as path from 'node:path';
|
||||||
|
import { getErrorMessage } from '../utils/errors.js';
|
||||||
import { SandboxPolicyManager } from '../policy/sandboxPolicyManager.js';
|
import { SandboxPolicyManager } from '../policy/sandboxPolicyManager.js';
|
||||||
import { inspect } from 'node:util';
|
import { inspect } from 'node:util';
|
||||||
import process from 'node:process';
|
import process from 'node:process';
|
||||||
@ -710,6 +711,7 @@ export interface ConfigParameters {
|
|||||||
plan?: boolean;
|
plan?: boolean;
|
||||||
tracker?: boolean;
|
tracker?: boolean;
|
||||||
planSettings?: PlanSettings;
|
planSettings?: PlanSettings;
|
||||||
|
extensionPlanDirs?: Record<string, string>;
|
||||||
worktreeSettings?: WorktreeSettings;
|
worktreeSettings?: WorktreeSettings;
|
||||||
modelSteering?: boolean;
|
modelSteering?: boolean;
|
||||||
onModelChange?: (model: string) => void;
|
onModelChange?: (model: string) => void;
|
||||||
@ -773,6 +775,9 @@ export class Config implements McpContext, AgentLoopContext {
|
|||||||
private readonly extensionsEnabled: boolean;
|
private readonly extensionsEnabled: boolean;
|
||||||
private mcpServers: Record<string, MCPServerConfig> | undefined;
|
private mcpServers: Record<string, MCPServerConfig> | undefined;
|
||||||
private readonly mcpEnablementCallbacks?: McpEnablementCallbacks;
|
private readonly mcpEnablementCallbacks?: McpEnablementCallbacks;
|
||||||
|
private activeExtensionContext?: string;
|
||||||
|
private initializedPlanDirs = new Set<string>();
|
||||||
|
private readonly extensionPlanDirs: Record<string, string>;
|
||||||
private userMemory: string | HierarchicalMemory;
|
private userMemory: string | HierarchicalMemory;
|
||||||
private geminiMdFileCount: number;
|
private geminiMdFileCount: number;
|
||||||
private geminiMdFilePaths: string[];
|
private geminiMdFilePaths: string[];
|
||||||
@ -1037,6 +1042,7 @@ export class Config implements McpContext, AgentLoopContext {
|
|||||||
this.mcpServerCommand = params.mcpServerCommand;
|
this.mcpServerCommand = params.mcpServerCommand;
|
||||||
this.mcpServers = params.mcpServers;
|
this.mcpServers = params.mcpServers;
|
||||||
this.mcpEnablementCallbacks = params.mcpEnablementCallbacks;
|
this.mcpEnablementCallbacks = params.mcpEnablementCallbacks;
|
||||||
|
this.extensionPlanDirs = params.extensionPlanDirs ?? {};
|
||||||
this.mcpEnabled = params.mcpEnabled ?? true;
|
this.mcpEnabled = params.mcpEnabled ?? true;
|
||||||
this.extensionsEnabled = params.extensionsEnabled ?? true;
|
this.extensionsEnabled = params.extensionsEnabled ?? true;
|
||||||
this.allowedMcpServers = params.allowedMcpServers ?? [];
|
this.allowedMcpServers = params.allowedMcpServers ?? [];
|
||||||
@ -1408,20 +1414,6 @@ export class Config implements McpContext, AgentLoopContext {
|
|||||||
this.workspaceContext.addDirectory(dir);
|
this.workspaceContext.addDirectory(dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add plans directory to workspace context for plan file storage
|
|
||||||
if (this.planEnabled) {
|
|
||||||
const plansDir = this.storage.getPlansDir();
|
|
||||||
try {
|
|
||||||
await fs.promises.access(plansDir);
|
|
||||||
this.workspaceContext.addDirectory(plansDir);
|
|
||||||
} catch {
|
|
||||||
// Directory does not exist yet, so we don't add it to the workspace context.
|
|
||||||
// It will be created when the first plan is written. Since custom plan
|
|
||||||
// directories must be within the project root, they are automatically
|
|
||||||
// covered by the project-wide file discovery once created.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Initialize centralized FileDiscoveryService
|
// Initialize centralized FileDiscoveryService
|
||||||
const discoverToolsHandle = startupProfiler.start('discover_tools');
|
const discoverToolsHandle = startupProfiler.start('discover_tools');
|
||||||
this.getFileService();
|
this.getFileService();
|
||||||
@ -2251,6 +2243,57 @@ export class Config implements McpContext, AgentLoopContext {
|
|||||||
return this.mcpEnabled;
|
return this.mcpEnabled;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
getActiveExtensionContext(): string | undefined {
|
||||||
|
return this.activeExtensionContext;
|
||||||
|
}
|
||||||
|
|
||||||
|
setActiveExtensionContext(context: string | undefined): void {
|
||||||
|
this.activeExtensionContext = context;
|
||||||
|
}
|
||||||
|
|
||||||
|
hasExtensionPlanDir(name: string): boolean {
|
||||||
|
return !!this.extensionPlanDirs[name];
|
||||||
|
}
|
||||||
|
|
||||||
|
getActiveExtensionPlanDir(): string | undefined {
|
||||||
|
if (this.activeExtensionContext) {
|
||||||
|
return this.extensionPlanDirs[this.activeExtensionContext];
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
getPlansDir(): string {
|
||||||
|
const plansDir = this.storage.getPlansDir(this.getActiveExtensionPlanDir());
|
||||||
|
|
||||||
|
if (this.initializedPlanDirs.has(plansDir)) {
|
||||||
|
return plansDir;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.planEnabled && this.isPlanMode()) {
|
||||||
|
try {
|
||||||
|
fs.mkdirSync(plansDir, { recursive: true });
|
||||||
|
|
||||||
|
let realPlansDir = plansDir;
|
||||||
|
try {
|
||||||
|
realPlansDir = resolveToRealPath(plansDir);
|
||||||
|
} catch {
|
||||||
|
// Ignore failures in mock environments
|
||||||
|
}
|
||||||
|
this.workspaceContext.addDirectory(realPlansDir);
|
||||||
|
} catch (e: unknown) {
|
||||||
|
debugLogger.error(
|
||||||
|
`Failed to initialize active plan directory at '${plansDir}': ${getErrorMessage(e)}`,
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
this.initializedPlanDirs.add(plansDir);
|
||||||
|
}
|
||||||
|
} else if (!this.planEnabled) {
|
||||||
|
this.initializedPlanDirs.add(plansDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
return plansDir;
|
||||||
|
}
|
||||||
|
|
||||||
getMcpEnablementCallbacks(): McpEnablementCallbacks | undefined {
|
getMcpEnablementCallbacks(): McpEnablementCallbacks | undefined {
|
||||||
return this.mcpEnablementCallbacks;
|
return this.mcpEnablementCallbacks;
|
||||||
}
|
}
|
||||||
|
|||||||
@ -10,6 +10,7 @@ import * as path from 'node:path';
|
|||||||
import * as os from 'node:os';
|
import * as os from 'node:os';
|
||||||
import { lock } from 'proper-lockfile';
|
import { lock } from 'proper-lockfile';
|
||||||
import { debugLogger } from '../utils/debugLogger.js';
|
import { debugLogger } from '../utils/debugLogger.js';
|
||||||
|
import { isNodeError, getErrorMessage } from '../utils/errors.js';
|
||||||
|
|
||||||
export interface RegistryData {
|
export interface RegistryData {
|
||||||
projects: Record<string, string>;
|
projects: Record<string, string>;
|
||||||
@ -62,7 +63,7 @@ export class ProjectRegistry {
|
|||||||
const content = await fs.promises.readFile(this.registryPath, 'utf8');
|
const content = await fs.promises.readFile(this.registryPath, 'utf8');
|
||||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
|
||||||
return JSON.parse(content);
|
return JSON.parse(content);
|
||||||
} catch (e) {
|
} catch (e: unknown) {
|
||||||
debugLogger.debug('Failed to load registry: ', e);
|
debugLogger.debug('Failed to load registry: ', e);
|
||||||
// If the registry is corrupted, we'll start fresh to avoid blocking the CLI
|
// If the registry is corrupted, we'll start fresh to avoid blocking the CLI
|
||||||
return { projects: {} };
|
return { projects: {} };
|
||||||
@ -83,17 +84,37 @@ export class ProjectRegistry {
|
|||||||
await fs.promises.mkdir(dir, { recursive: true });
|
await fs.promises.mkdir(dir, { recursive: true });
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
let attempt = 0;
|
||||||
const content = JSON.stringify(data, null, 2);
|
const maxAttempts = 5;
|
||||||
// Use a randomized tmp path to avoid ENOENT crashes when save() is called concurrently
|
const retryDelayMs = 100;
|
||||||
const tmpPath = this.registryPath + '.' + randomUUID() + '.tmp';
|
|
||||||
await fs.promises.writeFile(tmpPath, content, 'utf8');
|
while (attempt < maxAttempts) {
|
||||||
await fs.promises.rename(tmpPath, this.registryPath);
|
try {
|
||||||
} catch (error) {
|
const content = JSON.stringify(data, null, 2);
|
||||||
debugLogger.error(
|
// Use a randomized tmp path to avoid ENOENT crashes when save() is called concurrently
|
||||||
`Failed to save project registry to ${this.registryPath}:`,
|
const tmpPath = this.registryPath + '.' + randomUUID() + '.tmp';
|
||||||
error,
|
await fs.promises.writeFile(tmpPath, content, 'utf8');
|
||||||
);
|
await fs.promises.rename(tmpPath, this.registryPath);
|
||||||
|
return; // Success
|
||||||
|
} catch (error: unknown) {
|
||||||
|
attempt++;
|
||||||
|
const isRetryable =
|
||||||
|
isNodeError(error) &&
|
||||||
|
(error.code === 'EPERM' ||
|
||||||
|
error.code === 'EBUSY' ||
|
||||||
|
error.code === 'EACCES');
|
||||||
|
|
||||||
|
if (attempt >= maxAttempts || !isRetryable) {
|
||||||
|
debugLogger.error(
|
||||||
|
`Failed to save project registry to ${this.registryPath} after ${attempt} attempts:`,
|
||||||
|
getErrorMessage(error),
|
||||||
|
);
|
||||||
|
return; // Stop trying
|
||||||
|
} else {
|
||||||
|
// Wait before retrying (exponential backoff could be used here too)
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, retryDelayMs));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -177,7 +198,7 @@ export class ProjectRegistry {
|
|||||||
if (this.normalizePath(owner) !== this.normalizePath(projectPath)) {
|
if (this.normalizePath(owner) !== this.normalizePath(projectPath)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e: unknown) {
|
||||||
debugLogger.debug(
|
debugLogger.debug(
|
||||||
`Failed to read ownership marker ${markerPath}:`,
|
`Failed to read ownership marker ${markerPath}:`,
|
||||||
e,
|
e,
|
||||||
@ -220,7 +241,7 @@ export class ProjectRegistry {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e: unknown) {
|
||||||
debugLogger.debug(`Failed to scan base dir ${baseDir}:`, e);
|
debugLogger.debug(`Failed to scan base dir ${baseDir}:`, e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -239,6 +260,12 @@ export class ProjectRegistry {
|
|||||||
const existingIds = new Set(Object.values(existingMappings));
|
const existingIds = new Set(Object.values(existingMappings));
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
|
if (counter > 1000) {
|
||||||
|
throw new Error(
|
||||||
|
'Failed to generate a unique project short ID after 1000 attempts. Check for fs mocks or filesystem permission issues.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const candidate = counter === 0 ? slug : `${slug}-${counter}`;
|
const candidate = counter === 0 ? slug : `${slug}-${counter}`;
|
||||||
counter++;
|
counter++;
|
||||||
|
|
||||||
|
|||||||
@ -358,6 +358,26 @@ describe('Storage – additional helpers', () => {
|
|||||||
expected: '',
|
expected: '',
|
||||||
expectedError: `Custom plans directory 'symlink-to-outside' resolves to '${path.resolve('/outside/project/root')}', which is outside the project root '${resolveToRealPath(projectRoot)}'.`,
|
expectedError: `Custom plans directory 'symlink-to-outside' resolves to '${path.resolve('/outside/project/root')}', which is outside the project root '${resolveToRealPath(projectRoot)}'.`,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: 'non-existent plan dir in a symlinked project root',
|
||||||
|
customDir: 'new-plans',
|
||||||
|
setup: () => {
|
||||||
|
vi.mocked(fs.realpathSync).mockImplementation((p: fs.PathLike) => {
|
||||||
|
const pStr = p.toString();
|
||||||
|
if (pStr === projectRoot) {
|
||||||
|
return '/private/tmp/project';
|
||||||
|
}
|
||||||
|
if (pStr.includes('new-plans')) {
|
||||||
|
const err = new Error('ENOENT') as NodeJS.ErrnoException;
|
||||||
|
err.code = 'ENOENT';
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
return pStr;
|
||||||
|
});
|
||||||
|
return () => vi.mocked(fs.realpathSync).mockRestore();
|
||||||
|
},
|
||||||
|
expected: path.resolve(projectRoot, 'new-plans'),
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
testCases.forEach(({ name, customDir, expected, expectedError, setup }) => {
|
testCases.forEach(({ name, customDir, expected, expectedError, setup }) => {
|
||||||
|
|||||||
@ -18,6 +18,7 @@ import {
|
|||||||
} from '../utils/paths.js';
|
} from '../utils/paths.js';
|
||||||
import { ProjectRegistry } from './projectRegistry.js';
|
import { ProjectRegistry } from './projectRegistry.js';
|
||||||
import { StorageMigration } from './storageMigration.js';
|
import { StorageMigration } from './storageMigration.js';
|
||||||
|
import { isNodeError } from '../utils/errors.js';
|
||||||
|
|
||||||
export const OAUTH_FILE = 'oauth_creds.json';
|
export const OAUTH_FILE = 'oauth_creds.json';
|
||||||
const TMP_DIR_NAME = 'tmp';
|
const TMP_DIR_NAME = 'tmp';
|
||||||
@ -320,18 +321,26 @@ export class Storage {
|
|||||||
return path.join(this.getProjectTempDir(), 'tracker');
|
return path.join(this.getProjectTempDir(), 'tracker');
|
||||||
}
|
}
|
||||||
|
|
||||||
getPlansDir(): string {
|
getPlansDir(extensionPlanDir?: string): string {
|
||||||
if (this.customPlansDir) {
|
const customDir = extensionPlanDir || this.customPlansDir;
|
||||||
const resolvedPath = path.resolve(
|
if (customDir) {
|
||||||
this.getProjectRoot(),
|
const resolvedPath = path.resolve(this.getProjectRoot(), customDir);
|
||||||
this.customPlansDir,
|
|
||||||
);
|
|
||||||
const realProjectRoot = resolveToRealPath(this.getProjectRoot());
|
const realProjectRoot = resolveToRealPath(this.getProjectRoot());
|
||||||
const realResolvedPath = resolveToRealPath(resolvedPath);
|
let realResolvedPath = resolvedPath;
|
||||||
|
|
||||||
|
try {
|
||||||
|
realResolvedPath = resolveToRealPath(resolvedPath);
|
||||||
|
} catch (e: unknown) {
|
||||||
|
if (!(isNodeError(e) && (e.code === 'ENOENT' || e.code === 'EISDIR'))) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
// Construct the fallback path safely against the real project root
|
||||||
|
realResolvedPath = path.resolve(realProjectRoot, customDir);
|
||||||
|
}
|
||||||
|
|
||||||
if (!isSubpath(realProjectRoot, realResolvedPath)) {
|
if (!isSubpath(realProjectRoot, realResolvedPath)) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Custom plans directory '${this.customPlansDir}' resolves to '${realResolvedPath}', which is outside the project root '${realProjectRoot}'.`,
|
`Custom plans directory '${customDir}' resolves to '${realResolvedPath}', which is outside the project root '${realProjectRoot}'.`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@ -572,7 +572,7 @@ For example:
|
|||||||
|
|
||||||
# Active Approval Mode: Plan
|
# Active Approval Mode: Plan
|
||||||
|
|
||||||
You are operating in **Plan Mode**. Your goal is to produce an implementation plan in \`/tmp/project-temp/plans/\` and get user approval before editing source code.
|
You are operating in **Plan Mode**. Your goal is to produce an implementation plan in \`/tmp/plans/\` and get user approval before editing source code.
|
||||||
|
|
||||||
## Available Tools
|
## Available Tools
|
||||||
The following tools are available in Plan Mode:
|
The following tools are available in Plan Mode:
|
||||||
@ -588,8 +588,8 @@ The following tools are available in Plan Mode:
|
|||||||
</available_tools>
|
</available_tools>
|
||||||
|
|
||||||
## Rules
|
## Rules
|
||||||
1. **Read-Only:** You cannot modify source code. You may ONLY use read-only tools to explore, and you can only write to \`/tmp/project-temp/plans/\`. If the user asks you to modify source code directly, you MUST explain that you are in Plan Mode and must first create a plan and get approval.
|
1. **Read-Only:** You cannot modify source code. You may ONLY use read-only tools to explore, and you can only write to \`/tmp/plans/\`. If the user asks you to modify source code directly, you MUST explain that you are in Plan Mode and must first create a plan and get approval.
|
||||||
2. **Write Constraint:** \`write_file\` and \`replace\` may ONLY be used to write .md plan files to \`/tmp/project-temp/plans/\`. They cannot modify source code.
|
2. **Write Constraint:** \`write_file\` and \`replace\` may ONLY be used to write .md plan files to \`/tmp/plans/\`. They cannot modify source code.
|
||||||
3. **Efficiency:** Autonomously combine discovery and drafting phases to minimize conversational turns. If the request is ambiguous, use \`ask_user\` to clarify. Use multi-select to offer flexibility and include detailed descriptions for each option to help the user understand the implications of their choice.
|
3. **Efficiency:** Autonomously combine discovery and drafting phases to minimize conversational turns. If the request is ambiguous, use \`ask_user\` to clarify. Use multi-select to offer flexibility and include detailed descriptions for each option to help the user understand the implications of their choice.
|
||||||
4. **Inquiries and Directives:** Distinguish between Inquiries and Directives to minimize unnecessary planning.
|
4. **Inquiries and Directives:** Distinguish between Inquiries and Directives to minimize unnecessary planning.
|
||||||
- **Inquiries:** If the request is an **Inquiry** (e.g., "How does X work?"), answer directly. DO NOT create a plan.
|
- **Inquiries:** If the request is an **Inquiry** (e.g., "How does X work?"), answer directly. DO NOT create a plan.
|
||||||
@ -612,7 +612,7 @@ The depth of your consultation should be proportional to the task's complexity.
|
|||||||
**CRITICAL:** You MUST NOT proceed to Step 3 (Draft) or Step 4 (Review & Approval) in the same turn as your initial strategy proposal. You MUST wait for user feedback and reach a clear agreement before drafting or submitting the plan.
|
**CRITICAL:** You MUST NOT proceed to Step 3 (Draft) or Step 4 (Review & Approval) in the same turn as your initial strategy proposal. You MUST wait for user feedback and reach a clear agreement before drafting or submitting the plan.
|
||||||
|
|
||||||
### 3. Draft
|
### 3. Draft
|
||||||
Write the implementation plan to \`/tmp/project-temp/plans/\`. The plan's structure adapts to the task:
|
Write the implementation plan to \`/tmp/plans/\`. The plan's structure adapts to the task:
|
||||||
- **Simple Tasks:** Include a bulleted list of specific **Changes** and **Verification** steps.
|
- **Simple Tasks:** Include a bulleted list of specific **Changes** and **Verification** steps.
|
||||||
- **Standard Tasks:** Include an **Objective**, **Key Files & Context**, **Implementation Steps**, and **Verification & Testing**.
|
- **Standard Tasks:** Include an **Objective**, **Key Files & Context**, **Implementation Steps**, and **Verification & Testing**.
|
||||||
- **Complex Tasks:** Include **Background & Motivation**, **Scope & Impact**, **Proposed Solution**, **Alternatives Considered**, a phased **Implementation Plan**, **Verification**, and **Migration & Rollback** strategies.
|
- **Complex Tasks:** Include **Background & Motivation**, **Scope & Impact**, **Proposed Solution**, **Alternatives Considered**, a phased **Implementation Plan**, **Verification**, and **Migration & Rollback** strategies.
|
||||||
|
|||||||
@ -93,9 +93,10 @@ describe('Core System Prompt (prompts.ts)', () => {
|
|||||||
getToolRegistry: vi.fn().mockReturnValue(mockRegistry),
|
getToolRegistry: vi.fn().mockReturnValue(mockRegistry),
|
||||||
getEnableShellOutputEfficiency: vi.fn().mockReturnValue(true),
|
getEnableShellOutputEfficiency: vi.fn().mockReturnValue(true),
|
||||||
getSandboxEnabled: vi.fn().mockReturnValue(false),
|
getSandboxEnabled: vi.fn().mockReturnValue(false),
|
||||||
|
getPlansDir: vi.fn().mockReturnValue('/tmp/plans'),
|
||||||
storage: {
|
storage: {
|
||||||
getProjectTempDir: vi.fn().mockReturnValue('/tmp/project-temp'),
|
getProjectTempDir: vi.fn().mockReturnValue('/tmp/project-temp'),
|
||||||
getPlansDir: vi.fn().mockReturnValue('/tmp/project-temp/plans'),
|
getPlansDir: vi.fn().mockReturnValue('/tmp/plans'),
|
||||||
getProjectTempTrackerDir: vi
|
getProjectTempTrackerDir: vi
|
||||||
.fn()
|
.fn()
|
||||||
.mockReturnValue('/mock/.gemini/tmp/session/tracker'),
|
.mockReturnValue('/mock/.gemini/tmp/session/tracker'),
|
||||||
@ -451,6 +452,7 @@ describe('Core System Prompt (prompts.ts)', () => {
|
|||||||
getToolRegistry: vi.fn().mockReturnValue(mockToolRegistry),
|
getToolRegistry: vi.fn().mockReturnValue(mockToolRegistry),
|
||||||
getEnableShellOutputEfficiency: vi.fn().mockReturnValue(true),
|
getEnableShellOutputEfficiency: vi.fn().mockReturnValue(true),
|
||||||
getSandboxEnabled: vi.fn().mockReturnValue(false),
|
getSandboxEnabled: vi.fn().mockReturnValue(false),
|
||||||
|
getPlansDir: vi.fn().mockReturnValue('/tmp/plans'),
|
||||||
storage: {
|
storage: {
|
||||||
getProjectTempDir: vi.fn().mockReturnValue('/tmp/project-temp'),
|
getProjectTempDir: vi.fn().mockReturnValue('/tmp/project-temp'),
|
||||||
},
|
},
|
||||||
|
|||||||
@ -61,6 +61,7 @@ describe('PromptProvider', () => {
|
|||||||
topicState: new TopicState(),
|
topicState: new TopicState(),
|
||||||
getEnableShellOutputEfficiency: vi.fn().mockReturnValue(true),
|
getEnableShellOutputEfficiency: vi.fn().mockReturnValue(true),
|
||||||
getSandboxEnabled: vi.fn().mockReturnValue(false),
|
getSandboxEnabled: vi.fn().mockReturnValue(false),
|
||||||
|
getPlansDir: vi.fn().mockReturnValue('/tmp/project-temp/plans'),
|
||||||
storage: {
|
storage: {
|
||||||
getProjectTempDir: vi.fn().mockReturnValue('/tmp/project-temp'),
|
getProjectTempDir: vi.fn().mockReturnValue('/tmp/project-temp'),
|
||||||
getPlansDir: vi.fn().mockReturnValue('/tmp/project-temp/plans'),
|
getPlansDir: vi.fn().mockReturnValue('/tmp/project-temp/plans'),
|
||||||
|
|||||||
@ -195,7 +195,7 @@ export class PromptProvider {
|
|||||||
() => ({
|
() => ({
|
||||||
interactive: interactiveMode,
|
interactive: interactiveMode,
|
||||||
planModeToolsList,
|
planModeToolsList,
|
||||||
plansDir: context.config.storage.getPlansDir(),
|
plansDir: context.config.getPlansDir(),
|
||||||
approvedPlanPath: context.config.getApprovedPlanPath(),
|
approvedPlanPath: context.config.getApprovedPlanPath(),
|
||||||
}),
|
}),
|
||||||
isPlanMode,
|
isPlanMode,
|
||||||
|
|||||||
@ -132,9 +132,10 @@ describe('EditTool', () => {
|
|||||||
getDisableLLMCorrection: vi.fn(() => true),
|
getDisableLLMCorrection: vi.fn(() => true),
|
||||||
getExperiments: () => {},
|
getExperiments: () => {},
|
||||||
isPlanMode: vi.fn(() => false),
|
isPlanMode: vi.fn(() => false),
|
||||||
|
getPlansDir: vi.fn().mockReturnValue('/tmp/project/plans'),
|
||||||
storage: {
|
storage: {
|
||||||
getProjectTempDir: vi.fn().mockReturnValue('/tmp/project'),
|
getProjectTempDir: vi.fn().mockReturnValue('/tmp/project'),
|
||||||
getPlansDir: vi.fn().mockReturnValue('/tmp/plans'),
|
getPlansDir: vi.fn().mockReturnValue('/tmp/project/plans'),
|
||||||
},
|
},
|
||||||
isPathAllowed(this: Config, absolutePath: string): boolean {
|
isPathAllowed(this: Config, absolutePath: string): boolean {
|
||||||
const workspaceContext = this.getWorkspaceContext();
|
const workspaceContext = this.getWorkspaceContext();
|
||||||
@ -1334,6 +1335,7 @@ function doIt() {
|
|||||||
fs.mkdirSync(plansDir);
|
fs.mkdirSync(plansDir);
|
||||||
|
|
||||||
vi.mocked(mockConfig.isPlanMode).mockReturnValue(true);
|
vi.mocked(mockConfig.isPlanMode).mockReturnValue(true);
|
||||||
|
vi.mocked(mockConfig.getPlansDir).mockReturnValue(plansDir);
|
||||||
vi.mocked(mockConfig.storage.getPlansDir).mockReturnValue(plansDir);
|
vi.mocked(mockConfig.storage.getPlansDir).mockReturnValue(plansDir);
|
||||||
|
|
||||||
const filePath = path.join(rootDir, 'test-file.txt');
|
const filePath = path.join(rootDir, 'test-file.txt');
|
||||||
|
|||||||
@ -466,10 +466,7 @@ class EditToolInvocation
|
|||||||
);
|
);
|
||||||
if (this.config.isPlanMode()) {
|
if (this.config.isPlanMode()) {
|
||||||
const safeFilename = path.basename(this.params.file_path);
|
const safeFilename = path.basename(this.params.file_path);
|
||||||
this.resolvedPath = path.join(
|
this.resolvedPath = path.join(this.config.getPlansDir(), safeFilename);
|
||||||
this.config.storage.getPlansDir(),
|
|
||||||
safeFilename,
|
|
||||||
);
|
|
||||||
} else if (!path.isAbsolute(this.params.file_path)) {
|
} else if (!path.isAbsolute(this.params.file_path)) {
|
||||||
const result = correctPath(this.params.file_path, this.config);
|
const result = correctPath(this.params.file_path, this.config);
|
||||||
if (result.success) {
|
if (result.success) {
|
||||||
|
|||||||
@ -11,7 +11,6 @@ import type { Config } from '../config/config.js';
|
|||||||
import type { MessageBus } from '../confirmation-bus/message-bus.js';
|
import type { MessageBus } from '../confirmation-bus/message-bus.js';
|
||||||
import { ToolConfirmationOutcome } from './tools.js';
|
import { ToolConfirmationOutcome } from './tools.js';
|
||||||
import { ApprovalMode } from '../policy/types.js';
|
import { ApprovalMode } from '../policy/types.js';
|
||||||
import fs from 'node:fs';
|
|
||||||
|
|
||||||
vi.mock('node:fs', async () => {
|
vi.mock('node:fs', async () => {
|
||||||
const actual = await vi.importActual<typeof import('node:fs')>('node:fs');
|
const actual = await vi.importActual<typeof import('node:fs')>('node:fs');
|
||||||
@ -39,6 +38,7 @@ describe('EnterPlanModeTool', () => {
|
|||||||
|
|
||||||
mockConfig = {
|
mockConfig = {
|
||||||
setApprovalMode: vi.fn(),
|
setApprovalMode: vi.fn(),
|
||||||
|
getPlansDir: vi.fn().mockReturnValue('/mock/plans/dir'),
|
||||||
storage: {
|
storage: {
|
||||||
getPlansDir: vi.fn().mockReturnValue('/mock/plans/dir'),
|
getPlansDir: vi.fn().mockReturnValue('/mock/plans/dir'),
|
||||||
} as unknown as Config['storage'],
|
} as unknown as Config['storage'],
|
||||||
@ -119,7 +119,6 @@ describe('EnterPlanModeTool', () => {
|
|||||||
describe('execute', () => {
|
describe('execute', () => {
|
||||||
it('should set approval mode to PLAN and return message', async () => {
|
it('should set approval mode to PLAN and return message', async () => {
|
||||||
const invocation = tool.build({});
|
const invocation = tool.build({});
|
||||||
vi.mocked(fs.existsSync).mockReturnValue(true);
|
|
||||||
|
|
||||||
const result = await invocation.execute({
|
const result = await invocation.execute({
|
||||||
abortSignal: new AbortController().signal,
|
abortSignal: new AbortController().signal,
|
||||||
@ -132,21 +131,20 @@ describe('EnterPlanModeTool', () => {
|
|||||||
expect(result.returnDisplay).toBe('Switching to Plan mode');
|
expect(result.returnDisplay).toBe('Switching to Plan mode');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should create plans directory if it does not exist', async () => {
|
it('should call getPlansDir immediately after setting ApprovalMode.PLAN to ensure JIT directory creation', async () => {
|
||||||
const invocation = tool.build({});
|
const invocation = tool.build({});
|
||||||
vi.mocked(fs.existsSync).mockReturnValue(false);
|
|
||||||
|
|
||||||
await invocation.execute({ abortSignal: new AbortController().signal });
|
await invocation.execute({ abortSignal: new AbortController().signal });
|
||||||
|
|
||||||
expect(fs.mkdirSync).toHaveBeenCalledWith('/mock/plans/dir', {
|
expect(mockConfig.setApprovalMode).toHaveBeenCalledWith(
|
||||||
recursive: true,
|
ApprovalMode.PLAN,
|
||||||
});
|
);
|
||||||
|
expect(mockConfig.getPlansDir).toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should include optional reason in output display but not in llmContent', async () => {
|
it('should include optional reason in output display but not in llmContent', async () => {
|
||||||
const reason = 'Design new database schema';
|
const reason = 'Design new database schema';
|
||||||
const invocation = tool.build({ reason });
|
const invocation = tool.build({ reason });
|
||||||
vi.mocked(fs.existsSync).mockReturnValue(true);
|
|
||||||
|
|
||||||
const result = await invocation.execute({
|
const result = await invocation.execute({
|
||||||
abortSignal: new AbortController().signal,
|
abortSignal: new AbortController().signal,
|
||||||
|
|||||||
@ -4,7 +4,6 @@
|
|||||||
* SPDX-License-Identifier: Apache-2.0
|
* SPDX-License-Identifier: Apache-2.0
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import fs from 'node:fs';
|
|
||||||
import {
|
import {
|
||||||
BaseDeclarativeTool,
|
BaseDeclarativeTool,
|
||||||
BaseToolInvocation,
|
BaseToolInvocation,
|
||||||
@ -125,17 +124,16 @@ export class EnterPlanModeInvocation extends BaseToolInvocation<
|
|||||||
|
|
||||||
this.config.setApprovalMode(ApprovalMode.PLAN);
|
this.config.setApprovalMode(ApprovalMode.PLAN);
|
||||||
|
|
||||||
// Ensure plans directory exists so that the agent can write the plan file.
|
// Trigger JIT provisioning immediately. In sandboxed environments,
|
||||||
// In sandboxed environments, the plans directory must exist on the host
|
// the plans directory must exist on the host before it can be bound/allowed.
|
||||||
// before it can be bound/allowed in the sandbox.
|
try {
|
||||||
const plansDir = this.config.storage.getPlansDir();
|
this.config.getPlansDir();
|
||||||
if (!fs.existsSync(plansDir)) {
|
} catch (e) {
|
||||||
try {
|
// Log error but don't fail; write_file will try again later if possible
|
||||||
fs.mkdirSync(plansDir, { recursive: true });
|
debugLogger.error(
|
||||||
} catch (e) {
|
'Failed to create plans directory during initialization.',
|
||||||
// Log error but don't fail; write_file will try again later
|
e,
|
||||||
debugLogger.error(`Failed to create plans directory: ${plansDir}`, e);
|
);
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@ -44,6 +44,7 @@ describe('ExitPlanModeTool', () => {
|
|||||||
getTargetDir: vi.fn().mockReturnValue(tempRootDir),
|
getTargetDir: vi.fn().mockReturnValue(tempRootDir),
|
||||||
setApprovalMode: vi.fn(),
|
setApprovalMode: vi.fn(),
|
||||||
setApprovedPlanPath: vi.fn(),
|
setApprovedPlanPath: vi.fn(),
|
||||||
|
getPlansDir: vi.fn().mockReturnValue(mockPlansDir),
|
||||||
storage: {
|
storage: {
|
||||||
getPlansDir: vi.fn().mockReturnValue(mockPlansDir),
|
getPlansDir: vi.fn().mockReturnValue(mockPlansDir),
|
||||||
} as unknown as Config['storage'],
|
} as unknown as Config['storage'],
|
||||||
|
|||||||
@ -61,11 +61,8 @@ export class ExitPlanModeTool extends BaseDeclarativeTool<
|
|||||||
}
|
}
|
||||||
|
|
||||||
const safeFilename = path.basename(params.plan_filename);
|
const safeFilename = path.basename(params.plan_filename);
|
||||||
const plansDir = resolveToRealPath(this.config.storage.getPlansDir());
|
const plansDir = resolveToRealPath(this.config.getPlansDir());
|
||||||
const resolvedPath = path.join(
|
const resolvedPath = path.join(this.config.getPlansDir(), safeFilename);
|
||||||
this.config.storage.getPlansDir(),
|
|
||||||
safeFilename,
|
|
||||||
);
|
|
||||||
|
|
||||||
const realPath = resolveToRealPath(resolvedPath);
|
const realPath = resolveToRealPath(resolvedPath);
|
||||||
|
|
||||||
@ -121,7 +118,7 @@ export class ExitPlanModeInvocation extends BaseToolInvocation<
|
|||||||
|
|
||||||
const pathError = await validatePlanPath(
|
const pathError = await validatePlanPath(
|
||||||
this.params.plan_filename,
|
this.params.plan_filename,
|
||||||
this.config.storage.getPlansDir(),
|
this.config.getPlansDir(),
|
||||||
);
|
);
|
||||||
if (pathError) {
|
if (pathError) {
|
||||||
this.planValidationError = pathError;
|
this.planValidationError = pathError;
|
||||||
@ -171,7 +168,7 @@ export class ExitPlanModeInvocation extends BaseToolInvocation<
|
|||||||
}
|
}
|
||||||
|
|
||||||
getDescription(): string {
|
getDescription(): string {
|
||||||
return `Requesting plan approval for: ${path.join(this.config.storage.getPlansDir(), this.params.plan_filename)}`;
|
return `Requesting plan approval for: ${path.join(this.config.getPlansDir(), this.params.plan_filename)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -180,7 +177,7 @@ export class ExitPlanModeInvocation extends BaseToolInvocation<
|
|||||||
*/
|
*/
|
||||||
private getResolvedPlanPath(): string {
|
private getResolvedPlanPath(): string {
|
||||||
const safeFilename = path.basename(this.params.plan_filename);
|
const safeFilename = path.basename(this.params.plan_filename);
|
||||||
return path.join(this.config.storage.getPlansDir(), safeFilename);
|
return path.join(this.config.getPlansDir(), safeFilename);
|
||||||
}
|
}
|
||||||
|
|
||||||
async execute({ abortSignal: _signal }: ExecuteOptions): Promise<ToolResult> {
|
async execute({ abortSignal: _signal }: ExecuteOptions): Promise<ToolResult> {
|
||||||
|
|||||||
@ -634,7 +634,7 @@ export class ToolRegistry {
|
|||||||
*/
|
*/
|
||||||
getFunctionDeclarations(modelId?: string): FunctionDeclaration[] {
|
getFunctionDeclarations(modelId?: string): FunctionDeclaration[] {
|
||||||
const isPlanMode = this.config.getApprovalMode() === ApprovalMode.PLAN;
|
const isPlanMode = this.config.getApprovalMode() === ApprovalMode.PLAN;
|
||||||
const plansDir = this.config.storage.getPlansDir();
|
const plansDir = this.config.getPlansDir();
|
||||||
|
|
||||||
const declarations: FunctionDeclaration[] = [];
|
const declarations: FunctionDeclaration[] = [];
|
||||||
const seenNames = new Set<string>();
|
const seenNames = new Set<string>();
|
||||||
|
|||||||
@ -107,6 +107,7 @@ const mockConfigInternal = {
|
|||||||
getDisableLLMCorrection: vi.fn(() => true),
|
getDisableLLMCorrection: vi.fn(() => true),
|
||||||
isPlanMode: vi.fn(() => false),
|
isPlanMode: vi.fn(() => false),
|
||||||
getActiveModel: () => 'test-model',
|
getActiveModel: () => 'test-model',
|
||||||
|
getPlansDir: vi.fn().mockReturnValue('/tmp/plans'),
|
||||||
storage: {
|
storage: {
|
||||||
getProjectTempDir: vi.fn().mockReturnValue('/tmp/project'),
|
getProjectTempDir: vi.fn().mockReturnValue('/tmp/project'),
|
||||||
},
|
},
|
||||||
|
|||||||
@ -169,10 +169,7 @@ class WriteFileToolInvocation extends BaseToolInvocation<
|
|||||||
|
|
||||||
if (this.config.isPlanMode()) {
|
if (this.config.isPlanMode()) {
|
||||||
const safeFilename = path.basename(this.params.file_path);
|
const safeFilename = path.basename(this.params.file_path);
|
||||||
this.resolvedPath = path.join(
|
this.resolvedPath = path.join(this.config.getPlansDir(), safeFilename);
|
||||||
this.config.storage.getPlansDir(),
|
|
||||||
safeFilename,
|
|
||||||
);
|
|
||||||
} else {
|
} else {
|
||||||
this.resolvedPath = path.resolve(
|
this.resolvedPath = path.resolve(
|
||||||
this.config.getTargetDir(),
|
this.config.getTargetDir(),
|
||||||
|
|||||||
@ -70,7 +70,11 @@ if (!geminiSandbox) {
|
|||||||
geminiSandbox = process.env.GEMINI_SANDBOX;
|
geminiSandbox = process.env.GEMINI_SANDBOX;
|
||||||
}
|
}
|
||||||
|
|
||||||
geminiSandbox = (geminiSandbox || '').toLowerCase();
|
if (typeof geminiSandbox === 'object' && geminiSandbox !== null) {
|
||||||
|
geminiSandbox = geminiSandbox.enabled ? 'true' : 'false';
|
||||||
|
}
|
||||||
|
|
||||||
|
geminiSandbox = (geminiSandbox || '').toString().toLowerCase();
|
||||||
|
|
||||||
const commandExists = (cmd) => {
|
const commandExists = (cmd) => {
|
||||||
const checkCommand = os.platform() === 'win32' ? 'where' : 'command -v';
|
const checkCommand = os.platform() === 'win32' ? 'where' : 'command -v';
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user