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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { ExitPlanModeTool, ExitPlanModeInvocation } from './exit-plan-mode.js';
import { createMockMessageBus } from '../test-utils/mock-message-bus.js';
import path from 'node:path';
import type { Config } from '../config/config.js';
import type { MessageBus } from '../confirmation-bus/message-bus.js';
import { ToolConfirmationOutcome } from './tools.js';
import { ApprovalMode } from '../policy/types.js';
import * as fs from 'node:fs';
import os from 'node:os';
import { validatePlanPath } from '../utils/planUtils.js';
import * as loggers from '../telemetry/loggers.js';

vi.mock('../telemetry/loggers.js', () => ({
  logPlanExecution: vi.fn(),
}));

describe('ExitPlanModeTool', () => {
  let tool: ExitPlanModeTool;
  let mockMessageBus: ReturnType<typeof createMockMessageBus>;
  let mockConfig: Partial<Config>;
  let tempRootDir: string;
  let mockPlansDir: string;

  beforeEach(() => {
    vi.useFakeTimers();
    mockMessageBus = createMockMessageBus();
    vi.mocked(mockMessageBus.publish).mockResolvedValue(undefined);

    tempRootDir = fs.realpathSync(
      fs.mkdtempSync(path.join(os.tmpdir(), 'exit-plan-test-')),
    );
    const plansDirRaw = path.join(tempRootDir, 'plans');
    fs.mkdirSync(plansDirRaw, { recursive: true });
    mockPlansDir = fs.realpathSync(plansDirRaw);

    mockConfig = {
      getTargetDir: vi.fn().mockReturnValue(tempRootDir),
      getProjectRoot: vi.fn().mockReturnValue(tempRootDir),
      setApprovalMode: vi.fn(),
      setApprovedPlanPath: vi.fn(),
      storage: {
        getPlansDir: vi.fn().mockReturnValue(mockPlansDir),
      } as unknown as Config['storage'],
      isInteractive: vi.fn().mockReturnValue(true),
    };
    tool = new ExitPlanModeTool(
      mockConfig as Config,
      mockMessageBus as unknown as MessageBus,
    );
    // Mock getMessageBusDecision on the invocation prototype
    vi.spyOn(
      ExitPlanModeInvocation.prototype as unknown as {
        getMessageBusDecision: () => Promise<string>;
      },
      'getMessageBusDecision',
    ).mockResolvedValue('ask_user');
  });

  afterEach(() => {
    if (fs.existsSync(tempRootDir)) {
      fs.rmSync(tempRootDir, { recursive: true, force: true });
    }
    vi.useRealTimers();
    vi.restoreAllMocks();
  });

  const createPlanFile = (name: string, content: string) => {
    const filePath = path.join(mockPlansDir, name);
    // Ensure parent directory exists for nested tests
    fs.mkdirSync(path.dirname(filePath), { recursive: true });
    fs.writeFileSync(filePath, content);
    return name;
  };

  describe('shouldConfirmExecute', () => {
    it('should return plan approval confirmation details when plan has content', async () => {
      const planRelativePath = createPlanFile('test-plan.md', '# My Plan');
      const invocation = tool.build({ plan_filename: planRelativePath });

      const result = await invocation.shouldConfirmExecute(
        new AbortController().signal,
      );

      expect(result).not.toBe(false);
      if (result === false) return;

      expect(result.type).toBe('exit_plan_mode');
      expect(result.title).toBe('Plan Approval');
      if (result.type === 'exit_plan_mode') {
        expect(result.planPath).toBe(path.join(mockPlansDir, 'test-plan.md'));
      }
      expect(typeof result.onConfirm).toBe('function');
    });

    it('should return false when plan file is empty', async () => {
      const planRelativePath = createPlanFile('empty.md', '   ');
      const invocation = tool.build({ plan_filename: planRelativePath });

      const result = await invocation.shouldConfirmExecute(
        new AbortController().signal,
      );

      expect(result).toBe(false);
    });

    it('should return false when plan file cannot be read', async () => {
      const planRelativePath = path.join('plans', 'non-existent.md');
      const invocation = tool.build({ plan_filename: planRelativePath });

      const result = await invocation.shouldConfirmExecute(
        new AbortController().signal,
      );

      expect(result).toBe(false);
    });

    it('should auto-approve when policy decision is ALLOW', async () => {
      const planRelativePath = createPlanFile('test.md', '# Content');
      const invocation = tool.build({ plan_filename: planRelativePath });

      vi.spyOn(
        invocation as unknown as {
          getMessageBusDecision: () => Promise<string>;
        },
        'getMessageBusDecision',
      ).mockResolvedValue('allow');

      const result = await invocation.shouldConfirmExecute(
        new AbortController().signal,
      );

      expect(result).toBe(false);
      // Verify it auto-approved internally
      const executeResult = await invocation.execute({
        abortSignal: new AbortController().signal,
      });
      expect(executeResult.llmContent).toContain('Plan approved');
    });

    it('should throw error when policy decision is DENY', async () => {
      const planRelativePath = createPlanFile('test.md', '# Content');
      const invocation = tool.build({ plan_filename: planRelativePath });

      vi.spyOn(
        invocation as unknown as {
          getMessageBusDecision: () => Promise<string>;
        },
        'getMessageBusDecision',
      ).mockResolvedValue('deny');

      await expect(
        invocation.shouldConfirmExecute(new AbortController().signal),
      ).rejects.toThrow(/denied by policy/);
    });
  });

  describe('execute with invalid plan', () => {
    it('should return error when plan file is empty', async () => {
      const planRelativePath = createPlanFile('empty.md', '');
      const invocation = tool.build({ plan_filename: planRelativePath });

      await invocation.shouldConfirmExecute(new AbortController().signal);
      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
      });

      expect(result.llmContent).toContain('Plan file is empty');
      expect(result.llmContent).toContain('write content to the plan');
    });

    it('should return error when plan file cannot be read', async () => {
      const planRelativePath = 'ghost.md';
      const invocation = tool.build({ plan_filename: planRelativePath });

      await invocation.shouldConfirmExecute(new AbortController().signal);
      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
      });

      expect(result.llmContent).toContain('Plan file does not exist');
    });
  });

  describe('execute', () => {
    it('should return approval message when plan is approved with DEFAULT mode', async () => {
      const planRelativePath = createPlanFile('test.md', '# Content');
      const invocation = tool.build({ plan_filename: planRelativePath });

      const confirmDetails = await invocation.shouldConfirmExecute(
        new AbortController().signal,
      );
      expect(confirmDetails).not.toBe(false);
      if (confirmDetails === false) return;

      await confirmDetails.onConfirm(ToolConfirmationOutcome.ProceedOnce, {
        approved: true,
        approvalMode: ApprovalMode.DEFAULT,
      });

      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
      });
      const expectedPath = path.join(mockPlansDir, 'test.md');

      expect(result).toEqual({
        llmContent: `Plan approved. Switching to Default mode (edits will require confirmation).

The approved implementation plan is stored at: ${expectedPath}
Read and follow the plan strictly during implementation.`,
        returnDisplay: `Plan approved: ${expectedPath}`,
      });
      expect(mockConfig.setApprovedPlanPath).toHaveBeenCalledWith(expectedPath);
    });

    it('should return approval message when plan is approved with AUTO_EDIT mode', async () => {
      const planRelativePath = createPlanFile('test.md', '# Content');
      const invocation = tool.build({ plan_filename: planRelativePath });

      const confirmDetails = await invocation.shouldConfirmExecute(
        new AbortController().signal,
      );
      expect(confirmDetails).not.toBe(false);
      if (confirmDetails === false) return;

      await confirmDetails.onConfirm(ToolConfirmationOutcome.ProceedOnce, {
        approved: true,
        approvalMode: ApprovalMode.AUTO_EDIT,
      });

      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
      });
      const expectedPath = path.join(mockPlansDir, 'test.md');

      expect(result).toEqual({
        llmContent: `Plan approved. Switching to Auto-Edit mode (edits will be applied automatically).

The approved implementation plan is stored at: ${expectedPath}
Read and follow the plan strictly during implementation.`,
        returnDisplay: `Plan approved: ${expectedPath}`,
      });
      expect(mockConfig.setApprovalMode).toHaveBeenCalledWith(
        ApprovalMode.AUTO_EDIT,
      );
      expect(mockConfig.setApprovedPlanPath).toHaveBeenCalledWith(expectedPath);
    });

    it('should return feedback message when plan is rejected with feedback', async () => {
      const planRelativePath = createPlanFile('test.md', '# Content');
      const invocation = tool.build({ plan_filename: planRelativePath });

      const confirmDetails = await invocation.shouldConfirmExecute(
        new AbortController().signal,
      );
      expect(confirmDetails).not.toBe(false);
      if (confirmDetails === false) return;

      await confirmDetails.onConfirm(ToolConfirmationOutcome.ProceedOnce, {
        approved: false,
        feedback: 'Please add more details.',
      });

      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
      });
      const expectedPath = path.join(mockPlansDir, 'test.md');

      expect(result).toEqual({
        llmContent: `Plan rejected. User feedback: Please add more details.

The plan is stored at: ${expectedPath}
Revise the plan based on the feedback.`,
        returnDisplay: 'Feedback: Please add more details.',
      });
    });

    it('should handle rejection without feedback gracefully', async () => {
      const planRelativePath = createPlanFile('test.md', '# Content');
      const invocation = tool.build({ plan_filename: planRelativePath });

      const confirmDetails = await invocation.shouldConfirmExecute(
        new AbortController().signal,
      );
      expect(confirmDetails).not.toBe(false);
      if (confirmDetails === false) return;

      await confirmDetails.onConfirm(ToolConfirmationOutcome.ProceedOnce, {
        approved: false,
      });

      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
      });
      const expectedPath = path.join(mockPlansDir, 'test.md');

      expect(result).toEqual({
        llmContent: `Plan rejected. No feedback provided.

The plan is stored at: ${expectedPath}
Ask the user for specific feedback on how to improve the plan.`,
        returnDisplay: 'Rejected (no feedback)',
      });
    });

    it('should log plan execution event when plan is approved', async () => {
      const planRelativePath = createPlanFile('test.md', '# Content');
      const invocation = tool.build({ plan_filename: planRelativePath });

      const confirmDetails = await invocation.shouldConfirmExecute(
        new AbortController().signal,
      );
      if (confirmDetails === false) return;

      await confirmDetails.onConfirm(ToolConfirmationOutcome.ProceedOnce, {
        approved: true,
        approvalMode: ApprovalMode.AUTO_EDIT,
      });

      await invocation.execute({ abortSignal: new AbortController().signal });

      expect(loggers.logPlanExecution).toHaveBeenCalledWith(
        mockConfig,
        expect.objectContaining({
          approval_mode: ApprovalMode.AUTO_EDIT,
        }),
      );
    });

    it('should return cancellation message when cancelled', async () => {
      const planRelativePath = createPlanFile('test.md', '# Content');
      const invocation = tool.build({ plan_filename: planRelativePath });

      const confirmDetails = await invocation.shouldConfirmExecute(
        new AbortController().signal,
      );
      expect(confirmDetails).not.toBe(false);
      if (confirmDetails === false) return;

      await confirmDetails.onConfirm(ToolConfirmationOutcome.Cancel);

      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
      });

      expect(result).toEqual({
        llmContent:
          'User cancelled the plan approval dialog. The plan was not approved and you are still in Plan Mode.',
        returnDisplay: 'Cancelled',
      });
    });
  });

  describe('execute when shouldConfirmExecute is never called', () => {
    it('should approve with DEFAULT mode when approvalPayload is null (policy ALLOW skips confirmation)', async () => {
      const planRelativePath = createPlanFile('test.md', '# Content');
      const invocation = tool.build({ plan_filename: planRelativePath });

      // Simulate the scheduler's policy ALLOW path: execute() is called
      // directly without ever calling shouldConfirmExecute(), leaving
      // approvalPayload null.
      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
      });
      const expectedPath = path.join(mockPlansDir, 'test.md');

      expect(result.llmContent).toContain('Plan approved');
      expect(result.returnDisplay).toContain('Plan approved');
      expect(mockConfig.setApprovalMode).toHaveBeenCalledWith(
        ApprovalMode.DEFAULT,
      );
      expect(mockConfig.setApprovedPlanPath).toHaveBeenCalledWith(expectedPath);
    });
  });

  describe('getAllowApprovalMode (internal)', () => {
    it('should return YOLO when config.isInteractive() is false', async () => {
      mockConfig.isInteractive = vi.fn().mockReturnValue(false);
      const planRelativePath = createPlanFile('test.md', '# Content');
      const invocation = tool.build({ plan_filename: planRelativePath });

      // Directly call execute to trigger the internal getAllowApprovalMode
      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
      });

      expect(result.llmContent).toContain('YOLO mode');
      expect(mockConfig.setApprovalMode).toHaveBeenCalledWith(
        ApprovalMode.YOLO,
      );
    });

    it('should return DEFAULT when config.isInteractive() is true', async () => {
      mockConfig.isInteractive = vi.fn().mockReturnValue(true);
      const planRelativePath = createPlanFile('test.md', '# Content');
      const invocation = tool.build({ plan_filename: planRelativePath });

      // Directly call execute to trigger the internal getAllowApprovalMode
      const result = await invocation.execute({
        abortSignal: new AbortController().signal,
      });

      expect(result.llmContent).toContain('Default mode');
      expect(mockConfig.setApprovalMode).toHaveBeenCalledWith(
        ApprovalMode.DEFAULT,
      );
    });
  });

  describe('getApprovalModeDescription (internal)', () => {
    it('should handle all valid approval modes', async () => {
      const planRelativePath = createPlanFile('test.md', '# Content');
      const invocation = tool.build({ plan_filename: planRelativePath });

      const testMode = async (mode: ApprovalMode, expected: string) => {
        const confirmDetails = await invocation.shouldConfirmExecute(
          new AbortController().signal,
        );
        if (confirmDetails === false) return;

        await confirmDetails.onConfirm(ToolConfirmationOutcome.ProceedOnce, {
          approved: true,
          approvalMode: mode,
        });

        const result = await invocation.execute({
          abortSignal: new AbortController().signal,
        });
        expect(result.llmContent).toContain(expected);
      };

      await testMode(
        ApprovalMode.AUTO_EDIT,
        'Auto-Edit mode (edits will be applied automatically)',
      );
      await testMode(
        ApprovalMode.DEFAULT,
        'Default mode (edits will require confirmation)',
      );
      await testMode(
        ApprovalMode.YOLO,
        'YOLO mode (all tool calls auto-approved)',
      );
    });

    it('should throw for invalid post-planning modes', async () => {
      const planRelativePath = createPlanFile('test.md', '# Content');
      const invocation = tool.build({ plan_filename: planRelativePath });

      const testInvalidMode = async (mode: ApprovalMode) => {
        const confirmDetails = await invocation.shouldConfirmExecute(
          new AbortController().signal,
        );
        if (confirmDetails === false) return;

        await confirmDetails.onConfirm(ToolConfirmationOutcome.ProceedOnce, {
          approved: true,
          approvalMode: mode,
        });

        await expect(
          invocation.execute({ abortSignal: new AbortController().signal }),
        ).rejects.toThrow(/Unexpected approval mode/);
      };

      await testInvalidMode(ApprovalMode.PLAN);
    });
  });

  describe('validateToolParams', () => {
    it('should reject empty plan_filename', () => {
      const result = tool.validateToolParams({ plan_filename: '' });
      expect(result).toBe('plan_filename is required.');
    });

    it('should reject whitespace-only plan_filename', () => {
      const result = tool.validateToolParams({ plan_filename: '   ' });
      expect(result).toBe('plan_filename is required.');
    });

    it('should reject non-existent plan file', async () => {
      const result = await validatePlanPath(
        'ghost.md',
        mockPlansDir,
        tempRootDir,
      );
      expect(result).toContain('Plan file does not exist');
    });

    it('should reject symbolic links pointing outside the plans directory', () => {
      const outsideFile = path.join(tempRootDir, 'outside.txt');
      fs.writeFileSync(outsideFile, 'secret');
      const maliciousPath = path.join(mockPlansDir, 'malicious.md');
      fs.symlinkSync(outsideFile, maliciousPath);

      const result = tool.validateToolParams({
        plan_filename: 'malicious.md',
      });

      expect(result).toBe(
        `Access denied: plan path (malicious.md) must be within the designated plans directory (${mockPlansDir}).`,
      );
    });

    it('should accept valid path within plans directory', () => {
      createPlanFile('valid.md', '# Content');
      const result = tool.validateToolParams({
        plan_filename: 'valid.md',
      });
      expect(result).toBeNull();
    });
  });
});