From 46d3b2a3ede8e8e3536d6448cdc286e166d63ca3 Mon Sep 17 00:00:00 2001 From: Toshii <94262432+0xToshii@users.noreply.github.com> Date: Mon, 20 Oct 2025 17:04:44 -0700 Subject: [PATCH] auto compact updates (#6909) * update prompting around first task message and summarization prompt and add file read parsing * replace first user message to handle issue of refousing on old task after condense * add line about focusing on initial task for history * adding prompting around our removing of context history and verbosity * prompting changes * fix spelling nit in prompting * update displayPath,absolutePath logic to match read file tool handler * increment the auto approval usage --- .../context-management/ContextManager.ts | 2 +- src/core/prompts/contextManagement.ts | 25 +++- src/core/prompts/responses.ts | 11 +- src/core/task/ToolExecutor.ts | 2 +- src/core/task/index.ts | 6 +- .../tools/handlers/SummarizeTaskHandler.ts | 109 +++++++++++++++++- 6 files changed, 135 insertions(+), 20 deletions(-) diff --git a/src/core/context/context-management/ContextManager.ts b/src/core/context/context-management/ContextManager.ts index 58d11ab6..b7e6caff 100644 --- a/src/core/context/context-management/ContextManager.ts +++ b/src/core/context/context-management/ContextManager.ts @@ -513,7 +513,7 @@ export class ContextManager { } if (firstUserMessage) { - const processedFirstUserMessage = formatResponse.processFirstUserMessageForTruncation(firstUserMessage) + const processedFirstUserMessage = formatResponse.processFirstUserMessageForTruncation() const innerMap = new Map() innerMap.set(0, [[timestamp, "text", [processedFirstUserMessage], []]]) diff --git a/src/core/prompts/contextManagement.ts b/src/core/prompts/contextManagement.ts index 0563de60..0f0369f8 100644 --- a/src/core/prompts/contextManagement.ts +++ b/src/core/prompts/contextManagement.ts @@ -1,11 +1,19 @@ -export const summarizeTask = (focusChainSettings?: { enabled: boolean }) => - ` +export const summarizeTask = (focusChainSettings?: { enabled: boolean }, cwd?: string, isMultiRootEnabled?: boolean) => { + // Build CWD display text + const CWD = cwd ? cwd.toPosix() : "" + + // Build MULTI_ROOT_HINT text (matches pattern in tools.ts) + const MULTI_ROOT_HINT = isMultiRootEnabled + ? " Use @workspace:path syntax (e.g., @frontend:src/index.ts) to specify a workspace." + : "" + + return ` The current conversation is rapidly running out of context. Now, your urgent task is to create a comprehensive detailed summary of the conversation so far, paying close attention to the user's explicit requests and your previous actions. This summary should be thorough in capturing technical details, code patterns, and architectural decisions that would be essential for continuing development work without losing context. You have only two options: If you are immediately prepared to call the attempt_completion tool, and have completed all items in your task_progress list, you may call attempt_completion at this time. If you are not prepared to call the attempt_completion tool, and have not completed all items in your task_progress list, you must call the summarize_task tool - in this case you must call the summarize_task tool whether you are in PLAN or ACT mode. -You MUST ONLY respond to this message by using either the attempt_completion tool or the summarize_task tool call. +You MUST ONLY respond to this message by using either the attempt_completion tool or the summarize_task tool call. When using the summarize_task tool call, you must include ALL information in the summary required for continuing with the task at hand. This is because you will lose access to all messages other than this summary. When responding with the summarize_task tool call, follow these instructions: @@ -24,13 +32,16 @@ Your summary should include the following sections: 4. Problem Solving: Document problems solved and any ongoing troubleshooting efforts. 5. Pending Tasks: Outline any pending tasks that you have explicitly been asked to work on. 6. Task Evolution: If the user provided additional requests or modified the original task during the conversation, document this progression: + - Original Task: [Summary of the initial user request, including copying verbatim any relevant information/steps required to continue working] - Task Modifications: [Chronological list of how the user redirected or modified the work since the original task] - Current Active Task: [What the user most recently asked to work on] - Context for Changes: [Why the task evolved - user feedback, new requirements, etc. (Include direct quotes from user messages that caused task changes to prevent drift after context compacting)] 7. Current Work: Describe in detail precisely what was being worked on immediately before this summary request, paying special attention to the most recent messages from both user and assistant. Include file names and code snippets where applicable. 8. Next Step: List the next step that you will take that is related to the most recent work you were doing. IMPORTANT: ensure that this step is DIRECTLY in line with the user's explicit requests, and the task you were working on immediately before this summary request. If your last task was concluded, then only list next steps if they are explicitly in line with the users request. Do not start on tangential requests without confirming with the user first. - If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation. -9. You should pay special attention to the most recent user message, as it indicates the user's most recent intent. + If there is a next step, include direct quotes from the most recent conversation showing exactly what task you were working on and where you left off. This should be verbatim to ensure there's no drift in task interpretation. +9. Required Files: List the most important files needed for continuing the work you laid out in Next Step. This is optional and if no files are required or there is no next step then simply don't include this section. List each file path on a new line starting with "- " such as: - src/main.js. List the files from most important to least important. You must list the minimum number of files necessary to continue with the task. + Only list files you know will for sure be necessary, rather than speculating. The file paths must be relative to the current working directory ${CWD}.${MULTI_ROOT_HINT} +10. You should pay special attention to the most recent user message, as it indicates the user's most recent intent. ${ focusChainSettings?.enabled @@ -77,6 +88,9 @@ Here's an example of how your output should be structured: [Precise description of current work] 7. Optional Next Step: [Optional Next step to take] +8. Optional Required Files: + - [file path 1] + - [file path 2] ${ focusChainSettings?.enabled @@ -93,6 +107,7 @@ ${ \n ` +} export const continuationPrompt = (summaryText: string) => ` This session is being continued from a previous conversation that ran out of context. The conversation is summarized below: diff --git a/src/core/prompts/responses.ts b/src/core/prompts/responses.ts index ea0f8024..328e9894 100644 --- a/src/core/prompts/responses.ts +++ b/src/core/prompts/responses.ts @@ -11,15 +11,8 @@ export const formatResponse = { contextTruncationNotice: () => `[NOTE] Some previous conversation history with the user has been removed to maintain optimal context window length. The initial user task has been retained for continuity, while intermediate conversation history has been removed. Keep this in mind as you continue assisting the user. Pay special attention to the user's latest messages.`, - processFirstUserMessageForTruncation: (originalContent: string) => { - const MAX_CHARS = 400_000 - - if (originalContent.length <= MAX_CHARS) { - return originalContent - } - - const truncated = originalContent.substring(0, MAX_CHARS) - return truncated + "\n\n[[NOTE] This message was truncated past this point to preserve context window space.]" + processFirstUserMessageForTruncation: () => { + return "[Continue assisting the user!]" }, condense: () => diff --git a/src/core/task/ToolExecutor.ts b/src/core/task/ToolExecutor.ts index 9467064c..41d1f722 100644 --- a/src/core/task/ToolExecutor.ts +++ b/src/core/task/ToolExecutor.ts @@ -205,7 +205,7 @@ export class ToolExecutor { this.coordinator.register(new NewTaskHandler()) this.coordinator.register(new AttemptCompletionHandler()) this.coordinator.register(new CondenseHandler()) - this.coordinator.register(new SummarizeTaskHandler()) + this.coordinator.register(new SummarizeTaskHandler(validator)) this.coordinator.register(new ReportBugHandler()) } diff --git a/src/core/task/index.ts b/src/core/task/index.ts index d58fb276..f413b622 100644 --- a/src/core/task/index.ts +++ b/src/core/task/index.ts @@ -2398,7 +2398,11 @@ export class Task { if (shouldCompact) { userContent.push({ type: "text", - text: summarizeTask(this.stateManager.getGlobalSettingsKey("focusChainSettings")), + text: summarizeTask( + this.stateManager.getGlobalSettingsKey("focusChainSettings"), + this.cwd, + isMultiRootEnabled(this.stateManager), + ), }) } } else { diff --git a/src/core/task/tools/handlers/SummarizeTaskHandler.ts b/src/core/task/tools/handlers/SummarizeTaskHandler.ts index cb23b671..530986bb 100644 --- a/src/core/task/tools/handlers/SummarizeTaskHandler.ts +++ b/src/core/task/tools/handlers/SummarizeTaskHandler.ts @@ -2,18 +2,21 @@ import type { ToolUse } from "@core/assistant-message" import { continuationPrompt } from "@core/prompts/contextManagement" import { formatResponse } from "@core/prompts/responses" import { ensureTaskDirectoryExists } from "@core/storage/disk" +import { resolveWorkspacePath } from "@core/workspace" +import { extractFileContent } from "@integrations/misc/extract-file-content" import { ClineSayTool } from "@shared/ExtensionMessage" import { telemetryService } from "@/services/telemetry" import { ClineDefaultTool } from "@/shared/tools" import type { ToolResponse } from "../../index" import type { IPartialBlockHandler, IToolHandler } from "../ToolExecutorCoordinator" +import type { ToolValidator } from "../ToolValidator" import type { TaskConfig } from "../types/TaskConfig" import type { StronglyTypedUIHelpers } from "../types/UIHelpers" export class SummarizeTaskHandler implements IToolHandler, IPartialBlockHandler { readonly name = ClineDefaultTool.SUMMARIZE_TASK - constructor() {} + constructor(private validator: ToolValidator) {} getDescription(block: ToolUse): string { return `[${block.name}]` @@ -39,8 +42,108 @@ export class SummarizeTaskHandler implements IToolHandler, IPartialBlockHandler await config.callbacks.say("tool", completeMessage, undefined, undefined, false) - // Use the continuationPrompt to format the tool result - const toolResult = formatResponse.toolResult(continuationPrompt(context)) + // Parse "Required Files" section from context and read files + // We impose a max number of files which are allowed to be read in as well as on + // the number of files which are allowed to be processed in total + // We also impose a limit on the max number of chars these files reads can consume + const loadedFilePaths: string[] = [] + let fileContents = "" + const filePathRegex = /9\.\s*(?:Optional\s+)?Required Files:\s*((?:\n\s*-\s*.+)+)/m + const match = context.match(filePathRegex) + + if (match) { + const fileListText = match[1] + const filePaths: string[] = [] + const lines = fileListText.split("\n") + + for (const line of lines) { + const pathMatch = line.match(/^\s*-\s*(.+)$/) + if (pathMatch) { + filePaths.push(pathMatch[1].trim()) + } + } + + let filesProcessed = 0 + let filesLoaded = 0 + let totalChars = 0 + const MAX_FILES_LOADED = 8 + const MAX_FILES_PROCESSED = 10 + const MAX_CHARS = 100_000 + + // Prevents duplicate file reads, if occurs + const loadedFiles = new Set() + + // Read each file only if auto-approved + // We consider the list of files still good context for task continuation even if user doesn't have auto approval on + for (const relPath of filePaths) { + // Validate that we have not loaded this file previously + const normalizedPath = relPath.toLowerCase() + if (loadedFiles.has(normalizedPath)) { + continue + } + loadedFiles.add(normalizedPath) + + filesProcessed++ + if (filesProcessed > MAX_FILES_PROCESSED) { + break + } + + // Check .clineignore first and skip ignored files + const accessValidation = this.validator.checkClineIgnorePath(relPath) + if (!accessValidation.ok) { + continue + } + + // Only process if auto-approved (respects workspace/outside-workspace settings) + if (await config.callbacks.shouldAutoApproveToolWithPath(ClineDefaultTool.FILE_READ, relPath)) { + try { + // Resolve path (handles multi-root workspaces) + const pathResult = resolveWorkspacePath(config, relPath, "SummarizeTaskHandler") + const { absolutePath, displayPath } = + typeof pathResult === "string" ? { absolutePath: pathResult, displayPath: relPath } : pathResult + + // Increment counter for successful auto-approved read + config.taskState.consecutiveAutoApprovedRequestsCount++ + + // Read file content, we dont allow images to be read here + // This throws if an image or if we can't read the file, implicitly skipping + const fileContent = await extractFileContent(absolutePath, false) + + // Check if adding this file would exceed character limit + if (totalChars + fileContent.text.length > MAX_CHARS) { + break // exceed our character alotment + } + + // Track the file read + await config.services.fileContextTracker.trackFileContext(relPath, "file_mentioned") + + // Append file content in the same format as file mentions + fileContents += `\n\n\n${fileContent.text}\n` + loadedFilePaths.push(displayPath) + + totalChars += fileContent.text.length + filesLoaded++ + + if (filesLoaded >= MAX_FILES_LOADED) { + break + } + } catch (error) { + // File read failed - log but continue with other files + console.error(`Failed to read ${relPath} during summarization:`, error) + } + } + // If not auto-approved, skip silently + } + } + + // Use the continuationPrompt to format the tool result, appending file contents + if (fileContents) { + const fileMentionString = loadedFilePaths.map((path) => `'${path}'`).join(", ") + " (see below for file content)" + fileContents = + `\n\nThe following files were automatically read based on the files listed in the Required Files section: ${fileMentionString}. These are the latest versions of these files - you should reference them directly and not re-read them:` + + fileContents + } + const toolResult = formatResponse.toolResult(continuationPrompt(context) + fileContents) // Handle context management const apiConversationHistory = config.messageState.getApiConversationHistory()