Open source AI coding agent. Designed for large projects and real world tasks.
Go aiai-agentsai-developer-toolsai-toolsclicommand-linedeveloper-toolsgitgolanggpt-4llmopenaipolyglot-programmingterminalterminal-basedterminal-ui
lots of work on 'apply' git integration, cli plan files fixes, 'apply' conflicts, and starting on separated build/rebuild functionality
Dane Schneiderf3cd0b3e947d
diff --git a/cli/cmd/apply.go b/cli/cmd/apply.goindex d343bcaa..660c4ebd 100644--- a/cli/cmd/apply.go+++ b/cli/cmd/apply.go@@ -7,12 +7,19 @@ import ("os""path/filepath""plandex/lib"+ "plandex/types""strings"+ "github.com/erikgeiser/promptkit/selection"+ "github.com/fatih/color"+ "github.com/olekukonko/tablewriter""github.com/spf13/cobra")+var autoConfirm bool+func init() {+ applyCmd.Flags().BoolVarP(&autoConfirm, "yes", "y", false, "Automatically confirm unless plan is outdated")RootCmd.AddCommand(applyCmd)}@@ -41,13 +48,22 @@ func apply(cmd *cobra.Command, args []string) error {name = lib.CurrentPlanName}+ if name == "" {+ fmt.Println("π€·ββοΈ No plan specified and no current plan")+ return nil+ }+rootDir := filepath.Join(plandexDir, name)- if _, err := os.Stat(rootDir); os.IsNotExist(err) {- return fmt.Errorf("error: plan with name '%+v' does not exist", name)+ _, err = os.Stat(rootDir)++ if os.IsNotExist(err) {+ fmt.Printf("π€·ββοΈ Plan with name '%s' doesn't exist\n", name)+ return nil+ } else if err != nil {+ return fmt.Errorf("error checking if plan exists: %w", err)}- appliedAny := falsecurrentPlanFiles, planResByPath, _, err := lib.GetCurrentPlanStateWithContext()if err != nil {@@ -58,12 +74,16 @@ func apply(cmd *cobra.Command, args []string) error {pathsRemoved := []string{}pathsOutdated := []string{}+ pathsUnmodified := []string{}+ pathsNew := []string{}+ pathsRemovedOrOutdatedSet := map[string]bool{}for path := range currentPlanFiles.Files {contextSha := currentPlanFiles.ContextShas[path]if contextSha == "" {// the path wasn't in context+ pathsNew = append(pathsNew, path)continue}@@ -75,6 +95,7 @@ func apply(cmd *cobra.Command, args []string) error {if os.IsNotExist(err) {pathsRemoved = append(pathsRemoved, path)+ pathsRemovedOrOutdatedSet[path] = true} else if err != nil {return fmt.Errorf("failed to check existence of %s: %w", dstPath, err)}@@ -90,20 +111,105 @@ func apply(cmd *cobra.Command, args []string) error {hash := sha256.Sum256(bytes)fileSha := hex.EncodeToString(hash[:])- if fileSha != contextSha {+ if fileSha == contextSha {+ pathsUnmodified = append(pathsUnmodified, path)+ } else {pathsOutdated = append(pathsOutdated, path)+ pathsRemovedOrOutdatedSet[path] = true}}- if len(pathsRemoved) > 0 || len(pathsOutdated) > 0 {- fmt.Println("β οΈ Files in context have been modified since the plan was generated:")+ table := tablewriter.NewWriter(os.Stdout)+ table.SetHeader([]string{"Path", "Status"})+ table.SetAutoWrapText(false)++ var unmodifiedLabel = "Unmodified"++ hasConflicts := (len(pathsRemoved) + len(pathsOutdated)) > 0++ if hasConflicts {+ fmt.Println("β οΈ Files in context have been modified since the plan was generated")+ fmt.Println()+for _, path := range pathsRemoved {- fmt.Println(" - " + path + " was removed")+ table.Rich([]string{path, "π΄ Removed"}, []tablewriter.Colors{+ {tablewriter.FgHiRedColor, tablewriter.Bold},+ {tablewriter.FgHiRedColor},+ })}+for _, path := range pathsOutdated {- fmt.Println(" - " + path + " was modified")+ table.Rich([]string{path, "π Modified"}, []tablewriter.Colors{+ {tablewriter.FgHiYellowColor, tablewriter.Bold},+ {tablewriter.FgHiYellowColor},+ })+ }+ } else {+ fmt.Printf("β‘οΈ %d files will be updated\n\n", len(pathsUnmodified)+len(pathsNew))+ unmodifiedLabel = "Changes"+ }++ for _, path := range pathsNew {+ table.Rich([]string{path, "π’ New File"}, []tablewriter.Colors{+ {tablewriter.FgHiGreenColor, tablewriter.Bold},+ {tablewriter.FgHiGreenColor},+ })+ }++ for _, path := range pathsUnmodified {+ table.Rich([]string{path, "π΅ " + unmodifiedLabel}, []tablewriter.Colors{+ {tablewriter.FgHiCyanColor, tablewriter.Bold},+ {tablewriter.FgHiCyanColor},+ })+ }++ table.Render()++ var conflictStrategy types.PlanOutdatedStrategy++ if hasConflicts {+ fmt.Println()++ if conflictStrategy == "" {+ options := []types.PlanOutdatedStrategy{+ types.PlanOutdatedStrategyOverwrite,+ }++ if len(currentPlanFiles.Files) > (len(pathsRemoved) + len(pathsOutdated)) {+ options = append(options, types.PlanOutdatedStrategyApplyUnmodified)+ }++ options = append(options,+ types.PlanOutdatedStrategyRebuild,+ types.PlanOutdatedStrategyCancel,+ )++ sp := selection.New("π€ How do you want to handle it?", options)+ sp.Filter = nil++ choice, err := sp.RunPrompt()+ if err != nil {+ fmt.Printf("Error selecting choice: %v\n", err)+ os.Exit(1)+ }++ conflictStrategy = choice}- os.Exit(0)+ }++ switch conflictStrategy {+ case types.PlanOutdatedStrategyOverwrite:+ fmt.Println("β‘οΈ Will force apply and overwrite modifications")++ case types.PlanOutdatedStrategyApplyUnmodified:+ fmt.Println("β‘οΈ Will apply only new and unmodified files")++ case types.PlanOutdatedStrategyRebuild:+ fmt.Println("β‘οΈ Will rebuild the plan with updated context")++ case types.PlanOutdatedStrategyCancel:+ fmt.Println("π Will abort and exit")+ return nil}isRepo := lib.CwdIsGitRepo()@@ -123,21 +229,54 @@ func apply(cmd *cobra.Command, args []string) error {if err != nil {return fmt.Errorf("failed to create git stash: %w", err)}++ defer func() {+ err := lib.GitStashPop(conflictStrategy)+ if err != nil {+ fmt.Printf("failed to pop git stash: %v\n", err)+ }+ }()}}+ toApply := map[string]string{}for path, content := range currentPlanFiles.Files {- // Compute destination path- dstPath := filepath.Join(lib.ProjectRoot, path)- // Write the file- err = os.WriteFile(dstPath, []byte(content), 0644)- if err != nil {- return fmt.Errorf("failed to write %s: %w", dstPath, err)+ outdated := pathsRemovedOrOutdatedSet[path]+ if outdated {+ if conflictStrategy == types.PlanOutdatedStrategyOverwrite {+ toApply[path] = content+ }+ } else {+ toApply[path] = content}- appliedAny = true}- if appliedAny {+ if len(toApply) == 0 {+ fmt.Println("π€·ββοΈ No changes to apply")+ } else {+ if !autoConfirm && !hasConflicts {+ shouldContinue, err := lib.ConfirmYesNo("Apply changes to %d files?", len(toApply))++ if err != nil {+ return fmt.Errorf("failed to get confirmation user input: %s", err)+ }++ if !shouldContinue {+ fmt.Println("π« Will abort and exit")+ return nil+ }+ }++ for path, content := range toApply {+ // Compute destination path+ dstPath := filepath.Join(lib.ProjectRoot, path)+ // Write the file+ err = os.WriteFile(dstPath, []byte(content), 0644)+ if err != nil {+ return fmt.Errorf("failed to write %s: %w", dstPath, err)+ }+ }+err := lib.SetPendingResultsApplied(planResByPath)if err != nil {return fmt.Errorf("failed to set pending results applied: %w", err)@@ -150,22 +289,13 @@ func apply(cmd *cobra.Command, args []string) error {}// Commit the changes- // After commit, try to pop the stash if one was created- if hasUncommittedChanges {- err := lib.GitStashPopNoConflict()- if err != nil {- return fmt.Errorf("failed to pop git stash: %w", err)- }- }- err = lib.GitCommit(lib.ProjectRoot, "π€ Plandex β "+desc.CommitMsg, true)+ err = lib.GitAddAndCommit(lib.ProjectRoot, color.New(color.BgBlue, color.FgHiWhite, color.Bold).Sprintln(" π€ Plandex ")+desc.CommitMsg, true)if err != nil {return fmt.Errorf("failed to commit changes: %w", err)}}fmt.Println("β Applied changes")- } else {- return fmt.Errorf("this plan has no changes to apply")}return nildiff --git a/cli/cmd/tell.go b/cli/cmd/tell.goindex a6df43d8..8cbb65d0 100644--- a/cli/cmd/tell.go+++ b/cli/cmd/tell.go@@ -98,11 +98,15 @@ func tell(cmd *cobra.Command, args []string) {return}+ // fmt.Println("lib.Propose(prompt)")+err := lib.Propose(prompt)if err != nil {fmt.Fprintln(os.Stderr, "Prompt error:", err)return}++ // fmt.Println("lib.Propose(prompt) success")}func prepareEditorCommand(editor string, filename string) *exec.Cmd {diff --git a/cli/go.mod b/cli/go.modindex cd0bcbc2..54c21b41 100644--- a/cli/go.mod+++ b/cli/go.mod@@ -15,6 +15,7 @@ require (require (github.com/alecthomas/chroma v0.10.0 // indirectgithub.com/andybalholm/cascadia v1.3.1 // indirect+ github.com/atotto/clipboard v0.1.4 // indirectgithub.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirectgithub.com/aymerick/douceur v0.2.0 // indirectgithub.com/containerd/console v1.0.4-0.20230313162750-1ae8d489ac81 // indirect@@ -23,19 +24,19 @@ require (github.com/gorilla/css v1.0.0 // indirectgithub.com/lucasb-eyer/go-colorful v1.2.0 // indirectgithub.com/mattn/go-colorable v0.1.12 // indirect- github.com/mattn/go-isatty v0.0.18 // indirect+ github.com/mattn/go-isatty v0.0.19 // indirectgithub.com/mattn/go-localereader v0.0.1 // indirectgithub.com/microcosm-cc/bluemonday v1.0.21 // indirectgithub.com/mitchellh/go-homedir v1.1.0 // indirect- github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b // indirect+ github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirectgithub.com/muesli/cancelreader v0.2.2 // indirectgithub.com/muesli/reflow v0.3.0 // indirect- github.com/muesli/termenv v0.15.1 // indirect- github.com/rivo/uniseg v0.4.3 // indirect+ github.com/muesli/termenv v0.15.2 // indirect+ github.com/rivo/uniseg v0.4.4 // indirectgithub.com/yuin/goldmark v1.5.2 // indirectgithub.com/yuin/goldmark-emoji v1.0.1 // indirectgolang.org/x/net v0.7.0 // indirect- golang.org/x/sync v0.1.0 // indirect+ golang.org/x/sync v0.3.0 // indirectgolang.org/x/sys v0.12.0 // indirect)@@ -47,6 +48,7 @@ require (github.com/charmbracelet/glamour v0.6.0github.com/charmbracelet/glow v1.5.1github.com/eiannone/keyboard v0.0.0-20220611211555-0d226195f203+ github.com/erikgeiser/promptkit v0.9.0github.com/inconshreveable/mousetrap v1.1.0 // indirectgithub.com/mattn/go-runewidth v0.0.15 // indirectgithub.com/pkoukk/tiktoken-go v0.1.6 // indirectdiff --git a/cli/go.sum b/cli/go.sumindex e29323b1..a2fb830e 100644--- a/cli/go.sum+++ b/cli/go.sum@@ -205,6 +205,7 @@ github.com/armon/go-metrics v0.4.0/go.mod h1:E6amYzXo6aW1tqzoZGT755KkbgrJsSdpwZ+github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=github.com/atotto/clipboard v0.1.2/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=+github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI=github.com/aymanbagabas/go-osc52 v1.0.3/go.mod h1:zT8H+Rk4VSabYN90pWyugflM3ZhpTZNC7cASDfUCdT4=github.com/aymanbagabas/go-osc52 v1.2.1/go.mod h1:zT8H+Rk4VSabYN90pWyugflM3ZhpTZNC7cASDfUCdT4=@@ -292,6 +293,8 @@ github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mgithub.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0=github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE=github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=+github.com/erikgeiser/promptkit v0.9.0 h1:3qL1mS/ntCrXdb8sTP/ka82CJ9kEQaGuYXNrYJkWYBc=+github.com/erikgeiser/promptkit v0.9.0/go.mod h1:pU9dtogSe3Jlc2AY77EP7R4WFP/vgD4v+iImC83KsCo=github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=github.com/fatih/color v1.9.0/go.mod h1:eQcE1qtQxscV5RaZvpXrrb8Drkc3/DdQ+uUYCNjL+zU=github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w=@@ -501,6 +504,8 @@ github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98=github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=+github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=+github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=github.com/mattn/go-localereader v0.0.1 h1:ygSAOl7ZXTx4RdPYinUpg6W99U8jWvWi9Ye2JC/oIi4=github.com/mattn/go-localereader v0.0.1/go.mod h1:8fBrzywKY7BI3czFoHkuzRoWE9C+EiG4R1k4Cjx5p88=github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=@@ -534,6 +539,8 @@ github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3Rllmbgithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b h1:1XF24mVaiu7u+CFywTdcDo2ie1pzzhwjt6RHqzpMU34=github.com/muesli/ansi v0.0.0-20211018074035-2e021307bc4b/go.mod h1:fQuZ0gauxyBcmsdE3ZT4NasjaRdxmbCS0jRHsrWu3Ho=+github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI=+github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6/go.mod h1:CJlz5H+gyd6CUWT45Oy4q24RdLyn7Md9Vj2/ldJBSIo=github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=github.com/muesli/gitcha v0.2.0/go.mod h1:Ri8m9TZS4+ORG4JVmVKUQcWZuxDvUW3UKxMdQfzG2zI=@@ -550,6 +557,8 @@ github.com/muesli/termenv v0.13.0/go.mod h1:sP1+uffeLaEYpyOTb8pLCUctGcGLnoFjSn4Ygithub.com/muesli/termenv v0.14.0/go.mod h1:kG/pF1E7fh949Xhe156crRUrHNyK221IuGO7Ez60Uc8=github.com/muesli/termenv v0.15.1 h1:UzuTb/+hhlBugQz28rpzey4ZuKcZ03MeKsoG7IJZIxs=github.com/muesli/termenv v0.15.1/go.mod h1:HeAQPTzpfs016yGtA4g00CsdYnVLJvxsS4ANqrZs2sQ=+github.com/muesli/termenv v0.15.2 h1:GohcuySI0QmI3wN8Ok9PtKGkgkFIk7y6Vpb5PvrY+Wo=+github.com/muesli/termenv v0.15.2/go.mod h1:Epx+iuz8sNs7mNKhxzH4fWXGNpZwUaJKRS1noLXviQ8=github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=github.com/mwitkow/go-conntrack v0.0.0-20190716064945-2f068394615f/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=@@ -597,6 +606,8 @@ github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJgithub.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=github.com/rivo/uniseg v0.4.3 h1:utMvzDsuh3suAEnhH0RdHmoPbU648o6CvXxTx4SBMOw=github.com/rivo/uniseg v0.4.3/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=+github.com/rivo/uniseg v0.4.4 h1:8TfxU8dW6PdqD27gjM8MVNuicgxIjxpm4K7x4jp8sis=+github.com/rivo/uniseg v0.4.4/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=@@ -839,6 +850,8 @@ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJgolang.org/x/sync v0.0.0-20220929204114-8fcdb60fdcc0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=+golang.org/x/sync v0.3.0 h1:ftCYgMx6zT/asHUrPw8BLLscYtGznsLAnjq5RH9P66E=+golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=diff --git a/cli/lib/git.go b/cli/lib/git.goindex d9817f4e..16d7470b 100644--- a/cli/lib/git.go+++ b/cli/lib/git.go@@ -5,6 +5,7 @@ import ("fmt""os/exec""path/filepath"+ "plandex/types""strconv""strings""sync"@@ -24,7 +25,7 @@ func InitGitRepo(dir string) error {return fmt.Errorf("error initializing git repository for dir: %s, err: %v, output: %s", dir, err, string(res))}- return GitAddAndCommit(dir, "New plan")+ return GitAddAndCommit(dir, "New plan", false)}func AddGitSubmodule(rootDir, submoduleDir string) error {@@ -62,7 +63,12 @@ func UpdateAndInitSubmodules(rootDir string) error {return nil}-func GitAddAndCommit(dir, message string) error {+func GitAddAndCommit(dir, message string, lockMutex bool) error {+ if lockMutex {+ gitMutex.Lock()+ defer gitMutex.Unlock()+ }+err := GitAdd(dir, ".", false)if err != nil {return fmt.Errorf("error adding files to git repository for dir: %s, err: %v", dir, err)@@ -130,17 +136,24 @@ func GitStashCreate(message string) error {return nil}-func GitStashPopNoConflict() error {+// this matches output for git version 2.39.3+// need to test on other versions and check for more variations+// there isn't any structured way to get stash conflicts from git, unfortunately+const PopStashConflictMsg = "overwritten by merge"+const ConflictMsgFilesEnd = "commit your changes"++func GitStashPop(conflictStrategy types.PlanOutdatedStrategy) error {gitMutex.Lock()defer gitMutex.Unlock()res, err := exec.Command("git", "stash", "pop").CombinedOutput()- fmt.Println("'git stash pop' output:")- fmt.Println(string(res))-if err != nil {- if strings.Contains(string(res), "CONFLICT") {+ if strings.Contains(string(res), PopStashConflictMsg) {+ if conflictStrategy != types.PlanOutdatedStrategyOverwrite {+ return fmt.Errorf("conflict popping git stash with unsupported conflict strategy: %s", conflictStrategy)+ }+// Parse the output to find which files have conflictsconflictFiles := parseConflictFiles(string(res))for _, file := range conflictFiles {@@ -156,7 +169,7 @@ func GitStashPopNoConflict() error {}return nil} else {- return fmt.Errorf("error popping git stash: %v, output: %s", err, string(res))+ return fmt.Errorf("error popping git stash: %v", err)}}@@ -166,14 +179,20 @@ func GitStashPopNoConflict() error {func parseConflictFiles(gitOutput string) []string {var conflictFiles []stringlines := strings.Split(gitOutput, "\n")++ inFilesSection := false+for _, line := range lines {- if strings.Contains(line, "CONFLICT") {- // Extract the filename from the line- parts := strings.Fields(line)- if len(parts) > 1 {- filename := parts[len(parts)-1]- conflictFiles = append(conflictFiles, filename)+ if inFilesSection {+ file := strings.TrimSpace(line)+ if file == "" {+ continue}+ conflictFiles = append(conflictFiles, strings.TrimSpace(line))+ } else if strings.Contains(line, PopStashConflictMsg) {+ inFilesSection = true+ } else if strings.Contains(line, ConflictMsgFilesEnd) {+ break}}return conflictFiles@@ -192,14 +211,19 @@ func CwdIsGitRepo() bool {return isGitRepo}-func gitCommitRootUpdate(commitMsg string) error {- err := GitAdd(CurrentPlanDir, ".", true)+func gitCommitRootUpdate(commitMsg string, lockMutex bool) error {+ if lockMutex {+ gitMutex.Lock()+ defer gitMutex.Unlock()+ }++ err := GitAdd(CurrentPlanDir, ".", false)if err != nil {return fmt.Errorf("failed to root plan dir changes: %s", err)}// Commit these staged submodule changes in the root repo- err = GitCommit(CurrentPlanDir, commitMsg, true)+ err = GitCommit(CurrentPlanDir, commitMsg, false)if err != nil {return fmt.Errorf("failed to commit submodule updates in root dir: %s", err)}@@ -209,42 +233,51 @@ func gitCommitRootUpdate(commitMsg string) error {}func GitCommitContextUpdate(commitMsg string) error {- err := GitAddAndCommit(ContextSubdir, commitMsg)+ gitMutex.Lock()+ defer gitMutex.Unlock()++ err := GitAddAndCommit(ContextSubdir, commitMsg, false)if err != nil {return fmt.Errorf("failed to commit context: %v", err)}- err = GitAdd(CurrentPlanDir, ContextSubdir, true)+ err = GitAdd(CurrentPlanDir, ContextSubdir, false)if err != nil {return fmt.Errorf("failed to stage submodule changes in context dir: %s", err)}- return gitCommitRootUpdate(commitMsg)+ return gitCommitRootUpdate(commitMsg, false)}func GitCommitConvoUpdate(commitMsg string) error {- err := GitAddAndCommit(ConversationSubdir, commitMsg)+ gitMutex.Lock()+ defer gitMutex.Unlock()++ err := GitAddAndCommit(ConversationSubdir, commitMsg, false)if err != nil {return fmt.Errorf("failed to commit convo update: %v", err)}- err = GitAdd(CurrentPlanDir, ConversationSubdir, true)+ err = GitAdd(CurrentPlanDir, ConversationSubdir, false)if err != nil {return fmt.Errorf("failed to stage submodule changes in convo dir: %s", err)}- return gitCommitRootUpdate(commitMsg)+ return gitCommitRootUpdate(commitMsg, false)}func GitCommitPlanUpdate(commitMsg string) error {- err := GitAddAndCommit(ResultsSubdir, commitMsg)+ gitMutex.Lock()+ defer gitMutex.Unlock()++ err := GitAddAndCommit(ResultsSubdir, commitMsg, false)if err != nil {return fmt.Errorf("failed to commit files to plan dir: %s", err)}- return gitCommitRootUpdate(commitMsg)+ return gitCommitRootUpdate(commitMsg, false)}// GetGitCommitHistory retrieves the git commit history for the given directory.diff --git a/cli/lib/plan_files.go b/cli/lib/plan_files.goindex 316cea28..338c74f9 100644--- a/cli/lib/plan_files.go+++ b/cli/lib/plan_files.go@@ -73,12 +73,11 @@ func GetCurrentPlanStateWithContext() (*shared.CurrentPlanFiles, shared.PlanResufor path, planResults := range planResByPath {updated := files[path]- lastInsertedIdx := 0// fmt.Printf("path: %s\n", path)// fmt.Printf("updated: %s\n", updated)- for _, planRes := range planResults {+ for i, planRes := range planResults {if !planRes.IsPending() {continue}@@ -94,6 +93,7 @@ func GetCurrentPlanStateWithContext() (*shared.CurrentPlanFiles, shared.PlanResu}contextSha := shas[path]+if contextSha != "" && planRes.ContextSha != contextSha {return nil, nil, nil, fmt.Errorf("result sha doesn't match context sha: %s", path)}@@ -102,8 +102,9 @@ func GetCurrentPlanStateWithContext() (*shared.CurrentPlanFiles, shared.PlanResucontinue}- for i, replacement := range planRes.Replacements {- if replacement.Failed || replacement.RejectedAt != "" {+ lastInsertedIdx := 0+ for j, replacement := range planRes.Replacements {+ if !replacement.IsPending() {continue}@@ -111,17 +112,23 @@ func GetCurrentPlanStateWithContext() (*shared.CurrentPlanFiles, shared.PlanResusub := updated[lastInsertedIdx:]originalIdx := strings.Index(sub, replacement.Old)+ // fmt.Println("replacement.Old: " + replacement.Old)+ // fmt.Println("Pre: " + pre)+ // fmt.Println("Sub: " + sub)+ // fmt.Println("Idx: " + fmt.Sprintf("%d", i))+ // fmt.Printf("OriginalIdx: %d\n", originalIdx)+ // fmt.Printf("LastInsertedIdx: %d\n", lastInsertedIdx)+if originalIdx == -1 {// replacement failed, return error (checked server-side so this shouldn't happen)- // fmt.Printf("replacement failed. path: %s, ts: %s, i: %d", path, planRes.Ts, i)- // fmt.Println("Replacement: " + replacement.Old + " -> " + replacement.New)- // fmt.Println("Pre: " + pre)- // fmt.Println("Sub: " + sub)- // fmt.Println("Idx: " + fmt.Sprintf("%d", lastInsertedIdx))+ err := fmt.Errorf("replacement failed. path: %s, ts: %s, resIdx: %d, replaceIdx: %d", path, planRes.Ts, i, j)++ fmt.Println(err.Error())+// fmt.Println("Updated: " + updated)- return nil, nil, nil, fmt.Errorf("replacement failed. path: %s, ts: %s, i: %d", path, planRes.Ts, i)+ return nil, nil, nil, err} else {replaced := strings.Replace(sub, replacement.Old, replacement.New, 1)updated = pre + replaced@@ -221,8 +228,8 @@ func getPlanResultsByPath() (shared.PlanResultsByPath, error) {return nil, fmt.Errorf("error reading results dir: %v", err)}- // sort results by timestampfor _, results := range resByPath {+ // sort results by timestamp ascendingsort.Slice(results, func(i, j int) bool {return results[i].Ts < results[j].Ts})diff --git a/cli/lib/proposal.go b/cli/lib/proposal.goindex eec20db9..f9c34e8e 100644--- a/cli/lib/proposal.go+++ b/cli/lib/proposal.go@@ -63,6 +63,8 @@ func Propose(prompt string) error {}}+ // fmt.Println("Checked current plan is draft")+timestamp := shared.StringTs()reply := ""done := make(chan struct{})@@ -100,8 +102,12 @@ func Propose(prompt string) error {}}+ // fmt.Println("Initialized locals")+promptNumTokens := shared.GetNumTokens(prompt)+ // fmt.Println("Got prompt num tokens")+err = appendConversation(types.AppendConversationParams{Timestamp: timestamp,PlanState: planState,@@ -111,6 +117,8 @@ func Propose(prompt string) error {},})+ // fmt.Println("Appended conversation")+if err != nil {return fmt.Errorf("failed to append prompt to conversation: %s", err)}@@ -120,7 +128,6 @@ func Propose(prompt string) error {MoveCursorToTopLeft()mdFull, _ := GetMarkdown(reply)fmt.Println(mdFull)- fmt.Print(displayHotkeys())termState = mdFull}@@ -134,6 +141,8 @@ func Propose(prompt string) error {}}()+ // fmt.Println("Starting proposal")+keyChan := make(chan *key, 1)ctx, cancelKeywatch := context.WithCancel(context.Background())errChn := make(chan error, 1)@@ -143,9 +152,6 @@ func Propose(prompt string) error {printReply()BackToMain()fmt.Print(termState)- s = spinner.New(spinner.CharSets[33], 100*time.Millisecond)- s.Prefix = " "- s.Start()}appendConvoReply := func() error {@@ -165,13 +171,15 @@ func Propose(prompt string) error {writeFileProgress := func() {files := desc.Files- // Clear previous lines- if filesFinished {- MoveUpLines(len(files))- } else {- MoveUpLines(len(files) + 4)++ if len(files) == 0 {+ return}+ // Clear previous lines++ MoveUpLines(len(files) + 4)+for _, filePath := range files {numStreamedTokens := numStreamedTokensByPath[filePath]@@ -189,7 +197,7 @@ func Propose(prompt string) error {fmt.Printf(fmtStr+"\n", fmtArgs...)}- if !filesFinished {+ if !(filesFinished && streamFinished) {fmt.Println()fmt.Printf(displayHotkeys() + "\n")}@@ -203,6 +211,9 @@ func Propose(prompt string) error {var apiReq *shared.PromptRequestvar handleStream types.OnStreamPlan++ // fmt.Println("Starting handleStream")+handleStream = func(params types.OnStreamPlanParams) {if running {queue <- params@@ -291,13 +302,16 @@ func Propose(prompt string) error {if filesFinished {close(done)closedDone = true+ writeFileProgress()}case shared.STATE_DESCRIBING:if content == shared.STREAM_DESCRIPTION_PHASE {- endReply()return}++ describeStart := time.Now()+bytes := []byte(content)err := json.Unmarshal(bytes, &desc)@@ -306,6 +320,12 @@ func Propose(prompt string) error {return}+ if len(desc.Files) > 0 {+ s = spinner.New(spinner.CharSets[33], 100*time.Millisecond)+ s.Prefix = " "+ s.Start()+ }+err = os.MkdirAll(DescriptionsSubdir, os.ModePerm)if err != nil {onError(fmt.Errorf("failed to create plan descriptions directory: %s", err))@@ -318,14 +338,30 @@ func Propose(prompt string) error {return}+ // fmt.Println("appending convo reply")+err = appendConvoReply()if err != nil {onError(fmt.Errorf("failed to append reply to conversation: %s", err))return}+ // fmt.Println("appended convo reply")++ // wait a bit if necessary to avoid jarring output of conversation as soon as stream finishes+ elapsed := time.Since(describeStart)+ if elapsed < 1500*time.Millisecond {+ time.Sleep(1500*time.Millisecond - elapsed)+ }++ // fmt.Println("waited elapsed")++ endReply()++ // fmt.Println("ended reply")+ s.Stop()+if desc.MadePlan && (len(desc.Files) > 0) {- s.Stop()fmt.Println(" " + color.New(color.BgGreen, color.FgHiWhite, color.Bold).Sprint(" π ") + color.New(color.BgGreen, color.FgHiWhite).Sprint("Building plan "))for _, filePath := range desc.Files {fmt.Printf(" π %s\n", filePath)@@ -376,6 +412,7 @@ func Propose(prompt string) error {if streamFinished {close(done)closedDone = true+ writeFileProgress()}}}@@ -388,17 +425,21 @@ func Propose(prompt string) error {return fmt.Errorf("failed to send prompt to server: %s", err)}+ // fmt.Println("Sent prompt to server")+for _, part := range apiReq.ModelContext {contextByFilePath[part.FilePath] = part}+ // fmt.Println("Got context")+go func(ctx context.Context, errChn chan error) {for {select {case <-ctx.Done():returndefault:- k, err := getUserInput()+ k, err := GetUserInput()if err != nil {errChn <- errreturn@@ -429,6 +470,8 @@ Loop:}}+ // fmt.Println("Started key loop")+if desc != nil {if desc.MadePlan && len(desc.Files) > 0 {fmt.Println()@@ -448,6 +491,8 @@ Loop:PrintCmds(" ", "rewind")}+ // fmt.Println("Finished proposal")+return nil}@@ -533,35 +578,13 @@ func checkOutdatedContext(s *spinner.Spinner) (bool, error) {fmt.Println()- var input func() (bool, error)- input = func() (bool, error) {- color.New(color.FgHiGreen, color.Bold).Println("Update context now? (y)es | (n)o | (c)ancel")- color.New(color.FgHiGreen, color.Bold).Print("> ")+ _, canceled, err := ConfirmYesNoCancel("Update context now?")- char, err := getUserInput()- if err != nil {- return false, fmt.Errorf("failed to get user input: %s", err)- }-- fmt.Println(string(char))- if char == 'y' || char == 'Y' {- MustUpdateContextWithOuput()- return true, nil- } else if char == 'n' || char == 'N' {- return true, nil- } else if char == 'c' || char == 'C' {- return false, nil- } else {- fmt.Println()- color.New(color.FgHiRed, color.Bold).Print("Invalid input.\nEnter 'y' for yes, 'n' for no, or 'c' to cancel.\n\n")- return input()- }- }-- shouldContinue, err := input()if err != nil {return false, fmt.Errorf("failed to get user input: %s", err)}+ shouldContinue := canceled+return shouldContinue, nil}diff --git a/cli/lib/term.go b/cli/lib/term.goindex 3aa2328d..c5c718a9 100644--- a/cli/lib/term.go+++ b/cli/lib/term.go@@ -11,11 +11,11 @@ import ("golang.org/x/term")-var cmdDesc = map[string][2]string{+var CmdDesc = map[string][2]string{"new": {"", "start a new plan"},// "current": {"c", "show current plan"},"cd": {"", "set current plan by name or index"},- "load": {"l", "load files/directories/urls/notes or pipe data into context"},+ "load": {"l", "load files, dirs, urls, notes or piped data into context"},"tell": {"t", "describe a task, ask a question, or chat"},// "diffs": {"d", "show diffs between plan and project files"},// "preview": {"pv", "preview the plan in a branch"},@@ -33,7 +33,7 @@ var cmdDesc = map[string][2]string{func PrintCmds(prefix string, cmds ...string) {for _, cmd := range cmds {- config, ok := cmdDesc[cmd]+ config, ok := CmdDesc[cmd]if !ok {continue}@@ -109,51 +109,64 @@ func PageOutputReverse(output string) {}}-// Function for 'a' key action-func handleAbortKey(proposalId string) error {- return Abort(proposalId)-}+func GetUserInput() (rune, error) {+ if err := keyboard.Open(); err != nil {+ return 0, fmt.Errorf("failed to open keyboard: %s", err)+ }+ defer func() {+ _ = keyboard.Close()+ }()-// // Function for 'r' key action-// func handleReviseKey(proposalId string) error {-// // Terminate current operation-// err := Api.Abort(proposalId)-// if err != nil {-// return err-// }+ char, _, err := keyboard.GetKey()+ if err != nil {+ return 0, fmt.Errorf("failed to read keypress: %s", err)+ }-// // Prompt the user for new message-// fmt.Println(">\"")-// reader := bufio.NewReader(os.Stdin)-// newMessage, _ := reader.ReadString('"')+ return char, nil+}-// // Propose the new message-// err = Propose(newMessage)-// if err != nil {-// return err-// }+func ConfirmYesNo(fmtStr string, fmtArgs ...interface{}) (bool, error) {+ color.New(color.FgHiGreen, color.Bold).Printf(fmtStr+" (y)es | (n)o", fmtArgs...)+ color.New(color.FgHiGreen, color.Bold).Print("> ")-// fmt.Println("Revision proposed.")-// return nil-// }+ char, err := GetUserInput()+ if err != nil {+ return false, fmt.Errorf("failed to get user input: %s", err)+ }-func handleKeyPress(input rune, proposalId string) error {- switch input {- case 's':- return handleAbortKey(proposalId)- // case 'r':- // return handleReviseKey(proposalId)- default:- return fmt.Errorf("invalid key pressed: %s", string(input))+ fmt.Println(string(char))+ if char == 'y' || char == 'Y' {+ return true, nil+ } else if char == 'n' || char == 'N' {+ return false, nil+ } else {+ fmt.Println()+ color.New(color.FgHiRed, color.Bold).Print("Invalid input.\nEnter 'y' for yes or 'n' for no.\n\n")+ return ConfirmYesNo(fmtStr, fmtArgs...)}}-func getTerminalWidth() (int, error) {- width, _, err := term.GetSize(int(os.Stdout.Fd()))+func ConfirmYesNoCancel(fmtStr string, fmtArgs ...interface{}) (bool, bool, error) {+ color.New(color.FgHiGreen, color.Bold).Printf(fmtStr+" (y)es | (n)o | (c)ancel", fmtArgs...)+ color.New(color.FgHiGreen, color.Bold).Print("> ")++ char, err := GetUserInput()if err != nil {- return 0, err+ return false, false, fmt.Errorf("failed to get user input: %s", err)+ }++ fmt.Println(string(char))+ if char == 'y' || char == 'Y' {+ return true, false, nil+ } else if char == 'n' || char == 'N' {+ return false, false, nil+ } else if char == 'c' || char == 'C' {+ return false, true, nil+ } else {+ fmt.Println()+ color.New(color.FgHiRed, color.Bold).Print("Invalid input.\nEnter 'y' for yes, 'n' for no, or 'c' for cancel.\n\n")+ return ConfirmYesNoCancel(fmtStr, fmtArgs...)}- return width, nil}func GetDivisionLine() string {@@ -166,26 +179,31 @@ func GetDivisionLine() string {return strings.Repeat("β", terminalWidth)}-func displayHotkeys() string {- divisionLine := GetDivisionLine()-- return divisionLine + "\n" +- " \x1b[1m(s)\x1b[0m" + `top-` + divisionLine+func handleAbortKey(proposalId string) error {+ return Abort(proposalId)}-func getUserInput() (rune, error) {- if err := keyboard.Open(); err != nil {- return 0, fmt.Errorf("failed to open keyboard: %s\n", err)+func handleKeyPress(input rune, proposalId string) error {+ switch input {+ case 's':+ return handleAbortKey(proposalId)+ default:+ return fmt.Errorf("invalid key pressed: %s", string(input))}- defer func() {- _ = keyboard.Close()- }()+}- char, _, err := keyboard.GetKey()+func getTerminalWidth() (int, error) {+ width, _, err := term.GetSize(int(os.Stdout.Fd()))if err != nil {- return 0, fmt.Errorf("failed to read keypress: %s\n", err)+ return 0, err}+ return width, nil+}- return char, nil+func displayHotkeys() string {+ divisionLine := GetDivisionLine()++ return divisionLine + "\n" ++ " \x1b[1m(s)\x1b[0m" + `top+` + divisionLine}diff --git a/cli/types/types.go b/cli/types/types.goindex 0d726ce2..1591e6e9 100644--- a/cli/types/types.go+++ b/cli/types/types.go@@ -65,3 +65,12 @@ type LoadContextParams struct {Recursive boolNamesOnly bool}++type PlanOutdatedStrategy string++const (+ PlanOutdatedStrategyOverwrite PlanOutdatedStrategy = "Clear the modifications and then apply"+ PlanOutdatedStrategyApplyUnmodified PlanOutdatedStrategy = "Apply only new and unmodified files"+ PlanOutdatedStrategyRebuild PlanOutdatedStrategy = "Rebuild the plan with updated context"+ PlanOutdatedStrategyCancel PlanOutdatedStrategy = "Cancel"+)diff --git a/server/handlers/build.go b/server/handlers/build.gonew file mode 100644index 00000000..5ac8282f--- /dev/null+++ b/server/handlers/build.go@@ -0,0 +1 @@+package handlersdiff --git a/server/handlers/proposal.go b/server/handlers/create.gosimilarity index 100%rename from server/handlers/proposal.gorename to server/handlers/create.godiff --git a/server/handlers/name.go b/server/handlers/name.goindex 8a436309..b0560ba3 100644--- a/server/handlers/name.go+++ b/server/handlers/name.go@@ -43,7 +43,7 @@ func FileNameHandler(w http.ResponseWriter, r *http.Request) {return}- log.Println("Successfully processed file name request")+ log.Println("Successfully processed file name request", string(modelResp))// Return the response from OpenAI to the clientw.Write(modelResp)}diff --git a/server/main.go b/server/main.goindex ece9f115..35898ae5 100644--- a/server/main.go+++ b/server/main.go@@ -22,11 +22,16 @@ func main() {r := mux.NewRouter()+ r.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {+ fmt.Fprintf(w, "OK")+ })+r.HandleFunc("/proposal", handlers.ProposalHandler).Methods("POST")r.HandleFunc("/abort", handlers.AbortProposalHandler).Methods("DELETE")r.HandleFunc("/short-summary", handlers.ShortSummaryHandler).Methods("POST")r.HandleFunc("/filename", handlers.FileNameHandler).Methods("POST")r.HandleFunc("/convo-summary/{rootId}", handlers.ConvoSummaryHandler).Methods("GET")+ // r.HandleFunc("/build", handlers.BuildHandler).Methods("PUT")// Get port from the environment variable or default to 8088port := os.Getenv("PORT")diff --git a/server/model/prompts/replace.go b/server/model/prompts/build.gosimilarity index 86%rename from server/model/prompts/replace.gorename to server/model/prompts/build.goindex bccac55e..cde4c24f 100644--- a/server/model/prompts/replace.go+++ b/server/model/prompts/build.go@@ -9,7 +9,8 @@ import ("github.com/sashabaranov/go-openai/jsonschema")-const SysReplace = `+func GetBuildSysPrompt(filePath, currentStatePrompt string) string {+ return fmt.Sprintf(`[YOUR INSTRUCTIONS]You are an AI replacer. You apply changes from a plan to a given code file using the 'writeReplacements' function. You call 'writeReplacements' with a valid JSON array of replacements.@@ -22,7 +23,9 @@ Lean toward using fewer replacements. If you can apply all the changes in a singDO NOT INCLUDE any sections that are just comments, placeholders, references to the original file, or TODOs that are not yet implemented. Only include actual changes that move the plan forward and are ready to be applied to the file.-These replacements will be applied automatically by a program to the file exactly as written, so the 'old' text must be an EXACT SUBSTRING of the current state of the file. Pay special attention to any special characters in the strings, extra spaces, or anything else that might cause 'old' not to be an exact substring.+These replacements will be applied automatically by a program to the file exactly as written, so the 'old' text must be an EXACT SUBSTRING of the **current state of the file**. The current state of the file will be provided below, labelled with '**Current state of file for %s:**'. It does *not* include any of the suggested changes from the latest response. The 'old' text MUST be an exact substring of the current state of the file, not the suggested changes from the latest response.++Pay special attention to any special characters in the strings, extra spaces, or anything else that might cause 'old' not to be an exact substring.The 'old' text should be unique and unambiguous in the current file. It must not overlap with any other 'old' text in the list of replacements. Make the 'old' text as short as it can be while still being unique and unambiguous. If the 'old' text can be a single line, it should be. If it must be multiple lines, it should be as few lines as possible.@@ -34,7 +37,7 @@ Replacement examples below. Note: >>> and <<< indicate the start and end of an e1.)If the current file is:-` + "```" + `+`+"```"+`package mainimport "fmt"@@ -42,7 +45,7 @@ import "fmt"func main() {fmt.Println("Hello, world!")}-` + "```" + `+`+"```"+`And the previous response was:@@ -50,21 +53,21 @@ And the previous response was:You can change the main.go file to print the current time instead of "Hello, world!".:- main.go:-` + "```" + `+`+"```"+`func main() {fmt.Println(time.Now())}-` + "```" + `+`+"```"+`You'll also need to import the time package:- main.go:-` + "```" + `+`+"```"+`import ("fmt""time")-` + "```" + `+`+"```"+`<<<Then you would call the 'writeReplacements' function like this:@@ -86,13 +89,13 @@ writeReplacements({2.)If the current file is:-` + "```" + `+`+"```"+`package helpersfunc Add(a, b int) int {return a + b}-` + "```" + `+`+"```"+`And the previous response was:@@ -100,11 +103,11 @@ And the previous response was:Add another function to the helpers.go file that subtracts two numbers:- helpers.go:-` + "```" + `+`+"```"+`func Subtract(a, b int) int {return a - b}-` + "```" + `+`+"```"+`<<<Then you would call the 'writeReplacements' function like this:@@ -121,7 +124,7 @@ writeReplacements({3.)If the current file is:-` + "```" + `+`+"```"+`package mainimport "fmt"@@ -129,7 +132,7 @@ import "fmt"func main() {fmt.Println("Hello, world!")}-` + "```" + `+`+"```"+`And the previous response was:@@ -137,12 +140,12 @@ And the previous response was:You can change the main.go file to print "I love you!" in addition to "Hello, world!".:- main.go:-` + "```" + `+`+"```"+`func main() {fmt.Println("Hello, world!")fmt.Println("I love you!")}-` + "```" + `+`+"```"+`<<<Then you would call the 'writeReplacements' function like this:@@ -157,7 +160,17 @@ writeReplacements({]})-[END INSTRUCTIONS]`+[END INSTRUCTIONS]+%s+`, filePath, currentStatePrompt)+}++func GetBuildCurrentStatePrompt(filePath, currentState string) string {+ if currentState == "" {+ return ""+ }+ return fmt.Sprintf("\n\n**Current state of file for %s:**\n```\n%s\n```", filePath, currentState) + "\n\n"+}var ReplaceFn = openai.FunctionDefinition{Name: "writeReplacements",diff --git a/server/model/proposal/build.go b/server/model/proposal/build.goindex d8d64773..9bf61a32 100644--- a/server/model/proposal/build.go+++ b/server/model/proposal/build.go@@ -134,6 +134,10 @@ func buildPlan(params buildPlanParams) error {if fileInCurrentPlan {currentState = currentPlanFile++ fmt.Printf("File %s found in current plan. Using current state.\n", filePath)+ fmt.Println("Current state:")+ fmt.Println(currentState)} else if contextPart != nil {currentState = contextPart.Body}@@ -168,15 +172,13 @@ func buildPlan(params buildPlanParams) error {// fmt.Println("File context:", fileContext)replacePrompt := prompts.GetReplacePrompt(filePath)- if currentState != "" {- fmt.Println("Adding current state before replace prompt")- replacePrompt = fmt.Sprintf("\nCurrent state of %s:\n```\n%s\n```", filePath, currentState) + "\n\n" + replacePrompt- }+ currentStatePrompt := prompts.GetBuildCurrentStatePrompt(filePath, currentState)+ sysPrompt := prompts.GetBuildSysPrompt(filePath, currentStatePrompt)fileMessages := []openai.ChatCompletionMessage{{Role: openai.ChatMessageRoleSystem,- Content: prompts.SysReplace,+ Content: sysPrompt,}, {Role: openai.ChatMessageRoleUser,Content: proposal.Request.Prompt,@@ -255,7 +257,8 @@ func buildPlan(params buildPlanParams) error {handleErrorRetry := func(maxRetryErr error, shouldSleep bool, isReplacementsRetry bool, res *shared.PlanResult) {fmt.Printf("Error for file %s: %v\n", filePath, maxRetryErr)- if numRetry >= MaxRetries {+ if (isReplacementsRetry && numReplacementsRetry >= MaxReplacementRetries) ||+ (!isReplacementsRetry && numRetry >= MaxRetries) {onBuildFileError(filePath, maxRetryErr)} else {if shouldSleep {@@ -393,14 +396,12 @@ func buildPlan(params buildPlanParams) error {}}- if numRetry < MaxReplacementRetries {- handleErrorRetry(- nil,- false,- true,- planResult,- )- }+ handleErrorRetry(+ fmt.Errorf("failed replacements for file '%s' after %d retries", filePath, numReplacementsRetry),+ false,+ true,+ planResult,+ )return}