Skip to content

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

lots of cleanup of no longer used build/verify/fix code, better name for default model, basis for whole file fallback option for edits

Dane Schneidercaf476da10d9
diff --git a/app/cli/cmd/model_packs.go b/app/cli/cmd/model_packs.go
index 18ef2a07..4189f4e5 100644
--- a/app/cli/cmd/model_packs.go
+++ b/app/cli/cmd/model_packs.go
@@ -207,10 +207,8 @@ func createModelPack(cmd *cobra.Command, args []string) {
mp.Namer = getModelRoleConfig(customModels, shared.ModelRoleName)
mp.CommitMsg = getModelRoleConfig(customModels, shared.ModelRoleCommitMsg)
mp.ExecStatus = getModelRoleConfig(customModels, shared.ModelRoleExecStatus)
- verifier := getModelRoleConfig(customModels, shared.ModelRoleVerifier)
- mp.Verifier = &verifier
- autoFix := getModelRoleConfig(customModels, shared.ModelRoleAutoFix)
- mp.AutoFix = &autoFix
+ wholeFileBuilder := getModelRoleConfig(customModels, shared.ModelRoleWholeFileBuilder)
+ mp.WholeFileBuilder = &wholeFileBuilder
term.StartSpinner("")
apiErr = api.Client.CreateModelPack(mp)
diff --git a/app/cli/cmd/models.go b/app/cli/cmd/models.go
index 652cfc7a..873543c3 100644
--- a/app/cli/cmd/models.go
+++ b/app/cli/cmd/models.go
@@ -455,8 +455,7 @@ func renderSettings(settings *shared.PlanSettings) {
addModelRow(string(shared.ModelRoleName), modelPack.Namer)
addModelRow(string(shared.ModelRoleCommitMsg), modelPack.CommitMsg)
addModelRow(string(shared.ModelRoleExecStatus), modelPack.ExecStatus)
- addModelRow(string(shared.ModelRoleVerifier), modelPack.GetVerifier())
- addModelRow(string(shared.ModelRoleAutoFix), modelPack.GetAutoFix())
+ addModelRow(string(shared.ModelRoleWholeFileBuilder), modelPack.GetWholeFileBuilder())
table.Render()
fmt.Println()
diff --git a/app/cli/cmd/set_model.go b/app/cli/cmd/set_model.go
index 8172edba..114c7fae 100644
--- a/app/cli/cmd/set_model.go
+++ b/app/cli/cmd/set_model.go
@@ -473,22 +473,13 @@ func updateModelSettings(args []string, originalSettings *shared.PlanSettings) *
settings.ModelPack.Builder.TopP = float32(*topP)
}
- case shared.ModelRoleAutoFix:
+ case shared.ModelRoleWholeFileBuilder:
if selectedModel != nil {
- settings.ModelPack.AutoFix.BaseModelConfig = selectedModel.BaseModelConfig
+ settings.ModelPack.WholeFileBuilder.BaseModelConfig = selectedModel.BaseModelConfig
} else if temperature != nil {
- settings.ModelPack.AutoFix.Temperature = float32(*temperature)
+ settings.ModelPack.WholeFileBuilder.Temperature = float32(*temperature)
} else if topP != nil {
- settings.ModelPack.AutoFix.TopP = float32(*topP)
- }
-
- case shared.ModelRoleVerifier:
- if selectedModel != nil {
- settings.ModelPack.Verifier.BaseModelConfig = selectedModel.BaseModelConfig
- } else if temperature != nil {
- settings.ModelPack.Verifier.Temperature = float32(*temperature)
- } else if topP != nil {
- settings.ModelPack.Verifier.TopP = float32(*topP)
+ settings.ModelPack.WholeFileBuilder.TopP = float32(*topP)
}
case shared.ModelRoleName:
diff --git a/app/server/db/data_models.go b/app/server/db/data_models.go
index 5fc3362c..7837caea 100644
--- a/app/server/db/data_models.go
+++ b/app/server/db/data_models.go
@@ -526,19 +526,10 @@ type PlanFileResult struct {
AnyFailed bool `json:"anyFailed"`
Error string `json:"error"`
- CanVerify bool `json:"canVerify"`
- RanVerifyAt *time.Time `json:"ranVerifyAt,omitempty"`
- VerifyPassed bool `json:"verifyPassed"`
-
WillCheckSyntax bool `json:"willCheckSyntax"`
SyntaxValid bool `json:"syntaxValid"`
SyntaxErrors []string `json:"syntaxErrors"`
- IsFix bool `json:"isFix"`
- IsSyntaxFix bool `json:"isSyntaxFix"`
- IsOtherFix bool `json:"isOtherFix"`
- FixEpoch int `json:"fixEpoch"`
-
AppliedAt *time.Time `json:"appliedAt,omitempty"`
RejectedAt *time.Time `json:"rejectedAt,omitempty"`
CreatedAt time.Time `json:"createdAt"`
@@ -559,12 +550,6 @@ func (res *PlanFileResult) ToApi() *shared.PlanFileResult {
RejectedAt: res.RejectedAt,
Replacements: res.Replacements,
RemovedFile: res.RemovedFile,
- CanVerify: res.CanVerify,
- RanVerifyAt: res.RanVerifyAt,
- VerifyPassed: res.VerifyPassed,
- IsFix: res.IsFix,
- IsSyntaxFix: res.IsSyntaxFix,
- IsOtherFix: res.IsOtherFix,
CreatedAt: res.CreatedAt,
UpdatedAt: res.UpdatedAt,
}
diff --git a/app/server/handlers/client_helper.go b/app/server/handlers/client_helper.go
index 8c5714bf..a90d67a8 100644
--- a/app/server/handlers/client_helper.go
+++ b/app/server/handlers/client_helper.go
@@ -94,13 +94,8 @@ func initClients(params initClientsParams) map[string]*openai.Client {
continue
}
- if planSettings.ModelPack.GetVerifier().BaseModelConfig.ApiKeyEnvVar == envVar {
- endpointsByApiKeyEnvVar[envVar] = planSettings.ModelPack.GetVerifier().BaseModelConfig.BaseUrl
- continue
- }
-
- if planSettings.ModelPack.GetAutoFix().BaseModelConfig.ApiKeyEnvVar == envVar {
- endpointsByApiKeyEnvVar[envVar] = planSettings.ModelPack.GetAutoFix().BaseModelConfig.BaseUrl
+ if planSettings.ModelPack.GetWholeFileBuilder().BaseModelConfig.ApiKeyEnvVar == envVar {
+ endpointsByApiKeyEnvVar[envVar] = planSettings.ModelPack.GetWholeFileBuilder().BaseModelConfig.BaseUrl
continue
}
}
diff --git a/app/server/model/plan/build_exec.go b/app/server/model/plan/build_exec.go
index 76740de8..88b2e1cc 100644
--- a/app/server/model/plan/build_exec.go
+++ b/app/server/model/plan/build_exec.go
@@ -1,16 +1,11 @@
package plan
import (
- "encoding/json"
"fmt"
"log"
"plandex-server/db"
- "plandex-server/hooks"
- "plandex-server/model"
- "plandex-server/model/prompts"
"plandex-server/types"
- "github.com/davecgh/go-spew/spew"
"github.com/plandex/plandex/shared"
"github.com/sashabaranov/go-openai"
)
@@ -165,13 +160,8 @@ func (buildState *activeBuildStreamState) execPlanBuild(activeBuild *types.Activ
return
}
- if activeBuild.IsVerification {
- log.Println("execPlanBuild - fileState.verifyFileBuild()")
- fileState.verifyFileBuild()
- } else {
- log.Println("execPlanBuild - fileState.buildFile()")
- fileState.buildFile()
- }
+ log.Println("execPlanBuild - fileState.buildFile()")
+ fileState.buildFile()
}
func (fileState *activeBuildStreamFileState) buildFile() {
@@ -383,175 +373,3 @@ func (fileState *activeBuildStreamFileState) buildFile() {
log.Println("buildFile - building structured edits")
fileState.buildStructuredEdits()
}
-
-func (fileState *activeBuildStreamFileState) buildFileLineNums() {
- auth := fileState.auth
- filePath := fileState.filePath
- activeBuild := fileState.activeBuild
- clients := fileState.clients
- planId := fileState.plan.Id
- branch := fileState.branch
- config := fileState.settings.ModelPack.Builder
- originalFile := fileState.preBuildState
-
- activePlan := GetActivePlan(planId, branch)
-
- if activePlan == nil {
- log.Printf("Active plan not found for plan ID %s and branch %s\n", planId, branch)
- return
- }
-
- log.Println("buildFileLineNums - getting file from model: " + filePath)
- // log.Println("File context:", fileContext)
- // log.Println("currentState:", currentState)
-
- sysPrompt := prompts.GetBuildLineNumbersSysPrompt(filePath, originalFile, fmt.Sprintf("%s\n\n```%s```", activeBuild.FileDescription, activeBuild.FileContent))
-
- fileMessages := []openai.ChatCompletionMessage{
- {
- Role: openai.ChatMessageRoleSystem,
- Content: sysPrompt,
- },
- }
-
- promptTokens, err := shared.GetNumTokens(sysPrompt)
-
- if err != nil {
- log.Printf("Error getting num tokens for prompt: %v\n", err)
- fileState.onBuildFileError(fmt.Errorf("error getting num tokens for prompt: %v", err))
- return
- }
-
- inputTokens := prompts.ExtraTokensPerRequest + prompts.ExtraTokensPerMessage + promptTokens
-
- fileState.inputTokens = inputTokens
-
- _, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
- Auth: auth,
- Plan: fileState.plan,
- WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
- InputTokens: inputTokens,
- OutputTokens: shared.AvailableModelsByName[fileState.settings.ModelPack.Builder.BaseModelConfig.ModelName].DefaultReservedOutputTokens,
- ModelName: fileState.settings.ModelPack.Builder.BaseModelConfig.ModelName,
- },
- })
- if apiErr != nil {
- activePlan.StreamDoneCh <- apiErr
- return
- }
-
- log.Println("buildFileLineNums - calling model for file: " + filePath)
-
- // for _, msg := range fileMessages {
- // log.Printf("%s: %s\n", msg.Role, msg.Content)
- // }
-
- var responseFormat *openai.ChatCompletionResponseFormat
- if config.BaseModelConfig.HasJsonResponseMode {
- responseFormat = &openai.ChatCompletionResponseFormat{Type: "json_object"}
- }
-
- // log.Println("responseFormat:", responseFormat)
- // log.Println("Model:", config.BaseModelConfig.ModelName)
-
- modelReq := openai.ChatCompletionRequest{
- Model: config.BaseModelConfig.ModelName,
- Tools: []openai.Tool{
- {
- Type: "function",
- Function: &prompts.ListReplacementsFn,
- },
- },
- ToolChoice: openai.ToolChoice{
- Type: "function",
- Function: openai.ToolFunction{
- Name: prompts.ListReplacementsFn.Name,
- },
- },
- Messages: fileMessages,
- Temperature: config.Temperature,
- TopP: config.TopP,
- ResponseFormat: responseFormat,
- }
-
- envVar := config.BaseModelConfig.ApiKeyEnvVar
- client := clients[envVar]
-
- if config.BaseModelConfig.HasStreamingFunctionCalls {
- modelReq.StreamOptions = &openai.StreamOptions{
- IncludeUsage: true,
- }
-
- stream, err := model.CreateChatCompletionStreamWithRetries(client, activePlan.Ctx, modelReq)
- if err != nil {
- log.Printf("Error creating plan file stream for path '%s': %v\n", filePath, err)
- fileState.onBuildFileError(fmt.Errorf("error creating plan file stream for path '%s': %v", filePath, err))
- return
- }
-
- go fileState.listenStreamChangesWithLineNums(stream)
- } else {
-
- log.Println("request:")
- log.Println(spew.Sdump(modelReq))
-
- resp, err := model.CreateChatCompletionWithRetries(client, activePlan.Ctx, modelReq)
-
- if err != nil {
- log.Printf("Error building file '%s': %v\n", filePath, err)
- fileState.onBuildFileError(fmt.Errorf("error building file '%s': %v", filePath, err))
- return
- }
-
- log.Println("buildFileLineNums - usage:")
- spew.Dump(resp.Usage)
-
- _, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- Auth: auth,
- Plan: fileState.plan,
- DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
- InputTokens: resp.Usage.PromptTokens,
- OutputTokens: resp.Usage.CompletionTokens,
- ModelName: fileState.settings.ModelPack.Builder.BaseModelConfig.ModelName,
- ModelProvider: fileState.settings.ModelPack.Builder.BaseModelConfig.Provider,
- ModelPackName: fileState.settings.ModelPack.Name,
- ModelRole: shared.ModelRoleBuilder,
- Purpose: "Generated file update (ref expansion)",
- },
- })
-
- if apiErr != nil {
- activePlan.StreamDoneCh <- apiErr
- return
- }
-
- var s string
- var res types.ChangesWithLineNums
-
- for _, choice := range resp.Choices {
- if len(choice.Message.ToolCalls) == 1 &&
- choice.Message.ToolCalls[0].Function.Name == prompts.ListReplacementsFn.Name {
- fnCall := choice.Message.ToolCalls[0].Function
- s = fnCall.Arguments
- break
- }
- }
-
- if s == "" {
- log.Println("no ListReplacements function call found in response")
- fileState.lineNumsRetryOrError(fmt.Errorf("no ListReplacements function call found in response"))
- return
- }
-
- bytes := []byte(s)
-
- err = json.Unmarshal(bytes, &res)
- if err != nil {
- log.Printf("Error unmarshalling build response: %v\n", err)
- fileState.lineNumsRetryOrError(fmt.Errorf("error unmarshalling build response: %v", err))
- return
- }
-
- fileState.onLineNumsBuildResult(res)
- }
-}
diff --git a/app/server/model/plan/build_finish.go b/app/server/model/plan/build_finish.go
index 487b8ad9..f0a590df 100644
--- a/app/server/model/plan/build_finish.go
+++ b/app/server/model/plan/build_finish.go
@@ -275,34 +275,6 @@ func (fileState *activeBuildStreamFileState) onFinishBuildFile(planRes *db.PlanF
}
}
- // if we have a syntax error, fix it if we aren't out of retries
- if planRes != nil && planRes.WillCheckSyntax && !planRes.SyntaxValid {
- if planRes.IsFix {
- if planRes.FixEpoch >= FixSyntaxEpochs-1 {
- // we're out of retries, just continue on to queue processing
- log.Printf("Out of retries for syntax fix for file %s\n", filePath)
- } else {
- fileState.syntaxNumEpoch++
- fileState.syntaxNumRetry = 0
- fileState.isFixingSyntax = true
- fileState.syntaxErrors = planRes.SyntaxErrors
- fileState.preBuildState = fileState.updated
- fileState.updated = updated
- log.Printf("Retrying syntax fix for file %s\n", filePath)
- go fileState.fixFileLineNums()
- return
- }
- } else {
- fileState.isFixingSyntax = true
- fileState.syntaxErrors = planRes.SyntaxErrors
- fileState.preBuildState = fileState.updated
- fileState.updated = updated
- log.Printf("Fixing syntax for file %s\n", filePath)
- go fileState.fixFileLineNums()
- return
- }
- }
-
activeBuild.Success = true
// if more builds are queued, start the next one regardless of whether this is a verification build or not, then return
@@ -332,7 +304,7 @@ func (fileState *activeBuildStreamFileState) onFinishBuildFile(planRes *db.PlanF
// otherwise:
// if this is a verification build or a new file build (new files aren't verified), check if the build is finished and call onFinishBuild if it is
// if this is not a verification build, trigger the verification build
- if activeBuild.IsVerification || fileState.isNewFile || (planRes != nil && !planRes.CanVerify) {
+ if fileState.isNewFile {
buildFinished := false
UpdateActivePlan(planId, branch, func(ap *types.ActivePlan) {
@@ -353,13 +325,11 @@ func (fileState *activeBuildStreamFileState) onFinishBuildFile(planRes *db.PlanF
log.Println("Triggering verification build")
go fileState.execPlanBuild(&types.ActiveBuild{
- ReplyId: activeBuild.ReplyId,
- FileDescription: activeBuild.FileDescription,
- FileContent: activeBuild.FileContent,
- Path: activeBuild.Path,
- Idx: activeBuild.Idx,
- IsVerification: true,
- ToVerifyUpdatedState: updated,
+ ReplyId: activeBuild.ReplyId,
+ FileDescription: activeBuild.FileDescription,
+ FileContent: activeBuild.FileContent,
+ Path: activeBuild.Path,
+ Idx: activeBuild.Idx,
})
}
diff --git a/app/server/model/plan/build_fix.go b/app/server/model/plan/build_fix.go
deleted file mode 100644
index bd87bd89..00000000
--- a/app/server/model/plan/build_fix.go
+++ /dev/null
@@ -1,190 +0,0 @@
-package plan
-
-import (
- "encoding/json"
- "fmt"
- "log"
- "plandex-server/hooks"
- "plandex-server/model"
- "plandex-server/model/prompts"
- "plandex-server/types"
- "strings"
-
- "github.com/plandex/plandex/shared"
- "github.com/sashabaranov/go-openai"
-)
-
-func (fileState *activeBuildStreamFileState) fixFileLineNums() {
- auth := fileState.auth
- filePath := fileState.filePath
- activeBuild := fileState.activeBuild
- clients := fileState.clients
- planId := fileState.plan.Id
- branch := fileState.branch
- config := fileState.settings.ModelPack.GetAutoFix()
- incorrectlyUpdated := fileState.updated
-
- activePlan := GetActivePlan(planId, branch)
-
- if activePlan == nil {
- log.Printf("fixFileLineNums - Active plan not found for plan ID %s and branch %s\n", planId, branch)
- return
- }
-
- // hash := sha256.Sum256([]byte(incorrectlyUpdated))
- // sha := hex.EncodeToString(hash[:])
-
- // log.Printf("%s - fixFileLineNums - Incorrectly updated content hash: %s\n", filePath, sha)
-
- log.Println("fixFileLineNums - getting file from model: " + filePath)
- // log.Println("File context:", fileContext)
-
- reasoning := ""
- if len(fileState.syntaxErrors) > 0 {
- reasoning += "The following are syntax errors identified by the tree-sitter library. Here are line numbers:\n\n" + strings.Join(fileState.syntaxErrors, "\n")
- }
-
- if fileState.verificationErrors != "" {
- if len(fileState.syntaxErrors) > 0 {
- reasoning += "\n\n"
- reasoning += "The following are other problems identified in the file:\n\n"
- } else {
- reasoning += "Here are the problems identified in the file:\n\n"
- }
- reasoning += fileState.verificationErrors
- }
-
- sysPrompt := prompts.GetBuildFixesLineNumbersSysPrompt(fileState.preBuildState, fmt.Sprintf("%s\n\n```%s```", activeBuild.FileDescription, activeBuild.FileContent), incorrectlyUpdated, reasoning)
-
- fileMessages := []openai.ChatCompletionMessage{
- {
- Role: openai.ChatMessageRoleSystem,
- Content: sysPrompt,
- },
- }
-
- promptTokens, err := shared.GetNumTokens(sysPrompt)
-
- if err != nil {
- log.Printf("Error getting num tokens for prompt: %v\n", err)
- fileState.onBuildFileError(fmt.Errorf("error getting num tokens for prompt: %v", err))
- return
- }
-
- inputTokens := prompts.ExtraTokensPerRequest + prompts.ExtraTokensPerMessage + promptTokens
-
- fileState.inputTokens = inputTokens
-
- _, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
- Auth: auth,
- Plan: fileState.plan,
- WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
- InputTokens: inputTokens,
- OutputTokens: shared.AvailableModelsByName[fileState.settings.ModelPack.GetAutoFix().BaseModelConfig.ModelName].DefaultReservedOutputTokens,
- ModelName: fileState.settings.ModelPack.GetAutoFix().BaseModelConfig.ModelName,
- },
- })
- if apiErr != nil {
- activePlan.StreamDoneCh <- apiErr
- return
- }
-
- log.Println("fixFileLineNums - calling model for file: " + filePath)
-
- // for _, msg := range fileMessages {
- // log.Printf("%s: %s\n", msg.Role, msg.Content)
- // }
-
- var responseFormat *openai.ChatCompletionResponseFormat
- if config.BaseModelConfig.HasJsonResponseMode {
- responseFormat = &openai.ChatCompletionResponseFormat{Type: "json_object"}
- }
-
- // log.Println("responseFormat:", responseFormat)
- // log.Println("Model:", config.BaseModelConfig.ModelName)
-
- modelReq := openai.ChatCompletionRequest{
- Model: config.BaseModelConfig.ModelName,
- Tools: []openai.Tool{
- {
- Type: "function",
- Function: &prompts.ListReplacementsFn,
- },
- },
- ToolChoice: openai.ToolChoice{
- Type: "function",
- Function: openai.ToolFunction{
- Name: prompts.ListReplacementsFn.Name,
- },
- },
- Messages: fileMessages,
- Temperature: config.Temperature,
- TopP: config.TopP,
- ResponseFormat: responseFormat,
- StreamOptions: &openai.StreamOptions{
- IncludeUsage: true,
- },
- }
-
- envVar := config.BaseModelConfig.ApiKeyEnvVar
- client := clients[envVar]
-
- if config.BaseModelConfig.HasStreamingFunctionCalls {
-
- stream, err := model.CreateChatCompletionStreamWithRetries(client, activePlan.Ctx, modelReq)
- if err != nil {
- log.Printf("Error creating plan file stream for path '%s': %v\n", filePath, err)
- fileState.onBuildFileError(fmt.Errorf("error creating plan file stream for path '%s': %v", filePath, err))
- return
- }
-
- go fileState.listenStreamFixChanges(stream)
- } else {
- buildInfo := &shared.BuildInfo{
- Path: filePath,
- NumTokens: 0,
- Finished: false,
- }
- activePlan.Stream(shared.StreamMessage{
- Type: shared.StreamMessageBuildInfo,
- BuildInfo: buildInfo,
- })
-
- resp, err := model.CreateChatCompletionWithRetries(client, activePlan.Ctx, modelReq)
-
- if err != nil {
- log.Printf("Error building file '%s': %v\n", filePath, err)
- fileState.onBuildFileError(fmt.Errorf("error building file '%s': %v", filePath, err))
- return
- }
-
- var s string
- var res types.ChangesWithLineNums
-
- for _, choice := range resp.Choices {
- if len(choice.Message.ToolCalls) == 1 &&
- choice.Message.ToolCalls[0].Function.Name == prompts.ListReplacementsFn.Name {
- fnCall := choice.Message.ToolCalls[0].Function
- s = fnCall.Arguments
- break
- }
- }
-
- if s == "" {
- log.Println("no ListReplacements function call found in response")
- fileState.fixRetryOrAbort(fmt.Errorf("No ListReplacements function call found in response. This usually means the model failed to generate a valid response."))
- return
- }
-
- bytes := []byte(s)
-
- err = json.Unmarshal(bytes, &res)
- if err != nil {
- log.Printf("Error unmarshalling fix response: %v\n", err)
- fileState.fixRetryOrAbort(fmt.Errorf("Error unmarshalling fix response: %v | This usually means the model failed to generate valid JSON.", err))
- return
- }
-
- fileState.onFixResult(res)
- }
-}
diff --git a/app/server/model/plan/build_fix_result.go b/app/server/model/plan/build_fix_result.go
deleted file mode 100644
index d39f8ffb..00000000
--- a/app/server/model/plan/build_fix_result.go
+++ /dev/null
@@ -1,178 +0,0 @@
-package plan
-
-import (
- "fmt"
- "log"
- "math/rand"
- "plandex-server/types"
- "sort"
- "time"
-
- "github.com/davecgh/go-spew/spew"
- "github.com/plandex/plandex/shared"
-)
-
-func (fileState *activeBuildStreamFileState) onFixResult(res types.ChangesWithLineNums) {
-
- filePath := fileState.filePath
- build := fileState.build
- currentOrgId := fileState.currentOrgId
- planId := fileState.plan.Id
- branch := fileState.branch
-
- activePlan := GetActivePlan(planId, branch)
-
- if activePlan == nil {
- log.Printf("listenStreamFixChanges - Active plan not found for plan ID %s on branch %s\n", planId, branch)
- return
- }
- sorted := []*shared.StreamedChangeWithLineNums{}
-
- // Sort the changes by start line
- for _, change := range res.Changes {
- if change.HasChange {
- sorted = append(sorted, change)
- }
- }
-
- // Sort the changes by start line
- sort.Slice(sorted, func(i, j int) bool {
- var iStartLine int
- var jStartLine int
-
- // Convert the line number part to an integer
- iStartLine, _, err := sorted[i].Old.GetLines()
-
- if err != nil {
- log.Printf("listenStream - Error getting start line for change %v: %v\n", sorted[i], err)
- fileState.lineNumsRetryOrError(fmt.Errorf("listenStream - error getting start line for change %v: %v", sorted[i], err))
- return false
- }
-
- jStartLine, _, err = sorted[j].Old.GetLines()
-
- if err != nil {
- log.Printf("listenStream - Error getting start line for change %v: %v\n", sorted[j], err)
- fileState.lineNumsRetryOrError(fmt.Errorf("listenStream - error getting start line for change %v: %v", sorted[j], err))
- return false
- }
-
- return iStartLine < jStartLine
- })
-
- fileState.streamedChangesWithLineNums = sorted
-
- var overlapStrategy OverlapStrategy = OverlapStrategyError
- if fileState.fixFileNumRetry > 1 {
- overlapStrategy = OverlapStrategySkip
- }
-
- planFileResult, updated, allSucceeded, err := GetPlanResult(
- activePlan.Ctx,
- PlanResultParams{
- OrgId: currentOrgId,
- PlanId: planId,
- PlanBuildId: build.Id,
- ConvoMessageId: build.ConvoMessageId,
- FilePath: filePath,
- PreBuildState: fileState.updated,
- ChangesWithLineNums: res.Changes,
- OverlapStrategy: overlapStrategy,
-
- IsFix: true,
- IsSyntaxFix: fileState.isFixingSyntax,
- IsOtherFix: fileState.isFixingOther,
-
- FixEpoch: fileState.syntaxNumEpoch,
-
- CheckSyntax: true,
- },
- )
-
- if err != nil {
- log.Println("listenStreamFixChanges - Error getting plan result:", err)
- fileState.fixRetryOrAbort(fmt.Errorf("listenStreamFixChanges - error getting plan result for file '%s': %v", filePath, err))
- return
- }
-
- if !allSucceeded {
- log.Println("listenStreamFixChanges - Failed replacements:")
- for _, replacement := range planFileResult.Replacements {
- if replacement.Failed {
- spew.Dump(replacement)
- }
- }
-
- // no retry here as this should never happen
- fileState.onBuildFileError(fmt.Errorf("listenStreamFixChanges - replacements failed for file '%s'", filePath))
- return
-
- }
-
- log.Println("listenStreamFixChanges - Plan file result:")
- // spew.Dump(planFileResult)
-
- // reset fix state
- fileState.isFixingSyntax = false
- fileState.isFixingOther = false
-
- // if we are below the number of FixSyntaxRetries, and the syntax is invalid, short-circuit here and retry
- // otherwise if the syntax is invalid but we're out of retries, continue to onFinishBuildFile, which will handle epoch-based retries (i.e. running additional fixes on top of this failed fix) if applicable
- if planFileResult.WillCheckSyntax && !planFileResult.SyntaxValid {
- if fileState.syntaxNumRetry < FixSyntaxRetries {
- fileState.isFixingSyntax = true
- fileState.syntaxNumRetry++
- go fileState.fixFileLineNums()
- return
- }
- }
-
- buildInfo := &shared.BuildInfo{
- Path: filePath,
- NumTokens: 0,
- Finished: true,
- }
- activePlan.Stream(shared.StreamMessage{
- Type: shared.StreamMessageBuildInfo,
- BuildInfo: buildInfo,
- })
- time.Sleep(50 * time.Millisecond)
-
- fileState.onFinishBuildFile(planFileResult, updated)
-}
-
-func (fileState *activeBuildStreamFileState) fixRetryOrAbort(err error) {
- if fileState.fixFileNumRetry < MaxBuildErrorRetries {
- fileState.fixFileNumRetry++
- fileState.activeBuild.FixBuffer = ""
- fileState.activeBuild.FixBufferTokens = 0
- log.Printf("Retrying fix file '%s' due to error: %v\n", fileState.filePath, err)
-
- // Exponential backoff
- time.Sleep(time.Duration((fileState.verifyFileNumRetry*fileState.verifyFileNumRetry)/2)*200*time.Millisecond + time.Duration(rand.Intn(500))*time.Millisecond)
-
- fileState.fixFileLineNums()
- } else {
- log.Printf("Aborting fix file '%s' due to error: %v\n", fileState.filePath, err)
-
- activePlan := GetActivePlan(fileState.plan.Id, fileState.branch)
-
- if activePlan == nil {
- log.Println("fixRetryOrAbort - Active plan not found")
- return
- }
-
- buildInfo := &shared.BuildInfo{
- Path: fileState.filePath,
- NumTokens: 0,
- Finished: true,
- }
- activePlan.Stream(shared.StreamMessage{
- Type: shared.StreamMessageBuildInfo,
- BuildInfo: buildInfo,
- })
- time.Sleep(50 * time.Millisecond)
-
- fileState.onFinishBuildFile(nil, "")
- }
-}
diff --git a/app/server/model/plan/build_fix_stream.go b/app/server/model/plan/build_fix_stream.go
deleted file mode 100644
index 65685932..00000000
--- a/app/server/model/plan/build_fix_stream.go
+++ /dev/null
@@ -1,236 +0,0 @@
-package plan
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "log"
- "math"
- "plandex-server/hooks"
- "plandex-server/model"
- "plandex-server/types"
- "strings"
- "time"
-
- "github.com/davecgh/go-spew/spew"
- "github.com/plandex/plandex/shared"
- "github.com/sashabaranov/go-openai"
-)
-
-func (fileState *activeBuildStreamFileState) listenStreamFixChanges(stream *openai.ChatCompletionStream) {
- auth := fileState.auth
- filePath := fileState.filePath
- planId := fileState.plan.Id
- branch := fileState.branch
-
- activePlan := GetActivePlan(planId, branch)
-
- if activePlan == nil {
- log.Printf("listenStreamFixChanges - Active plan not found for plan ID %s on branch %s\n", planId, branch)
- return
- }
-
- defer stream.Close()
-
- // Create a timer that will trigger if no chunk is received within the specified duration
- timer := time.NewTimer(model.OPENAI_STREAM_CHUNK_TIMEOUT)
- defer timer.Stop()
-
- streamFinished := false
-
- execHookOnStop := func(sendStreamErr bool) {
- _, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- Auth: auth,
- Plan: fileState.plan,
- DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
- InputTokens: fileState.inputTokens,
- OutputTokens: fileState.activeBuild.FixBufferTokens,
- ModelName: fileState.settings.ModelPack.GetAutoFix().BaseModelConfig.ModelName,
- ModelProvider: fileState.settings.ModelPack.GetAutoFix().BaseModelConfig.Provider,
- ModelPackName: fileState.settings.ModelPack.Name,
- ModelRole: shared.ModelRoleAutoFix,
- Purpose: "Generated file update for auto-fix",
- },
- })
-
- if apiErr != nil {
- log.Printf("Error executing did send model request hook after cancel or error: %v\n", apiErr)
-
- if sendStreamErr {
- activePlan := GetActivePlan(planId, branch)
-
- if activePlan == nil {
- log.Printf("listenStreamFixChanges - Active plan not found for plan ID %s on branch %s\n", planId, branch)
- return
- }
-
- activePlan.StreamDoneCh <- apiErr
- }
- }
- }
-
- for {
- select {
- case <-activePlan.Ctx.Done():
- // The main context was canceled (not the timer)
- execHookOnStop(false)
- return
- case <-timer.C:
- log.Println("\nFix: stream timed out due to inactivity")
-
- execHookOnStop(true)
-
- if streamFinished {
- log.Println("\nFix stream finished-timed out waiting for usage chunk")
- return
- }
-
- fileState.fixRetryOrAbort(fmt.Errorf("listenStreamFixChanges - stream timeout due to inactivity for file '%s' | This usually means the model is not responding.", filePath))
- return
- default:
- response, err := stream.Recv()
-
- if err == nil {
- // Successfully received a chunk, reset the timer
- if !timer.Stop() {
- <-timer.C
- }
- timer.Reset(model.OPENAI_STREAM_CHUNK_TIMEOUT)
- } else {
- log.Printf("listenStreamFixChanges - File %s: Error receiving stream chunk: %v\n", filePath, err)
-
- if err == context.Canceled {
- log.Printf("listenStreamFixChanges - File %s: Stream canceled\n", filePath)
- execHookOnStop(false)
- return
- }
-
- execHookOnStop(true)
-
- if !streamFinished {
- fileState.fixRetryOrAbort(fmt.Errorf("listenStreamFixChanges - stream error: %v", err))
- }
- return
- }
-
- if len(response.Choices) == 0 {
- if response.Usage != nil {
- log.Println("Fix stream usage:")
- spew.Dump(response.Usage)
-
- _, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- Auth: auth,
- Plan: fileState.plan,
- DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
- InputTokens: response.Usage.PromptTokens,
- OutputTokens: response.Usage.CompletionTokens,
- ModelName: fileState.settings.ModelPack.GetAutoFix().BaseModelConfig.ModelName,
- ModelProvider: fileState.settings.ModelPack.GetAutoFix().BaseModelConfig.Provider,
- ModelPackName: fileState.settings.ModelPack.Name,
- ModelRole: shared.ModelRoleAutoFix,
- Purpose: "Generated file update for auto-fix",
- },
- })
-
- if apiErr != nil {
- log.Printf("Fix stream: error executing did send model request hook: %v\n", apiErr)
-
- // ensure the active plan is still available
- activePlan := GetActivePlan(planId, branch)
-
- if activePlan == nil {
- log.Printf(" Active plan not found for plan ID %s on branch %s\n", planId, branch)
- return
- }
-
- activePlan.StreamDoneCh <- apiErr
- }
- return
- }
-
- execHookOnStop(true)
- fileState.fixRetryOrAbort(fmt.Errorf("listenStreamFixChanges - stream error: no choices | This usually means the model failed to generate a valid response."))
- return
- }
-
- // if stream finished and it's not a usage chunk, keep listening for usage chunk
- if streamFinished {
- // log.Printf("listenStreamFixChanges - File %s: Stream finished, no usage chunk-will keep listening\n", filePath)
- continue
- }
-
- var content string
- choice := response.Choices[0]
- delta := choice.Delta
-
- if len(delta.ToolCalls) > 0 {
- content = delta.ToolCalls[0].Function.Arguments
-
- trimmed := strings.TrimSpace(content)
- if trimmed == "{%invalidjson%}" || trimmed == "``(no output)``````" {
- log.Println("listenStreamFixChanges - File", filePath+":", "%invalidjson%} token in streamed chunk")
- execHookOnStop(true)
- fileState.fixRetryOrAbort(fmt.Errorf("listenStreamFixChanges - invalid JSON in streamed chunk for file '%s' | This usually means the model failed to generate valid JSON.", filePath))
- return
- }
-
- buildInfo := &shared.BuildInfo{
- Path: filePath,
- NumTokens: 1,
- Finished: false,
- }
-
- // log.Printf("listenStreamFixChanges - %s: %s", filePath, content)
- activePlan.Stream(shared.StreamMessage{
- Type: shared.StreamMessageBuildInfo,
- BuildInfo: buildInfo,
- })
-
- fileState.activeBuild.FixBuffer += content
- fileState.activeBuild.FixBufferTokens++
-
- // After a reasonable threshhold, if buffer has significantly more tokens than original file + proposed changes, something is wrong
- cutoff := int(math.Max(float64(fileState.activeBuild.CurrentFileTokens+fileState.activeBuild.FileContentTokens), 500) * 20)
- if fileState.activeBuild.FixBufferTokens > 500 && fileState.activeBuild.FixBufferTokens > cutoff {
- log.Printf("File %s: Stream buffer tokens too high\n", filePath)
- log.Printf("Current file tokens: %d\n", fileState.activeBuild.CurrentFileTokens)
- log.Printf("File content tokens: %d\n", fileState.activeBuild.FileContentTokens)
- log.Printf("Cutoff: %d\n", cutoff)
- log.Printf("Buffer tokens: %d\n", fileState.activeBuild.FixBufferTokens)
- log.Println("Buffer:")
- log.Println(fileState.activeBuild.FixBuffer)
-
- execHookOnStop(true)
- fileState.fixRetryOrAbort(fmt.Errorf("listenStreamFixChanges - stream buffer tokens too high for file '%s' | This usually means the model failed to generate valid JSON.", filePath))
- return
- }
- }
-
- var streamed types.ChangesWithLineNums
- err = json.Unmarshal([]byte(fileState.activeBuild.FixBuffer), &streamed)
-
- if err == nil {
- log.Printf("listenStreamFixChanges - File %s: Parsed streamed replacements\n", filePath)
- // spew.Dump(streamed)
- streamFinished = true // Stream finished successfully
-
- log.Printf("listenStreamFixChanges - File %s: Stream finished\n", filePath)
- fileState.onFixResult(streamed)
-
- // Reset the timer for the usage chunk
- if !timer.Stop() {
- <-timer.C
- }
- timer.Reset(model.OPENAI_USAGE_CHUNK_TIMEOUT)
-
- continue // continue for usage chunk
- } else if len(delta.ToolCalls) == 0 {
- log.Printf("listenStreamFixChanges - File %s: Stream chunk missing function call. Reason: %s\n", filePath, choice.FinishReason)
-
- execHookOnStop(true)
- fileState.fixRetryOrAbort(fmt.Errorf("listenStreamFixChanges - stream chunk missing function call. File: %s | This usually means the model failed to generate a valid response.", filePath))
- return
- }
- }
- }
-}
diff --git a/app/server/model/plan/build_full_file.go b/app/server/model/plan/build_full_file.go
new file mode 100644
index 00000000..8203775d
--- /dev/null
+++ b/app/server/model/plan/build_full_file.go
@@ -0,0 +1,29 @@
+package plan
+
+import (
+ "fmt"
+ "log"
+)
+
+func (fileState *activeBuildStreamFileState) buildFullFile() {
+ auth := fileState.auth
+ filePath := fileState.filePath
+ activeBuild := fileState.activeBuild
+ clients := fileState.clients
+ planId := fileState.plan.Id
+ branch := fileState.branch
+ config := fileState.settings.ModelPack.Builder
+ originalFile := fileState.preBuildState
+
+ activePlan := GetActivePlan(planId, branch)
+
+ if activePlan == nil {
+ log.Printf("Active plan not found for plan ID %s and branch %s\n", planId, branch)
+ fileState.onBuildFileError(fmt.Errorf("active plan not found for plan ID %s and branch %s", planId, branch))
+ return
+ }
+
+ proposedContent := activeBuild.FileContent
+ desc := activeBuild.FileDescription
+
+}
diff --git a/app/server/model/plan/build_refs.go b/app/server/model/plan/build_refs.go
deleted file mode 100644
index 26cf60ed..00000000
--- a/app/server/model/plan/build_refs.go
+++ /dev/null
@@ -1,289 +0,0 @@
-package plan
-
-import (
- "encoding/xml"
- "fmt"
- "log"
- "math/rand"
- "plandex-server/db"
- "plandex-server/diff"
- "plandex-server/hooks"
- "plandex-server/model"
- "plandex-server/model/prompts"
- "plandex-server/syntax"
- "strings"
- "time"
-
- "github.com/davecgh/go-spew/spew"
- "github.com/plandex/plandex/shared"
- "github.com/sashabaranov/go-openai"
-)
-
-type Reference struct {
- Comment string `xml:"comment,attr"`
- Description string `xml:"description,attr"`
- ProposedLine string `xml:"proposedLine,attr"`
- OriginalStart string `xml:"originalStart,attr"`
- OriginalEnd string `xml:"originalEnd,attr"`
-}
-
-type References struct {
- XMLName xml.Name `xml:"references"`
- References []Reference `xml:"reference"`
-}
-
-const ExpandRefsRetries = 1
-
-func (fileState *activeBuildStreamFileState) buildExpandReferences() {
- auth := fileState.auth
- filePath := fileState.filePath
- activeBuild := fileState.activeBuild
- clients := fileState.clients
- planId := fileState.plan.Id
- branch := fileState.branch
- config := fileState.settings.ModelPack.Builder
- originalFile := fileState.preBuildState
-
- activePlan := GetActivePlan(planId, branch)
-
- if activePlan == nil {
- log.Printf("Active plan not found for plan ID %s and branch %s\n", planId, branch)
- return
- }
-
- log.Println("buildExpandReferences - getting references prompt")
-
- refsSysPrompt := prompts.GetReferencesPrompt(filePath, originalFile, activeBuild.FileContent, activeBuild.FileDescription)
-
- refsFileMessages := []openai.ChatCompletionMessage{
- {
- Role: openai.ChatMessageRoleSystem,
- Content: refsSysPrompt,
- },
- }
-
- promptTokens, err := shared.GetNumTokens(refsSysPrompt)
-
- if err != nil {
- log.Printf("buildExpandReferences - error getting num tokens for prompt: %v\n", err)
- fileState.onBuildFileError(fmt.Errorf("error getting num tokens for prompt: %v", err))
- return
- }
-
- inputTokens := prompts.ExtraTokensPerRequest + prompts.ExtraTokensPerMessage + promptTokens
-
- fileState.inputTokens = inputTokens
-
- _, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
- Auth: auth,
- Plan: fileState.plan,
- WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
- InputTokens: inputTokens,
- OutputTokens: shared.AvailableModelsByName[fileState.settings.ModelPack.Builder.BaseModelConfig.ModelName].DefaultReservedOutputTokens,
- ModelName: fileState.settings.ModelPack.Builder.BaseModelConfig.ModelName,
- },
- })
- if apiErr != nil {
- activePlan.StreamDoneCh <- apiErr
- return
- }
-
- log.Println("buildExpandReferences - calling model for references")
-
- modelReq := openai.ChatCompletionRequest{
- Model: config.BaseModelConfig.ModelName,
- Messages: refsFileMessages,
- Temperature: config.Temperature,
- TopP: config.TopP,
- }
-
- envVar := config.BaseModelConfig.ApiKeyEnvVar
- client := clients[envVar]
-
- resp, err := model.CreateChatCompletionWithRetries(client, activePlan.Ctx, modelReq)
-
- if err != nil {
- log.Printf("buildExpandReferences - error calling model: %v\n", err)
- fileState.expandRefsRetryOrError(fmt.Errorf("error calling model: %v", err))
- return
- }
-
- log.Println("buildExpandReferences - usage:")
- spew.Dump(resp.Usage)
-
- _, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- Auth: auth,
- Plan: fileState.plan,
- DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
- InputTokens: resp.Usage.PromptTokens,
- OutputTokens: resp.Usage.CompletionTokens,
- ModelName: fileState.settings.ModelPack.Builder.BaseModelConfig.ModelName,
- ModelProvider: fileState.settings.ModelPack.Builder.BaseModelConfig.Provider,
- ModelPackName: fileState.settings.ModelPack.Name,
- ModelRole: shared.ModelRoleBuilder,
- Purpose: "Generated file update (ref expansion)",
- },
- })
-
- if apiErr != nil {
- activePlan.StreamDoneCh <- apiErr
- return
- }
-
- if len(resp.Choices) == 0 {
- log.Printf("buildExpandReferences - no choices in response\n")
- fileState.expandRefsRetryOrError(fmt.Errorf("no choices in response"))
- return
- }
-
- refsChoice := resp.Choices[0]
- refsXml := refsChoice.Message.Content
-
- log.Println("buildExpandReferences - refsXml:")
- log.Println(refsXml)
-
- refsSplit := strings.Split(refsXml, "<references>")
- if len(refsSplit) != 2 {
- log.Printf("buildExpandReferences - error processing references xml\n")
- fileState.expandRefsRetryOrError(fmt.Errorf("error processing references xml"))
- return
- }
-
- processedXml := "<references>" + refsSplit[1]
- processedXml = EscapeInvalidXMLAttributeCharacters(processedXml)
- refsXml = processedXml
-
- var refs References
-
- err = xml.Unmarshal([]byte(processedXml), &refs)
- if err != nil {
- log.Printf("buildExpandReferences - error unmarshalling xml: %v\n", err)
- fileState.expandRefsRetryOrError(fmt.Errorf("error unmarshalling xml: %v", err))
- return
- }
-
- log.Printf("buildExpandReferences - got %d references\n", len(refs.References))
-
- fileContentLines := strings.Split(activeBuild.FileContent, "\n")
- inputTextLines := strings.Split(originalFile, "\n")
-
- for _, ref := range refs.References {
- var proposedLine, originalStart, originalEnd int
-
- proposedLine, err = shared.ExtractLineNumberWithPrefix(ref.ProposedLine, "pdx-new-")
- if err != nil {
- log.Printf("Error extracting line number from proposed line: %v", err)
- fileState.expandRefsRetryOrError(fmt.Errorf("error extracting line number from proposed line: %v", err))
- return
- }
-
- originalStart, err = shared.ExtractLineNumberWithPrefix(ref.OriginalStart, "pdx-")
- if err != nil {
- log.Printf("Error extracting line number from start: %v", err)
- fileState.expandRefsRetryOrError(fmt.Errorf("error extracting line number from start: %v", err))
- return
- }
- originalEnd, err = shared.ExtractLineNumberWithPrefix(ref.OriginalEnd, "pdx-")
- if err != nil {
- log.Printf("Error extracting line number from end: %v", err)
- fileState.expandRefsRetryOrError(fmt.Errorf("error extracting line number from end: %v", err))
- return
- }
-
- if originalStart > originalEnd {
- originalStart, originalEnd = originalEnd, originalStart
- }
-
- if originalEnd > len(inputTextLines) {
- log.Printf("Start line is greater than end line or end line is greater than the number of lines in the file: %d > %d", originalStart, originalEnd)
- fileState.expandRefsRetryOrError(fmt.Errorf("start line is greater than end line or end line is greater than the number of lines in the file: %d > %d", originalStart, originalEnd))
- return
- }
-
- // Replace the proposed line with the referenced section from inputTextLines
- referencedSection := inputTextLines[originalStart-1 : originalEnd]
-
- if proposedLine-1 >= 0 && proposedLine-1 < len(fileContentLines) {
- fileContentLines[proposedLine-1] = strings.Join(referencedSection, "\n")
- } else {
- log.Printf("Proposed line is out of bounds: %d", proposedLine)
- fileState.expandRefsRetryOrError(fmt.Errorf("proposed line is out of bounds: %d", proposedLine))
- return
- }
- }
-
- updatedFile := strings.Join(fileContentLines, "\n")
-
- buildInfo := &shared.BuildInfo{
- Path: filePath,
- NumTokens: 0,
- Finished: true,
- }
- activePlan.Stream(shared.StreamMessage{
- Type: shared.StreamMessageBuildInfo,
- BuildInfo: buildInfo,
- })
- time.Sleep(50 * time.Millisecond)
-
- fileState.updated = updatedFile
-
- replacements, err := diff.GetDiffReplacements(originalFile, updatedFile)
- if err != nil {
- log.Printf("buildExpandReferences - error getting diff replacements: %v\n", err)
- fileState.expandRefsRetryOrError(fmt.Errorf("error getting diff replacements: %v", err))
- return
- }
-
- res := db.PlanFileResult{
- TypeVersion: 1,
- OrgId: fileState.plan.OrgId,
- PlanId: fileState.plan.Id,
- PlanBuildId: fileState.build.Id,
- ConvoMessageId: fileState.convoMessageId,
- Content: "",
- Path: filePath,
- Replacements: replacements,
- CanVerify: false, // not sure yet whether verification is needed with ref expansion
- }
-
- validationRes, err := syntax.Validate(activePlan.Ctx, filePath, updatedFile)
- if err != nil {
- log.Printf("buildExpandReferences - error validating syntax: %v\n", err)
- fileState.expandRefsRetryOrError(fmt.Errorf("error validating syntax: %v", err))
- return
- }
-
- res.WillCheckSyntax = validationRes.HasParser && !validationRes.TimedOut
- res.SyntaxValid = validationRes.Valid
- res.SyntaxErrors = validationRes.Errors
-
- fileState.onFinishBuildFile(&res, updatedFile)
-}
-
-func (fileState *activeBuildStreamFileState) expandRefsRetryOrError(err error) {
- if fileState.expandRefsNumRetry < ExpandRefsRetries {
- fileState.expandRefsNumRetry++
-
- log.Printf("buildExpandReferences - retrying expand refs file '%s' due to error: %v\n", fileState.filePath, err)
-
- activePlan := GetActivePlan(fileState.plan.Id, fileState.branch)
-
- if activePlan == nil {
- log.Printf("buildExpandReferences - active plan not found for plan ID %s and branch %s\n", fileState.plan.Id, fileState.branch)
- return
- }
-
- select {
- case <-activePlan.Ctx.Done():
- log.Printf("buildExpandReferences - context canceled\n")
- return
- case <-time.After(time.Duration(fileState.expandRefsNumRetry*fileState.expandRefsNumRetry)*200*time.Millisecond + time.Duration(rand.Intn(500))*time.Millisecond):
- break
- }
-
- fileState.buildExpandReferences()
- } else {
- fileState.onBuildFileError(err)
- }
-
-}
diff --git a/app/server/model/plan/build_result.go b/app/server/model/plan/build_result.go
index 26cfba09..44107ea9 100644
--- a/app/server/model/plan/build_result.go
+++ b/app/server/model/plan/build_result.go
@@ -4,13 +4,10 @@ import (
"context"
"fmt"
"log"
- "math/rand"
"plandex-server/db"
"plandex-server/syntax"
- "plandex-server/types"
"sort"
"strings"
- "time"
"github.com/davecgh/go-spew/spew"
"github.com/google/uuid"
@@ -317,11 +314,6 @@ func GetPlanResultUpdated(ctx context.Context, params PlanResultParamsUpdated) (
Path: filePath,
Replacements: replacements,
AnyFailed: !allSucceeded,
- CanVerify: !params.IsOtherFix,
- IsFix: params.IsFix,
- IsSyntaxFix: params.IsSyntaxFix,
- IsOtherFix: params.IsOtherFix,
- FixEpoch: params.FixEpoch,
}
if params.CheckSyntax {
@@ -339,145 +331,6 @@ func GetPlanResultUpdated(ctx context.Context, params PlanResultParamsUpdated) (
return &res, updated, allSucceeded, nil
}
-func (fileState *activeBuildStreamFileState) onLineNumsBuildResult(res types.ChangesWithLineNums) {
- log.Printf("onLineNumsBuildResult - File: %s\n", fileState.filePath)
-
- filePath := fileState.filePath
- build := fileState.build
- currentOrgId := fileState.currentOrgId
- planId := fileState.plan.Id
- branch := fileState.branch
- preBuildState := fileState.preBuildState
-
- activePlan := GetActivePlan(planId, branch)
-
- if activePlan == nil {
- log.Printf("onLineNumsBuildResult - File %s: Active plan not found for plan ID %s on branch %s\n", filePath, planId, branch)
- return
- }
-
- sorted := []*shared.StreamedChangeWithLineNums{}
-
- for _, change := range res.Changes {
- if change.HasChange {
- sorted = append(sorted, change)
- }
- }
-
- // Sort the streamed changes by start line
- sort.Slice(sorted, func(i, j int) bool {
- var iStartLine int
- var jStartLine int
-
- iStartLine, _, err := sorted[i].Old.GetLines()
-
- if err != nil {
- log.Printf("onLineNumsBuildResult - File %s: Error getting start line for change %v: %v\n", filePath, sorted[i], err)
- fileState.lineNumsRetryOrError(fmt.Errorf("onLineNumsBuildResult - error getting start line for change %v: %v", sorted[i], err))
- return false
- }
-
- jStartLine, _, err = sorted[j].Old.GetLines()
-
- if err != nil {
- log.Printf("onLineNumsBuildResult - File %s: Error getting start line for change %v: %v\n", filePath, sorted[j], err)
- fileState.lineNumsRetryOrError(fmt.Errorf("onLineNumsBuildResult - error getting start line for change %v: %v", sorted[j], err))
- return false
- }
-
- return iStartLine < jStartLine
- })
-
- log.Printf("onLineNumsBuildResult - File %s: fileState.streamedChangesWithLineNums = sorted\n", filePath)
- log.Printf("onLineNumsBuildResult - File %s: num changes: %d\n", filePath, len(sorted))
-
- fileState.streamedChangesWithLineNums = sorted
-
- var overlapStrategy OverlapStrategy = OverlapStrategyError
- if fileState.lineNumsNumRetry > 1 {
- overlapStrategy = OverlapStrategySkip
- }
-
- planFileResult, updatedFile, allSucceeded, err := GetPlanResult(
- activePlan.Ctx,
- PlanResultParams{
- OrgId: currentOrgId,
- PlanId: planId,
- PlanBuildId: build.Id,
- ConvoMessageId: build.ConvoMessageId,
- FilePath: filePath,
- PreBuildState: preBuildState,
- ChangesWithLineNums: sorted,
- OverlapStrategy: overlapStrategy,
- CheckSyntax: false,
- },
- )
-
- if err != nil {
- log.Printf("onLineNumsBuildResult - File %s: Error getting plan result: %v\n", filePath, err)
- fileState.lineNumsRetryOrError(fmt.Errorf("onLineNumsBuildResult - error getting plan result for file '%s': %v", filePath, err))
- return
- }
-
- if !allSucceeded {
- log.Printf("onLineNumsBuildResult - File %s: Failed replacements:\n", filePath)
- for _, replacement := range planFileResult.Replacements {
- if replacement.Failed {
- spew.Dump(replacement)
- }
- }
-
- fileState.onBuildFileError(fmt.Errorf("onLineNumsBuildResult - replacements failed for file '%s'", filePath))
- return
- }
-
- buildInfo := &shared.BuildInfo{
- Path: filePath,
- NumTokens: 0,
- Finished: true,
- }
- activePlan.Stream(shared.StreamMessage{
- Type: shared.StreamMessageBuildInfo,
- BuildInfo: buildInfo,
- })
- time.Sleep(50 * time.Millisecond)
-
- fileState.updated = updatedFile
-
- log.Printf("onLineNumsBuildResult - File %s: Plan file result: %v\n", filePath, planFileResult != nil)
- log.Printf("onLineNumsBuildResult - File %s: updatedFile exists: %v\n", filePath, updatedFile != "")
-
- fileState.onFinishBuildFile(planFileResult, updatedFile)
-}
-
-func (fileState *activeBuildStreamFileState) lineNumsRetryOrError(err error) {
- if fileState.lineNumsNumRetry < MaxBuildErrorRetries {
- fileState.lineNumsNumRetry++
- fileState.activeBuild.WithLineNumsBuffer = ""
- fileState.activeBuild.WithLineNumsBufferTokens = 0
- log.Printf("lineNumsRetryOrError - Retrying line nums build file '%s' due to error: %v\n", fileState.filePath, err)
-
- activePlan := GetActivePlan(fileState.plan.Id, fileState.branch)
-
- if activePlan == nil {
- log.Printf("lineNumsRetryOrError - File %s: Active plan not found\n", fileState.filePath)
- return
- }
-
- select {
- case <-activePlan.Ctx.Done():
- log.Printf("lineNumsRetryOrError - File %s: Context canceled. Exiting.\n", fileState.filePath)
- return
- case <-time.After(time.Duration((fileState.verifyFileNumRetry*fileState.verifyFileNumRetry)/2)*200*time.Millisecond + time.Duration(rand.Intn(500))*time.Millisecond):
- break
- }
-
- fileState.buildFileLineNums()
- } else {
- fileState.onBuildFileError(err)
- }
-}
-
func GetPlanResult(ctx context.Context, params PlanResultParams) (*db.PlanFileResult, string, bool, error) {
orgId := params.OrgId
planId := params.PlanId
@@ -596,11 +449,6 @@ func GetPlanResult(ctx context.Context, params PlanResultParams) (*db.PlanFileRe
Path: filePath,
Replacements: replacements,
AnyFailed: !allSucceeded,
- CanVerify: !params.IsOtherFix,
- IsFix: params.IsFix,
- IsSyntaxFix: params.IsSyntaxFix,
- IsOtherFix: params.IsOtherFix,
- FixEpoch: params.FixEpoch,
}
if params.CheckSyntax {
diff --git a/app/server/model/plan/build_stream_line_nums.go b/app/server/model/plan/build_stream_line_nums.go
deleted file mode 100644
index 567c74a1..00000000
--- a/app/server/model/plan/build_stream_line_nums.go
+++ /dev/null
@@ -1,248 +0,0 @@
-package plan
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "log"
- "math"
- "plandex-server/hooks"
- "plandex-server/model"
- "plandex-server/types"
- "strings"
- "time"
-
- "github.com/davecgh/go-spew/spew"
- "github.com/plandex/plandex/shared"
- "github.com/sashabaranov/go-openai"
-)
-
-func (fileState *activeBuildStreamFileState) listenStreamChangesWithLineNums(stream *openai.ChatCompletionStream) {
- auth := fileState.auth
- filePath := fileState.filePath
- planId := fileState.plan.Id
- branch := fileState.branch
-
- log.Printf("listenStream - Listening for streamed changes with line numbers for file %s\n", filePath)
-
- activePlan := GetActivePlan(planId, branch)
-
- if activePlan == nil {
- log.Printf("listenStream - Active plan not found for plan ID %s on branch %s\n", planId, branch)
- return
- }
-
- defer stream.Close()
-
- // Create a timer that will trigger if no chunk is received within the specified duration
- timer := time.NewTimer(model.OPENAI_STREAM_CHUNK_TIMEOUT)
- defer timer.Stop()
-
- streamFinished := false
-
- execHookOnStop := func(sendStreamErr bool) {
- _, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- Auth: auth,
- Plan: fileState.plan,
- DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
- InputTokens: fileState.inputTokens,
- OutputTokens: fileState.activeBuild.WithLineNumsBufferTokens,
- ModelName: fileState.settings.ModelPack.Builder.BaseModelConfig.ModelName,
- ModelProvider: fileState.settings.ModelPack.Builder.BaseModelConfig.Provider,
- ModelPackName: fileState.settings.ModelPack.Name,
- ModelRole: shared.ModelRoleBuilder,
- Purpose: "Generated file update (line numbers)",
- },
- })
-
- if apiErr != nil {
- log.Printf("Error executing did send model request hook after cancel or error: %v\n", apiErr)
-
- if sendStreamErr {
- activePlan := GetActivePlan(planId, branch)
-
- if activePlan == nil {
- log.Printf("listenStream - Active plan not found for plan ID %s on branch %s\n", planId, branch)
- return
- }
-
- activePlan.StreamDoneCh <- apiErr
- }
- }
- }
-
- log.Printf("listenStream - File %s: Listening for stream chunks\n", filePath)
-
- for {
- select {
- case <-activePlan.Ctx.Done():
- // The main context was canceled (not the timer)
- execHookOnStop(false)
- return
- case <-timer.C:
- log.Println("\nBuild: stream timed out due to inactivity")
- execHookOnStop(true)
- if streamFinished {
- log.Println("\nBuild stream finished-timed out waiting for usage chunk")
- return
- }
-
- fileState.lineNumsRetryOrError(fmt.Errorf("listenStream - stream timeout due to inactivity for file '%s' | This usually means the model is not responding.", filePath))
- return
- default:
- response, err := stream.Recv()
-
- if err == nil {
- // Successfully received a chunk, reset the timer
- if !timer.Stop() {
- <-timer.C
- }
- timer.Reset(model.OPENAI_STREAM_CHUNK_TIMEOUT)
- } else {
- log.Printf("listenStream - File %s: Error receiving stream chunk: %v\n", filePath, err)
-
- if err == context.Canceled {
- log.Printf("listenStream - File %s: Stream canceled\n", filePath)
- // log.Println("current buffer:")
- // log.Println(fileState.activeBuild.WithLineNumsBuffer)
- execHookOnStop(false)
- return
- }
-
- execHookOnStop(true)
-
- if !streamFinished {
- fileState.lineNumsRetryOrError(fmt.Errorf("listenStream - stream error for file '%s': %v", filePath, err))
- }
- return
- }
-
- if len(response.Choices) == 0 {
- if response.Usage != nil {
- log.Printf("listenStream - File %s: Stream usage chunk\n", filePath)
- spew.Dump(response.Usage)
-
- _, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- Auth: auth,
- Plan: fileState.plan,
- DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
- InputTokens: response.Usage.PromptTokens,
- OutputTokens: response.Usage.CompletionTokens,
- ModelName: fileState.settings.ModelPack.Builder.BaseModelConfig.ModelName,
- ModelProvider: fileState.settings.ModelPack.Builder.BaseModelConfig.Provider,
- ModelPackName: fileState.settings.ModelPack.Name,
- ModelRole: shared.ModelRoleBuilder,
- Purpose: "Generated file update",
- },
- })
-
- if apiErr != nil {
- log.Printf("Build stream: error executing did send model request hook: %v\n", apiErr)
-
- // ensure the active plan is still available
- activePlan := GetActivePlan(planId, branch)
-
- if activePlan == nil {
- log.Printf(" Active plan not found for plan ID %s on branch %s\n", planId, branch)
- return
- }
-
- activePlan.StreamDoneCh <- apiErr
- }
- return
- }
-
- execHookOnStop(true)
- fileState.lineNumsRetryOrError(fmt.Errorf("listenStream - stream error: no choices | This usually means the model failed to generate a valid response."))
- return
- }
-
- // if stream finished and it's not a usage chunk, keep listening for usage chunk
- if streamFinished {
- // log.Printf("listenStream - File %s: Stream finished, no usage chunk-will keep listening\n", filePath)
- continue
- }
-
- choice := response.Choices[0]
- var content string
- delta := response.Choices[0].Delta
-
- if len(delta.ToolCalls) > 0 {
- content = delta.ToolCalls[0].Function.Arguments
-
- trimmed := strings.TrimSpace(content)
- if trimmed == "{%invalidjson%}" || trimmed == "``(no output)``````" {
- log.Println("File", filePath+":", "%invalidjson%} token in streamed chunk")
- execHookOnStop(true)
- fileState.lineNumsRetryOrError(fmt.Errorf("Invalid JSON in streamed chunk for file '%s' | This usually means the model failed to generate valid JSON.", filePath))
- return
- }
-
- buildInfo := &shared.BuildInfo{
- Path: filePath,
- NumTokens: 1,
- Finished: false,
- }
-
- // log.Printf("%s: %s", filePath, content)
- activePlan.Stream(shared.StreamMessage{
- Type: shared.StreamMessageBuildInfo,
- BuildInfo: buildInfo,
- })
-
- fileState.activeBuild.WithLineNumsBuffer += content
- fileState.activeBuild.WithLineNumsBufferTokens++
-
- // After a reasonable threshhold, if buffer has significantly more tokens than original file + proposed changes, something is wrong
- cutoff := int(math.Max(float64(fileState.activeBuild.CurrentFileTokens+fileState.activeBuild.FileContentTokens), 500) * 20)
- if fileState.activeBuild.WithLineNumsBufferTokens > 500 && fileState.activeBuild.WithLineNumsBufferTokens > cutoff {
- log.Printf("File %s: Stream buffer tokens too high\n", filePath)
- log.Printf("Current file tokens: %d\n", fileState.activeBuild.CurrentFileTokens)
- log.Printf("File content tokens: %d\n", fileState.activeBuild.FileContentTokens)
- log.Printf("Cutoff: %d\n", cutoff)
- log.Printf("Buffer tokens: %d\n", fileState.activeBuild.WithLineNumsBufferTokens)
- log.Println("Buffer:")
- log.Println(fileState.activeBuild.WithLineNumsBuffer)
-
- execHookOnStop(true)
- fileState.lineNumsRetryOrError(fmt.Errorf("listenStream - stream buffer tokens too high for file '%s' | This usually means the model failed to generate valid JSON.", filePath))
- return
- }
- }
-
- var streamed types.ChangesWithLineNums
- err = json.Unmarshal([]byte(fileState.activeBuild.WithLineNumsBuffer), &streamed)
-
- if err == nil {
- log.Printf("listenStream - File %s: Parsed streamed replacements\n", filePath)
- // spew.Dump(streamed)
-
- streamFinished = true // Stream finished successfully
-
- log.Printf("listenStream - File %s: calling onLineNumsBuildResult\n", filePath)
- fileState.onLineNumsBuildResult(streamed)
-
- // Reset the timer for the usage chunk
- if !timer.Stop() {
- <-timer.C
- }
- timer.Reset(model.OPENAI_USAGE_CHUNK_TIMEOUT)
-
- log.Printf("listenStream - File %s: continue for usage chunk\n", filePath)
-
- continue // continue for usage chunk
- } else if len(delta.ToolCalls) == 0 {
- log.Println("listenStream - Stream chunk missing function call.")
- // log.Println(spew.Sdump(response))
- // log.Println(spew.Sdump(fileState))
-
- // log.Println("Current buffer:")
- // log.Println(fileState.activeBuild.WithLineNumsBuffer)
-
- execHookOnStop(true)
- fileState.lineNumsRetryOrError(fmt.Errorf("listenStream - stream chunk missing function call. Reason: %s, File: %s | This usually means the model failed to generate a valid response.", choice.FinishReason, filePath))
- return
- }
- }
- }
-}
diff --git a/app/server/model/plan/build_structured_edits.go b/app/server/model/plan/build_structured_edits.go
index c43eba41..77a116d6 100644
--- a/app/server/model/plan/build_structured_edits.go
+++ b/app/server/model/plan/build_structured_edits.go
@@ -21,6 +21,7 @@ import (
)
const BuildStructuredEditsMaxTries = 4
+const BuildStructuredEditsTriesBeforeFullFile = 2
func (fileState *activeBuildStreamFileState) buildStructuredEdits() {
auth := fileState.auth
@@ -278,7 +279,6 @@ func (fileState *activeBuildStreamFileState) buildStructuredEdits() {
Content: "",
Path: filePath,
Replacements: replacements,
- CanVerify: false, // no verification step with structural edits
}
fileState.onFinishBuildFile(&res, updatedFile)
diff --git a/app/server/model/plan/build_verify.go b/app/server/model/plan/build_verify.go
deleted file mode 100644
index abd977f4..00000000
--- a/app/server/model/plan/build_verify.go
+++ /dev/null
@@ -1,208 +0,0 @@
-package plan
-
-import (
- "encoding/json"
- "fmt"
- "log"
- diff_pkg "plandex-server/diff"
- "plandex-server/hooks"
- "plandex-server/model"
- "plandex-server/model/prompts"
- "plandex-server/types"
-
- "github.com/plandex/plandex/shared"
- "github.com/sashabaranov/go-openai"
-)
-
-func (fileState *activeBuildStreamFileState) verifyFileBuild() {
- auth := fileState.auth
- filePath := fileState.filePath
- planId := fileState.plan.Id
- branch := fileState.branch
- clients := fileState.clients
- config := fileState.settings.ModelPack.GetVerifier()
- updated := fileState.activeBuild.ToVerifyUpdatedState
-
- activePlan := GetActivePlan(planId, branch)
-
- if activePlan == nil {
- log.Printf("Active plan not found for plan ID %s and branch %s\n", planId, branch)
- return
- }
-
- log.Printf("verifyFileBuild - Verifying file %s\n", filePath)
-
- // log.Println("File context:", fileContext)
-
- // log.Printf("preBuildState has content: %v\n", preBuildState != "")
- // log.Printf("updated has content: %v\n", updated != "")
- // log.Printf("activeBuild.FileDescription has content: %v\n", activeBuild.FileDescription != "")
- // log.Printf("activeBuild.FileContent has content: %v\n", activeBuild.FileContent != "")
-
- verifyState, err := fileState.GetVerifyState()
-
- if err != nil {
- log.Printf("Error getting verify state for file '%s': %v\n", filePath, err)
- fileState.onBuildFileError(fmt.Errorf("error getting verify state for file '%s': %v", filePath, err))
- return
- }
-
- if verifyState == nil {
- log.Printf("verifyFileBuild - Verify state not found for file '%s'\n", filePath)
- log.Println("finishing file build")
- fileState.onFinishBuildFile(nil, "")
- return
- }
-
- var diff string
- if verifyState.preBuildFileState != "" {
- diff, err = diff_pkg.GetDiffs(verifyState.preBuildFileState, updated)
-
- if err != nil {
- log.Printf("Error getting diffs for file '%s': %v\n", filePath, err)
- fileState.onBuildFileError(fmt.Errorf("error getting diffs for file '%s': %v", filePath, err))
- return
- }
- }
-
- log.Println("verifyFileBuild - got diff for file: " + filePath)
-
- sysPrompt := prompts.GetVerifyPrompt(
- verifyState.preBuildFileState,
- updated,
- verifyState.proposedChanges,
- diff,
- )
-
- // log.Println("verifyFileBuild - verify prompt:\n", sysPrompt)
-
- fileMessages := []openai.ChatCompletionMessage{
- {
- Role: openai.ChatMessageRoleSystem,
- Content: sysPrompt,
- },
- }
-
- promptTokens, err := shared.GetNumTokens(sysPrompt)
-
- if err != nil {
- log.Printf("Error getting num tokens for prompt: %v\n", err)
- fileState.onBuildFileError(fmt.Errorf("error getting num tokens for prompt: %v", err))
- return
- }
-
- inputTokens := prompts.ExtraTokensPerRequest + prompts.ExtraTokensPerMessage + promptTokens
-
- fileState.inputTokens = inputTokens
-
- _, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{
- Auth: auth,
- Plan: fileState.plan,
- WillSendModelRequestParams: &hooks.WillSendModelRequestParams{
- InputTokens: inputTokens,
- OutputTokens: shared.AvailableModelsByName[fileState.settings.ModelPack.GetVerifier().BaseModelConfig.ModelName].DefaultReservedOutputTokens,
- ModelName: fileState.settings.ModelPack.GetVerifier().BaseModelConfig.ModelName,
- },
- })
- if apiErr != nil {
- log.Printf("verifyFileBuild - Error executing will send model request hook: %v\n", apiErr)
- activePlan.StreamDoneCh <- apiErr
- return
- }
-
- log.Println("verifyFileBuild - Calling verify model for file: " + filePath)
-
- // for _, msg := range fileMessages {
- // log.Printf("%s: %s\n", msg.Role, msg.Content)
- // }
-
- var responseFormat *openai.ChatCompletionResponseFormat
- if config.BaseModelConfig.HasJsonResponseMode {
- responseFormat = &openai.ChatCompletionResponseFormat{Type: "json_object"}
- }
-
- modelReq := openai.ChatCompletionRequest{
- Model: config.BaseModelConfig.ModelName,
- Tools: []openai.Tool{
- {
- Type: "function",
- Function: &prompts.VerifyOutputFn,
- },
- },
- ToolChoice: openai.ToolChoice{
- Type: "function",
- Function: openai.ToolFunction{
- Name: prompts.VerifyOutputFn.Name,
- },
- },
- Messages: fileMessages,
- Temperature: config.Temperature,
- TopP: config.TopP,
- ResponseFormat: responseFormat,
- StreamOptions: &openai.StreamOptions{
- IncludeUsage: true,
- },
- }
-
- envVar := config.BaseModelConfig.ApiKeyEnvVar
- client := clients[envVar]
-
- if config.BaseModelConfig.HasStreamingFunctionCalls {
- stream, err := model.CreateChatCompletionStreamWithRetries(client, activePlan.Ctx, modelReq)
- if err != nil {
- log.Printf("Error creating plan file stream for path '%s': %v\n", filePath, err)
- fileState.onBuildFileError(fmt.Errorf("error creating plan file stream for path '%s': %v", filePath, err))
- return
- }
-
- go fileState.listenStreamVerifyOutput(stream)
- } else {
- buildInfo := &shared.BuildInfo{
- Path: filePath,
- NumTokens: 0,
- Finished: false,
- }
- activePlan.Stream(shared.StreamMessage{
- Type: shared.StreamMessageBuildInfo,
- BuildInfo: buildInfo,
- })
-
- resp, err := model.CreateChatCompletionWithRetries(client, activePlan.Ctx, modelReq)
-
- if err != nil {
- log.Printf("Error verifying file '%s': %v\n", filePath, err)
- fileState.onBuildFileError(fmt.Errorf("error verifying file '%s': %v", filePath, err))
- return
- }
-
- var s string
- var res types.VerifyResult
-
- for _, choice := range resp.Choices {
- if len(choice.Message.ToolCalls) == 1 &&
- choice.Message.ToolCalls[0].Function.Name == prompts.VerifyOutputFn.Name {
- fnCall := choice.Message.ToolCalls[0].Function
- s = fnCall.Arguments
- break
- }
- }
-
- if s == "" {
- log.Println("no VerifyOutput function call found in response")
- fileState.verifyRetryOrAbort(fmt.Errorf("No VerifyOutput function call found in response. This usually means the model failed to generate a valid response."))
- return
- }
-
- bytes := []byte(s)
-
- err = json.Unmarshal(bytes, &res)
- if err != nil {
- log.Printf("Error unmarshalling verify response: %v\n", err)
- fileState.verifyRetryOrAbort(fmt.Errorf("error unmarshalling verify response: %v", err))
- return
- }
-
- fileState.onVerifyResult(res)
- }
-
-}
diff --git a/app/server/model/plan/build_verify_result.go b/app/server/model/plan/build_verify_result.go
deleted file mode 100644
index 9ee5e56b..00000000
--- a/app/server/model/plan/build_verify_result.go
+++ /dev/null
@@ -1,78 +0,0 @@
-package plan
-
-import (
- "log"
- "math/rand"
- "plandex-server/types"
- "time"
-
- "github.com/plandex/plandex/shared"
-)
-
-func (fileState *activeBuildStreamFileState) onVerifyResult(res types.VerifyResult) {
-
- filePath := fileState.filePath
- planId := fileState.plan.Id
- branch := fileState.branch
-
- activePlan := GetActivePlan(planId, branch)
-
- if activePlan == nil {
- log.Printf("listenStreamVerifyOutput - Active plan not found for plan ID %s on branch %s\n", planId, branch)
- return
- }
-
- if res.IsCorrect() {
- buildInfo := &shared.BuildInfo{
- Path: filePath,
- NumTokens: 0,
- Finished: true,
- }
- activePlan.Stream(shared.StreamMessage{
- Type: shared.StreamMessageBuildInfo,
- BuildInfo: buildInfo,
- })
- log.Println("build verify - res.IsCorrect")
-
- time.Sleep(50 * time.Millisecond)
-
- fileState.onFinishBuildFile(nil, "")
- } else {
-
- log.Printf("listenStreamVerifyOutput - File %s: Streamed verify result is incorrect\n", filePath)
-
- fileState.verificationErrors = res.GetReasoning()
- fileState.isFixingOther = true
-
- // log.Println("Verification errors:")
- // log.Println(fileState.verificationErrors)
-
- select {
- case <-activePlan.Ctx.Done():
- log.Println("listenStreamVerifyOutput - Context canceled. Exiting.")
- return
- case <-time.After(time.Duration(rand.Intn(1001)) * time.Millisecond):
- break
- }
- fileState.fixFileLineNums()
- }
-
-}
-
-func (fileState *activeBuildStreamFileState) verifyRetryOrAbort(err error) {
- if fileState.verifyFileNumRetry < MaxBuildErrorRetries {
- fileState.verifyFileNumRetry++
- fileState.activeBuild.VerifyBuffer = ""
- fileState.activeBuild.VerifyBufferTokens = 0
- log.Printf("Retrying verify file '%s' due to error: %v\n", fileState.filePath, err)
-
- // Exponential backoff
- time.Sleep(time.Duration((fileState.verifyFileNumRetry*fileState.verifyFileNumRetry)/2)*200*time.Millisecond + time.Duration(rand.Intn(500))*time.Millisecond)
-
- fileState.verifyFileBuild()
- } else {
- log.Printf("Aborting verify file '%s' due to error: %v\n", fileState.filePath, err)
-
- fileState.onFinishBuildFile(nil, "")
- }
-}
diff --git a/app/server/model/plan/build_verify_state.go b/app/server/model/plan/build_verify_state.go
deleted file mode 100644
index 5c2bf0ef..00000000
--- a/app/server/model/plan/build_verify_state.go
+++ /dev/null
@@ -1,164 +0,0 @@
-package plan
-
-import (
- "fmt"
- "log"
- "plandex-server/db"
- "plandex-server/types"
- "time"
-)
-
-type verifyState struct {
- proposedChanges string
- preBuildFileState string
-}
-
-func (fileState *activeBuildStreamFileState) GetVerifyState() (*verifyState, error) {
- planState := fileState.currentPlanState
- convo := fileState.convo
- path := fileState.filePath
-
- fileResults := planState.PlanResult.FileResultsByPath[path]
-
- if fileResults == nil {
- log.Println("No file results for path: ", path)
- return nil, nil
- }
-
- proposedChanges := ""
- convoMessageIds := map[string]bool{}
- startingReplacementId := ""
-
- for _, fileResult := range fileResults {
- if !fileResult.IsPending() {
- continue
- }
-
- if fileResult.CanVerify && fileResult.RanVerifyAt != nil {
- convoMessageIds = map[string]bool{}
- startingReplacementId = ""
- } else if !fileResult.IsFix {
- convoMessageIds[fileResult.ConvoMessageId] = true
- if len(fileResult.Replacements) > 0 {
- startingReplacementId = fileResult.Replacements[0].Id
- }
- }
- }
-
- for _, convoMessage := range convo {
- if convoMessageIds[convoMessage.Id] {
- parser := types.NewReplyParser()
- parser.AddChunk(convoMessage.Message, false)
- parserRes := parser.FinishAndRead()
-
- for i, file := range parserRes.Files {
- if file == path {
- desc := parserRes.FileDescriptions[i]
- fileContents := parserRes.FileContents[i]
-
- proposedChanges += fmt.Sprintf("%s\n\n```\n%s\n```\n\n", desc, fileContents)
- }
- }
-
- }
- }
-
- var preBuildState string
-
- if startingReplacementId == "" {
- if planState.ContextsByPath[path] != nil {
- preBuildState = planState.ContextsByPath[path].Body
- }
- } else {
- files, err := planState.GetFilesBeforeReplacement(startingReplacementId)
-
- if err != nil {
- return nil, fmt.Errorf("error getting files before replacement: %v", err)
- }
-
- if files.Files[path] == "" {
- return nil, fmt.Errorf("no file content before replacement")
- }
-
- preBuildState = files.Files[path]
- }
-
- return &verifyState{
- proposedChanges: proposedChanges,
- preBuildFileState: preBuildState,
- }, nil
-
-}
-
-func (fileState *activeBuildStreamFileState) MarkLatestResultVerified(passed bool) error {
- planId := fileState.plan.Id
- branch := fileState.branch
- currentOrgId := fileState.currentOrgId
- currentUserId := fileState.currentUserId
- build := fileState.build
-
- activePlan := GetActivePlan(planId, branch)
-
- repoLockId, err := db.LockRepo(
- db.LockRepoParams{
- OrgId: currentOrgId,
- UserId: currentUserId,
- PlanId: planId,
- Branch: branch,
- PlanBuildId: build.Id,
- Scope: db.LockScopeWrite,
- Ctx: activePlan.Ctx,
- CancelFn: activePlan.CancelFn,
- },
- )
- if err != nil {
- log.Printf("Error locking repo for build file: %v\n", err)
- return fmt.Errorf("error locking repo for build file: %v", err)
- }
-
- err = func() error {
- var err error
- defer func() {
- if err != nil {
- log.Printf("Error: %v\n", err)
- err = db.GitClearUncommittedChanges(currentOrgId, planId)
- if err != nil {
- log.Printf("Error clearing uncommitted changes: %v\n", err)
- }
- }
-
- err := db.DeleteRepoLock(repoLockId)
- if err != nil {
- log.Printf("Error unlocking repo: %v\n", err)
- }
- }()
-
- results, err := db.GetPlanFileResults(currentOrgId, planId)
-
- if err != nil {
- return fmt.Errorf("error getting plan file results: %v", err)
- }
-
- if len(results) == 0 {
- return fmt.Errorf("no file results for path: %s", fileState.filePath)
- }
-
- latestPlanRes := results[len(results)-1]
- now := time.Now()
- latestPlanRes.RanVerifyAt = &now
- latestPlanRes.VerifyPassed = passed
-
- err = db.StorePlanResult(latestPlanRes)
- if err != nil {
- log.Printf("Error storing plan result: %v\n", err)
- return fmt.Errorf("error storing plan result: %v", err)
- }
- return nil
- }()
-
- if err != nil {
- return err
- }
-
- return nil
-}
diff --git a/app/server/model/plan/build_verify_stream.go b/app/server/model/plan/build_verify_stream.go
deleted file mode 100644
index d6aa5de2..00000000
--- a/app/server/model/plan/build_verify_stream.go
+++ /dev/null
@@ -1,222 +0,0 @@
-package plan
-
-import (
- "context"
- "encoding/json"
- "fmt"
- "log"
- "plandex-server/hooks"
- "plandex-server/model"
- "plandex-server/types"
- "strings"
- "time"
-
- "github.com/davecgh/go-spew/spew"
- "github.com/plandex/plandex/shared"
- "github.com/sashabaranov/go-openai"
-)
-
-func (fileState *activeBuildStreamFileState) listenStreamVerifyOutput(stream *openai.ChatCompletionStream) {
- auth := fileState.auth
- filePath := fileState.filePath
- planId := fileState.plan.Id
- branch := fileState.branch
-
- activePlan := GetActivePlan(planId, branch)
-
- if activePlan == nil {
- log.Printf("listenStreamVerifyOutput - Active plan not found for plan ID %s on branch %s\n", planId, branch)
- return
- }
-
- defer stream.Close()
-
- // Create a timer that will trigger if no chunk is received within the specified duration
- timer := time.NewTimer(model.OPENAI_STREAM_CHUNK_TIMEOUT)
- defer timer.Stop()
-
- streamFinished := false
-
- execHookOnStop := func(sendStreamErr bool) {
- _, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- Auth: auth,
- Plan: fileState.plan,
- DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
- InputTokens: fileState.inputTokens,
- OutputTokens: fileState.activeBuild.VerifyBufferTokens,
- ModelName: fileState.settings.ModelPack.GetVerifier().BaseModelConfig.ModelName,
- ModelProvider: fileState.settings.ModelPack.GetVerifier().BaseModelConfig.Provider,
- ModelPackName: fileState.settings.ModelPack.Name,
- ModelRole: shared.ModelRoleVerifier,
- Purpose: "Verified file update",
- },
- })
-
- if apiErr != nil {
- log.Printf("Error executing did send model request hook after cancel or error: %v\n", apiErr)
-
- if sendStreamErr {
- activePlan := GetActivePlan(planId, branch)
-
- if activePlan == nil {
- log.Printf(" Active plan not found for plan ID %s on branch %s\n", planId, branch)
- return
- }
-
- activePlan.StreamDoneCh <- apiErr
- }
-
- }
- }
-
- for {
- select {
- case <-activePlan.Ctx.Done():
- // The main context was canceled (not the timer)
- execHookOnStop(false)
- return
- case <-timer.C:
- log.Println("\nVerify: stream timeout due to inactivity")
-
- execHookOnStop(true)
-
- if streamFinished {
- log.Println("\nVerify stream finished-timed out waiting for usage chunk")
- return
- }
-
- fileState.verifyRetryOrAbort(fmt.Errorf("listenStreamVerifyOutput - stream timeout due to inactivity for file '%s' | This usually means the model is not responding.", filePath))
- return
- default:
- response, err := stream.Recv()
-
- if err == nil {
- // Successfully received a chunk, reset the timer
- if !timer.Stop() {
- <-timer.C
- }
- timer.Reset(model.OPENAI_STREAM_CHUNK_TIMEOUT)
- } else {
- log.Printf("listenStreamVerifyOutput - File %s: Error receiving stream chunk: %v\n", filePath, err)
-
- if err == context.Canceled {
- log.Printf("listenStreamVerifyOutput - File %s: Stream canceled\n", filePath)
- execHookOnStop(false)
- return
- }
-
- execHookOnStop(true)
-
- if !streamFinished {
- fileState.verifyRetryOrAbort(fmt.Errorf("listenStreamVerifyOutput - stream error: %v", err))
- }
- return
- }
-
- if len(response.Choices) == 0 {
- if response.Usage != nil {
- log.Println("Verify stream usage:")
- spew.Dump(response.Usage)
-
- _, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{
- Auth: auth,
- Plan: fileState.plan,
- DidSendModelRequestParams: &hooks.DidSendModelRequestParams{
- InputTokens: response.Usage.PromptTokens,
- OutputTokens: response.Usage.CompletionTokens,
- ModelName: fileState.settings.ModelPack.GetVerifier().BaseModelConfig.ModelName,
- ModelProvider: fileState.settings.ModelPack.GetVerifier().BaseModelConfig.Provider,
- ModelPackName: fileState.settings.ModelPack.Name,
- ModelRole: shared.ModelRoleVerifier,
- Purpose: "Verified file update",
- },
- })
-
- if apiErr != nil {
- // stream has already finished so just log the error
- log.Printf("Verify stream: executing did send model request hook: %v\n", err)
-
- // ensure the active plan is still available
- activePlan := GetActivePlan(planId, branch)
-
- if activePlan == nil {
- log.Printf(" Active plan not found for plan ID %s on branch %s\n", planId, branch)
- return
- }
-
- activePlan.StreamDoneCh <- apiErr
- }
- return
- }
-
- execHookOnStop(true)
- fileState.verifyRetryOrAbort(fmt.Errorf("listenStreamVerifyOutput - stream error: no choices | This usually means the model failed to generate a valid response."))
- return
- }
-
- // if stream finished and it's not a usage chunk, keep listening for usage chunk
- if streamFinished {
- // log.Printf("listenStreamVerifyOutput - File %s: Stream finished, no usage chunk-will keep listening\n", filePath)
- continue
- }
-
- choice := response.Choices[0]
- var content string
- delta := choice.Delta
-
- if len(delta.ToolCalls) > 0 {
- content = delta.ToolCalls[0].Function.Arguments
-
- trimmed := strings.TrimSpace(content)
- if trimmed == "{%invalidjson%}" || trimmed == "``(no output)``````" {
- log.Println("File", filePath+":", "%invalidjson%} token in streamed chunk")
- execHookOnStop(true)
- fileState.verifyRetryOrAbort(fmt.Errorf("invalid JSON in streamed chunk for file '%s'", filePath))
- return
- }
-
- buildInfo := &shared.BuildInfo{
- Path: filePath,
- NumTokens: 1,
- Finished: false,
- }
-
- // log.Printf("%s: %s", filePath, content)
- activePlan.Stream(shared.StreamMessage{
- Type: shared.StreamMessageBuildInfo,
- BuildInfo: buildInfo,
- })
-
- fileState.activeBuild.VerifyBuffer += content
- fileState.activeBuild.VerifyBufferTokens++
- }
-
- var streamed types.VerifyResult
- err = json.Unmarshal([]byte(fileState.activeBuild.VerifyBuffer), &streamed)
-
- if err == nil {
- log.Printf("listenStreamVerifyOutput - File %s: Parsed streamed verify result\n", filePath)
- // spew.Dump(streamed)
- streamFinished = true // Stream finished successfully
-
- log.Printf("listenStreamVerifyOutput - File %s: Streamed verify result\n", filePath)
- fileState.onVerifyResult(streamed)
-
- // Reset the timer for the usage chunk
- if !timer.Stop() {
- <-timer.C
- }
- timer.Reset(model.OPENAI_USAGE_CHUNK_TIMEOUT)
-
- continue // continue for usage chunk
- } else if len(delta.ToolCalls) == 0 {
-
- log.Printf("listenStreamVerifyOuput - File %s: Stream chunk missing function call. Reason: %s\n", filePath, choice.FinishReason)
-
- execHookOnStop(true)
- fileState.verifyRetryOrAbort(fmt.Errorf("listenStreamVerifyOutput - stream chunk missing function call. Reason: %s, File: %s", choice.FinishReason, filePath))
- }
- }
- }
-
-}
diff --git a/app/server/model/prompts/build.go b/app/server/model/prompts/build.go
index 2260d445..5265b1f5 100644
--- a/app/server/model/prompts/build.go
+++ b/app/server/model/prompts/build.go
@@ -2,729 +2,316 @@ package prompts
import (
"fmt"
+ "plandex-server/syntax"
"github.com/plandex/plandex/shared"
- "github.com/sashabaranov/go-openai"
- "github.com/sashabaranov/go-openai/jsonschema"
)
-func GetBuildLineNumbersSysPrompt(filePath, preBuildState, changes string) string {
- // hash := sha256.Sum256([]byte(currentState))
- // sha := hex.EncodeToString(hash[:])
-
- // log.Println("GetBuildLineNumbersSysPrompt currentState sha:", sha)
-
- preBuildStateWithLineNums := shared.AddLineNums(preBuildState)
-
- return getListChangesLineNumsPrompt(false) + "\n\n" + getPreBuildStatePrompt(filePath, preBuildStateWithLineNums) + "\n\n" + getBuildPromptWithLineNums(changes)
-}
-
-func GetBuildLineNumbersSysPromptUpdated(filePath, preBuildState, changesFile, changesDesc, nonExpandedRefs string) string {
- // hash := sha256.Sum256([]byte(currentState))
- // sha := hex.EncodeToString(hash[:])
-
- // log.Println("GetBuildLineNumbersSysPrompt currentState sha:", sha)
-
+func GetWholeFilePrompt(filePath, preBuildState, changesFile, changesDesc string) string {
preBuildStateWithLineNums := shared.AddLineNums(preBuildState)
changesWithLineNums := shared.AddLineNumsWithPrefix(changesFile, "pdx-new-")
- res := getListChangesLineNumsPrompt(nonExpandedRefs != "") + "\n\n" + getPreBuildStatePrompt(filePath, preBuildStateWithLineNums) + "\n\n" + "**Proposed updates:**\n" + changesDesc
-
- if nonExpandedRefs == "" {
- res += "\n```\n" + changesWithLineNums + "\n```"
- } else {
- res += "\n\nWithout expanded references:\n\n```\n" + nonExpandedRefs + "\n```" + "\n\n" + "With expanded references:\n\n```\n" + changesWithLineNums + "\n```"
- }
+ s := WholeFileBeginning + ReferencesPrompt + WholeFileEnding + "\n\n" + getPreBuildStatePrompt(filePath, preBuildStateWithLineNums) + "\n\n"
- return res
-}
-
-func GetBuildFixesLineNumbersSysPrompt(original, changes, updated, reasoning string) string {
- // hash := sha256.Sum256([]byte(updated))
- // sha := hex.EncodeToString(hash[:])
- // log.Println("GetBuildFixesLineNumbersSysPrompt updated sha:", sha)
-
- updatedWithLineNums := shared.AddLineNums(updated)
-
- return getFixChangesLineNumsPrompt() + "\n\n" + getBuildPromptForFixesWithLineNums(original, changes, updatedWithLineNums, reasoning)
-}
-
-func getBuildPromptWithLineNums(changes string) string {
- s := ""
-
- s += "Proposed updates:\n```\n" + changes + "\n```"
-
- s += "\n\n" + "Now call the 'listChangesWithLineNums' function with a valid JSON array of changes according to your instructions. You must always call 'listChangesWithLineNums' with one or more valid changes. Don't call any other function."
+ s += fmt.Sprintf("Proposed updates:\n%s\n```\n%s\n```", changesDesc, changesWithLineNums)
return s
}
-func getBuildPromptForFixesWithLineNums(original, changes, updated, reasoning string) string {
- s := ""
-
- if original != "" {
- s += "**Original file:**\n\n```\n" + original + "\n```"
- }
-
- s += "**Proposed updates:**\n\n" + changes + "\n\n--\n\n"
-
- s += fmt.Sprintf("**The incorrectly updated file is:**\n\n```\n%s\n```\n\n**The problems with the file are:**\n\n%s\n\n--", updated, reasoning)
-
- s += "\n\n" + "Now call the 'listChangesWithLineNums' function with a valid JSON array of changes according to your instructions. You must always call 'listChangesWithLineNums' with one or more valid changes. Don't call any other function."
-
- return s
-}
-
-func getPreBuildStatePrompt(filePath, preBuildState string) string {
- if preBuildState == "" {
- return ""
- }
-
- return fmt.Sprintf("**The current file is %s. Original state of the file:**\n```\n%s\n```", filePath, preBuildState) + "\n\n"
-}
-
-const replacementIntro = `
-You are an AI that analyzes a code file and an AI-generated plan to update the code file and produces a list of changes.
+var ExampleReferences = `
+A reference comment is a comment that references code in the *original file* for the purpose of making it clear where a change should be applied. Examples of reference comments include:
+
+ - // ... existing code...
+ - # Existing code...
+ - /* ... */
+ - // Rest of the function...
+ - <!-- rest of div tag -->
+ - // ... rest of function ...
+ - // rest of component...
+ - # other methods...
+ - // ... rest of init code...
+ - // rest of the class...
+ - // other properties
+ - // other methods
+ // ... existing properties ...
+ // ... existing values ...
+ // ... existing text ...
+
+Reference comments often won't exactly match one of the above examples, but they will always be referencing a block of code from the *original file* that is left out of the *proposed updates* for the sake of focusing on the specific change that is being made.
+
+Reference comments do NOT need to be valid comments for the given file type. For file types like JSON or plain text that do not use comments, reference comments in the form of '// ... existing properties ...' or '// ... existing values ...' or '// ... existing text ...' can still be present. These MUST be treated as valid reference comments regardless of the file type or the validity of the syntax.
`
-const entireFilePrompt = `
-In the 'entireFileReasoning' key, evaluate whether the *proposed updates* contain the final state of the ENTIRE updated file *with all changes applied* and with nothing missing. Evaluate whether the *proposed updates* contain the file updated state of the entire file. Think carefully through the sections of the file and evaluate whether every section that should be included in the final result is present in the *proposed updates*. Evaluate whether the *original file* contains any code that is *NOT* inlcluded in the *proposed updates* AND *SHOULD* be included in the final result.
-
-Note that here you are *not* evaluating which sections have changed or not changed, but only whether the *proposed updates* contains the entire updated file.
-
-You are also NOT evaluating whether the *proposed updates* contains any new code that is not part of the *original file*. You are only evaluating whether ALL the code from both the *original file* and *proposed updates* that should be present in the final result when the two are combined is present in the *proposed updates*.
-
-The 'entireFile' key should be set to true if the *proposed updates* contain the final state of the ENTIRE updated file *with all changes applied* and with nothing missing. If the *proposed updates* do not contain the final state of the ENTIRE updated file *with all changes applied* and with nothing missing, set 'entireFile' to false.
-
-If 'entireFile' is set to true, 'changes' must be an empty array and 'problems' must be an empty string.
-`
-
-const changesKeyPrompt = `
-'changes': An array of changes. Each change is an object with properties: 'section', 'summary', 'newReasoning', 'reasoning', 'structureReasoning', 'closingSyntaxReasoning', 'orderReasoning', 'hasChange', 'insertBefore', 'insertAfter', 'old', 'new'
-
-If 'entireFile' is set to true, 'changes' must be an empty array.
+const RefsBeginning = `
+You are an AI that analyzes an *original file* and *proposed updates* to that file and then identifies *all* *reference comments* present in the *proposed updates*.
-Note: all line numbers that are used below are prefixed with 'pdx-' when referencing lines in the *original file*, like this 'pdx-5: for i := 0; i < 10; i++ {'. This is to help you identify the line numbers in the *original file*. You *must* include the 'pdx-' prefix in the line numbers in the 'old' property.
-
-'insertBefore' is an object with properties: 'shouldInsertBefore' (boolean), 'line' (string).
-
- If 'shouldInsertBefore' is true:
- - 'line' must be *entire line* that *exactly match* a line from the *original file* including the line number with 'pdx-' prefix.
- - The 'old' property of the change should be filled with empty strings.
- - The 'new' key of the change should contain the content to be inserted before the specified line.
-
-'insertAfter' is an object with properties: 'shouldInsertAfter' (boolean), 'line' (string).
-
- If 'shouldInsertAfter' is true:
- - 'line' must be *entire line* that *exactly match* a line from the *original file* including the line number with 'pdx-' prefix.
- - The 'old' property of the change should be filled with empty strings.
- - The 'new' key of the change should contain the content to be inserted after the specified line.
-
- If 'shouldInsertAfter' is false, then 'line' should be an empty string. 'old' and 'new' should be filled according to your other instructions.
-
-If 'insertBefore', or 'insertAfter' is set to true, the 'old' property of the change ABSOLUTELY MUST be filled by empty strings. Do NOT fill the 'old' property with any other values if 'insertBefore', or 'insertAfter' is set to true. The 'new' property should be filled according to your other instructions to the exact, correct section of the *proposed updates* that should be prepended, appended, inserted between, inserted before, or inserted after the specified lines.
-
-Expand the lines the 'new' property refers to in the *proposed updates* where needed to include line breaks and preserve formatting.
-
-Note: all line numbers that are used below are prefixed with 'pdx-' when referencing lines in the *original file*, like this 'pdx-5: for i := 0; i < 10; i++ {'. This is to help you identify the line numbers in the *original file*. You *must* include the 'pdx-' prefix in the line numbers in the 'old' property.
-
-Line numbers that are used below are prefixed with 'pdx-new-' when referencing lines in the *proposed updates*, like this 'pdx-new-5: for i := 0; i < 10; i++ {'. This is to help you identify the line numbers in the *proposed updates*. You *must* include the 'pdx-new-' prefix in the line numbers in the 'new' property.
`
-const summaryChangePrompt = `
-The 'section' property is the name of the section from the 'originalSections' array that the change applies to. Each change must apply to a single section.
-
-The 'summary' property is a brief summary of the change.
-
-'summary' examples:
- - 'Update loop that aggregates the results to iterate 10 times instead of 5 and log the value of someVar.'
- - 'Update the Org model to include StripeCustomerId and StripeSubscriptionId fields.'
- - 'Add function ExecQuery to execute a query.'
-
-The 'newReasoning' property evaluates what needs to be included in the 'new' section to ensure that *ALL* the code from the *proposed changes* are correctly applied to the resulting file. Carefully consider whether the code from the *proposed updates* contain code structures that need to be properly closed in the resulting file. For example, "the <Route> tag needs to be closed properly in the resulting file, so the 'new' section should end on the closing tag at pdx-new-10: </Route>".
-
-The 'structureReasoning' property is an object with 2 properties: 'old' and 'new'.
-
- The 'old' property is an object with 3 properties: 'structure', 'structureOpens', and 'structureCloses'.
-
- 'structure' is the *code structure* (e.g. 'function', 'class', 'loop', 'conditional', etc.) that this change is contained by. If the change is not contained within a code structure and is instead at the top level of the file, output 'top level'. This must be the MOST specific, deeply nested code structure that contains the change. You must output only a single structure or 'top level'. Identify the structure unambiguously. If a structure is being *replaced*, the 'structure' property must identify the exact structure that is being replaced. If new code is being added to a structure, the 'structure' property must identify the structure that the new code is being added to.
-
- 'structureOpens' is the entire line from the *original file* that contains the opening symbol of the code structure identified in the 'structure' property, including the line number prefixed with 'pdx-'. Empty if the code structure is 'top level'.
-
- 'structureCloses' is the entire line from the *original file* that contains the closing symbol of the code structure identified in the 'structure' property, including the line number prefixed with 'pdx-'. Empty if the code structure is 'top level'.
-
- When determining 'structureOpens' and 'structureCloses' properties for 'old', evaluate both the *original file* AND the *proposed updates* to help you identify the correct closing symbol.
-
- The 'new' property is an object with 3 properties: 'structure', 'structureOpens', and 'structureCloses'.
-
- 'structure' is the *code structure* (e.g. 'function', 'class', 'loop', 'conditional', etc.) in the *proposed updates* that should be inserted. If the code that should be inserted is 'flat' and not contained within a code structure, either because the *proposed updates* themselves are 'flat' or because surrounding code structures in the *proposed updates* are already contained by the *original file*, output 'flat'. If you output a structure and not 'flat', it must be the MOST specific, deeply nested code structure that contains the new code to be inserted. You must output only a single structure or 'flat'. Identify the structure unambiguously.
-
- 'structureOpens' is the entire line from the *proposed updates* that contains the opening symbol of the code structure identified in the 'structure' property, including the line number prefixed with 'pdx-new-'. Must be an EXACT MATCH to a line from the *proposed updates*. Empty if the code structure is 'flat'.
-
- 'structureCloses' is the entire line from the *proposed updates* that contains the closing symbol of the code structure identified in the 'structure' property, including the line number prefixed with 'pdx-new-'. Must be an EXACT MATCH to a line from the *proposed updates*. Empty if the code structure is 'flat'.
-
-If you are adding new code to the *end* of an existing code structure (and not replacing any existing code), you must use the 'insertBefore' property to add the new code before the closing symbol of the existing code structure.
-
-If you are adding new code to the *beginning* of an existing code structure (and not replacing any existing code), you must use the 'insertAfter' property to add the new code after the opening symbol of the existing code structure.
+const WholeFileBeginning = `
+After identifying all references, you will output the *entire file* with the *proposed updates* correctly applied. ALL references will be replaced by the appropriate code from the *original file*. You will correctly merge the code from the *original file* with the *proposed updates* and output the entire file.
-If you are replacing existing code, you must always use the 'old' property to specify the code that should be replaced.
-
-The 'closingSyntaxReasoning' property, for each code structure related to the change, list what is the BOTTOM-MOST, RIGHT-MOST, *FINAL* closing symbol after which *ALL* code structures in the section are closed.
-
-For example, if there is a section like:
-
----
-pdx-new-32: <Route
-pdx-new-33: path="/instructor-grid"
-pdx-new-33: element={loggedIn ? <InstructorGridPage /> : <Navigate to=\"/\" />} />
-pdx-new-34: />
---
-
-The 'closingSyntaxReasoning' property should explain that the final closing symbol is /> on line pdx-new-34. Even though the 'InstructorGridPage' and 'Navigate' code structures are closed properly on pdx-new-33, it is NOT the final closing symbol because the 'Route' code structure is not closed. The 'closingSyntaxReasoning' property in this example would explain that the final closing symbol that closes all code structures in the section is /> on line pdx-new-34.
-
-The 'closingSyntaxReasoning' section ABSOLUTELY MUST include a mention of each section that is specified in the 'structureReasoning' property. If the 'insertAfter' property is used, the 'closingSyntaxReasoning' section MUST include a mention of the 'insertAfter' section. And the 'closingSyntaxReasoning' section MUST ALWAYS include a mention of the 'new' section.
-
-The same applies to the 'line' property of the 'insertAfter' section. For example, if in the *original file* there is a section like:
-
----
-pdx-20: <Route
-pdx-21: path="/instructor-grid"
-pdx-22: element={loggedIn ? <InstructorGridPage /> : <Navigate to=\"/\" />} />
-pdx-23: />
---
-
-For example, if the plan is to insert code from the *proposed updates* after the 'Route' code structure using the 'insertAfter' property, then 'closingSyntaxReasoning' property should explain that the final closing symbol is /> on line pdx-23. Even though the 'InstructorGridPage' and 'Navigate' code structures are closed properly on pdx-22, it is NOT the final closing symbol because the 'Route' code structure is not closed. The 'closingSyntaxReasoning' property in this example would explain that the final closing symbol that closes all code structures in the section is /> on line pdx-23.
-
-'closingSyntaxReasoning' must use this template: 'Old: [syntax reasoning for old section] | New: [syntax reasoning for new section]'.
-
-The 'orderReasoning' property evaluates how the change should be applied in order to preserve the order of code from the *proposed updates*. State at what position the new code would need to be inserted (or to overwrite) in order to preserve the order of code from the *proposed updates*. For example, "To ensure the order is preserved, it's important that the new import of 'fmt' ('pdx-new-3: import "fmt"') should be added after the import of 'os' ('pdx-1: import "os"') and before the import of 'log' ('pdx-2: import "log"')." Do not state in this key what should be the start and end lines of the change, either in the *original file* or the *proposed updates*. Instead, make note of which invariants need to be preserved in terms of the order of the code in order for the *proposed updates* to be applied correctly.
-
-The 'hasChange' property is a boolean that indicates whether there is anything to change. If there is nothing to change, set 'hasChange' to false. If there is something to change, set 'hasChange' to true.
-
-The 'reasoning' property is an explanation of how the change relates to the strategy outlined in the 'problems' key and in the 'orginalSections' array from above. Which 'originalSections' does this change apply to?
-
-If this is a partial change , where should the change begin and end in the *original file* in order to avoid removing or overwriting code that should not be removed? Include specific line numbers prefixed with 'pdx-'. This explanation MUST be include in the 'reasoning' key for partial changes, and the explanation must begin with "To avoid removing". Example: "To avoid removing any existing imports, the change should be begin on line pdx-5 to avoid removing the existing imports."
-
-You must then consider what the first and last line of the 'new' section should be. Should the 'new' section start on a function signature and end on a closing bracket? Start on a variable declaration and end on a newline? Start on an opening tag and end on a closing tag? What needs to be included in the 'new' section to ensure the code will be syntactically correct and the plan will be applied as intended? Answer these questions.
-
-You MUST include closing symbols in the 'new' section such that EVERY code structure in the *proposed updates* is closed properly. ALWAYS expand the 'new' section to include closing syntax that is related to the code structures present in the 'new' section.
-
-Next, state your reasoning in the format "Because [reason(s)] the last line of the new section should be the [line of code explained in words] on [line number in the *proposed updates* prefixed with 'pdx-new-']. And because [reason(s)], the first line of the new section should be the [line of code explained in words] on [line number in the *proposed updates* prefixed with 'pdx-new-'].". The 'reasoning' key ABSOLUTELY MUST include your stated reasoning in the afore-stated format. You must never leave it out.
-
-If the next non-newline character after the change in the *original file* is a *closing symbol* for a code structure like a closing bracket, parenthesis, quote, brace, tag, etc., explicitly list each closing symbol and state whether it closes a code structure that is present in the 'old' section. If it does, state that the 'old' section must now be expaned to include this closing symbol, and state what the new last line of the 'old' section should be, including the line number prefixed with 'pdx-'.
-
-If the next non-newline character after the change in the *proposed updates* is an *closing symbol* for a code structure like a closing bracket, parenthesis, quote, brace, tag, etc., explicitly list each closing symbol and state whether it closes a code structure that is present in the 'new' section. If it does, state that the 'new' section must now be expanded to include this closing symbol, and state what the new last line of the 'new' section should be, including the line number prefixed with 'pdx-new-'.
-
-You must not try to make the reasoning in any reasoning key too succinct. It needs to properly address these issues in order for the change to be correctly applied in complex scenarios. Make sure you have fully evaluated the considerations and consequences of how this change will be applied. Be thorough, meticulous, and perfectionist. Use the space needed to fully explain the reasoning and spell out in detail all the factors that need to be considered, even if the reasoning seems obvious.
`
-const lineNumsOldPrompt = `
-The 'old' property is an object with 2 properties: 'startLineString' and 'endLineString'.
-
- 'startLineString' is the **entire, exact line** where the section to be replaced begins in the *original file*, including the line number. Unless it's the first change, 'startLineString' ABSOLUTELY MUST begin with a line number that is HIGHER than both the 'endLineString' of the previous change and the 'startLineString' of the previous change. **The line number and line MUST EXACTLY MATCH a line from the *original file*.** It must be only a *SINGLE LINE* and not contain any line breaks.
+var ReferencesPrompt = ExampleReferences + `
- If the previous change's 'old' property 'endLineString' starts with 'pdx-75: ', then the current change's 'startLineString' MUST start with 'pdx-76: ' or higher. It MUST NOT be 'pdx-75: ' or lower. If the previous change's 'old' property 'startLineString' starts with 'pdx-88: ' and the previous change's 'old' property 'endLineString' is an empty string, then the current change's 'startLineString' MUST start with 'pdx-89: ' or higher. If the previous change's 'old' property 'startLineString' starts with 'pdx-100: ' and the previous change's 'old' property 'endLineString' starts with 'pdx-105: ', then the current change's 'startLineString' MUST start with 'pdx-106: ' or higher.
-
- 'endLineString' is the **entire, exact line** where the section to be replaced ends in the *original file*. Pay careful attention to spaces and indentation. 'startLineString' and 'endLineString' must be *entire lines* and *not partial lines*. Even if a line is very long, you must include the entire line, including the line number and all text on the line. **The line number and line MUST EXACTLY MATCH a line from the *original file*.** It must be only a *SINGLE LINE* and not contain any line breaks.
-
- **For a single line replacement, 'endLineString' MUST be an empty string.**
-
- If the 'reasoning' key above includes guidance on where to start and/or end the change, use that guidance to determine the 'startLineString' and 'endLineString'. If the reasoning key states that the change should begin at a specific line number to avoid removing or overwriting code that should not be removed, ensure that 'startLineString' starts with that line number. If the reasoning key states that the change should end at a specific line number to avoid removing or overwriting code that should not be removed, ensure that 'endLineString' ends with that line number. You MUST follow the guidance in the 'reasoning' key.
-
- 'endLineString' MUST ALWAYS come *after* 'startLineString' in the *original file*. It must start with a line number that is HIGHER than the 'startLineString' line number. If 'startLineString' starts with 'pdx-22: ', then 'endLineString' MUST either be an empty string (for a single line replacement) or start with 'pdx-23: ' or higher (for a multi-line replacement).
-
- If 'hasChange' is false both 'startLineString' and 'endLineString' must be empty strings. If 'hasChange' is true, 'startLineString' and 'endLineString' must be valid strings that exactly match lines from the *original file*. If 'hasChange' is true, 'startLineString' and 'endLineString' MUST NEVER be empty strings.
-`
+ *NOT EVERY COMMENT IS A REFERENCE.* If a comment refers to code that is present in the *proposed updates* then it is *not* a reference. Similarly, if a comment explains something about the change being made in the *proposed updates*, it is also *not* a reference.
-const changeLineInclusionAndNewPrompt = `
-The 'new' property is an object with 2 properties: 'startLineString' and 'endLineString'.
+ A reference comment MUST EXIST in the *proposed updates*. Do not include a reference comment unless it exists VERBATIM in the *proposed updates*.
- 'startLineString' is the **entire, exact line** where the updated code that the 'old' section will be replaced with begins *in the *proposed updates**, including the line number. Unless it's the first change, 'startLineString' ABSOLUTELY MUST begin with a line number that is HIGHER than both the 'new' property 'endLineString' of the previous change and the 'startLineString' of the previous change. **The line number and line MUST EXACTLY MATCH a line from the *proposed updates*.** It must be only a *SINGLE LINE* and not contain any line breaks. IT ABSOLUTELY MUST match a line from the **proposed updates**.
+ Before outputting the references, first output a section that lists *EVERY* comment in the *proposed updates*, including the line number of each comment prefixed by 'pdx-new-'. Below each comment, evaluate whether it is a reference comment. Focus on whether the comment is clearly referencing a block of code in the *original file*, whether it is explaining a change being made, or whether it is a comment that was carried over from the *original file* but does *not* reference any code that was left out of the *proposed updates*. After this evaluation, state whether each comment is a reference comment or not. Only list valid *comments* for the given programming language in the comments section. Do not include non-comment lines of code in the comments section.
- If the previous change's 'new' property 'endLineString' starts with 'pdx-new-75: ', then the current change's 'startLineString' MUST start with 'pdx-new-76: ' or higher. It MUST NOT be 'pdx-new-75: ' or lower. If the previous change's 'new' property 'startLineString' starts with 'pdx-new-88: ' and the previous change's 'new' property 'endLineString' is an empty string, then the current change's 'startLineString' MUST start with 'pdx-new-89: ' or higher. If the previous change's 'new' property 'startLineString' starts with 'pdx-new-100: ' and the previous change's 'new' property 'endLineString' starts with 'pdx-new-105: ', then the current change's 'startLineString' MUST start with 'pdx-new-106: ' or higher.
-
- 'endLineString' is the **entire, exact line** where the section to be replaced ends in the *proposed updates*. Pay careful attention to spaces and indentation. 'startLineString' and 'endLineString' must be *entire lines* and *not partial lines*. Even if a line is very long, you must include the entire line, including the line number and all text on the line. **The line number and line MUST EXACTLY MATCH a line from the *proposed updates*.** It must be only a *SINGLE LINE* and not contain any line breaks. IT ABSOLUTELY MUST match a line from the **proposed updates**. For multi-line changes, the 'endLineString' of the 'new' section MUST NOT be empty.
-
- **For a single line replacement, 'endLineString' MUST be an empty string.**
-
- 'endLineString' MUST ALWAYS come *after* 'startLineString' in the *proposed updates*. It must start with a line number that is HIGHER than the 'startLineString' line number. If 'startLineString' starts with 'pdx-new-22: ', then 'endLineString' MUST either be an empty string (for a single line replacement) or start with 'pdx-new-23: ' or higher (for a multi-line replacement).
+ Example:
- If 'hasChange' is false, both 'startLineString' and 'endLineString' must be empty strings. If 'hasChange' is true, 'startLineString' and 'endLineString' must be valid strings that exactly match lines from the *proposed updates*. If 'hasChange' is true, 'startLineString' and 'endLineString' MUST NEVER be empty strings.
+ ---
+ Comments:
-If the 'hasChange' property is false, the 'new' property must be an empty string. If the 'hasChange' property is true, the 'new' property must be a valid string.
+ pdx-new-2: // ... existing code to start transaction ...
+ Evaluation: refers the code at the beginning of the 'update' function that starts the database transaction.
+ Reference: true
-Expand the lines the 'new' property refers to in the *proposed updates* where needed to include line breaks and preserve formatting.
+ pdx-new-6: // ... existing update code ...
+ Evaluation: refers the code inside the 'update' function that updates the user.
+ Reference: true
-'includeOldReasoning' is a string. Evaluate whether the section of code from the *original file* that the old property refers to should be included in the final result.
+ pdx-new-9: // ... existing code to commit db transaction...
+ Evaluation: refers the code inside the 'update' function that commits the database transaction.
+ Reference: true
-If the code from the 'new' section should fully replace the code from the 'old' property, say "Fully replace" and stop.
+ pdx-new-4: // verify user permission before performing update
+ Evaluation: describes the change being made. Does not refer to any code in the *original file*.
+ Reference: false
-If the 'old' section spans multiple lines of the *original file*, say "Multiple lines, don't include." and stop.
+ pdx-new-85: // Rest of the main function...
+ Evaluation: refers to the rest of the main function that is left unchanged.
+ Reference: true
-Otherwise, if the code from the 'old' property is a *single line* and it's not in the *proposed updates*, state this. In that case, proceed to evaluate whether the code from the old property makes more sense at the beginning or end of the change from the new property. State which makes more sense and why. For example, "The closing </Routes> tag should be included in the final result. It should be added *after* the 'new' code from the *proposed updates*.
-
-'appendOld' must be true if 'includeOldReasoning' determined that the code from the old property should be included in the final result and that it makes the most sense to include it at the end of the change from the new property.
-
-'prependOld' must be true if 'includeOldReasoning' determined that the code from the old property should be included in the final result and that it makes the most sense to include it at the beginning of the change from the new property.
+ pdx-new-25: # Delete the object
+ Evaluation: describes the change being made. Does not refer to any code in the *original file*.
+ Reference: false
`
-const changeRulesPrompt = `
-Apply changes intelligently **in order** to avoid syntax errors, breaking code, or removing code from the *original file* that should not be removed. Consider the reason behind the update and make sure the result is consistent with the intention of the plan.
-
-Changes MUST be ordered based on their position in the *original file*. ALWAYS go from top to bottom IN ORDER when generating changes.
+const RefsOnlyEnding = `
+ *
-When generating changes, you MUST consider the list of sections from the 'originalSections' array. If a section is marked as 'shouldChange', there MUST be at least one corresponding change in the 'changes' array that addresses that section.
-
-You ABSOLUTELY MUST NOT overwrite or delete code from the *original file* unless the plan *clearly intends* for the code to be overwritten or removed. Do NOT replace a full section of code with only new code unless that is the clear intention of the plan. Instead, merge the original code and the *proposed updates* together intelligently according to the intention of the plan.
-
-Pay *EXTREMELY close attention* to opening and closing brackets, parentheses, and braces. Never leave them unbalanced when the changes are applied. Also pay *EXTREMELY close attention* to newlines and indentation. Make sure that the indentation of the new code is consistent with the indentation of the original code, and syntactically correct. Do NOT remove extraneous newlines from the *original file* unless it is explicitly mentioned in the *proposed updates*.
-
-You ABSOLUTELY MUST NOT generate overlapping changes.
-
-Changes must be ordered in the array according to the order they appear in the *original file*. The 'startLineString' of each 'old' property ABSOLUTELY MUST come after the 'endLineString' of the previous 'old' property. If the 'problems' key includes guidance on the order that changes should be applied, you MUST follow that guidance and generate the changes in the order specified.
-
-You MUST NOT repeat changes to the same block of lines multiple teams. You MUST NOT duplicate changes. It is extremely important that a given change is only applied *once*.
-
-ALL THE CODE in the *proposed updates* must be accounted for in the 'changes' array. You MUST NOT leave out any new code, changes, or deletions that are introduced in the *proposed updates*.
-
-Break up changes when they apply to different sections of the file, as listed in the 'originalSections' array.
-`
-
-const lineNumsJsonPrompt = `
-The 'listChangesWithLineNums' function MUST be called *valid JSON*. Double quotes within json properties of the 'listChangesWithLineNums' function call parameters JSON object *must be properly escaped* with a backslash. Pay careful attention to newlines, tabs, and other special characters. The JSON object must be properly formatted and must include all required keys. **You generate perfect JSON -every- time**, no matter how many quotes or special characters are in the input. You must always call 'listChangesWithLineNums' with a valid JSON object. Don't call any other function.
+ Do NOT include any additional text after the <references> element. The output must end after </references>. DO NOT use the string <references> anywhere else in the output. ONLY use it to start the <references> element.
`
-const commentsPrompt = `
-The 'comments' key is an array of objects with two properties: 'txt' and 'reference'. 'txt' is the exact text of a code comment. 'reference' is a boolean that indicates whether the comment is a placeholder of or reference to the original code, like "// rest of the function..." or "# existing init code...", or "// rest of the main function" or "// rest of your function..." or "// Existing methods..." or "// Remaining methods" or "// Existing code..." or "// ... existing setup code ..." or "// Existing code..." or "// ... existing code ..." or "// ..." or other comments which reference code from the *original file*. References DO NOT need to exactly match any of the previous examples. Use your judgement to determine whether each comment is a reference. If 'reference' is true, the comment is a placeholder or reference to the original code. If 'reference' is false, the comment is not a placeholder or reference to the original code.
+const WholeFileEnding = `
+ *
-In 'comments', you must list EVERY comment included in the *proposed updates*. Only list *code comments* that are valid comments for the programming language being used. Do not list logging statements or any other non-comment text that is not a valid code comment. If there are no code comments in the *proposed updates*, 'comments' must be an empty array.
-
-If there are multiple identical comments in the *proposed updates*, you MUST list them *all* in the 'comments' array--list each identical comment as a separate object in the array.
-`
+ Now output the entire file with the *proposed updates* correctly applied. ALL identified references MUST be replaced by the appropriate code from the *original file*. You MUST correctly merge the code from the *original file* with the *proposed updates* and output the entire file. The resulting file MUST NOT include any reference comments.
-const problemsStrategyPrompt = `
-In the 'problems' key, you MUST explain how you will strategically generate changes in order to avoid any problems in the updated file.
-
-If 'entireFile' is set to true, 'problems' must be an empty string.
-
-You must consider whether you will apply partial changes, prepend or append to the file, or insert before or after specific lines. Choose whichever is the simplest, most effective, and least error-prone method of making your changes. Before choosing, evaluate the consequences of each option and choose the one that will cause the fewest errors and the easiest changes.
+ The resulting file MUST be syntactically and semantically correct. All code structures must be properly balanced.
+
+ The full resulting file should be output within a <file> element, like this:
-You must consider how you will avoid *incorrectly removing or overwriting code* from the *original file*. Explain whether any code from the *original file* needs to be merged with the *proposed updates* in order to avoid removing or overwriting code that should not be removed.
+ <file>
+ package main
-It is ABSOLUTELY CRITICAL that no pre-existing code or functionality is removed or overwritten unless the plan explicitly intends for it to be removed or overwritten. New code and functionality introduced in the *proposed updates* MUST be *merged* with existing code and functionality in the *original file*. Explain how you will achieve this.
+ import "logger"
-You must consider how you will *avoid incorrect duplication* in making your changes. For example if a 'main' function is present in the *original file* and the *proposed updates* include update code for the 'main' function, you must ensure the changes are applied within the existing 'main' function rather than incorrectly adding a duplicate 'main' function.
+ function main() {
+ logger.info("Hello, world!");
+ exec()
+ }
+ </file>
-If the *proposed updates* include large sections that are identical to the *original file*, consider whether the changes can be made more minimal in order to only replace sections of code that are *changing*. If you are making the changes more minimal and specific, explain how you will do this.
+ Do NOT include line numbers in the <file> element. Do NOT include reference comments in the <file> element. Output the ENTIRE file, no matter how long it is, with NO EXCEPTIONS. Include the resulting file *only* with no other text. Do NOT wrap the file output in triple backticks or any other formatting, except for the <file> element tags.
-You MUST also explicitly state the *order* that all the changes you've listed will be applied. Changes MUST be applied in the order they appear in the *original file*. ALWAYS go from top to bottom in order when making your changes.
+ Do NOT include any additional text after the <file> element. The output must end after </file>. DO NOT use the string <file> anywhere else in the output. ONLY use it to start the <file> element.
`
-const originalSectionsPrompt = `
-The 'originalSections' key is an array of objects with four properties: 'description', 'structure', 'reasoning', 'sectionStartLine', 'sectionEndLine', 'shouldChange', and 'shouldRemove'. In the 'originalSections' key you must logically divide the *original file* into sections based on functionality, logic, code structure, and general organization.
+func GetValidateEditsPrompt(
+ path,
+ original,
+ desc,
+ proposed,
+ diff string,
+ reasons []syntax.NeedsVerifyReason,
+) string {
+ var s string
-You must list every section that exists in the *original file*. When large sections of the *original file* are not changing, combine them into a single section. Only include sections from the *original file*. Do NOT include sections from the *proposed updates*.
+ s += fmt.Sprintf(`
+[Explanation Rules]
-Don't make the sections overly small and granular unless there is a clear semantic reason to do so. For example, if there are many small functions in a file, don't create a section for each section. Sections should be larger than that and instead reflect the general structure of a file, rather than being a long list of every top-level code structure.
-
-'description' is a brief summary of the section and its purpose.
-
-'structure' is an object with three properties: 'structure', 'structureOpens', and 'structureCloses'.
- 'structure' is the OUTERMOST code structure (namespace, class, function, etc.) of the section. State whether the full structure is contained within the section or whether the section only contains part of the structure. If the seciton is not contained within a structure, output 'top level'.
-
- 'structureOpens' is the entire line from the *original file* that contains the opening symbol of the code structure identified in the 'structure' property, including the line number prefixed with 'pdx-'. Empty if the code structure is 'top level'. Empty if the the section does not contain the opening symbol of the identified structure. If the section clearly contains an entire structure, like "SomeClass definition", then the 'structureOpens' property must be set and must be the line that opens the structure.
+%s
- 'structureCloses' is the entire line from the *original file* that contains the closing symbol of the code structure identified in the 'structure' property, including the line number prefixed with 'pdx-'. Empty if the code structure is 'top level'. Empty if the the section does not contain the closing symbol of the identified structure. If the secton clearly contains an entire structure, like "SomeClass definition", then the 'structureCloses' property must be set and must be the line that closes the structure.
+[End Explanation Rules]
-'reasoning' is a brief evaluation of how this section relates to the *proposed updates*, and whether all or any part of it will be changed, removed, or preserved as is. If only part of the section should be changed, explain which part(s) will change and which parts will remain the same, and further explain how you will avoid incorrectly removing or overwriting code that should not be removed.
+[Proposed Updates Rules]
-Anytime there is a partial change to a section, it is CRITICAL that you explain BOTH which parts of the section should be *changed* and which parts will be *preserved* and how you will ensure this when generating changes below. You MUST include this explanation in the 'reasoning' key when there's a partial change. It must begin with "To avoid removing". If new code is being added, note *where* in the section it will be added, and include line numbers prefixed with 'pdx-'. For example, "To avoid removing any existing imports, the new imports will be added after the existing imports, which end on pdx-5." or "To avoid removing any existing init code, the new code for checking the GOENV environment variable will be added before the existing init code, which starts on pdx-10."
+%s
-'sectionStartLine' is the line number, prefixed with 'pdx-', where the section begins in the *original file*. Include only the line number, not the line itself. If 'structure.structureOpens' is not empty, 'sectionStartLine' MUST be the same as 'structure.structureOpens'.
+[End Proposed Updates Rules]
+`, ChangeExplanationPrompt, UpdateFormatPrompt)
-'sectionEndLine' is the line number, prefixed with 'pdx-', where the section ends in the *original file*. Include only the line number, not the line itself. If 'structure.structureCloses' is not empty, 'sectionEndLine' MUST be the same as 'structure.structureCloses'.
+ s += fmt.Sprintf("Path: %s\n\nOriginal file:\n%s\n\nProposed changes explanation:\n%s\n\nProposed changes:\n%s", path, original, desc, proposed)
+ s += fmt.Sprintf("\n\nApplied changes:\n%s", diff)
+ s += `You will examine the original file, proposed changes explanation, proposed changes, and applied changes diff.`
-'shouldChange' is a boolean that indicates whether the section should be changed.
+ var editsIncorrect bool
-'shouldRemove' is a boolean that indicates whether the section should be removed.
-
-A section should only be changed or removed if the *proposed updates* clearly intend for it to be changed or removed.
-`
-
-func getListChangesLineNumsPrompt(expandedRefs bool) string {
- res := replacementIntro + `
+ for _, reason := range reasons {
+ if reason == syntax.NeedsVerifyReasonAmbiguousLocation {
+ editsIncorrect = true
+ s += `The proposed changes were applied to an ambiguous location. This may mean that anchors were written incorrectly (with incorrect spacing or indentation, for example), or else that the ordering of anchors was incorrect. It may also mean that necessary surrounding context and anchors were not included.`
+ } else if reason == syntax.NeedsVerifyReasonNoChanges {
+ s += `The proposed changes did not cause any change to the resulting file when applied. Was this intentional?`
+ } else if reason == syntax.NeedsVerifyReasonCodeRemoved {
+ s += `The proposed changes removed or replaced code. Was this intentional?`
+ } else if reason == syntax.NeedsVerifyReasonCodeDuplicated {
+ s += `The proposed may have duplicated code. Was this intentional?`
+ }
+ }
- [YOUR INSTRUCTIONS]
+ if editsIncorrect {
+ s += EditsIncorrectPrompt
+ } else {
+ s += EditsValidatePrompt
+ }
- Call the 'listChangesWithLineNums' function with a valid JSON object that includes the 'originalSections', 'entireFileReasoning', 'entireFile', 'problems', and 'changes' keys.
-
- ` + originalSectionsPrompt + `
+ s += getEditsExamples(!editsIncorrect)
- ` + entireFilePrompt + `
+ s += `
- ` + problemsStrategyPrompt + `
-
- ` + changesKeyPrompt + `
-
- ` + summaryChangePrompt + `
-
- ` + lineNumsOldPrompt + `
-
- ` + changeLineInclusionAndNewPrompt
-
- if expandedRefs {
- res += `
- While the code changes *without* expanded references have been included to help you understand the scope of the change, the 'new' key of each change object *ABSOLUTELY MUST ALWAYS* refer to the *proposed updates* *with* expanded references and pdx-new- prefixed line numbers. When the *proposed updates* are mentioned above, this refers to the *proposed updates* *with* expanded references and pdx-new- prefixed line numbers.
-
- Use the changes *without* expanded references to understand specifically which code is changing and what the *order* of the code structures in the final updated file should be. It's extremely important that the code is ordered exactly as it is intended in the *proposed updates*.
-
- If the changes *without* expanded references look like this:
-
- ---
- class MyClass {
- // ... existing code ...
-
- someNewMethod() {
- doStuff();
- }
- }
- ---
-
- Then the newly added 'someNewMethod' method MUST go at the *end* of the 'MyClass' class.
- `
- }
+- You MUST NOT make *functional* changes when rewriting the explanation or proposed updates. Your job is not to change functionality or write additional code, but to ensure that the explanation and proposed updates follow all the rules correctly. Stick as close to the original proposed updates as possible when rewriting. Fix the problems, but keep everything else the same as much as possible, including comments, line breaks, spacing, etc.
- res += `
-
- Example change object:
- ---
- {
- summary: "Fix syntax error in loop body.",
- old: {
- startLineString: "pdx-5: for i := 0; i < 10; i++ { ",
- endLineString: "pdx-7: }",
- },
- new: {
- startLineString: "pdx-new-5: for i := 0; i < 10; i++ { ",
- endLineString: "pdx-new-7: }",
- },
- }
- ---
-
- ` + `
-
- ` + changeRulesPrompt + `
-
- ` + lineNumsJsonPrompt + `
-
- [END YOUR INSTRUCTIONS]
+- You MUST NOT add 'Plandex: removed' comments unless the intention of the plan and the explanation is to remove code. NEVER add 'Plandex: removed' comments to the *proposed updates* unless the *explanation* includes the word 'remove'. The *only* time you can add a 'Plandex: removed' comment is if 1 - you are correcting a mistaken comment that was intended as a removal comment, but used the wrong format—for example, if the 'Plandex: ' prefix was incorrectly omitted. In that case you must fix the comment in the fixed proposed updates. 2 - the explanation explicitly stats that code should be removed, but a necessary 'Plandex: removed' comment is missing from the proposed updates, causing the code that should have been removed to incorrectly remain in the file. In that case you must add the missing 'Plandex: removed' comment to the proposed updates in the correct location, with correct surrounding context and anchors.
`
- return res
+ return s
}
-func getFixChangesLineNumsPrompt() string {
-
- return `
- You are an AI that analyzes an *original file* (if present), an incorrectly updated file, the changes that were proposed, and a description of the problems with the file, and then produces a list of changes to apply to the *incorrectly updated file* that will fix *ALL* the problems.
-
- Problems you MUST fix include:
- - Syntax errors, including unbalanced brackets, parentheses, braces, quotes, indentation, and other code structure errors
- - Missing or incorrectly scoped declarations
- - Any other errors that make the code invalid and would prevent it from being run as-is for the programming language being used
- - Incorrectly applied changes
- - Incorrectly removed code
- - Incorrectly overwritten code
- - Incorrectly duplicated code
- - Incorrectly applied comments that reference the original code
-
- If the updated file includes references to the original code in comments like "// rest of the function..." or "# existing init code...", or "// rest of the main function..." or "// rest of your function..." or "// Existing methods..." **any other reference to the original code, the file is incorrect. References like these must be handled by including the exact code from the *original file* that the comment is referencing.
-
- [YOUR INSTRUCTIONS]
- Call the 'listChangesWithLineNums' function with a valid JSON object that includes the 'comments','problems' and 'changes' keys.
-
- 'comments': Since this is a fix, comments must be an empty array.
- 'problems': A string that describes all problems present within the updated file. Explain the cause of each problem and how it should be fixed. Do not just restate that there is a syntax error on a specific line. Explain what the syntax error is and how to fix it. Be exhaustive and include *every* problem that is present in the file.
-
- Since you are fixing an incorrectly updated file, you *MUST* include the 'problems' key and you *MUST* describe *all* problems present in the file. If there are multiple problems, list each one individually. If there are multiple identical problems, list each one individually.
-
- You should also explain your strategy for generating changes in the 'problems' key according to these instructions:
-
- ` + problemsStrategyPrompt + `
-
- ` + changesKeyPrompt + `
-
- ` + summaryChangePrompt + `
-
- ` + lineNumsOldPrompt + `
-
- ` + changeLineInclusionAndNewPrompt + `
-
- You MUST ensure the line numbers for the 'old' property correctly remove *ALL* code that has problems and that the 'new' property correctly fixes *ALL* the problems present in the updated file. You MUST NOT miss any problems, fail to fix any problems, or introduce any new problems.
-
- Example change object:
- ---
- {
- summary: "Fix syntax error in loop body.",
- old: {
- startLineString: "pdx-5: for i := 0; i < 10; i++ { ",
- endLineString: "pdx-7: }",
- },
- new: "for i := 0; i < 10; i++ {\n execQuery()\n }\n }\n}",
- }
- ---
-
- ` + changeRulesPrompt + `
-
- ` + lineNumsJsonPrompt + `
-
- [END YOUR INSTRUCTIONS]
+const EditsValidatePrompt = `
+- In a '## Evaluate Diff' section, examine the applied changes diff and determine whether the changes were applied correctly. Carefully asses whether:
+ a. Any code was removed that should have been kept.
+ b. Any code was duplicated that should not have been.
+ c. Any code was incorrectly inserted or replaced.
+ d. Any code was inserted at the wrong location.
+
+- If the changes were applied correctly, output "**Changes Applied Correctly**" after the evaluation and stop your response here. You MUST NOT output any further explanation or *any other text* after the "**Changes Applied Correctly**" string. End your response *immediately* after the "**Changes Applied Correctly**" string.
+
+- If the changes were *not* applied correctly, continue with the following steps:
+` + EditsIncorrectPrompt
+
+const EditsIncorrectPrompt = `
+- In a '## Evaluate Explanation' section, examine the proposed changes explanation and determine whether it is correct. Did it follow all the rules in the [Proposed Updates Rules] section?
+ a. If the changes are inserting, removing, or replacing code between two specific code structures, are these the correct code structures to use for the update? Are these structures *immediately* adjacent to each other or is there other code between them?
+ b. If the changes are inserting, removing, or replacing code between a specific code structure and the start or end of the file, are these the correct code structures or locations to use for the update? If the change is between the start of the file and a specific code structure, is there any other code between the start of the file and that code structure? (There must not be). If the change is between a specific code structure and the end of the file, is there any other code between that code structure and the end of the file? (There must not be).
+
+- If the proposed changes explanation is *not* correct, you must rewrite the proposed changes explanation to correctly follow *all* the rules in the [Proposed Updates Rules] section in a <PlandexProposedUpdatesExplanation> element. Include *only* the rewritten proposed changes explanation inside the <PlandexProposedUpdatesExplanation> element, and no other text. If the proposed changes explanation is already correct, skip this step.
+ - When rewriting the proposed changes explanation, DO NOT change the alter the *type* of the change. You must ONLY update the portion of the explanation that explains the *location* of the change, not the *type* of the change. For example, if the proposed changes explanation is "I'll add 'someFunction' at the end of the file, immediately after 'existingFunction1'", you must rewrite it to correctly explain the *location* of the change, like "I'll add 'someFunction' at the end of the file, immediately after 'existingFunction2'". You MUST NOT change the type of the change, such as from 'add' to 'remove'.
+ - If the explanation does not match the changes that were made in the proposed updates (for example, the explanation says to add code, but the proposed updates removed code), this means that the proposed updates are *incorrect*—you MUST NOT alter the explanation to match the incorrect proposed updates (for example, you MUST NOT change the explanation to remove code instead of adding it just because the proposed updates incorrectly removed code). Instead, focus on ensuring that the explanation correctly shows the *location* of the change so that the proposed updates can be corrected.
+ - If you are outputting a rewritten proposed changes explanation, YOU ABSOLUTELY MUST DO SO within the <PlandexProposedUpdatesExplanation> element. DO NOT output it outside of the <PlandexProposedUpdatesExplanation> element or anywhere else in your response—ONLY output the rewritten proposed changes explanation inside the <PlandexProposedUpdatesExplanation> element.
+
+- In a '## Evaluate Proposed Changes' section, examine the proposed changes and determine whether they are correct.
+ a. Did they follow all the rules in the [Proposed Updates Rules] section?
+ b. Are they consistent with the proposed changes explanation (or the rewritten proposed changes explanation, if you had to rewrite it)?
+ c. Is more surrounding context needed or are more *anchors* needed to resolve ambiguity in the proposed changes and *precisely* locate the change *unambiguously* in the original file?
+ d. Are any *reference comments* or *removal comments* written incorrectly? All reference comments must be *exactly* '... existing code ...' and all removal comments must be *exactly* 'plandex: removed code'. Each must use the correct comment syntax for the language. If any comments are variations of those rather than the exact strings, they are incorrect.
+ e. Are any *reference comments* or *removal comments* missing?
+ - If the proposed changes incorrectly removed code, this does *NOT MEAN* that a removal comment is missing; you MUST NOT say that a removal comment is missing in this case. *ONLY* state that a removal comment is missing if the explanation *explicitly* states that code should be removed and it was not correctly removed due to a missing removal comment.
+
+- In a <PlandexProposedUpdates> element, output the corrected proposed changes. Include *only* the corrected proposed changes inside the <PlandexProposedUpdates> element, and no other text. The corrected proposed changes MUST follow *all* the rules in the [Proposed Updates Rules] section.
+ - If you are outputting a corrected proposed changes, YOU ABSOLUTELY MUST DO SO within the <PlandexProposedUpdates> element. DO NOT output it outside of the <PlandexProposedUpdates> element or anywhere else in your response—ONLY output the corrected proposed changes inside the <PlandexProposedUpdates> element. You ABSOLUTELY MUST NOT use triple backticks or any other formatting around the rewritten proposed changes. Output ONLY the corrected proposed changes inside the <PlandexProposedUpdates> element with no other text or formatting.
+ - DO NOT include the proposed changes within a formatted code block. Include *ONLY* the code directly inside the <PlandexProposedUpdates> element.
+ - If more surrounding context or *anchors* are needed to resolve ambiguity in the proposed changes and *precisely* locate the change *unambiguously* in the original file, you MUST output the corrected proposed changes with the additional context or *anchors* included correctly.
+ - If any *reference comments* or *removal comments* are written incorrectly, you MUST output the corrected proposed changes with the *reference comments* or *removal comments* corrected. A reference comment must be *exactly* '... existing code ...' and a removal comment must be *exactly* 'plandex: removed code'. Use the correct comment syntax for the language.
+ - If any *reference comments* or *removal comments* are missing, you MUST output the corrected proposed changes with the *reference comments* or *removal comments* added.
+ - If the proposed changes incorrectly removed code, this does *NOT MEAN* that a removal comment is missing; you MUST NOT output a removal comment in this case. Instead, fix the proposed changes to prevent the removal of code that should have been kept.
+ - When outputting *anchors* in the proposed changes, lines from the proposed changes that match lines in the original file, spacing and indentation must be preserved *exactly* as they are in the original file—the two lines must be *exactly identical*.
`
-}
-
-var ListReplacementsFn = openai.FunctionDefinition{
- Name: "listChangesWithLineNums",
- Parameters: &jsonschema.Definition{
- Type: jsonschema.Object,
- Properties: map[string]jsonschema.Definition{
- "comments": {
- Type: jsonschema.Array,
- Items: &jsonschema.Definition{
- Type: jsonschema.Object,
- Properties: map[string]jsonschema.Definition{
- "txt": {
- Type: jsonschema.String,
- },
- "reference": {
- Type: jsonschema.Boolean,
- },
- },
- Required: []string{"txt", "reference"},
- },
- },
- "problems": {
- Type: jsonschema.String,
- },
- "changes": {
- Type: jsonschema.Array,
- Items: &jsonschema.Definition{
- Type: jsonschema.Object,
- Properties: map[string]jsonschema.Definition{
- "summary": {
- Type: jsonschema.String,
- },
- "hasChange": {
- Type: jsonschema.Boolean,
- },
- "old": {
- Type: jsonschema.Object,
- Properties: map[string]jsonschema.Definition{
- "entireFile": {
- Type: jsonschema.Boolean,
- },
- "startLineString": {
- Type: jsonschema.String,
- },
- "endLineString": {
- Type: jsonschema.String,
- },
- },
- Required: []string{"startLineString", "endLineString"},
- },
- "startLineIncludedReasoning": {
- Type: jsonschema.String,
- },
- "startLineIncluded": {
- Type: jsonschema.Boolean,
- },
- "endLineIncludedReasoning": {
- Type: jsonschema.String,
- },
- "endLineIncluded": {
- Type: jsonschema.Boolean,
- },
- "new": {
- Type: jsonschema.String,
- },
- },
- Required: []string{
- "summary",
- "hasChange",
- "old",
- "startLineIncludedReasoning",
- "startLineIncluded",
- "endLineIncludedReasoning",
- "endLineIncluded",
- "new",
- },
- },
- },
- },
- Required: []string{"comments", "problems", "changes"},
- },
-}
-func GetVerifyPrompt(preBuildState, updated, changes, diff string) string {
- s := `
-Based on an *original file* (if one exists), an AI-generated plan, an updated file, and a diff between the original and updated file, determine whether the updated file's syntax is correct and whether the *proposed updates* were applied correctly to the updated file.
+func getEditsExamples(evaluateDiff bool) string {
+ s := ""
-You must consider whether any of the following problems are present in the updated file:
-- Syntax errors, including unbalanced brackets, parentheses, braces, quotes, indentation, and other code structure errors
-- Missing or incorrectly scoped declarations
-- Any other errors that make the code invalid and would prevent it from being run as-is for the programming language being used
-- Code from the *original file* was incorrectly removed or overwritten.
-- Code was incorrectly duplicated. For example, if a file should have a single main function, but instead of updating the existing main function, the updated file includes multiple main functions, then the file is incorrect. The same applies to any other functions or elements that should not be duplicated.
-- Incorrectly included comments that reference the original code.. If the updated file includes comments like "// rest of the function..." or "# existing init code...", or "// rest of the main function..." or "// rest of your function..." or "// Existing methods...", "// Existing code..." **any other reference to the original code**, the file is incorrect. References like these must be handled by including the exact code from the *original file* that the comment is referencing.
+ if evaluateDiff {
+ s += `
+- Example Response if changes were applied correctly ('## Evaluate Diff' section included):
-If there is no *original file*, it means that a new file was created from scratch based on the AI-generated plan. In this case, the syntax in the new file must be valid and consistent with the intention of the plan. You must ensure there are no syntax errors or other clear mistakes in the new file.
+--
-Call the 'verifyOutput' function with a valid JSON object that include the following keys:
+## Evaluate Diff
-'syntaxErrorsReasoning': A string that succinctly explains whether there are any syntax or scoping errors in the updated file. Explain all syntax errors, scoping errors, or other code structure errors that are present in the updated file.
+The new function 'someFunction' was correctly added to the end of the file.
-'hasSyntaxErrors': A boolean that indicates whether there are any syntax errors in the updated file, based on the reasoning provided in 'syntaxErrorsReasoning'.
+**Changes Applied Correctly**
+--
-'removed': an array of objects with three properties: 'code', 'reasoning', and 'correct'.
- - 'code' is a string. It shows the section of code that was removed or overwritten in the updated file. This can be abbreviated by detailing how the section starts and end and describing the purpose of the code. If the section is longer than a few lines, rather than reproducding a long section of code verbatim, provide a summary of the code that was removed or overwritten, as well as the exact code which starts and ends the section. The summary and start/end code should be details enough to disambiguate the section of code that was removed or overwritten from any other similar sections of code in the file.
- - 'reasoning' is a string that explains whether, based on the *proposed updates*, this section was deliberately removed consistent with the intention of the plan, or whether the plan did NOT specify that this section should be removed, and the code was therefore removed incorrectly. Also consider whether this removal breaks the syntax or functionality of the code in the updated file based on the programming language being used--if it does, explain this and state that the removal was incorrect. If the removal either wasn't intended by the *proposed updates* *or* breaks the syntax or functionality of the code, the removal is incorrect. If the removal was consistent with the intention of the plan *and* did not break the syntax or functionality of the code, the removal is correct.
- - 'correct' is a boolean that indicates whether the removal or overwriting was correct based on the 'reasoning' provided. If the removal was correct, set 'correct' to true. If the removal was incorrect, set 'correct' to false.
+- Example Response if changes were *not* applied correctly, but explanation and proposed changes were correct:
-Based on supplied diffs, you must list EVERY code section that was removed or overwritten in the updated file in 'removed'. If there are no code sections that were removed or overwritten, 'removed' must be an empty array. If multiple code sections were removed or overwritten, list each one as a separate object in the 'removed' array. If multiple identical code sections were removed or overwritten, you MUST list them *all* in the 'removed' array--list each identical code section as a separate object in the array. Do NOT include removals that only modify whitespace. Do NOT include sections that were moved or refactored, only sections that were fully removed or overwritten.
+--
-'removedCodeErrorsReasoning': A string that succinctly explains whether any code was incorrectly removed or overwritten in the updated file based on the 'removed' array. If code was incorrectly removed or overwritten, succinctly explain why it was incorrect, and how the file can be corrected. If code was correctly removed or overwritten, consistent with the intention of the plan, state this.
+## Evaluate Diff
-'hasRemovedCodeErrors': A boolean that indicates whether any code was *incorrectly* removed or overwritten in the updated file, based on the reasoning provided in 'removedCodeErrorsReasoning'.
+The new function 'someFunction' was incorrectly added to the end of the file.
-'duplicationErrorsReasoning': A string that succinctly explains whether any code was *incorrectly* duplicated in the updated file. First explain whether any code, functions, or other elements are duplicated in the updated file, then explain whether the duplication is deliberate and consistent with the plan, and whether the duplication is correct and valid in the programming language being used.
+## Evaluate Explanation
-'hasDuplicationErrors': A boolean that indicates whether any code was *incorrectly* duplicated in the updated file, based on the reasoning provided in 'duplicationErrorsReasoning'. If code was *incorrectly* duplicated, set 'hasDuplicationErrors' to true. If code was *correctly* duplicated, consistent with the intention of the plan, set 'hasDuplicationErrors' to false.
+The explanation correctly describes how the new function should be added to the file.
-'comments': an array of objects with two properties: 'txt' and 'reference'. 'txt' is the exact text of a code comment. 'reference' is a boolean that indicates whether the comment is a placeholder of or reference to the original code, like "// rest of the function..." or "# existing init code...", or "// rest of the main function" or "// rest of your function..." or "// Existing methods..." or "// Remaining methods" or "// Existing code..." or "// ... existing setup code ..." or "// Existing code..." "// ... existing code ..." or "// ..." or other comments which reference code from the *original file*. References DO NOT need to exactly match any of the previous examples. Use your judgement to determine whether each comment is a reference. If 'reference' is true, the comment is a placeholder or reference to the original code. If 'reference' is false, the comment is not a placeholder or reference to the original code.
+## Evaluate Proposed Changes
-In 'comments', you must list EVERY comment included in the *updated file*. Only list *code comments* that are valid comments for the programming language being used. Do not list logging statements or any other non-comment text that is not a valid code comment. If there are no code comments in the *updated file*, 'comments' must be an empty array.
+The proposed changes correctly use a reference comment to indicate that the new function should be added after 'existingFunction' at the end of the file.
-If there are multiple identical comments in the *updated file*, you MUST list them *all* in the 'comments' array--list each identical comment as a separate object in the array.
+--
-'referenceErrorsReasoning': A string that succinctly explains whether any comments in the updated file are placeholders/references that should have been replaced with code from the *original file*. These are comments like "// rest of the function..." or "# existing init code...", or "// rest of the main function..." or "// rest of your function..." or "// Existing methods...", "// Existing code..." or other comments which reference code from the *original file*. Only include comments that *are not* present in the *original file* and *are* present in the *proposed updates*. If there are no such comments, explain that there are no reference errors.
+Note that if the changes were applied correctly, YOU ABSOLUTLY MUST NEVER output a <PlandexProposedUpdates> element. Just stop the response after the ## Evaluate Proposed Changes section.
+`
+ }
-'hasReferenceErrors': A boolean that indicates whether any comments in the updated file are placeholders/references that should be replaced with code from the *original file*, based on the reasoning provided in 'referenceErrorsReasoning'.
+ s += `
+- Example Response if explanation and proposed changes were *not* correct:
-In each of the reasoning keys above, be exhaustive and include *every* problem that is present in the file. But if there are no problems in a reasoning key, do NOT invent problems--explain according to your instructions for each key that there are no problems in that category.
+--
`
- if preBuildState != "" {
+ if evaluateDiff {
s += `
---
-
-## **Original file:**
-
-` + preBuildState + `
+## Evaluate Diff
---
+The proposed changes incorrectly removed the 'existingFunction2' function.
`
}
s += `
-## **Proposed updates:**
-[START PROPOSED UPDATES]
-
-` + changes + `
+## Evaluate Explanation
-[END PROPOSED UPDATES]
+The explanation incorrectly used 'existingFunction1' as an anchor when there is code between 'existingFunction1' and the end of the file. It should have used 'existingFunction2' instead.
`
- if preBuildState != "" {
- s += `
-
-## **Updated file:**
-
-`
- } else {
- s += `
- ## **New file:**
+ s += `
+<PlandexProposedUpdatesExplanation>
+ **Updating some/path/to/file.js:** I'll add 'someFunction' at the end of the file, immediately after 'existingFunction2'.
+</PlandexProposedUpdatesExplanation>
- `
- }
+## Evaluate Proposed Changes
- s += updated + "\n\n"
+The proposed changes incorrectly used 'existingFunction1' as an anchor when there is code between 'existingFunction1' and the end of the file. It should have used 'existingFunction2' instead.
- if diff != "" {
- s += "**Diff:**\n\n" + diff + "\n\n"
- }
+<PlandexProposedUpdates>
+// ... existing code ...
- s += `
+function existingFunction2() {
+ // ... existing code ...
+}
-Now call the 'verifyOutput' function with a valid JSON object. Don't call any other function.
+function someFunction() {
+ console.log("New behavior");
+ const res = await execUpdate();
+}
+</PlandexProposedUpdates>
-You absolutely MUST generate PERFECTLY VALID JSON. Pay extremely close attention to the JSON syntax and structure. Double quotes within JSON properties *MUST* be properly escaped with a backslash.`
+--
+`
return s
}
-var VerifyOutputFn = openai.FunctionDefinition{
- Name: "verifyOutput",
- Parameters: &jsonschema.Definition{
- Type: jsonschema.Object,
- Properties: map[string]jsonschema.Definition{
- "syntaxErrorsReasoning": {
- Type: jsonschema.String,
- },
- "hasSyntaxErrors": {
- Type: jsonschema.Boolean,
- },
- "removed": {
- Type: jsonschema.Array,
- Items: &jsonschema.Definition{
- Type: jsonschema.Object,
- Properties: map[string]jsonschema.Definition{
- "code": {
- Type: jsonschema.String,
- },
- "reasoning": {
- Type: jsonschema.String,
- },
- "correct": {
- Type: jsonschema.Boolean,
- },
- },
- Required: []string{"code", "reasoning", "correct"},
- },
- },
- "removedCodeErrorsReasoning": {
- Type: jsonschema.String,
- },
- "hasRemovedCodeErrors": {
- Type: jsonschema.Boolean,
- },
- "duplicationErrorsReasoning": {
- Type: jsonschema.String,
- },
- "hasDuplicationErrors": {
- Type: jsonschema.Boolean,
- },
- "comments": {
- Type: jsonschema.Array,
- Items: &jsonschema.Definition{
- Type: jsonschema.Object,
- Properties: map[string]jsonschema.Definition{
- "txt": {
- Type: jsonschema.String,
- },
- "reference": {
- Type: jsonschema.Boolean,
- },
- },
- Required: []string{"txt", "reference"},
- },
- },
- "referenceErrorsReasoning": {
- Type: jsonschema.String,
- },
- "hasReferenceErrors": {
- Type: jsonschema.Boolean,
- },
- },
- Required: []string{"syntaxErrorsReasoning", "hasSyntaxErrors", "removed",
- "removedCodeErrorsReasoning", "hasRemovedCodeErrors", "duplicationErrorsReasoning", "hasDuplicationErrors", "comments", "referenceErrorsReasoning", "hasReferenceErrors"},
- },
+func getPreBuildStatePrompt(filePath, preBuildState string) string {
+ if preBuildState == "" {
+ return ""
+ }
+
+ return fmt.Sprintf("**The current file is %s. Original state of the file:**\n```\n%s\n```", filePath, preBuildState) + "\n\n"
}
diff --git a/app/server/model/prompts/build_update.go b/app/server/model/prompts/build_update.go
deleted file mode 100644
index da02e656..00000000
--- a/app/server/model/prompts/build_update.go
+++ /dev/null
@@ -1,821 +0,0 @@
-package prompts
-
-import (
- "fmt"
- "plandex-server/syntax"
-
- "github.com/plandex/plandex/shared"
-)
-
-func GetSemanticAnchorsPrompt(filePath, preBuildState, changesFile, changesDesc string) string {
- preBuildStateWithLineNums := shared.AddLineNums(preBuildState)
- changesWithLineNums := shared.AddLineNumsWithPrefix(changesFile, "pdx-new-")
-
- s := SemanticAnchorsPrompt + "\n\n" + getPreBuildStatePrompt(filePath, preBuildStateWithLineNums) + "\n\n"
-
- s += fmt.Sprintf("Proposed updates:\n%s\n```\n%s\n```", changesDesc, changesWithLineNums)
-
- // fmt.Printf("SemanticAnchorsPrompt: %s\n", s)
-
- return s
-}
-
-func GetReferencesPrompt(filePath, preBuildState, changesFile, changesDesc string) string {
- preBuildStateWithLineNums := shared.AddLineNums(preBuildState)
- changesWithLineNums := shared.AddLineNumsWithPrefix(changesFile, "pdx-new-")
-
- s := RefsBeginning + ReferencesPrompt + RefsOnlyEnding + "\n\n" + getPreBuildStatePrompt(filePath, preBuildStateWithLineNums) + "\n\n"
-
- s += fmt.Sprintf("Proposed updates:\n%s\n```\n%s\n```", changesDesc, changesWithLineNums)
-
- return s
-}
-
-func GetWholeFilePrompt(filePath, preBuildState, changesFile, changesDesc string) string {
- preBuildStateWithLineNums := shared.AddLineNums(preBuildState)
- changesWithLineNums := shared.AddLineNumsWithPrefix(changesFile, "pdx-new-")
-
- s := WholeFileBeginning + ReferencesPrompt + WholeFileEnding + "\n\n" + getPreBuildStatePrompt(filePath, preBuildStateWithLineNums) + "\n\n"
-
- s += fmt.Sprintf("Proposed updates:\n%s\n```\n%s\n```", changesDesc, changesWithLineNums)
-
- return s
-}
-
-var SemanticAnchorsPrompt = `
-You are an AI that analyzes an *original file* and *proposed updates* to that file and then identifies all *semantic anchors* and *reference comments* present in the *proposed updates*.
-
--
-
-### Semantic Anchors
-
-A semantic anchor is a line in the *proposed updates* that is not exactly equal to a line in the *original file* but is nonetheless intended to match a line in the *original file*.
-
-For example, if the *original file* has:
-
- pdx-1: function update(name string, id string) {
- pdx-2: const tx = await client.startTransaction();
- pdx-3: tx.setMode(TransactionMode.Serializable);
- pdx-4: const updateQuery = 'UPDATE users SET name = $1 WHERE id = $2';
- pdx-5: await tx.execute(updateQuery, name, id);
- pdx-6: await client.commit();
- pdx-7: }
-
-And the *proposed updates* have:
-
- pdx-new-1: function update(name string, id string, log bool) {
- pdx-new-2: // ... existing code ...
- pdx-new-3: if (log) {
- pdx-new-4: console.log("Updating user");
- pdx-new-5: }
- pdx-new-6: }
-
-Then the line 'pdx-new-1: function update(name string, id string, log bool) {' is a semantic anchor since it is not exactly equal to a line in the *original file* (due to the addition of the 'log' parameter) but is clearly intended to match the line 'pdx-1: function update(name string, id string) {' in the *original file*.
-
-The line 'pdx-new-6: }' is *not* a semantic anchor since it is exactly equal to a line in the *original file*.
-
-Comments that are modified in the *proposed updates* (but are clearly still referring to the same comment in the *original file*) can also be semantic anchors.
-
-A line that is exactly equal (including whitespace) to a line in the *original file* MUST NEVER UNDER ANY CONCEIVABLE CIRCUMSTANCES be marked as a semantic anchor.
-
-For example, if the *original file* has:
-
-pdx-1: function main() {
-pdx-2: // Get response
-pdx-3: const response = await getResponse();
-pdx-4: return response;
-pdx-5: }
-
-And the *proposed updates* have:
-
-pdx-new-1: function main() {
-pdx-new-2: // Get response and parse JSON body
-pdx-new-3: let response = await getResponse();
-pdx-new-4: response = jsonResponse(response);
-pdx-new-5: return response;
-pdx-new-6: }
-
-Then both the lines 'pdx-new-2: // Get response and parse JSON body' and 'pdx-new-3: let response = await getResponse();' are semantic anchors since they are not exactly equal to a line in the *original file* but are clearly intended to match the lines 'pdx-2: // Get response' and 'pdx-3: const response = await getResponse();' in the *original file*. The line 'pdx-new-4: response = jsonResponse(response);' is *not* a semantic anchor since it doesn't refer to any code in the *original file*. The line 'pdx-new-6: return response;' is *not* a semantic anchor since it is exactly equal to a line in the *original file*.
-
-To mark a line a semantic anchor, it must be very clear from the description of the change and the *proposed updates* that a line from the *proposed updates* is intended to match a line in the *original file*. Do NOT mark lines as semantic anchors simply because they are similar to a line in the *original file*. The line must be clearly intended to match a line in the *original file*. If it's ambiguous whether a line is intended to match a line in the *original file*, it is *not* a semantic anchor.
-
-If a line in the *proposed updates* is identical to a line in the *original file*, but has changed position or is being used in a different context, it is *still NOT* a semantic anchor. You *MUST NOT* under any circumstances mark any line that is identical to a line in the *original file* as a semantic anchor. Semantic anchors are only for lines that have *changed* in the *proposed updates* but are still clearly intended to match a line from the *original file*.
-
-If a line in the *proposed updates* is a semantic anchor and there is a comment (or multiple comments) associated with the line that is being modified, carefully consider if the comment should also be marked as a semantic anchor. If the comment or comments clearly map to a corresponding comment in the *original file*, and the comment is modified in the *proposed updates*, then it MUST be marked as a semantic anchor. Correctly marking comments as sematic anchors is just as important as marking other lines of code as semantic anchors.
-
--
-
-### Reference Comments
-
-A reference comment is a comment that references code in the *original file* for the purpose of making it clear where a change should be applied. Examples of reference comments include:
-
- - // ... existing code...
- - # Existing code...
- - /* ... */
- - // Rest of the function...
- - <!-- rest of div tag -->
- - // ... rest of function ...
- - // rest of component...
- - # other methods...
- - // ... rest of init code...
- - // rest of the class...
- - // other properties
- - // other methods
- // ... existing properties ...
- // ... existing values ...
- // ... existing text ...
-
-Reference comments often won't exactly match one of the above examples, but they will always be referencing a block of code from the *original file* that is left out of the *proposed updates* for the sake of focusing on the specific change that is being made.
-
-For some file types that don't use comments like JSON or plain text, reference comments in the form of '// ... existing properties ...' or '// ... existing values ...' or '// ... existing text ...' can still be present. These MUST be treated as valid reference comments regardless of the validity of the comment syntax.
-
--
-
-### Removal Comments
-
-A removal comment is a comment that indicates that a section of code should be removed from the *original file*. Examples of removal comments include:
-
- - // removed code
- - # removed start of function
- - <!-- removed 'container' div -->
- - // remove 'checkMigration' method
-
-Removal comments often won't exactly match one of the above examples, but they will always be indicating that a section of code should be removed from the *original file*.
-
-For some file types that don't use comments like JSON or plain text, removal comments like '// removed keys ...' can still be present. These MUST be treated as valid removal comments regardless of the validity of the comment syntax.
-
--
-
-### Output
-
-**First,** output a single *brief* paragraph of general reasoning about the *proposed updates* and how they refer to the *original file*, focusing on the structure of each, which elements are changing, and how the changes map to the *original file*. Also make a brief note of any comments that are being modified or introduced in the *proposed updates* and whether/how they map to comments in the *original file*. Do NOT output a list of semantic anchors in this paragraph—save that for the next section.
-
-**Next,** output a <PlandexSummary> element that gives a very brief, one-sentence summary of the changes being made. Example:
-
-<PlandexSummary>
- Adds a 'log' parameter to the 'update' function and modifies the 'update' function to use it.
-</PlandexSummary>
-
-**Next,** output a section that lists *EVERY* comment in the *proposed updates*, including the line number of each comment prefixed by 'pdx-new-'. Below each comment, evaluate whether it is a *reference comment*, a *removal comment*, or neither.
-
-*To determined whether a comment is a reference comment*, focus on whether the comment is clearly referencing a block of code in the *original file*, whether it is explaining a change being made, or whether it is a comment that was carried over from the *original file* but does *not* reference any code that was left out of the *proposed updates*.
-
-*To determine whether a comment is a removal comment*, focus on whether the comment is clearly indicating that a section of code should be removed from the *original file*.
-
-After this evaluation, state whether each comment is a *reference comment*, a *removal comment*, or neither. Only list valid *comments* for the given programming language in the comments section. Do not include non-comment lines of code in the comments section. The only exception to this rule is for file types that don't use comments like JSON or plain text—for these treat lines beginning with '//' as reference comments. A *removal comment* *MUST NOT* also be marked as a *reference comment* and a *reference comment* *MUST NOT* also be marked as a *removal comment*.
-
-Reference comments example:
-
----
-Comments:
-
-pdx-new-2: // ... existing code to start transaction ...
-Evaluation: refers the code at the beginning of the 'update' function that starts the database transaction.
-Reference: true
-Removal: false
-
-pdx-new-6: // ... existing update code ...
-Evaluation: refers the code inside the 'update' function that updates the user.
-Reference: true
-Removal: false
-
-pdx-new-9: // Removed 'checkMigration' method
-Evaluation: refers the 'checkMigration' method that is being removed.
-Reference: false
-Removal: true
-
-pdx-new-15: // verify user permission before performing update
-Evaluation: describes the change being made. Does not refer to any code in the *original file*.
-Reference: false
-Removal: false
-
-pdx-new-85: // Rest of the main function...
-Evaluation: refers to the rest of the main function that is left unchanged.
-Reference: true
-Removal: false
-
-pdx-new-25: # removed rest of init code
-Evaluation: indicates that the rest of the init code should be removed from the *original file*.
-Reference: false
-Removal: true
----
-
-**Next,** for each reference (if there are any), output valid xml with this structure:
-
-<PlandexReferences>
- <Reference
- comment="// ... rest of function ..."
- proposedLine="pdx-new-10"
- />
-</PlandexReferences>
-
-If there are no reference comments, output an empty <PlandexReferences> element.
-
-**Next,** for each removal (if there are any), output valid xml with this structure:
-
-<PlandexRemovals>
- <Removal
- comment="# removed rest of init code"
- proposedLine="pdx-new-25"
- />
-</PlandexRemovals>
-
-If there are no removal comments, output an empty <PlandexRemovals> element.
-
-**Last,** output xml with this structure:
-
-<PlandexSemanticAnchors>
- <Anchor
- reasoning="'update function' signature with 'log' parameter added"
- proposedLine="pdx-new-1"
- originalLine="pdx-1"
- />
-</PlandexSemanticAnchors>
-
-Explanation of 'Anchor' tag attributes:
-
- **reasoning**: A brief explanation of why this line in the *proposed updates* is a *semantic anchor*—why it's intended to match a line in the *original file* (even though it's *not* exactly equal to that line).
-
- **proposedLine**: The line number, prefixed by 'pdx-new-', in the *proposed updates* that is intended to match a line in the *original file*. MUST be a line that exists in the *proposed updates*.
-
- **originalLine**: The line number, prefixed by 'pdx-', in the *original file* that the anchor is referring to. MUST be a line that exists in the *original file* and MUST ALWAYS be prefixed by 'pdx-' (never pdx-new-).
-
-If there are no semantic anchors, output an empty <PlandexSemanticAnchors> element. Do NOT invent semantic anchors if there are none. It's common for there to be no semantic anchors in the *proposed updates*. In that case, output an empty <PlandexSemanticAnchors> element.
-
-A *reference comment* or *removal comment* *MUST NOT* also be marked a semantic anchor. You MUST NEVER WITHOUT EXCEPTION mark *reference comments* or *removal comments* as semantic anchors.
-
-Every response must include a single <PlandexSummary> element and a single <PlandexSemanticAnchors> element.
-
-Do NOT include any other text or comments in your output.
-`
-
-var ExampleReferences = `
-A reference comment is a comment that references code in the *original file* for the purpose of making it clear where a change should be applied. Examples of reference comments include:
-
- - // ... existing code...
- - # Existing code...
- - /* ... */
- - // Rest of the function...
- - <!-- rest of div tag -->
- - // ... rest of function ...
- - // rest of component...
- - # other methods...
- - // ... rest of init code...
- - // rest of the class...
- - // other properties
- - // other methods
- // ... existing properties ...
- // ... existing values ...
- // ... existing text ...
-
-Reference comments often won't exactly match one of the above examples, but they will always be referencing a block of code from the *original file* that is left out of the *proposed updates* for the sake of focusing on the specific change that is being made.
-
-Reference comments do NOT need to be valid comments for the given file type. For file types like JSON or plain text that do not use comments, reference comments in the form of '// ... existing properties ...' or '// ... existing values ...' or '// ... existing text ...' can still be present. These MUST be treated as valid reference comments regardless of the file type or the validity of the syntax.
-`
-
-const RefsBeginning = `
-You are an AI that analyzes an *original file* and *proposed updates* to that file and then identifies *all* *reference comments* present in the *proposed updates*.
-
-`
-
-const WholeFileBeginning = `
-After identifying all references, you will output the *entire file* with the *proposed updates* correctly applied. ALL references will be replaced by the appropriate code from the *original file*. You will correctly merge the code from the *original file* with the *proposed updates* and output the entire file.
-
-`
-
-var ReferencesPrompt = ExampleReferences + `
-
- *NOT EVERY COMMENT IS A REFERENCE.* If a comment refers to code that is present in the *proposed updates* then it is *not* a reference. Similarly, if a comment explains something about the change being made in the *proposed updates*, it is also *not* a reference.
-
- A reference comment MUST EXIST in the *proposed updates*. Do not include a reference comment unless it exists VERBATIM in the *proposed updates*.
-
- Before outputting the references, first output a section that lists *EVERY* comment in the *proposed updates*, including the line number of each comment prefixed by 'pdx-new-'. Below each comment, evaluate whether it is a reference comment. Focus on whether the comment is clearly referencing a block of code in the *original file*, whether it is explaining a change being made, or whether it is a comment that was carried over from the *original file* but does *not* reference any code that was left out of the *proposed updates*. After this evaluation, state whether each comment is a reference comment or not. Only list valid *comments* for the given programming language in the comments section. Do not include non-comment lines of code in the comments section.
-
- Example:
-
- ---
- Comments:
-
- pdx-new-2: // ... existing code to start transaction ...
- Evaluation: refers the code at the beginning of the 'update' function that starts the database transaction.
- Reference: true
-
- pdx-new-6: // ... existing update code ...
- Evaluation: refers the code inside the 'update' function that updates the user.
- Reference: true
-
- pdx-new-9: // ... existing code to commit db transaction...
- Evaluation: refers the code inside the 'update' function that commits the database transaction.
- Reference: true
-
- pdx-new-4: // verify user permission before performing update
- Evaluation: describes the change being made. Does not refer to any code in the *original file*.
- Reference: false
-
- pdx-new-85: // Rest of the main function...
- Evaluation: refers to the rest of the main function that is left unchanged.
- Reference: true
-
- pdx-new-25: # Delete the object
- Evaluation: describes the change being made. Does not refer to any code in the *original file*.
- Reference: false
-
- ---
-
- Next, for each reference (if there are any), output valid xml with this structure:
-
- <references>
- <reference
- comment="// ... existing code..."
- description="Code after the addition of the conditional statement in the 'update' function"
- proposedLine="pdx-new-10"
- structure="'update' function"
- structureOpens="opening '{' on pdx-455"
- structureCloses="closing '}' on pdx-461"
- originalStart="pdx-456"
- originalEnd="pdx-460"
- />
- </references>
-
- Explanation of 'reference' tag attributes:
-
- **comment**: The comment that includes the reference.
-
- **description**: A brief description of the reference. Make a special note of where the reference *begins* and *ends in the *original file* so that it does *not* include any lines that are already present in the *proposed updates*.
-
- **proposedLine**: The line number, prefixed by 'pdx-new-', in the *proposed updates* that the reference is referring to. MUST be a line that exists in the *proposed updates* and contains the reference comment in 'comment' attribute.
-
- **structure**: The *code structure* (e.g. 'function', 'class', 'loop', 'conditional', etc.) that this reference is contained within. If it's not contained within a code structure and is instead at the top level of the file, output 'top level'. This must be the MOST specific, deeply nested code structure that contains the reference. You must output only a single structure or 'top level'. Identify the structure unambiguously.
-
- **structureOpens**: The entire line from the *original file*, prefixed by 'pdx-', that contains the opening symbol of the code structure identified in the 'structure' property. If the structure is 'top level', this MUST be an empty string. Otherwise, it MUST be a line that exists in the *original file* and MUST ALWAYS be prefixed by 'pdx-' (never pdx-new-).
-
- **structureCloses**: The entire line from the *original file*, prefixed by 'pdx-', that contains the closing symbol of the code structure identified in the 'structure' property. If the structure is 'top level', this MUST be an empty string. Otherwise, it MUST be a line that exists in the *original file* and MUST ALWAYS be prefixed by 'pdx-' (never pdx-new-).
-
- **originalStart**: The starting line number, prefixed by 'pdx-', in the *original file* that the reference is referring to. MUST be less than or equal to the 'originalEnd' line number and MUST be greater than or equal to 1. MUST be a line that exists in the *original file* and MUST ALWAYS be prefixed by 'pdx-' (never pdx-new-).
-
- **originalEnd**: The ending line number, prefixed by 'pdx-', in the *original file* that the reference is referring to. If the referenced code in the *original file* is a single line, the originalStart and originalEnd must be the same. 'originalEnd' MUST be greater than or equal to 'originalStart' and MUST be less than or equal to the last line number in the *original file*. MUST be a line that exists in the *original file* and MUST ALWAYS be prefixed by 'pdx-' (never pdx-new-).
-
- **Example:**
-
- ---
-
- **Original file:**
-
- ` + "```" + `
- pdx-1: function update(name string, id string) {
- pdx-2: const tx = await client.startTransaction();
- pdx-3: tx.setMode(TransactionMode.Serializable);
- pdx-4:
- pdx-5: const updateQuery = 'UPDATE users SET name = $1 WHERE id = $2';
- pdx-6: await tx.execute(updateQuery, name, id);
- pdx-7:
- pdx-8: try {
- pdx-9: await client.commit();
- pdx-10: } catch (error) {
- pdx-11: if (isRetryableError(error)) {
- pdx-12: await client.rollback();
- pdx-13: update();
- pdx-14: } else {
- pdx-15: throw error;
- pdx-16: }
- pdx-17: }
- pdx-18: }
- ` + "```" + `
-
- **Proposed changes:**
-
- Now we'll add a permission check so that the update only runs if the user has the necessary permissions.
-
- ` + "```" + `
- pdx-new-1: function update(name string, id string) {
- pdx-new-2: // ... existing code to start transaction ...
- pdx-new-3:
- pdx-new-4: // verify user permission before performing update
- pdx-new-5: if (canUpdate()) {
- pdx-new-6: // ... existing update code ...
- pdx-new-7: }
- pdx-new-8:
- pdx-new-9: // ... existing code to commit db transaction...
- pdx-new-10: }
- ` + "```" + `
-
- References:
-
- <references>
- <reference
- comment="// ... existing code to start transaction ..."
- description="Code for starting database transaction"
- proposedLine="pdx-new-2"
- structure="'update' function"
- structureOpens="opening '{' on pdx-1"
- structureCloses="closing '}' on pdx-18"
- originalStart="pdx-2"
- originalEnd="pdx-3"
- />
- <reference
- comment="// ... existing update code ..."
- description="Code inside the canUpdate() conditional for updating the user"
- proposedLine="pdx-new-6"
- structure="'update' function"
- structureOpens="opening '{' on pdx-1"
- structureCloses="closing '}' on pdx-18"
- originalStart="pdx-5"
- originalEnd="pdx-6"
- />
- <reference
- comment="// ... existing code to commit db transaction..."
- description="Code for committing the database transaction and handling errors"
- proposedLine="pdx-new-9"
- structure="'update' function"
- structureOpens="opening '{' on pdx-1"
- structureCloses="closing '}' on pdx-18"
- originalStart="pdx-8"
- originalEnd="pdx-17"
- />
- </references>
-
- ---
-
- Note that in the example, the "// verify user permission before performing update" comment is *not* a reference since it refers to code that is included in the *proposed updates* and does *not* refer to code in the *original file* that was left out of the *proposed updates*.
-
- In description attributes, make a special note of where the reference *begins* and *ends in the *original file* so that it does *not* include any lines that are already present in the *proposed updates*. Note that in the above example, the function signature and opening brace of the 'update' function is *not included* in the reference since it's already present in the *proposed updates*. And node in the last reference, the closing brace of the 'update' function is *not included* since it's already present in the *proposed updates*.
-
- If there are no clear references in the *proposed updates*, output an empty <references> element. The *proposed updates* often will not inlcude any reference comments. In that case, output an empty <references> element. Do NOT include reference comments that are not present in the *proposed updates* or comments that are not clearly references to a block of code in the *original file* that is left out of the *proposed updates* for the sake of focusing on the specific change that is being made.
-
- *
-
- You MUST carefully consider code structures when determining the 'originalStart' and 'originalEnd' lines for a reference. If a reference looks like this:
-
- pdx-new-1: class MyClass {
- pdx-new-2: constructor() {
- pdx-new-3: this.initialize();
- pdx-new-4: }
- pdx-new-5:
- pdx-new-6: // ... existing code ...
- pdx-new-7: }
-
- The the reference ONLY refers to the code within the 'MyClass' class. If there is additional code before or after the 'MyClass' class, it must not be included. The same applies to other code structures, like functions, loops, conditionals, etc.
-
- *
-
- When setting the 'originalStart' and 'originalEnd' lines for a reference, it is critically important that the code referenced in the *original file* falls COMPLETELY *within* the code structure specified in the 'structure' attribute. Do NOT include the lines that open or close the code structure in the 'originalStart' and 'originalEnd' lines, since these already exist in the *proposed updates*. Only the lines that *do not already exist* in the *proposed updates* can be included in the reference.
-
- If a reference comes at the beginning of a structure, followed by new or changed code, like this:
-
- pdx-new-1: class MyClass {
- pdx-new-2: // ... existing code ...
- pdx-new-3:
- pdx-new-4: function update() {
- pdx-new-5: const conn = await getConnection();
- pdx-new-6: const res = await execUpdate(conn);
- pdx-new-7: }
- pdx-new-8: }
-
- Then the '// ... existing code ...' reference must include ALL code from the *original file* inside the 'MyClass' structure. The 'originalStart' must be one line *after* the 'structureOpens' line and the 'originalEnd' must be one line *before* the 'structureCloses' line.
-
- *
-
- Similarly, if a reference comes at the end of a structure, preceded by new or changed code, like this:
-
- pdx-new-1: class MyClass {
- pdx-new-2: function update() {
- pdx-new-3: const conn = await getConnection();
- pdx-new-4: const res = await execUpdate(conn);
- pdx-new-5: }
- pdx-new-6: // ... existing code ...
- pdx-new-7: }
-
- Then the '// ... existing code ...' reference must include ALL code from the *original file* inside the 'MyClass' structure. The 'originalStart' must be one line *after* the 'structureOpens' line and the 'originalEnd' must be one line *before* the 'structureCloses' line.
-
- *
-
- If a structure has references at both the beginning and the end, with new or changed code in between, like this:
-
- pdx-new-1: class MyClass {
- pdx-new-2: // ... existing code ...
- pdx-new-3:
- pdx-new-4: function update() {
- pdx-new-5: const conn = await getConnection();
- pdx-new-6: const res = await execUpdate(conn);
- pdx-new-7: }
- pdx-new-8:
- pdx-new-9: // ... existing code ...
- pdx-new-10: }
-
- Then you must use your judgement to determine the location that the new code should be inserted in the final results. Based on where the new code is inserted, the first "pdx-new-2: // ... existing code ..." reference must include ALL code from the *original file* inside the 'MyClass' structure that should come *before* the new code. The 'originalStart' of the first reference must be one line *after* the 'structureOpens' line.
-
- The last "pdx-new-9: // ... existing code ..." reference must include ALL code from the *original file* inside the 'MyClass' structure that should come *after* the new code. The 'originalEnd' of the last reference must be one line *before* the 'structureCloses' line.
-
- In cases like the above example with multiple references within the same structure, you MUST NOT duplicate code in any of the references. Taken together, the references must cover the entire 'MyClass' structure with no code from the *original file* repeated or left out.
-
- *
-
- If there are commented out lines that still logically belong to a section that is referenced, you MUST include those lines in the reference.
-
- You MUST ensure that each reference includes the full logical section that it describes, including any comments that are part of that section. For example, if the description of a reference is "Imports", the reference must include *all* import statements in the section up to the next line that is included in the *proposed updates*, regardless of line breaks, comments, commented out imports, etc.
-
- For example, if the original file has:
-
- pdx-1: import { something } from "some-package";
- pdx-2: import { anotherThing } from "another-package";
- pdx-3: // import "another";
- pdx-4:
- pdx-5:
- pdx-6: import "yet-another-package";
- pdx-7: import { exec } from "exec-package";
- pdx-8:
- pdx-9: function main() {
- pdx-10: exec();
- pdx-11: }
-
- And the *proposed updates* have:
-
- pdx-new-1: // ... existing code ...
- pdx-new-2: import { logger } from "logger-package";
- pdx-new-3:
- pdx-new-4: function main() {
- pdx-new-5: exec();
- pdx-new-6: logger.info("Hello, world!");
- pdx-new-7: }
-
- Then the reference should look like this:
-
- <references>
- <reference
- comment="// ... existing code ..."
- description="Imports"
- proposedLine="pdx-new-1"
- structure="top level"
- structureOpens=""
- structureCloses=""
- originalStart="pdx-1"
- originalEnd="pdx-7"
- />
- </references>
-
- Note that ALL the import statements are included in the reference.
-
- *
-
- If a reference *includes* a code structure, DO NOT treat the reference as if it were *inside* the code structure. For example, if the *original file* has:
-
- pdx-1: class MyClass {
- pdx-2: function update() {
- pdx-3: const conn = await getConnection();
- pdx-4: const res = await execUpdate(conn);
- pdx-5: }
- pdx-6: }
- pdx-7:
- pdx-8: class AnotherClass {
- pdx-9: function doSomething() {
- pdx-10: const conn = getConnection();
- pdx-11: const res = execUpdate(conn);
- pdx-12: }
- pdx-13: }
-
- And the *proposed updates* have:
-
- pdx-new-1: class MyClass {
- pdx-new-2: function update() {
- pdx-new-3: const conn = getConnection();
- pdx-new-4: const res = execUpdate(conn);
- pdx-new-5: }
- pdx-new-6: }
- pdx-new-7:
- pdx-new-8: // ... existing code ...
-
- Then the "// ... existing code ..." reference must include the *entire* 'AnotherClass' structure, including the class definition and closing brace. Do NOT treat the reference as if it were *inside* the 'AnotherClass' structure.
-
- The reference for the above example would look like this:
-
- <references>
- <reference
- comment="// ... existing code ..."
- description="AnotherClass"
- proposedLine="pdx-new-8"
- structure="top level"
- structureOpens=""
- structureCloses=""
- originalStart="pdx-8"
- originalEnd="pdx-13"
- />
- </references>
-`
-
-const RefsOnlyEnding = `
- *
-
- Do NOT include any additional text after the <references> element. The output must end after </references>. DO NOT use the string <references> anywhere else in the output. ONLY use it to start the <references> element.
-`
-
-const WholeFileEnding = `
- *
-
- Now output the entire file with the *proposed updates* correctly applied. ALL identified references MUST be replaced by the appropriate code from the *original file*. You MUST correctly merge the code from the *original file* with the *proposed updates* and output the entire file. The resulting file MUST NOT include any reference comments.
-
- The resulting file MUST be syntactically and semantically correct. All code structures must be properly balanced.
-
- The full resulting file should be output within a <file> element, like this:
-
- <file>
- package main
-
- import "logger"
-
- function main() {
- logger.info("Hello, world!");
- exec()
- }
- </file>
-
- Do NOT include line numbers in the <file> element. Do NOT include reference comments in the <file> element. Output the ENTIRE file, no matter how long it is, with NO EXCEPTIONS. Include the resulting file *only* with no other text. Do NOT wrap the file output in triple backticks or any other formatting, except for the <file> element tags.
-
- Do NOT include any additional text after the <file> element. The output must end after </file>. DO NOT use the string <file> anywhere else in the output. ONLY use it to start the <file> element.
-`
-
-func GetValidateEditsPrompt(
- path,
- original,
- desc,
- proposed,
- diff string,
- reasons []syntax.NeedsVerifyReason,
-) string {
- var s string
-
- s += fmt.Sprintf(`
-[Explanation Rules]
-
-%s
-
-[End Explanation Rules]
-
-[Proposed Updates Rules]
-
-%s
-
-[End Proposed Updates Rules]
-`, ChangeExplanationPrompt, UpdateFormatPrompt)
-
- s += fmt.Sprintf("Path: %s\n\nOriginal file:\n%s\n\nProposed changes explanation:\n%s\n\nProposed changes:\n%s", path, original, desc, proposed)
- s += fmt.Sprintf("\n\nApplied changes:\n%s", diff)
- s += `You will examine the original file, proposed changes explanation, proposed changes, and applied changes diff.`
-
- var editsIncorrect bool
-
- for _, reason := range reasons {
- if reason == syntax.NeedsVerifyReasonAmbiguousLocation {
- editsIncorrect = true
- s += `The proposed changes were applied to an ambiguous location. This may mean that anchors were written incorrectly (with incorrect spacing or indentation, for example), or else that the ordering of anchors was incorrect. It may also mean that necessary surrounding context and anchors were not included.`
- } else if reason == syntax.NeedsVerifyReasonNoChanges {
- s += `The proposed changes did not cause any change to the resulting file when applied. Was this intentional?`
- } else if reason == syntax.NeedsVerifyReasonCodeRemoved {
- s += `The proposed changes removed or replaced code. Was this intentional?`
- } else if reason == syntax.NeedsVerifyReasonCodeDuplicated {
- s += `The proposed may have duplicated code. Was this intentional?`
- }
- }
-
- if editsIncorrect {
- s += EditsIncorrectPrompt
- } else {
- s += EditsValidatePrompt
- }
-
- s += getEditsExamples(!editsIncorrect)
-
- s += `
-
-- You MUST NOT make *functional* changes when rewriting the explanation or proposed updates. Your job is not to change functionality or write additional code, but to ensure that the explanation and proposed updates follow all the rules correctly. Stick as close to the original proposed updates as possible when rewriting. Fix the problems, but keep everything else the same as much as possible, including comments, line breaks, spacing, etc.
-
-- You MUST NOT add 'Plandex: removed' comments unless the intention of the plan and the explanation is to remove code. NEVER add 'Plandex: removed' comments to the *proposed updates* unless the *explanation* includes the word 'remove'. The *only* time you can add a 'Plandex: removed' comment is if 1 - you are correcting a mistaken comment that was intended as a removal comment, but used the wrong format—for example, if the 'Plandex: ' prefix was incorrectly omitted. In that case you must fix the comment in the fixed proposed updates. 2 - the explanation explicitly stats that code should be removed, but a necessary 'Plandex: removed' comment is missing from the proposed updates, causing the code that should have been removed to incorrectly remain in the file. In that case you must add the missing 'Plandex: removed' comment to the proposed updates in the correct location, with correct surrounding context and anchors.
-`
-
- return s
-}
-
-const EditsValidatePrompt = `
-- In a '## Evaluate Diff' section, examine the applied changes diff and determine whether the changes were applied correctly. Carefully asses whether:
- a. Any code was removed that should have been kept.
- b. Any code was duplicated that should not have been.
- c. Any code was incorrectly inserted or replaced.
- d. Any code was inserted at the wrong location.
-
-- If the changes were applied correctly, output "**Changes Applied Correctly**" after the evaluation and stop your response here. You MUST NOT output any further explanation or *any other text* after the "**Changes Applied Correctly**" string. End your response *immediately* after the "**Changes Applied Correctly**" string.
-
-- If the changes were *not* applied correctly, continue with the following steps:
-` + EditsIncorrectPrompt
-
-const EditsIncorrectPrompt = `
-- In a '## Evaluate Explanation' section, examine the proposed changes explanation and determine whether it is correct. Did it follow all the rules in the [Proposed Updates Rules] section?
- a. If the changes are inserting, removing, or replacing code between two specific code structures, are these the correct code structures to use for the update? Are these structures *immediately* adjacent to each other or is there other code between them?
- b. If the changes are inserting, removing, or replacing code between a specific code structure and the start or end of the file, are these the correct code structures or locations to use for the update? If the change is between the start of the file and a specific code structure, is there any other code between the start of the file and that code structure? (There must not be). If the change is between a specific code structure and the end of the file, is there any other code between that code structure and the end of the file? (There must not be).
-
-- If the proposed changes explanation is *not* correct, you must rewrite the proposed changes explanation to correctly follow *all* the rules in the [Proposed Updates Rules] section in a <PlandexProposedUpdatesExplanation> element. Include *only* the rewritten proposed changes explanation inside the <PlandexProposedUpdatesExplanation> element, and no other text. If the proposed changes explanation is already correct, skip this step.
- - When rewriting the proposed changes explanation, DO NOT change the alter the *type* of the change. You must ONLY update the portion of the explanation that explains the *location* of the change, not the *type* of the change. For example, if the proposed changes explanation is "I'll add 'someFunction' at the end of the file, immediately after 'existingFunction1'", you must rewrite it to correctly explain the *location* of the change, like "I'll add 'someFunction' at the end of the file, immediately after 'existingFunction2'". You MUST NOT change the type of the change, such as from 'add' to 'remove'.
- - If the explanation does not match the changes that were made in the proposed updates (for example, the explanation says to add code, but the proposed updates removed code), this means that the proposed updates are *incorrect*—you MUST NOT alter the explanation to match the incorrect proposed updates (for example, you MUST NOT change the explanation to remove code instead of adding it just because the proposed updates incorrectly removed code). Instead, focus on ensuring that the explanation correctly shows the *location* of the change so that the proposed updates can be corrected.
- - If you are outputting a rewritten proposed changes explanation, YOU ABSOLUTELY MUST DO SO within the <PlandexProposedUpdatesExplanation> element. DO NOT output it outside of the <PlandexProposedUpdatesExplanation> element or anywhere else in your response—ONLY output the rewritten proposed changes explanation inside the <PlandexProposedUpdatesExplanation> element.
-
-- In a '## Evaluate Proposed Changes' section, examine the proposed changes and determine whether they are correct.
- a. Did they follow all the rules in the [Proposed Updates Rules] section?
- b. Are they consistent with the proposed changes explanation (or the rewritten proposed changes explanation, if you had to rewrite it)?
- c. Is more surrounding context needed or are more *anchors* needed to resolve ambiguity in the proposed changes and *precisely* locate the change *unambiguously* in the original file?
- d. Are any *reference comments* or *removal comments* written incorrectly? All reference comments must be *exactly* '... existing code ...' and all removal comments must be *exactly* 'plandex: removed code'. Each must use the correct comment syntax for the language. If any comments are variations of those rather than the exact strings, they are incorrect.
- e. Are any *reference comments* or *removal comments* missing?
- - If the proposed changes incorrectly removed code, this does *NOT MEAN* that a removal comment is missing; you MUST NOT say that a removal comment is missing in this case. *ONLY* state that a removal comment is missing if the explanation *explicitly* states that code should be removed and it was not correctly removed due to a missing removal comment.
-
-- In a <PlandexProposedUpdates> element, output the corrected proposed changes. Include *only* the corrected proposed changes inside the <PlandexProposedUpdates> element, and no other text. The corrected proposed changes MUST follow *all* the rules in the [Proposed Updates Rules] section.
- - If you are outputting a corrected proposed changes, YOU ABSOLUTELY MUST DO SO within the <PlandexProposedUpdates> element. DO NOT output it outside of the <PlandexProposedUpdates> element or anywhere else in your response—ONLY output the corrected proposed changes inside the <PlandexProposedUpdates> element. You ABSOLUTELY MUST NOT use triple backticks or any other formatting around the rewritten proposed changes. Output ONLY the corrected proposed changes inside the <PlandexProposedUpdates> element with no other text or formatting.
- - DO NOT include the proposed changes within a formatted code block. Include *ONLY* the code directly inside the <PlandexProposedUpdates> element.
- - If more surrounding context or *anchors* are needed to resolve ambiguity in the proposed changes and *precisely* locate the change *unambiguously* in the original file, you MUST output the corrected proposed changes with the additional context or *anchors* included correctly.
- - If any *reference comments* or *removal comments* are written incorrectly, you MUST output the corrected proposed changes with the *reference comments* or *removal comments* corrected. A reference comment must be *exactly* '... existing code ...' and a removal comment must be *exactly* 'plandex: removed code'. Use the correct comment syntax for the language.
- - If any *reference comments* or *removal comments* are missing, you MUST output the corrected proposed changes with the *reference comments* or *removal comments* added.
- - If the proposed changes incorrectly removed code, this does *NOT MEAN* that a removal comment is missing; you MUST NOT output a removal comment in this case. Instead, fix the proposed changes to prevent the removal of code that should have been kept.
- - When outputting *anchors* in the proposed changes, lines from the proposed changes that match lines in the original file, spacing and indentation must be preserved *exactly* as they are in the original file—the two lines must be *exactly identical*.
-`
-
-func getEditsExamples(evaluateDiff bool) string {
- s := ""
-
- if evaluateDiff {
- s += `
-- Example Response if changes were applied correctly ('## Evaluate Diff' section included):
-
---
-
-## Evaluate Diff
-
-The new function 'someFunction' was correctly added to the end of the file.
-
-**Changes Applied Correctly**
---
-
-- Example Response if changes were *not* applied correctly, but explanation and proposed changes were correct:
-
---
-
-## Evaluate Diff
-
-The new function 'someFunction' was incorrectly added to the end of the file.
-
-## Evaluate Explanation
-
-The explanation correctly describes how the new function should be added to the file.
-
-## Evaluate Proposed Changes
-
-The proposed changes correctly use a reference comment to indicate that the new function should be added after 'existingFunction' at the end of the file.
-
---
-
-Note that if the changes were applied correctly, YOU ABSOLUTLY MUST NEVER output a <PlandexProposedUpdates> element. Just stop the response after the ## Evaluate Proposed Changes section.
-`
- }
-
- s += `
-- Example Response if explanation and proposed changes were *not* correct:
-
---
-`
-
- if evaluateDiff {
- s += `
-## Evaluate Diff
-
-The proposed changes incorrectly removed the 'existingFunction2' function.
-`
- }
-
- s += `
-## Evaluate Explanation
-
-The explanation incorrectly used 'existingFunction1' as an anchor when there is code between 'existingFunction1' and the end of the file. It should have used 'existingFunction2' instead.
-`
-
- s += `
-<PlandexProposedUpdatesExplanation>
- **Updating some/path/to/file.js:** I'll add 'someFunction' at the end of the file, immediately after 'existingFunction2'.
-</PlandexProposedUpdatesExplanation>
-
-## Evaluate Proposed Changes
-
-The proposed changes incorrectly used 'existingFunction1' as an anchor when there is code between 'existingFunction1' and the end of the file. It should have used 'existingFunction2' instead.
-
-<PlandexProposedUpdates>
-// ... existing code ...
-
-function existingFunction2() {
- // ... existing code ...
-}
-
-function someFunction() {
- console.log("New behavior");
- const res = await execUpdate();
-}
-</PlandexProposedUpdates>
-
---
-`
-
- return s
-}
diff --git a/app/server/types/active_plan.go b/app/server/types/active_plan.go
index 9ac22ff2..d445a642 100644
--- a/app/server/types/active_plan.go
+++ b/app/server/types/active_plan.go
@@ -16,27 +16,19 @@ import (
const MaxStreamRate = 70 * time.Millisecond
type ActiveBuild struct {
- ReplyId string
- FileDescription string
- FileContent string
- FileContentTokens int
- CurrentFileTokens int
- Path string
- Idx int
- WithLineNumsBuffer string
- WithLineNumsBufferTokens int
- VerifyBuffer string
- VerifyBufferTokens int
- FixBuffer string
- FixBufferTokens int
- Success bool
- Error error
- IsVerification bool
- ToVerifyUpdatedState string
- IsMoveOp bool
- MoveDestination string
- IsRemoveOp bool
- IsResetOp bool
+ ReplyId string
+ FileDescription string
+ FileContent string
+ FileContentTokens int
+ CurrentFileTokens int
+ Path string
+ Idx int
+ Success bool
+ Error error
+ IsMoveOp bool
+ MoveDestination string
+ IsRemoveOp bool
+ IsResetOp bool
}
type subscription struct {
diff --git a/app/shared/ai_models.go b/app/shared/ai_models.go
index 95e2a8fa..3c3f07e5 100644
--- a/app/shared/ai_models.go
+++ b/app/shared/ai_models.go
@@ -190,6 +190,10 @@ var DefaultConfigByRole = map[ModelRole]ModelRoleConfig{
Temperature: 0.1,
TopP: 0.1,
},
+ ModelRoleWholeFileBuilder: {
+ Temperature: 0.1,
+ TopP: 0.1,
+ },
ModelRoleName: {
Temperature: 0.8,
TopP: 0.5,
@@ -202,14 +206,6 @@ var DefaultConfigByRole = map[ModelRole]ModelRoleConfig{
Temperature: 0.1,
TopP: 0.1,
},
- ModelRoleVerifier: {
- Temperature: 0.2,
- TopP: 0.2,
- },
- ModelRoleAutoFix: {
- Temperature: 0.1,
- TopP: 0.1,
- },
}
var RequiredCompatibilityByRole = map[ModelRole]ModelCompatibility{
@@ -235,16 +231,6 @@ var RequiredCompatibilityByRole = map[ModelRole]ModelCompatibility{
IsOpenAICompatible: true,
HasFunctionCalling: true,
},
- ModelRoleVerifier: {
- IsOpenAICompatible: true,
- HasStreaming: true,
- HasFunctionCalling: true,
- },
- ModelRoleAutoFix: {
- IsOpenAICompatible: true,
- HasStreaming: true,
- HasFunctionCalling: true,
- },
}
func init() {
@@ -294,23 +280,11 @@ func init() {
Temperature: DefaultConfigByRole[ModelRoleExecStatus].Temperature,
TopP: DefaultConfigByRole[ModelRoleExecStatus].TopP,
},
- Verifier: &ModelRoleConfig{
- Role: ModelRoleVerifier,
- BaseModelConfig: AvailableModelsByName[openai.GPT4o].BaseModelConfig,
- Temperature: DefaultConfigByRole[ModelRoleVerifier].Temperature,
- TopP: DefaultConfigByRole[ModelRoleVerifier].TopP,
- },
- AutoFix: &ModelRoleConfig{
- Role: ModelRoleAutoFix,
- BaseModelConfig: AvailableModelsByName[openai.GPT4o].BaseModelConfig,
- Temperature: DefaultConfigByRole[ModelRoleAutoFix].Temperature,
- TopP: DefaultConfigByRole[ModelRoleAutoFix].TopP,
- },
}
OpenRouterClaude3Dot5SonnetGPT4oModelPack = ModelPack{
- Name: "anthropic-claude-3.5-sonnet-gpt-4o",
- Description: "Uses Anthropic's Claude 3.5 Sonnet model (via OpenRouter) for planning, summarization, and auto-continue, OpenAI gpt-4o for builds, and gpt-4o-mini for lighter tasks.",
+ Name: "plandex-default-pack",
+ Description: "Uses Anthropic's Claude 3.5 Sonnet model (via OpenRouter) for planning, summarization, diff-based edits, and auto-continue, OpenAI gpt-4o for whole-file edits, and gpt-4o-mini for lighter tasks.",
Planner: PlannerRoleConfig{
ModelRoleConfig: ModelRoleConfig{
Role: ModelRolePlanner,
@@ -332,6 +306,12 @@ func init() {
Temperature: DefaultConfigByRole[ModelRoleBuilder].Temperature,
TopP: DefaultConfigByRole[ModelRoleBuilder].TopP,
},
+ WholeFileBuilder: &ModelRoleConfig{
+ Role: ModelRoleWholeFileBuilder,
+ BaseModelConfig: AvailableModelsByName[openai.GPT4o].BaseModelConfig,
+ Temperature: DefaultConfigByRole[ModelRoleWholeFileBuilder].Temperature,
+ TopP: DefaultConfigByRole[ModelRoleWholeFileBuilder].TopP,
+ },
Namer: ModelRoleConfig{
Role: ModelRoleName,
BaseModelConfig: AvailableModelsByName["gpt-4o-mini"].BaseModelConfig,
@@ -350,18 +330,6 @@ func init() {
Temperature: DefaultConfigByRole[ModelRoleExecStatus].Temperature,
TopP: DefaultConfigByRole[ModelRoleExecStatus].TopP,
},
- Verifier: &ModelRoleConfig{
- Role: ModelRoleVerifier,
- BaseModelConfig: AvailableModelsByName[openai.GPT4o].BaseModelConfig,
- Temperature: DefaultConfigByRole[ModelRoleVerifier].Temperature,
- TopP: DefaultConfigByRole[ModelRoleVerifier].TopP,
- },
- AutoFix: &ModelRoleConfig{
- Role: ModelRoleAutoFix,
- BaseModelConfig: AvailableModelsByName[openai.GPT4o].BaseModelConfig,
- Temperature: DefaultConfigByRole[ModelRoleAutoFix].Temperature,
- TopP: DefaultConfigByRole[ModelRoleAutoFix].TopP,
- },
}
OpenRouterClaude3Dot5SonnetModelPack = ModelPack{
@@ -450,18 +418,6 @@ func init() {
Temperature: DefaultConfigByRole[ModelRoleExecStatus].Temperature,
TopP: DefaultConfigByRole[ModelRoleExecStatus].TopP,
},
- Verifier: &ModelRoleConfig{
- Role: ModelRoleVerifier,
- BaseModelConfig: AvailableModelsByName["google/gemini-pro-1.5"].BaseModelConfig,
- Temperature: DefaultConfigByRole[ModelRoleVerifier].Temperature,
- TopP: DefaultConfigByRole[ModelRoleVerifier].TopP,
- },
- AutoFix: &ModelRoleConfig{
- Role: ModelRoleAutoFix,
- BaseModelConfig: AvailableModelsByName["google/gemini-pro-1.5"].BaseModelConfig,
- Temperature: DefaultConfigByRole[ModelRoleAutoFix].Temperature,
- TopP: DefaultConfigByRole[ModelRoleAutoFix].TopP,
- },
}
}
diff --git a/app/shared/data_models.go b/app/shared/data_models.go
index b8884241..ff0e06ea 100644
--- a/app/shared/data_models.go
+++ b/app/shared/data_models.go
@@ -199,14 +199,6 @@ type PlanFileResult struct {
RemovedFile bool `json:"removedFile"`
- CanVerify bool `json:"canVerify"`
- RanVerifyAt *time.Time `json:"ranVerifyAt,omitempty"`
- VerifyPassed bool `json:"verifyPassed"`
-
- IsFix bool `json:"isFix"`
- IsSyntaxFix bool `json:"isSyntaxFix"`
- IsOtherFix bool `json:"isOtherFix"`
-
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
@@ -327,31 +319,20 @@ type ModelPack struct {
Name string `json:"name"`
Description string `json:"description"`
- Planner PlannerRoleConfig `json:"planner"`
- PlanSummary ModelRoleConfig `json:"planSummary"`
- Builder ModelRoleConfig `json:"builder"`
- Namer ModelRoleConfig `json:"namer"`
- CommitMsg ModelRoleConfig `json:"commitMsg"`
- ExecStatus ModelRoleConfig `json:"execStatus"`
-
- // optional for backwards compatibility
- Verifier *ModelRoleConfig `json:"verifier"`
- AutoFix *ModelRoleConfig `json:"autoFix"`
- Search *ModelRoleConfig `json:"search"`
-}
-
-func (m *ModelPack) GetVerifier() ModelRoleConfig {
- if m.Verifier == nil {
- return m.Builder
- }
- return *m.Verifier
+ Planner PlannerRoleConfig `json:"planner"`
+ PlanSummary ModelRoleConfig `json:"planSummary"`
+ Builder ModelRoleConfig `json:"builder"`
+ WholeFileBuilder *ModelRoleConfig `json:"wholeFileBuilder"` // optional, defaults to builder model — access via GetWholeFileBuilder()
+ Namer ModelRoleConfig `json:"namer"`
+ CommitMsg ModelRoleConfig `json:"commitMsg"`
+ ExecStatus ModelRoleConfig `json:"execStatus"`
}
-func (m *ModelPack) GetAutoFix() ModelRoleConfig {
- if m.AutoFix == nil {
+func (m *ModelPack) GetWholeFileBuilder() ModelRoleConfig {
+ if m.WholeFileBuilder == nil {
return m.Builder
}
- return *m.AutoFix
+ return *m.WholeFileBuilder
}
type ModelOverrides struct {
diff --git a/app/shared/plan_model_settings.go b/app/shared/plan_model_settings.go
index 0850d69d..182b410f 100644
--- a/app/shared/plan_model_settings.go
+++ b/app/shared/plan_model_settings.go
@@ -31,28 +31,25 @@ var ApiKeyByProvider = map[ModelProvider]string{
type ModelRole string
const (
- ModelRolePlanner ModelRole = "planner"
- ModelRolePlanSummary ModelRole = "summarizer"
- ModelRoleBuilder ModelRole = "builder"
- ModelRoleName ModelRole = "names"
- ModelRoleCommitMsg ModelRole = "commit-messages"
- ModelRoleExecStatus ModelRole = "auto-continue"
- ModelRoleSearch ModelRole = "search"
-
- ModelRoleVerifier ModelRole = "verifier"
- ModelRoleAutoFix ModelRole = "auto-fix"
+ ModelRolePlanner ModelRole = "planner"
+ ModelRolePlanSummary ModelRole = "summarizer"
+ ModelRoleBuilder ModelRole = "builder"
+ ModelRoleWholeFileBuilder ModelRole = "whole-file-builder"
+ ModelRoleName ModelRole = "names"
+ ModelRoleCommitMsg ModelRole = "commit-messages"
+ ModelRoleExecStatus ModelRole = "auto-continue"
+ ModelRoleSearch ModelRole = "search"
)
-var AllModelRoles = []ModelRole{ModelRolePlanner, ModelRolePlanSummary, ModelRoleBuilder, ModelRoleName, ModelRoleCommitMsg, ModelRoleExecStatus, ModelRoleVerifier, ModelRoleAutoFix}
+var AllModelRoles = []ModelRole{ModelRolePlanner, ModelRolePlanSummary, ModelRoleBuilder, ModelRoleWholeFileBuilder, ModelRoleName, ModelRoleCommitMsg, ModelRoleExecStatus}
var ModelRoleDescriptions = map[ModelRole]string{
- ModelRolePlanner: "replies to prompts and makes plans",
- ModelRolePlanSummary: "summarizes conversations exceeding max-convo-tokens",
- ModelRoleBuilder: "builds a plan into file diffs",
- ModelRoleName: "names plans",
- ModelRoleCommitMsg: "writes commit messages",
- ModelRoleExecStatus: "determines whether to auto-continue",
- ModelRoleVerifier: "verifies file correctness",
- ModelRoleAutoFix: "automatically fixes syntax errors",
+ ModelRolePlanner: "replies to prompts and makes plans",
+ ModelRolePlanSummary: "summarizes conversations exceeding max-convo-tokens",
+ ModelRoleBuilder: "builds a plan into file diffs",
+ ModelRoleWholeFileBuilder: "builds a plan into file diffs by writing the entire file",
+ ModelRoleName: "names plans",
+ ModelRoleCommitMsg: "writes commit messages",
+ ModelRoleExecStatus: "determines whether to auto-continue",
}
var SettingDescriptions = map[string]string{
"max-convo-tokens": "max conversation 🪙 before summarization",
@@ -112,12 +109,11 @@ func (ps PlanSettings) GetRequiredEnvVars() map[string]bool {
envVars[ms.Planner.BaseModelConfig.ApiKeyEnvVar] = true
envVars[ms.Builder.BaseModelConfig.ApiKeyEnvVar] = true
+ envVars[ms.WholeFileBuilder.BaseModelConfig.ApiKeyEnvVar] = true
envVars[ms.PlanSummary.BaseModelConfig.ApiKeyEnvVar] = true
envVars[ms.Namer.BaseModelConfig.ApiKeyEnvVar] = true
envVars[ms.CommitMsg.BaseModelConfig.ApiKeyEnvVar] = true
envVars[ms.ExecStatus.BaseModelConfig.ApiKeyEnvVar] = true
- envVars[ms.GetVerifier().BaseModelConfig.ApiKeyEnvVar] = true
- envVars[ms.GetAutoFix().BaseModelConfig.ApiKeyEnvVar] = true
// for backward compatibility with <= 0.8.4 server versions
if len(envVars) == 0 {