Skip to content
Closed
38 changes: 38 additions & 0 deletions backend/knowledge.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ This document provides an overview of the Manicode backend architecture, key com
10. [Security Considerations](#security-considerations)
11. [TODO List](#todo-list)
12. [Automatic URL Detection and Scraping](#automatic-url-detection-and-scraping)
13. [Planning System](#planning-system)

## Architecture Overview

Expand Down Expand Up @@ -194,3 +195,40 @@ This project uses Bun for testing instead of Jest. When writing tests, keep the
- Bun's test API is similar to Jest's, but there are some differences in implementation.
- When mocking methods, use `mock(object.method)` instead of Jest's `jest.spyOn(object, 'method')`.
- Bun's `mock` function expects 0-1 arguments, not 2 like Jest's `spyOn`.

## Plan Generation for Complex Requests

The backend now includes a feature to generate plans for complex user requests. This feature is designed to break down complex tasks into manageable steps and include appropriate verification processes.

Key components:
1. `check-plan-required.ts`: Determines if a plan is needed based on the complexity of the user's request.
2. `generate-plan.ts`: Creates a detailed plan with numbered steps and verification processes.
3. `main-prompt.ts`: Integrates plan generation into the main request handling flow.

The plan generation process:
1. `main-prompt.ts` calls `checkIfPlanRequired()` to determine if a plan is needed.
2. If a plan is required, `generatePlan()` is called to create a detailed plan.
3. The generated plan is streamed to the client using the `onResponseChunk` function, providing real-time updates.
4. The plan includes numbered steps, sub-steps, and appropriate verification steps (e.g., running type checkers, creating and running unit tests).

Important implementation details:
- The system prompt for plan generation is recreated to ensure it has the most up-to-date context.
- The warm cache call is only fired if no plan was required, optimizing performance by avoiding unnecessary caching when a plan is generated.

This feature enhances the system's ability to handle complex requests systematically and with proper verification. When working on request handling or AI prompts, consider whether the request might benefit from this plan generation feature.

## Planning System

The agent system prompt now includes a section explaining the planning process. Key points:

- The assistant is given a plan to implement for complex tasks.
- The assistant should implement one or more steps from the plan.
- After completing steps, the assistant reports progress using a specific format:
- Example: [STEP 1 COMPLETE] or [STEPS 2-4 COMPLETE]
- The progress report should not include the end token "[END]".

This planning system allows for more structured and trackable task implementation, especially for complex requests. It provides clear checkpoints for both the assistant and the user to understand the progress of a given task.

When implementing features or fixing bugs, consider whether the task would benefit from this structured planning approach, particularly for multi-step or complex changes to the codebase.


46 changes: 46 additions & 0 deletions backend/src/check-plan-required.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { Message } from 'common/actions'
import { System } from './claude'
import { promptClaude } from './claude'
import { claudeModels } from 'common/constants'
import { logger } from './util/logger'

export async function checkIfPlanRequired(
messages: Message[],
system: System,
clientSessionId: string,
fingerprintId: string,
userInputId: string,
userId?: string
): Promise<boolean> {
const planCheckPrompt = `
Given the user's request, determine if it requires a plan. A plan is needed if the request:
1. Requires at least 3 steps to complete
2. Is complex in nature
3. Requires verification of multiple parts

Analyze the request and respond with just the string:
"[REQUIRES_PLAN]" if a plan is needed, or
"[PLAN_UNNECESSARY]" if a plan is not needed.

Do not include any other text.

User request: ${messages[messages.length - 1].content}
`.trim()

const response = await promptClaude(
[...messages, { role: 'user', content: planCheckPrompt }],
{
model: claudeModels.sonnet,
system,
clientSessionId,
fingerprintId,
userInputId,
userId,
}
)

const requiresPlan = response.trim().includes('[REQUIRES_PLAN]')
logger.info({ response, requiresPlan }, 'Plan check response')

return requiresPlan
}
2 changes: 1 addition & 1 deletion backend/src/generate-patch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ ${newContent}
Are there any comments in the sketch that indicate surrounding code should remain as it is in the original file? For example, comments like "// ... existing code ..." or "# .... rest of the function ...". If so, please write "YES". Otherwise, write "NO".

If "YES", don't write anything else.
If "NO", please also consider the following question. In rare cases, the new content focuses on the change of a single function or section of code with the intention to edit just this section, but the assistant forgot to add placeholder comments above and below the section to indicate the rest of the file is preserved. Without these placeholder comments the sketch of the updated file is incomplete. One clue this is the case is if the new content is much shorter than the original file. If they are about the same length, the sketch is probably complete and does not require modification.
If "NO", please also consider the following question. In rare cases, the new content focuses on the change of a single function or section of code with the intention to edit just this section, but the assistant forgot to add placeholder comments above and below the section to indicate the rest of the file is preserved. Without these placeholder comments the sketch of the updated file is incomplete. One clue this is the case is if the new content is just a single function whereas the original file has multiple functions.
If you strongly believe this is the scenario, please write "INCOMPLETE_SKETCH". Otherwise (most likely), write "COMPLETE_SKETCH".
`.trim()

Expand Down
55 changes: 55 additions & 0 deletions backend/src/generate-plan.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { Message } from 'common/actions'
import { System } from './claude'
import { promptClaudeStream } from './claude'
import { claudeModels } from 'common/constants'

export async function generatePlan(
messages: Message[],
system: System,
clientSessionId: string,
fingerprintId: string,
userInputId: string,
onResponseChunk: (chunk: string) => void,
userId?: string
): Promise<string> {
const planGenerationPrompt = `
Based on the user's request, create a detailed plan for the assistant to follow with numbered steps to accomplish the task.

Please follow these guidelines:
1. Reduce the scope of the plan to the minimum necessary to accomplish the task. Try to avoid unnecessary steps and do not modify more files or run more terminal commands than absolutely necessary.
2. Break down the task into clear, actionable steps for the assistant to follow. The assistant can only edit files and run terminal commands as part of the plan. Do not include steps for the user to do.
3. Include appropriate verification steps along the way and at the end, such as running a command to do type checking and fixing errors, creating and running unit tests, or any other relevant checks.

User request: ${messages[messages.length - 1].content}

Please provide the plan in the following format:
1. [First step]
2. [Second step]
a. [Sub-step if necessary]
b. [Another sub-step if necessary]
3. [Verification step (if applicable)]
...

Please start by telling the user you will create a plan to address their request.
`

let fullPlan = ''
const stream = promptClaudeStream(
[...messages, { role: 'user', content: planGenerationPrompt }],
{
model: claudeModels.sonnet,
system,
clientSessionId,
fingerprintId,
userInputId,
userId,
}
)

for await (const chunk of stream) {
fullPlan += chunk
onResponseChunk(chunk)
}

return fullPlan.trim()
}
111 changes: 95 additions & 16 deletions backend/src/main-prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ import { promptClaudeStream } from './claude'
import { ProjectFileContext } from 'common/util/file'
import { didClientUseTool } from 'common/util/tools'
import { getSearchSystemPrompt, getAgentSystemPrompt } from './system-prompt'
import { STOP_MARKER, TOOL_RESULT_MARKER } from 'common/constants'
import {
PLAN_START_MARKER,
PLAN_STOP_MARKER,
STOP_MARKER,
TOOL_RESULT_MARKER,
} from 'common/constants'
import { FileChange, Message } from 'common/actions'
import { ToolCall } from 'common/actions'
import { requestFiles, requestFile } from './websockets/websocket-action'
Expand All @@ -18,6 +23,9 @@ import { processStreamWithTags } from './process-stream'
import { generateKnowledgeFiles } from './generate-knowledge-files'
import { countTokens } from './util/token-counter'
import { logger } from './util/logger'
import { checkIfPlanRequired } from './check-plan-required'
import { generatePlan } from './generate-plan'
import { buildArray } from 'common/util/array'

/**
* Prompt claude, handle tool calls, and generate file changes.
Expand All @@ -33,15 +41,28 @@ export async function mainPrompt(
userId?: string
) {
let fullResponse = ''
let continuedMessages: Message[] = fullResponse
? [{ role: 'assistant', content: fullResponse }]
: []
let genKnowledgeFilesPromise: Promise<Promise<FileChange | null>[]> =
Promise.resolve([])
const fileProcessingPromises: Promise<FileChange | null>[] = []
const lastMessage = messages[messages.length - 1]
const messagesWithoutLastMessage = messages.slice(0, -1)
let isPlanInProgress = checkIfPlanInProgress(messages)

if (!didClientUseTool(lastMessage)) {
if (!didClientUseTool(lastMessage) && !isPlanInProgress) {
// Step 1: Read more files.
const system = getSearchSystemPrompt(fileContext)

const planRequiredPromise = checkIfPlanRequired(
messages,
system,
clientSessionId,
fingerprintId,
userInputId,
userId
)
// If the fileContext.files is empty, use prompts to select files and add them to context.
const responseChunk = await updateFileContext(
ws,
Expand All @@ -56,11 +77,42 @@ export async function mainPrompt(
if (responseChunk !== null) {
onResponseChunk(responseChunk.readFilesMessage)
fullResponse += `\n\n${responseChunk.toolCallMessage}\n\n${responseChunk.readFilesMessage}`
}

const updatedSystem = getSearchSystemPrompt(fileContext)

const planRequired = await planRequiredPromise

if (planRequired) {
onResponseChunk('\n\n')
const plan = await generatePlan(
messages,
updatedSystem,
clientSessionId,
fingerprintId,
userInputId,
onResponseChunk,
userId
)
fullResponse += plan.replaceAll(STOP_MARKER, '').trim()
fullResponse += `\n\n${PLAN_START_MARKER}`
onResponseChunk('\n\n')
continuedMessages = [
{
role: 'assistant',
content: fullResponse,
},
{
role: 'user',
content: 'Please execute the plan.',
},
]
logger.info({ plan }, 'Generated plan')
isPlanInProgress = true
} else {
// Prompt cache the new files.
const system = getSearchSystemPrompt(fileContext)
warmCacheForRequestRelevantFiles(
system,
updatedSystem,
clientSessionId,
fingerprintId,
userInputId,
Expand Down Expand Up @@ -98,7 +150,7 @@ export async function mainPrompt(
const numAssistantMessages = messages
.slice(lastUserMessageIndex)
.filter((message) => message.role === 'assistant').length
const shouldPause = numAssistantMessages >= 3
const shouldPause = numAssistantMessages >= 10
if (shouldPause) {
const response = `\nI'll pause to get more instructions from the user.\n`
onResponseChunk(response)
Expand All @@ -110,9 +162,6 @@ export async function mainPrompt(
}

let toolCall: ToolCall | null = null
let continuedMessages: Message[] = fullResponse
? [{ role: 'assistant', content: fullResponse }]
: []
let isComplete = false
let iterationCount = 0
const MAX_ITERATIONS = 10
Expand All @@ -121,15 +170,20 @@ export async function mainPrompt(
if (lastMessage.role === 'user' && typeof lastMessage.content === 'string') {
newLastMessage = {
...lastMessage,
content: `${lastMessage.content}

<additional_instruction>
Please preserve as much of the existing code, its comments, and its behavior as possible. Make minimal edits to accomplish only the core of what is requested. Then pause to get more instructions from the user.
</additional_instruction>
<additional_instruction>
content: buildArray(
lastMessage.content,
`<additional_instruction>
Please preserve as much of the existing code, its comments, and its behavior as possible. Make minimal edits to accomplish only the core of what is requested.${isPlanInProgress ? '' : ' Then pause to get more instructions from the user.'}
</additional_instruction>`,
`<additional_instruction>
Always end your response with the following marker:
${STOP_MARKER}
</additional_instruction>`,
isPlanInProgress &&
`<additional_instruction>
You should attempt to execute the entire plan. When the plan is complete or it is hard to make progress, end your response with the following marker: ${PLAN_STOP_MARKER}
</additional_instruction>`
).join('\n\n'),
}
}

Expand Down Expand Up @@ -247,6 +301,10 @@ ${STOP_MARKER}
if (foundEndOfResponse) {
fullResponse += '\n[END]'
}
isPlanInProgress = checkIfPlanInProgress([
...messages,
{ role: 'assistant', content: fullResponse },
])

const maybeToolCall = toolCall as ToolCall | null

Expand Down Expand Up @@ -278,9 +336,18 @@ ${STOP_MARKER}
} else if (maybeToolCall !== null) {
isComplete = true
logger.debug(maybeToolCall, 'tool call')
} else if (fullResponse.includes(STOP_MARKER)) {
} else if (isPlanInProgress && fullResponse.includes(STOP_MARKER)) {
toolCall = {
id: Math.random().toString(36).slice(2),
name: 'continue_plan',
input: {},
}
isComplete = true
} else if (
fullResponse.includes(STOP_MARKER) ||
fullResponse.includes(PLAN_STOP_MARKER)
) {
isComplete = true
fullResponse = fullResponse.replace(STOP_MARKER, '')
logger.debug('Reached STOP_MARKER')
} else {
logger.debug('Continuing to generate')
Expand Down Expand Up @@ -321,6 +388,18 @@ ${STOP_MARKER}
}
}

function checkIfPlanInProgress(messages: Message[]): boolean {
const messagesString = JSON.stringify(messages)
const lastStartMarkerIndex = messagesString.lastIndexOf(PLAN_START_MARKER)
const lastStopMarkerIndex = messagesString.lastIndexOf(PLAN_STOP_MARKER)

if (lastStartMarkerIndex === -1 && lastStopMarkerIndex === -1) {
return false
}

return lastStartMarkerIndex > lastStopMarkerIndex
}

function getRelevantFileInfoMessage(filePaths: string[]) {
const readFilesMessage = `Reading the following files...<files>${filePaths.join(', ')}</files>`
const toolCallMessage = `<tool_call name="find_files">Please find the files relevant to the user request</tool_call>`
Expand Down
Loading