Skip to content

Open source AI coding agent. Designed for large projects and real world tasks.

fix + test case for structured edits algorithm issue with appending to end of file. fix for setting convo message subtask correctly before shifting current subtask. improve replacement fallback logic to use line numbers for disambiguation, improving accuracy. add types for line numbered text to help prevent confusion between plain and line numbered versions. when model streams are canceled during build flow, pass through cached tokens when using OpenAI models so that pricing accounts for caching.

Dane Schneider02ddc72a3a9b
diff --git a/app/server/db/convo_helpers.go b/app/server/db/convo_helpers.go
index 9c0efbfe..c67f9016 100644
--- a/app/server/db/convo_helpers.go
+++ b/app/server/db/convo_helpers.go
@@ -3,6 +3,7 @@ package db
import (
"encoding/json"
"fmt"
+ "log"
"os"
"path/filepath"
"sort"
@@ -159,6 +160,9 @@ func StoreConvoMessage(repo *GitRepo, message *ConvoMessage, currentUserId, bran
}
}
+ log.Println("StoreConvoMessage - message.Flags.CurrentStage.TellStage:", message.Flags.CurrentStage.TellStage)
+ log.Println("StoreConvoMessage - message.Subtask:", message.Subtask)
+
if message.Flags.CurrentStage.TellStage == shared.TellStageImplementation && message.Subtask != nil {
msg += "\n\n" + "📋 " + message.Subtask.Title
if len(message.Subtask.UsesFiles) > 0 {
diff --git a/app/server/model/model_request.go b/app/server/model/model_request.go
index 5b0f948f..21f44981 100644
--- a/app/server/model/model_request.go
+++ b/app/server/model/model_request.go
@@ -37,6 +37,8 @@ type ModelRequestParams struct {
AfterReq func()
OnStream func(string, string) bool
+
+ WillCacheNumTokens int
}
func ModelRequest(
@@ -134,6 +136,10 @@ func ModelRequest(
} else {
inputTokens = inputTokensEstimate
outputTokens = shared.GetNumTokensEstimate(res.Content)
+
+ if params.WillCacheNumTokens > 0 {
+ cachedTokens = params.WillCacheNumTokens
+ }
}
go func() {
diff --git a/app/server/model/plan/build_race.go b/app/server/model/plan/build_race.go
index 13e8b983..20bd779c 100644
--- a/app/server/model/plan/build_race.go
+++ b/app/server/model/plan/build_race.go
@@ -118,6 +118,8 @@ func (fileState *activeBuildStreamFileState) buildRace(
return
}
+ // log.Printf("buildRace - fast apply result:\n\n%s", fastApplyRes)
+
fastApplySyntaxErrors := fileState.validateSyntax(buildCtx, fastApplyRes)
fileState.builderRun.FastApplySyntaxErrors = fastApplySyntaxErrors
@@ -139,6 +141,7 @@ func (fileState *activeBuildStreamFileState) buildRace(
// just validate since we're already building replacements in parallel
maxAttempts: 1,
validateOnlyOnFinalAttempt: true,
+ isInitial: false,
})
if err != nil {
@@ -201,6 +204,7 @@ func (fileState *activeBuildStreamFileState) buildRace(
reasons: reasons,
syntaxErrors: syntaxErrors,
initialPhaseOnStream: onInitialStream,
+ isInitial: true,
})
fileState.builderRun.AutoApplyValidationFinishedAt = time.Now()
diff --git a/app/server/model/plan/build_structured_edits.go b/app/server/model/plan/build_structured_edits.go
index 8522b038..5c1a810b 100644
--- a/app/server/model/plan/build_structured_edits.go
+++ b/app/server/model/plan/build_structured_edits.go
@@ -105,8 +105,8 @@ func (fileState *activeBuildStreamFileState) buildStructuredEdits() {
},
)
log.Printf("buildStructuredEdits - %s - got ApplyChanges result\n", filePath)
- // log.Println("buildStructuredEdits - applyRes.NewFile:", applyRes.NewFile)
- log.Println("buildStructuredEdits - applyRes.NeedsVerifyReasons:", autoApplyRes.NeedsVerifyReasons)
+ // log.Printf("buildStructuredEdits - autoApplyRes.NewFile:\n\n%s", autoApplyRes.NewFile)
+ log.Println("buildStructuredEdits - autoApplyRes.NeedsVerifyReasons:", autoApplyRes.NeedsVerifyReasons)
autoApplySyntaxErrors = fileState.validateSyntax(buildCtx, autoApplyRes.NewFile)
diff --git a/app/server/model/plan/build_validate_and_fix.go b/app/server/model/plan/build_validate_and_fix.go
index 56d37d31..8235cbbd 100644
--- a/app/server/model/plan/build_validate_and_fix.go
+++ b/app/server/model/plan/build_validate_and_fix.go
@@ -31,6 +31,7 @@ type buildValidateLoopParams struct {
initialPhaseOnStream func(chunk string, buffer string) bool
validateOnlyOnFinalAttempt bool
maxAttempts int
+ isInitial bool
}
type buildValidateLoopResult struct {
@@ -112,6 +113,8 @@ func (fileState *activeBuildStreamFileState) buildValidateLoop(
reasons: reasons,
modelConfig: &modelConfig,
validateOnly: isLastAttempt && params.validateOnlyOnFinalAttempt,
+ phase: currentAttempt,
+ isInitial: params.isInitial,
}
log.Printf("Calling buildValidate for attempt %d", currentAttempt)
@@ -164,6 +167,7 @@ type buildValidateParams struct {
phase int
modelConfig *shared.ModelRoleConfig
validateOnly bool
+ isInitial bool
}
type buildValidateResult struct {
@@ -190,7 +194,6 @@ func (fileState *activeBuildStreamFileState) buildValidate(
onStream := params.onStream
syntaxErrors := params.syntaxErrors
reasons := params.reasons
-
// Get diff for validation
log.Printf("Getting diffs between original and updated content")
diff, err := diff_pkg.GetDiffs(originalFile, updated)
@@ -199,17 +202,20 @@ func (fileState *activeBuildStreamFileState) buildValidate(
return buildValidateResult{}, fmt.Errorf("error getting diffs: %v", err)
}
+ originalWithLineNums := shared.AddLineNums(originalFile)
+ proposedWithLineNums := shared.AddLineNums(proposedContent)
+
// Choose prompt and tools based on preferred format
log.Printf("Building XML validation replacements prompt")
- promptText := prompts.GetValidationReplacementsXmlPrompt(prompts.ValidationPromptParams{
- Path: filePath,
- Original: originalFile,
- Desc: desc,
- Proposed: proposedContent,
- Diff: diff,
- SyntaxErrors: syntaxErrors,
- Reasons: reasons,
+ promptText, headNumTokens := prompts.GetValidationReplacementsXmlPrompt(prompts.ValidationPromptParams{
+ Path: filePath,
+ OriginalWithLineNums: originalWithLineNums,
+ Desc: desc,
+ ProposedWithLineNums: proposedWithLineNums,
+ Diff: diff,
+ SyntaxErrors: syntaxErrors,
+ Reasons: reasons,
})
// log.Printf("Prompt to LLM: %s", promptText)
@@ -241,6 +247,12 @@ func (fileState *activeBuildStreamFileState) buildValidate(
stop = []string{"<PlandexComments>", "<PlandexReplacements>"}
}
+ var willCacheNumTokens int
+ isFirstPass := params.isInitial && params.phase == 1
+ if !isFirstPass && modelConfig.BaseModelConfig.Provider == shared.ModelProviderOpenAI {
+ willCacheNumTokens = headNumTokens
+ }
+
// Use ModelRequest for both formats
res, err := model.ModelRequest(ctx, model.ModelRequestParams{
Clients: clients,
@@ -263,6 +275,8 @@ func (fileState *activeBuildStreamFileState) buildValidate(
fileState.builderRun.ReplacementFinishedAt = time.Now()
},
OnStream: onStream,
+
+ WillCacheNumTokens: willCacheNumTokens,
})
if err != nil {
@@ -275,11 +289,13 @@ func (fileState *activeBuildStreamFileState) buildValidate(
return fileState.validationRetryOrError(ctx, params, err)
}
+ // log.Printf("Model response:\n\n%s", res.Content)
+
fileState.builderRun.GenerationIds = append(fileState.builderRun.GenerationIds, res.GenerationId)
log.Printf("Added generation ID: %s", res.GenerationId)
// Handle response based on format
- parseRes, err := handleXMLResponse(fileState, res.Content, originalFile, updated, params.validateOnly)
+ parseRes, err := handleXMLResponse(fileState, res.Content, originalWithLineNums, updated, params.validateOnly)
if err != nil {
log.Printf("Error handling response: %v", err)
@@ -294,7 +310,7 @@ func (fileState *activeBuildStreamFileState) buildValidate(
func handleXMLResponse(
fileState *activeBuildStreamFileState,
content string,
- originalFile string,
+ originalWithLineNums shared.LineNumberedTextType,
updated string,
validateOnly bool,
) (buildValidateResult, error) {
@@ -317,8 +333,9 @@ func handleXMLResponse(
}, nil
}
- originalFileLines := strings.Split(originalFile, "\n")
- updated = originalFile
+ originalFileLines := strings.Split(string(originalWithLineNums), "\n")
+
+ incremental := originalWithLineNums
log.Printf("Processing XML replacement blocks")
@@ -328,7 +345,7 @@ func handleXMLResponse(
log.Printf("No replacements found in XML response")
return buildValidateResult{
valid: false,
- updated: updated,
+ updated: shared.RemoveLineNums(incremental),
problem: "No replacements found in XML response",
}, nil
}
@@ -348,7 +365,9 @@ func handleXMLResponse(
old = strings.TrimSpace(old)
- // log.Printf("Old content trimmed:\n\n%s", old)
+ // log.Printf("Old content trimmed:\n\n%s", strconv.Quote(old))
+
+ // log.Printf("New content:\n\n%s", strconv.Quote(new))
if !strings.HasPrefix(old, "pdx-") {
log.Printf("Old content does not have a line number prefix for first line")
@@ -392,11 +411,11 @@ func handleXMLResponse(
old = strings.Join(originalFileLines[firstLineNum-1:lastLineNum], "\n")
}
- log.Printf("Applying replacement.\n\nOld:\n\n%s\n\nNew:\n\n%s", old, new)
+ // log.Printf("Applying replacement.\n\nOld:\n\n%s\n\nNew:\n\n%s", old, new)
- updated = strings.Replace(updated, old, new, 1)
+ incremental = shared.LineNumberedTextType(strings.Replace(string(incremental), old, new, 1))
- log.Printf("Updated content:\n\n%s", updated)
+ // log.Printf("Updated content:\n\n%s", string(incremental))
}
var problem string
@@ -409,7 +428,11 @@ func handleXMLResponse(
problem = split[0]
}
- return buildValidateResult{valid: false, updated: updated, problem: problem}, nil
+ final := shared.RemoveLineNums(incremental)
+
+ // log.Printf("Final content:\n\n%s", final)
+
+ return buildValidateResult{valid: false, updated: final, problem: problem}, nil
}
func (fileState *activeBuildStreamFileState) validationRetryOrError(buildCtx context.Context, validateParams buildValidateParams, err error) (buildValidateResult, error) {
diff --git a/app/server/model/plan/build_whole_file.go b/app/server/model/plan/build_whole_file.go
index 639a2bdf..5fdaae72 100644
--- a/app/server/model/plan/build_whole_file.go
+++ b/app/server/model/plan/build_whole_file.go
@@ -34,7 +34,10 @@ func (fileState *activeBuildStreamFileState) buildWholeFileFallback(buildCtx con
return "", fmt.Errorf("active plan not found for plan ID %s and branch %s", planId, branch)
}
- sysPrompt := prompts.GetWholeFilePrompt(filePath, originalFile, desc, proposedContent, comments)
+ originalFileWithLineNums := shared.AddLineNums(originalFile)
+ proposedContentWithLineNums := shared.AddLineNums(proposedContent)
+
+ sysPrompt, headNumTokens := prompts.GetWholeFilePrompt(filePath, originalFileWithLineNums, proposedContentWithLineNums, desc, comments)
messages := []types.ExtendedChatMessage{
{
@@ -69,6 +72,12 @@ func (fileState *activeBuildStreamFileState) buildWholeFileFallback(buildCtx con
}
+ // This allows proper accounting for cached input tokens even when the stream is cancelled -- OpenAI only for now
+ var willCacheNumTokens int
+ if modelConfig.BaseModelConfig.Provider == shared.ModelProviderOpenAI {
+ willCacheNumTokens = headNumTokens
+ }
+
modelRes, err := model.ModelRequest(buildCtx, model.ModelRequestParams{
Clients: clients,
Auth: auth,
@@ -91,6 +100,8 @@ func (fileState *activeBuildStreamFileState) buildWholeFileFallback(buildCtx con
AfterReq: func() {
fileState.builderRun.BuildWholeFileFinishedAt = time.Now()
},
+
+ WillCacheNumTokens: willCacheNumTokens,
})
if err != nil {
diff --git a/app/server/model/plan/tell_stream_processor.go b/app/server/model/plan/tell_stream_processor.go
index 404d602a..303377fd 100644
--- a/app/server/model/plan/tell_stream_processor.go
+++ b/app/server/model/plan/tell_stream_processor.go
@@ -462,7 +462,7 @@ func (state *activeTellStreamState) handleNewOperations(parserRes *types.ReplyPa
if req.BuildMode == shared.BuildModeAuto {
log.Printf("Queuing build for %s\n", op.Name())
// log.Println("Content:")
- // log.Println(fileContents[i])
+ // log.Println(strconv.Quote(op.Content))
buildState := &activeBuildStreamState{
modelStreamId: state.modelStreamId,
diff --git a/app/server/model/plan/tell_stream_store.go b/app/server/model/plan/tell_stream_store.go
index d0022e98..e1c8273f 100644
--- a/app/server/model/plan/tell_stream_store.go
+++ b/app/server/model/plan/tell_stream_store.go
@@ -58,6 +58,8 @@ func (state *activeTellStreamState) storeOnFinished(params storeOnFinishedParams
log.Println("storeOnFinished: subtaskFinished", subtaskFinished)
log.Println("storeOnFinished: removedSubtasks", removedSubtasks)
+ messageSubtask := state.currentSubtask
+
// first resolve subtask state
if hasNewSubtasks || len(removedSubtasks) > 0 || subtaskFinished {
if subtaskFinished && state.currentSubtask != nil {
@@ -117,7 +119,7 @@ func (state *activeTellStreamState) storeOnFinished(params storeOnFinishedParams
if len(autoLoadContextResult.autoLoadPaths) > 0 {
flags.DidLoadContext = true
}
- if subtaskFinished && state.currentSubtask != nil {
+ if subtaskFinished && messageSubtask != nil {
flags.DidCompleteTask = true
}
if allSubtasksFinished {
@@ -133,7 +135,7 @@ func (state *activeTellStreamState) storeOnFinished(params storeOnFinishedParams
assistantMsg, convoCommitMsg, err := state.storeAssistantReply(repo, storeAssistantReplyParams{
flags: flags,
- subtask: state.currentSubtask,
+ subtask: messageSubtask,
addedSubtasks: addedSubtasks,
activatedPaths: autoLoadContextResult.activatePaths,
removedSubtasks: removedSubtasks,
diff --git a/app/server/model/plan/tell_subtasks.go b/app/server/model/plan/tell_subtasks.go
index 25e400b5..93027f5d 100644
--- a/app/server/model/plan/tell_subtasks.go
+++ b/app/server/model/plan/tell_subtasks.go
@@ -93,8 +93,8 @@ func (state *activeTellStreamState) checkNewSubtasks() []*db.Subtask {
return nil
}
- log.Println("Found new subtasks:")
- log.Println(spew.Sdump(subtasks))
+ log.Println("Found new subtasks:", len(subtasks))
+ // log.Println(spew.Sdump(subtasks))
subtasksByName := map[string]*db.Subtask{}
@@ -151,7 +151,7 @@ func (state *activeTellStreamState) checkNewSubtasks() []*db.Subtask {
}
}
- log.Println("state.subtasks:\n", spew.Sdump(state.subtasks))
+ // log.Println("state.subtasks:\n", spew.Sdump(state.subtasks))
log.Println("state.currentSubtask:\n", spew.Sdump(state.currentSubtask))
return newSubtasks
@@ -174,8 +174,8 @@ func (state *activeTellStreamState) checkRemoveSubtasks() []string {
return nil
}
- log.Println("Found tasks to remove:")
- log.Println(spew.Sdump(tasksToRemove))
+ log.Println("Found tasks to remove:", len(tasksToRemove))
+ // log.Println(spew.Sdump(tasksToRemove))
// Create a map of task titles to remove for efficient lookup
removeMap := make(map[string]bool)
diff --git a/app/server/model/prompts/build_validation_replacements.go b/app/server/model/prompts/build_validation_replacements.go
index 74b2ad8f..aeb0cc8d 100644
--- a/app/server/model/prompts/build_validation_replacements.go
+++ b/app/server/model/prompts/build_validation_replacements.go
@@ -9,26 +9,28 @@ import (
)
type ValidationPromptParams struct {
- Path string
- Original string
- Desc string
- Proposed string
- Diff string
- Reasons []syntax.NeedsVerifyReason
- SyntaxErrors []string
+ Path string
+ OriginalWithLineNums shared.LineNumberedTextType
+ Desc string
+ ProposedWithLineNums shared.LineNumberedTextType
+ Diff string
+ Reasons []syntax.NeedsVerifyReason
+ SyntaxErrors []string
}
// GetValidationReplacementsXmlPrompt constructs the complete prompt string for XML responses.
-func GetValidationReplacementsXmlPrompt(params ValidationPromptParams) string {
+func GetValidationReplacementsXmlPrompt(params ValidationPromptParams) (string, int) {
reasons := params.Reasons
syntaxErrs := params.SyntaxErrors
path := params.Path
- original := params.Original
+ originalWithLineNums := params.OriginalWithLineNums
desc := params.Desc
- proposed := params.Proposed
+ proposedWithLineNums := params.ProposedWithLineNums
diff := params.Diff
- s := getBuildPromptHead(path, original, desc, proposed)
+ s := getBuildPromptHead(path, originalWithLineNums, desc, proposedWithLineNums)
+
+ headNumTokens := shared.GetNumTokensEstimate(s)
s += fmt.Sprintf(
`
@@ -207,14 +209,11 @@ IMPORTANT RULES:
5. Always include reasoning in a '## Evaluate Diff' section prior to outputting the <PlandexCorrect/> or <PlandexIncorrect/> tags.
`
- return s
+ return s, headNumTokens
}
// getBuildPromptHead describes the original file and proposed changes
-func getBuildPromptHead(filePath, preBuildState, desc, proposed string) string {
- preBuildStateWithLineNums := shared.AddLineNums(preBuildState)
- proposedWithLineNums := shared.AddLineNumsWithPrefix(proposed, "pdx-new-")
-
+func getBuildPromptHead(filePath string, preBuildStateWithLineNums shared.LineNumberedTextType, desc string, proposedWithLineNums shared.LineNumberedTextType) string {
return fmt.Sprintf(
`Path: %s
diff --git a/app/server/model/prompts/build_whole_file.go b/app/server/model/prompts/build_whole_file.go
index a9c8d90e..ff31e839 100644
--- a/app/server/model/prompts/build_whole_file.go
+++ b/app/server/model/prompts/build_whole_file.go
@@ -1,7 +1,11 @@
package prompts
-func GetWholeFilePrompt(filePath, preBuildState, changesFile, changesDesc, comments string) string {
- s := getBuildPromptHead(filePath, preBuildState, changesDesc, changesFile)
+import shared "plandex-shared"
+
+func GetWholeFilePrompt(filePath string, preBuildStateWithLineNums shared.LineNumberedTextType, changesWithLineNumsType shared.LineNumberedTextType, changesDesc string, comments string) (string, int) {
+ s := getBuildPromptHead(filePath, preBuildStateWithLineNums, changesDesc, changesWithLineNumsType)
+
+ headNumTokens := shared.GetNumTokensEstimate(s)
s += "## Comments\n\n"
@@ -12,7 +16,8 @@ func GetWholeFilePrompt(filePath, preBuildState, changesFile, changesDesc, comme
}
s += WholeFilePrompt
- return s
+
+ return s, headNumTokens
}
const WholeFilePrompt = `
diff --git a/app/server/model/prompts/explanation_format.go b/app/server/model/prompts/explanation_format.go
index 87aed2ea..d8e6d6ea 100644
--- a/app/server/model/prompts/explanation_format.go
+++ b/app/server/model/prompts/explanation_format.go
@@ -70,7 +70,7 @@ For each Type, follow these validation rules:
- Summary MUST briefly describe the new code being added and where it will be inserted
- Context MUST describe the surrounding code structures that help locate where the new code will be inserted. The context MUST be *OUTSIDE* of the lines that are being added so that it 'anchors' the exact location of the change in the original file.
- Preserve field must be omitted
- - Remove field must be omitted
+ - Replace field must be omitted
- In the code block, include the anchors identified in the 'Context' field, collapsed with a reference comment if they span more than a few lines, that are immediately before and after the new code being added. Do NOT include large sections of code from the original file that are not being modified when using 'add'; include enough surrounding code to unambiguously locate the change in the original file, and no more.
- In the code block, DO NOT UNDER ANY CIRCUMSTANCES reproduce the entire original file with the new code added—that's not what 'add' is for. If you're reproducing the entire original file, use 'overwrite' instead.
@@ -78,7 +78,7 @@ For each Type, follow these validation rules:
- Summary MUST briefly describe the new code being prepended to the start of the file
- Context MUST identify the first *existing* code structure in the original file (which will NOT be modified) that the new code will be added before
- Preserve field must be omitted
- - Remove field must be omitted
+ - Replace field must be omitted
- Code block MUST include JUST the first existing code structure in the original file (which will NOT be modified), collapsed with a reference comment if it spans more than a few lines, immediately followed by the new code being prepended. Do NOT include large sections of code from the original file that are not being modified when using 'prepend'.
- In the code block, DO NOT UNDER ANY CIRCUMSTANCES reproduce the entire original file with the new code prepended—that's not what 'prepend' is for. If you're reproducing the entire original file, use 'overwrite' instead.
@@ -86,13 +86,13 @@ For each Type, follow these validation rules:
- Summary MUST briefly describe the new code being appended to the end of the file
- Context MUST identify the last *existing* code structure in the original file (which will NOT be modified) that the new code will be added after
- Preserve field must be omitted
- - Remove field must be omitted
+ - Replace field must be omitted
- Code block MUST include JUST the last existing code structure in the original file (which will NOT be modified), collapsed with a reference comment if it spans more than a few lines, immediately followed by the new code being appended. Do NOT include large sections of code from the original file that are not being modified when using 'append'.
- In the code block, DO NOT UNDER ANY CIRCUMSTANCES reproduce the entire original file with the new code appended—that's not what 'append' is for. If you're reproducing the entire original file, use 'overwrite' instead.
- For 'replace':
- Summary MUST briefly describe the change
- - Remove field MUST list lines in the original file that are being replaced. Use the exact format: 'lines [startLineNumber]-[endLineNumber]' — e.g. 'lines 10-20' or for a single line, 'line [lineNumber]' — e.g. 'line 10' — DO NOT use any other format, or describe the lines in any other way.
+ - Replace field MUST list lines in the original file that are being replaced. Use the exact format: 'lines [startLineNumber]-[endLineNumber]' — e.g. 'lines 10-20' or for a single line, 'line [lineNumber]' — e.g. 'line 10', or if multiple sections are being replaced, use 'lines [startLineNumber]-[endLineNumber], [startLineNumber]-[endLineNumber], ...' — e.g. 'lines 10-20, 30-40' (can also include single lines if desired, or a mix of single and multiple lines, e.g. 'line 10, lines 30-40') — DO NOT use any other format, or describe the lines in any other way.
- Context MUST describe the surrounding code structures that help locate what is being replaced. Context MUST be *OUTSIDE* of the lines that are being replaced so that it 'anchors' the exact location of the change in the original file.
- Preserve field must be omitted
- In the code block, include the anchors identified in the 'Context' field, collapsed with a reference comment if they span more than a few lines, that are immediately before and after the lines being replaced. Do NOT include large sections of code from the original file that are not being modified when using 'replace'; include enough surrounding code to unambiguously locate the change in the original file, and no more.
@@ -100,7 +100,7 @@ For each Type, follow these validation rules:
- For 'remove':
- Summary MUST briefly describe the change
- - Remove field MUST list lines in the original file that are being removed. Use the exact format: 'lines [startLineNumber]-[endLineNumber]' — e.g. 'lines 10-20' or for a single line, 'line [lineNumber]' — e.g. 'line 10' — DO NOT use any other format, or describe the lines in any other way.
+ - Replace field MUST list lines in the original file that are being removed. Use the exact format: 'lines [startLineNumber]-[endLineNumber]' — e.g. 'lines 10-20' or for a single line, 'line [lineNumber]' — e.g. 'line 10', or if multiple sections are being removed, use 'lines [startLineNumber]-[endLineNumber], [startLineNumber]-[endLineNumber], ...' — e.g. 'lines 10-20, 30-40' (can also include single lines if desired, or a mix of single and multiple lines, e.g. 'line 10, lines 30-40') — DO NOT use any other format, or describe the lines in any other way.
- Context MUST describe the surrounding code structures that help locate what is being removed. Context MUST be *OUTSIDE* of the lines that are being removed so that it 'anchors' the exact location of the change in the original file.
- Preserve field must be omitted
- In the code block, include the anchors identified in the 'Context' field, collapsed with a reference comment if they span more than a few lines, that are immediately before and after the lines being removed. Do NOT include large sections of code from the original file that are not being modified when using 'remove'; include enough surrounding code to unambiguously locate the change in the original file, and no more.
diff --git a/app/server/model/prompts/implement.go b/app/server/model/prompts/implement.go
index 3999bae1..1e94a2b8 100644
--- a/app/server/model/prompts/implement.go
+++ b/app/server/model/prompts/implement.go
@@ -48,6 +48,7 @@ In a <PlandexBlock> tag attribute, the 'path' attribute MUST be the exact file p
- Do NOT omit the 'lang' or 'path' attributes from the <PlandexBlock> tag. EVERY <PlandexBlock> tag MUST ALWAYS have both 'lang' and 'path' attributes.
- Do NOT omit the *file path label* before the <PlandexBlock> tag. Every code block MUST ALWAYS be preceded by a file path label.
- Do NOT UNDER ANY CIRCUMSTANCES include line numbers in the <PlandexBlock> tag. While line numbers are included in the original file in context (prefixed with 'pdx-', like 'pdx-10: ') to assist you with describing the location of changes in the 'Action Explanation', they ABSOLUTELY MUST NOT be included in the <PlandexBlock> tag.
+- Do NOT escape newlines within the <PlandexBlock> tag unless there is a specific reason to do so, like you are outputting newlines in a quoted JSON string. For normal code, do NOT escape newlines.
Labelled code block example:
diff --git a/app/server/model/prompts/user_prompt.go b/app/server/model/prompts/user_prompt.go
index 686e0b3f..8879dd83 100644
--- a/app/server/model/prompts/user_prompt.go
+++ b/app/server/model/prompts/user_prompt.go
@@ -133,7 +133,9 @@ When *updating an existing file*, you MUST follow the instructions you've been g
- Never remove existing functionality unless explicitly instructed to do so.
- - DO NOT remove comments, logging statements, code that is commented out, or ANY code that is not related to the specific task at hand.
+ - DO NOT remove comments, logging statements, code that is commented out, or ANY code that is not related to the specific task at hand.
+
+ - Do NOT escape newlines within the <PlandexBlock> tag unless there is a specific reason to do so, like you are outputting newlines in a quoted JSON string. For normal code, do NOT escape newlines.
- Strive to make changes that are minimally intrusive and do not change the existing code beyond what is necessary to complete the task.
diff --git a/app/server/syntax/structured_edits_apply.go b/app/server/syntax/structured_edits_apply.go
index d561f3af..58716663 100644
--- a/app/server/syntax/structured_edits_apply.go
+++ b/app/server/syntax/structured_edits_apply.go
@@ -151,37 +151,62 @@ func ApplyChanges(
// Parse line ranges from summary field
// Matches formats like:
- // (original file line 10)
- // (original file lines 10-20)
- singleLineRegex := regexp.MustCompile(`\(Remove: line (\d+)\)`)
- lineRangeRegex := regexp.MustCompile(`\(Remove: lines (\d+)-(\d+)\)`)
-
- // Find all single line matches
- singleLineMatches := singleLineRegex.FindAllStringSubmatch(strings.ToLower(desc), -1)
- for _, match := range singleLineMatches {
- if len(match) > 1 {
- if lineNum, err := strconv.Atoi(match[1]); err == nil {
- removalRanges = append(removalRanges, RemovalRange{
- Start: lineNum,
- End: lineNum,
- })
+ // Replace: line 10
+ // Remove: line 10
+ // Replace: lines 10-20
+ // Remove: lines 10-20
+ singleLineRegex := regexp.MustCompile(`(?i)(Replace|Replaces|Remove|Removes).*?(\d+)`)
+ lineRangeRegex := regexp.MustCompile(`(?i)(Replace|Replaces|Remove|Removes).*?(\d+)-(\d+)`)
+
+ descLines := strings.Split(desc, "\n")
+
+ for _, line := range descLines {
+ line = strings.TrimSpace(line)
+
+ matchesRemaining := true
+ for matchesRemaining {
+ // first see if there's a multi-line match
+ if lineRangeMatch := lineRangeRegex.FindStringSubmatch(strings.ToLower(line)); len(lineRangeMatch) > 3 {
+ // we have a multi-line match
+ start, startErr := strconv.Atoi(lineRangeMatch[2])
+ end, endErr := strconv.Atoi(lineRangeMatch[3])
+ if startErr == nil && endErr == nil {
+ removalRanges = append(removalRanges, RemovalRange{
+ Start: start,
+ End: end,
+ })
+ line = strings.Replace(line, fmt.Sprintf("%d-%d", start, end), "", 1)
+ } else {
+ log.Println("ApplyChanges - multi-line match error")
+ log.Println(spew.Sdump(startErr))
+ log.Println(spew.Sdump(endErr))
+ matchesRemaining = false
+ }
+ } else {
+
+ // try single-line match
+ if singleLineMatch := singleLineRegex.FindStringSubmatch(strings.ToLower(line)); len(singleLineMatch) > 2 {
+ if lineNum, err := strconv.Atoi(singleLineMatch[2]); err == nil {
+ removalRanges = append(removalRanges, RemovalRange{
+ Start: lineNum,
+ End: lineNum,
+ })
+ line = strings.Replace(line, singleLineMatch[2], "", 1)
+ } else {
+ log.Println("ApplyChanges - single-line match error")
+ log.Println(spew.Sdump(err))
+ matchesRemaining = false
+ }
+ } else {
+ matchesRemaining = false
+ }
}
}
}
- // Find all line range matches
- lineRangeMatches := lineRangeRegex.FindAllStringSubmatch(strings.ToLower(desc), -1)
- for _, match := range lineRangeMatches {
- if len(match) > 2 {
- start, startErr := strconv.Atoi(match[1])
- end, endErr := strconv.Atoi(match[2])
- if startErr == nil && endErr == nil {
- removalRanges = append(removalRanges, RemovalRange{
- Start: start,
- End: end,
- })
- }
- }
+ if verboseLogging {
+ log.Println("ApplyChanges - removal ranges:")
+ log.Println(spew.Sdump(removalRanges))
}
var res *ApplyChangesResult
@@ -261,14 +286,14 @@ func ApplyChanges(
}
}
- // if verboseLogging {
- // fmt.Println("proposed:")
- // fmt.Println(proposed)
- // log.Println("ApplyChanges - references:")
- // spew.Dump(references)
- // log.Println("ApplyChanges - removals:")
- // spew.Dump(removals)
- // }
+ if verboseLogging {
+ fmt.Println("proposed:")
+ fmt.Println(proposed)
+ log.Println("ApplyChanges - references:")
+ spew.Dump(references)
+ log.Println("ApplyChanges - removals:")
+ spew.Dump(removals)
+ }
if !isPureInsert {
log.Println("ApplyChanges - removal ranges:")
@@ -348,12 +373,20 @@ func ApplyChanges(
originalLineMap[strings.TrimSpace(line)] = true
}
+ log.Println("NewFile:")
+ log.Println(strconv.Quote(res.NewFile))
+
newLines := strings.Split(res.NewFile, "\n")
newLineMap := make(map[string]bool)
for _, line := range newLines {
newLineMap[strings.TrimSpace(line)] = true
}
+ log.Println("ApplyChanges - originalLineMap:")
+ spew.Dump(originalLineMap)
+ log.Println("ApplyChanges - newLineMap:")
+ spew.Dump(newLineMap)
+
// Check for removed lines (lines in original that are not in new)
for line := range originalLineMap {
if !newLineMap[line] {
diff --git a/app/server/syntax/structured_edits_generic.go b/app/server/syntax/structured_edits_generic.go
index 24082be3..b8758f39 100644
--- a/app/server/syntax/structured_edits_generic.go
+++ b/app/server/syntax/structured_edits_generic.go
@@ -255,6 +255,8 @@ func ExecApplyGeneric(
return false
}
+ reachedEndOfOriginal := false
+
for idx, pLine := range proposedLines {
finalLine := idx == len(proposedLines)-1
pLineNum := idx + 1
@@ -263,9 +265,13 @@ func ExecApplyGeneric(
fmt.Printf("\n\ni: %d, num: %d, pLine: %q, refOpen: %v\n", idx, pLineNum, pLine, refOpen)
}
- isRef := refsByLine[Reference(pLineNum)]
- isRemoval := removalsByLine[Removal(pLineNum)]
- nextPLineIsRef := refsByLine[Reference(pLineNum+1)]
+ var isRef, isRemoval, nextPLineIsRef bool
+
+ if !reachedEndOfOriginal {
+ isRef = refsByLine[Reference(pLineNum)]
+ isRemoval = removalsByLine[Removal(pLineNum)]
+ nextPLineIsRef = refsByLine[Reference(pLineNum+1)]
+ }
if verboseLogging {
fmt.Printf("isRef: %v\n", isRef)
@@ -304,13 +310,13 @@ func ExecApplyGeneric(
addNewPostRefBuffer()
if oLineNum == len(originalLines) {
- break
+ reachedEndOfOriginal = true
}
continue
}
- if !refOpen && lastLineMatched {
+ if !reachedEndOfOriginal && !refOpen && lastLineMatched {
if strings.TrimSpace(pLine) == "" {
if verboseLogging {
fmt.Printf("pLine is blank\n")
@@ -336,7 +342,7 @@ func ExecApplyGeneric(
}
if oLineNum == len(originalLines) {
- break
+ reachedEndOfOriginal = true
}
continue
@@ -346,10 +352,13 @@ func ExecApplyGeneric(
var matching bool
prevOLineNum := oLineNum
- anchor := findAnchor(pLineNum)
- if anchor != nil {
- matching = true
- setOLineNum(int(*anchor))
+
+ if !reachedEndOfOriginal {
+ anchor := findAnchor(pLineNum)
+ if anchor != nil {
+ matching = true
+ setOLineNum(int(*anchor))
+ }
}
wroteRefs := false
@@ -432,7 +441,7 @@ func ExecApplyGeneric(
}
if oLineNum == len(originalLines) {
- break
+ reachedEndOfOriginal = true
}
}
diff --git a/app/server/syntax/structured_edits_test.go b/app/server/syntax/structured_edits_test.go
index 2bf8e7e1..55b338ac 100644
--- a/app/server/syntax/structured_edits_test.go
+++ b/app/server/syntax/structured_edits_test.go
@@ -138,7 +138,6 @@ func TestStructuredReplacements(t *testing.T) {
func init() {
log.Println("init")
}
-
type UserService struct {
db *DB
cache *Cache
@@ -1288,52 +1287,161 @@ func TestStructuredReplacements(t *testing.T) {
},
{
- name: "replacement with removal outside of line range",
+ name: "replacement with removal outside of single line range",
desc: `
- Type: replace
- Summary: Remove the notifyUpdate call (original file line 11)
- `,
+ Type: replace
+ Replace: line 11
+ `,
original: `func processRequest(req *Request) error {
- validateRequest(req)
- someOtherThing()
- startTransaction()
+ validateRequest(req)
+ someOtherThing()
+ startTransaction()
- err := updateData(req)
- if err != nil {
- return err
- }
+ err := updateData(req)
+ if err != nil {
+ return err
+ }
- notifyUpdate()
- commitTransaction()
- return nil
-}`,
+ notifyUpdate()
+ commitTransaction()
+ return nil
+ }`,
proposed: `func processRequest(req *Request) error {
- startTransaction()
+ startTransaction()
- err := updateData(req)
- if err != nil {
- return err
- }
+ err := updateData(req)
+ if err != nil {
+ return err
+ }
- commitTransaction()
- log.Info("processed request", req.ID)
- return nil
-}`,
+ commitTransaction()
+ log.Info("processed request", req.ID)
+ return nil
+ }`,
want: `func processRequest(req *Request) error {
- validateRequest(req)
- someOtherThing()
- startTransaction()
+ validateRequest(req)
+ someOtherThing()
+ startTransaction()
- err := updateData(req)
- if err != nil {
- return err
- }
+ err := updateData(req)
+ if err != nil {
+ return err
+ }
- commitTransaction()
- log.Info("processed request", req.ID)
- return nil
-}`,
+ commitTransaction()
+ log.Info("processed request", req.ID)
+ return nil
+ }`,
+ },
+
+ {
+ name: "replacement with removal inside of multi line range",
+ desc: `
+ Type: replace
+ Replace: lines 2-3, line 11
+ `,
+ original: `func processRequest(req *Request) error {
+ validateRequest(req)
+ someOtherThing()
+ startTransaction()
+
+ err := updateData(req)
+ if err != nil {
+ return err
+ }
+
+ notifyUpdate()
+ commitTransaction()
+ return nil
+ }`,
+ proposed: `func processRequest(req *Request) error {
+ startTransaction()
+
+ err := updateData(req)
+ if err != nil {
+ return err
+ }
+
+ commitTransaction()
+ log.Info("processed request", req.ID)
+ return nil
+ }`,
+ want: `func processRequest(req *Request) error {
+ startTransaction()
+
+ err := updateData(req)
+ if err != nil {
+ return err
+ }
+
+ commitTransaction()
+ log.Info("processed request", req.ID)
+ return nil
+ }`,
+ },
+
+ {
+ name: "add to end with full file included",
+ desc: `
+ Type: add
+ Summary: Add Tailwind CSS typography plugin
+ `,
+ isInsert: true,
+ original: `# Install dependencies for markdown processing
+echo "Installing dependencies for markdown processing..."
+npm install next-mdx-remote gray-matter --save
+echo "Dependencies installed successfully!"`,
+ proposed: `# Install dependencies for markdown processing
+echo "Installing dependencies for markdown processing..."
+npm install next-mdx-remote gray-matter --save
+echo "Dependencies installed successfully!"
+
+# Install Tailwind CSS typography plugin
+echo "Installing Tailwind CSS typography plugin..."
+npm install @tailwindcss/typography --save-dev
+echo "Tailwind CSS typography plugin installed successfully!"`,
+
+ want: `# Install dependencies for markdown processing
+echo "Installing dependencies for markdown processing..."
+npm install next-mdx-remote gray-matter --save
+echo "Dependencies installed successfully!"
+
+# Install Tailwind CSS typography plugin
+echo "Installing Tailwind CSS typography plugin..."
+npm install @tailwindcss/typography --save-dev
+echo "Tailwind CSS typography plugin installed successfully!"`,
+ },
+
+ {
+ name: "add to beginning with full file included",
+ desc: `
+ Type: add
+ Summary: Add Tailwind CSS typography plugin
+ `,
isInsert: true,
+ original: `# Install dependencies for markdown processing
+echo "Installing dependencies for markdown processing..."
+npm install next-mdx-remote gray-matter --save
+echo "Dependencies installed successfully!"`,
+ proposed: `# Install Tailwind CSS typography plugin
+echo "Installing Tailwind CSS typography plugin..."
+npm install @tailwindcss/typography --save-dev
+echo "Tailwind CSS typography plugin installed successfully!"
+
+# Install dependencies for markdown processing
+echo "Installing dependencies for markdown processing..."
+npm install next-mdx-remote gray-matter --save
+echo "Dependencies installed successfully!"`,
+
+ want: `# Install Tailwind CSS typography plugin
+echo "Installing Tailwind CSS typography plugin..."
+npm install @tailwindcss/typography --save-dev
+echo "Tailwind CSS typography plugin installed successfully!"
+
+# Install dependencies for markdown processing
+echo "Installing dependencies for markdown processing..."
+npm install next-mdx-remote gray-matter --save
+echo "Dependencies installed successfully!"`,
},
}
diff --git a/app/shared/plan_result.go b/app/shared/plan_result.go
index cc90aa8f..cd2fc746 100644
--- a/app/shared/plan_result.go
+++ b/app/shared/plan_result.go
@@ -93,13 +93,13 @@ func (p PlanFileResultsByPath) ConflictedPaths(filesByPath map[string]string) ma
maybeWithLineNums := updated
if res.ReplaceWithLineNums {
- maybeWithLineNums = AddLineNums(updated)
+ maybeWithLineNums = string(AddLineNums(updated))
}
var succeeded bool
updated, succeeded = ApplyReplacements(maybeWithLineNums, res.Replacements, false)
- updated = RemoveLineNums(updated)
+ updated = RemoveLineNums(LineNumberedTextType(updated))
// log.Println("updated:", updated)
// log.Println("succeeded:", succeeded)
diff --git a/app/shared/plan_result_replacements.go b/app/shared/plan_result_replacements.go
index 0858e1bf..8495d65d 100644
--- a/app/shared/plan_result_replacements.go
+++ b/app/shared/plan_result_replacements.go
@@ -231,7 +231,7 @@ func (planState *CurrentPlanState) GetFilesBeforeReplacement(
maybeWithLineNums := updated
if planRes.ReplaceWithLineNums {
- maybeWithLineNums = AddLineNums(updated)
+ maybeWithLineNums = string(AddLineNums(maybeWithLineNums))
}
// log.Println("Before replacements. updated:")
@@ -239,7 +239,7 @@ func (planState *CurrentPlanState) GetFilesBeforeReplacement(
updated, allSucceeded = ApplyReplacements(maybeWithLineNums, replacements, false)
- updated = RemoveLineNums(updated)
+ updated = string(RemoveLineNums(LineNumberedTextType(updated)))
if !allSucceeded {
log.Println("Failed to apply replacements")
diff --git a/app/shared/utils.go b/app/shared/utils.go
index 1ab477c9..946253c6 100644
--- a/app/shared/utils.go
+++ b/app/shared/utils.go
@@ -65,24 +65,26 @@ func Capitalize(s string) string {
return strings.ToUpper(s[:1]) + s[1:]
}
-func AddLineNums(s string) string {
- return AddLineNumsWithPrefix(s, "pdx-")
+type LineNumberedTextType string
+
+func AddLineNums(s string) LineNumberedTextType {
+ return LineNumberedTextType(AddLineNumsWithPrefix(s, "pdx-"))
}
-func AddLineNumsWithPrefix(s, prefix string) string {
+func AddLineNumsWithPrefix(s, prefix string) LineNumberedTextType {
var res string
for i, line := range strings.Split(s, "\n") {
res += fmt.Sprintf("%s%d: %s\n", prefix, i+1, line)
}
- return res
+ return LineNumberedTextType(res)
}
-func RemoveLineNums(s string) string {
+func RemoveLineNums(s LineNumberedTextType) string {
return RemoveLineNumsWithPrefix(s, "pdx-")
}
-func RemoveLineNumsWithPrefix(s, prefix string) string {
- return regexp.MustCompile(fmt.Sprintf(`(?m)^%s\d+: `, prefix)).ReplaceAllString(s, "")
+func RemoveLineNumsWithPrefix(s LineNumberedTextType, prefix string) string {
+ return regexp.MustCompile(fmt.Sprintf(`(?m)^%s\d+: `, prefix)).ReplaceAllString(string(s), "")
}
// indexRunes searches for the slice of runes `needle` in the slice of runes `haystack`