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
diff updates are working
Dane Schneideraf965b896b87
diff --git a/cli/cmd/apply.go b/cli/cmd/apply.goindex 0099249b..6342c38e 100644--- a/cli/cmd/apply.go+++ b/cli/cmd/apply.go@@ -70,7 +70,7 @@ func apply(cmd *cobra.Command, args []string) error {}// Compute destination path- dstPath := filepath.Join(".", relPath)+ dstPath := filepath.Join(lib.ProjectRoot, relPath)// Copy the fileerr = copyFile(srcPath, dstPath)diff --git a/cli/lib/context_load.go b/cli/lib/context_load.goindex 1daae8ec..30db0381 100644--- a/cli/lib/context_load.go+++ b/cli/lib/context_load.go@@ -348,6 +348,7 @@ func LoadContextOrDie(params *types.LoadContextParams) (int, int) {var summaryResp shared.SummarizeResponse// Waiting for the summary response or error+ // for i := 0; i < 2; i++ {for i := 0; i < 1; i++ {select {case err := <-errCh:diff --git a/cli/lib/fs.go b/cli/lib/fs.goindex a9fb563e..b88a5a96 100644--- a/cli/lib/fs.go+++ b/cli/lib/fs.go@@ -12,6 +12,7 @@ import (var Cwd stringvar PlandexDir string+var ProjectRoot stringvar HomePlandexDir stringvar CacheDir string@@ -56,7 +57,8 @@ func init() {go func() {defer wg.Done()- PlandexDir = FindPlandex()+ PlandexDir, ProjectRoot = FindPlandex()+err = LoadCurrentPlan()if err != nil {panic(err)@@ -123,17 +125,17 @@ func FindOrCreatePlandex() (string, bool, error) {return dir, false, nil}-func FindPlandex() string {+func FindPlandex() (string, string) {searchPath := Cwdfor searchPath != "/" {dir := filepath.Join(searchPath, ".plandex")if _, err := os.Stat(dir); !os.IsNotExist(err) {- return dir+ return dir, searchPath}searchPath = filepath.Dir(searchPath)}- return ""+ return "", ""}func CwdIsPlan() bool {diff --git a/cli/lib/proposal.go b/cli/lib/proposal.goindex fcd17010..a1ab66b1 100644--- a/cli/lib/proposal.go+++ b/cli/lib/proposal.go@@ -54,10 +54,10 @@ func Propose(prompt string) error {replyTokenCounter := shared.NewReplyInfo()var tokensAddedByFile map[string]int- currentPlanTokensByFilePath, err := loadCurrentPlanTokensByFilePath()- if err != nil {- return fmt.Errorf("failed to load token counts: %s\n", err)- }+ // currentPlanTokensByFilePath, err := loadCurrentPlanTokensByFilePath()+ // if err != nil {+ // return fmt.Errorf("failed to load token counts: %s\n", err)+ // }var parentProposalId stringvar planState types.PlanState@@ -240,7 +240,7 @@ func Propose(prompt string) error {// plan build mode started} else {- wroteFile, err := receiveFileChunk(&receiveFileChunkParams{+ wroteFile, err := receiveFileToken(&receiveFileChunkParams{Content: content,JsonBuffers: jsonBuffers,NumStreamedTokensByPath: numStreamedTokensByPath,@@ -258,8 +258,8 @@ func Propose(prompt string) error {moveUpLines(len(files))for _, filePath := range files {- contextPart, foundContext := contextByFilePath[filePath]- filePathInPlan := isFilePathInPlan(filePath)+ // contextPart, foundContext := contextByFilePath[filePath]+ // filePathInPlan := isFilePathInPlan(filePath)numStreamedTokens := numStreamedTokensByPath[filePath]added := tokensAddedByFile[filePath]@@ -270,22 +270,9 @@ func Propose(prompt string) error {if finished {fmtStr += " | done ✅"- } else {- if filePathInPlan {- fmtStr += " / %d estimated (%d base + ~%d changes)"- currentTotal := currentPlanTokensByFilePath[filePath]- total := currentTotal + added- fmtArgs = append(fmtArgs, total, currentTotal, added)- } else if foundContext {- fmtStr += " / %d estimated (%d base + ~%d changes)"- contextTotal := int(contextPart.NumTokens)- total := contextTotal + added-- fmtArgs = append(fmtArgs, total, contextTotal, added)- } else if added > 0 {- fmtStr += " / %d estimated"- fmtArgs = append(fmtArgs, added)- }+ } else if added > 0 {+ fmtStr += " / %d estimated"+ fmtArgs = append(fmtArgs, added)}clearCurrentLine()@@ -293,13 +280,13 @@ func Propose(prompt string) error {}if wroteFile {- fmt.Printf("Wrote %d / %d files", len(finishedByPath), len(files))+ // fmt.Printf("Wrote %d / %d files", len(finishedByPath), len(files))if len(finishedByPath) == len(files) {- err = writeFilesFromSections(apiReq, finishedByPath)- if err != nil {- onError(err)- return- }+ // err = writeFilesFromSections(apiReq, finishedByPath)+ // if err != nil {+ // onError(err)+ // return+ // }filesFinished = truediff --git a/cli/lib/stream.go b/cli/lib/stream.goindex 96bdc95c..a4854f8b 100644--- a/cli/lib/stream.go+++ b/cli/lib/stream.go@@ -6,6 +6,7 @@ import ("log""os""path/filepath"+ "sort""strings""github.com/plandex/plandex/shared"@@ -18,7 +19,7 @@ type receiveFileChunkParams struct {FinishedByPath map[string]bool}-func receiveFileChunk(params *receiveFileChunkParams) (bool, error) {+func receiveFileToken(params *receiveFileChunkParams) (bool, error) {content := params.ContentjsonBuffers := params.JsonBuffersnumStreamedTokensByPath := params.NumStreamedTokensByPath@@ -30,59 +31,129 @@ func receiveFileChunk(params *receiveFileChunkParams) (bool, error) {return false, fmt.Errorf("error parsing plan chunk: %v", err)}- _, sectionNum, err := shared.SplitSectionPath(chunk.Path)- if err != nil {- return false, fmt.Errorf("error parsing section number: %v", err)- }- isSection := sectionNum >= 0+ // _, sectionNum, err := shared.SplitSectionPath(chunk.Path)+ // if err != nil {+ // return false, fmt.Errorf("error parsing section number: %v", err)+ // }+ // isSection := sectionNum >= 0// fmt.Println("path: " + chunk.Path)// fmt.Println("isSection: " + fmt.Sprintf("%t", isSection))// fmt.Println("sectionNum: " + fmt.Sprintf("%d", sectionNum))// fmt.Println("filePath: " + filePath)- buffer, isFirstWriteToPath := jsonBuffers[chunk.Path]+ buffer := jsonBuffers[chunk.Path]buffer += chunk.ContentjsonBuffers[chunk.Path] = buffer- numTokens := int(shared.GetNumTokens(chunk.Content))- if isFirstWriteToPath {- numStreamedTokensByPath[chunk.Path] = numTokens- } else {- numStreamedTokensByPath[chunk.Path] += numTokens- }+ numStreamedTokensByPath[chunk.Path]++++ // log.Println("Received file chunk: " + chunk.Path)+ // log.Println("Number of tokens: " + fmt.Sprintf("%d", numStreamedTokensByPath[chunk.Path]))+ var streamedType stringvar streamed shared.StreamedFile- err = json.Unmarshal([]byte(jsonBuffers[chunk.Path]), &streamed)+ var replacements shared.StreamedReplacements++ err = json.Unmarshal([]byte(jsonBuffers[chunk.Path]), &replacements)+ if err == nil {+ streamedType = "replacements"+ } else {+ err = json.Unmarshal([]byte(jsonBuffers[chunk.Path]), &streamed)+ if err == nil {+ streamedType = "file"+ }+ }if err == nil {++ // log.Println("Parsed JSON. Streamed type: " + streamedType)+var writeToPath string- if isSection {- // log.Printf("Section. Writing to section path '%s'\n", chunk.Path)- writeToPath = filepath.Join(PlanSectionsDir, chunk.Path)+ writeToPath = filepath.Join(PlanFilesDir, chunk.Path)++ var content string++ if streamedType == "replacements" {++ exists := false+ if _, err := os.Stat(writeToPath); !os.IsNotExist(err) {+ exists = true+ }++ if exists {+ bytes, err := os.ReadFile(writeToPath)++ if err != nil {+ err = fmt.Errorf("failed to read file '%s': %v\n", writeToPath, err)+ log.Println(err)+ return false, fmt.Errorf("failed to read file '%s': %v\n", writeToPath, err)+ }++ content = string(bytes)+ } else {+ bytes, err := os.ReadFile(filepath.Join(ProjectRoot, chunk.Path))++ if err != nil {+ err = fmt.Errorf("failed to read file '%s': %v\n", chunk.Path, err)+ log.Println(err)+ return false, fmt.Errorf("failed to read file '%s': %v\n", chunk.Path, err)+ }++ content = string(bytes)+ }++ // log.Println("Content before replacements: " + content)++ // ensure replacements are ordered by index in content (error if not present)+ sort.Slice(replacements.Replacements, func(i, j int) bool {+ iIdx := strings.Index(content, replacements.Replacements[i].Old)+ jIdx := strings.Index(content, replacements.Replacements[j].Old)+ return iIdx < jIdx+ })++ lastInsertedIdx := 0+ for _, replacement := range replacements.Replacements {+ pre := content[:lastInsertedIdx]+ sub := content[lastInsertedIdx:]+ idx := strings.Index(sub, replacement.Old)+ if idx == -1 {+ err = fmt.Errorf("failed to find replacement string '%s' in file '%s'\n", replacement.Old, chunk.Path)+ log.Println(err)+ return false, err+ }++ updated := strings.Replace(sub, replacement.Old, replacement.New, 1)++ // log.Println("Replacement: " + replacement.Old + " -> " + replacement.New)+ // log.Println("Pre: " + pre)+ // log.Println("Sub: " + sub)+ // log.Println("Idx: " + fmt.Sprintf("%d", idx))+ // log.Println("Updated: " + updated)++ content = pre + updated++ lastInsertedIdx = lastInsertedIdx + idx + len(replacement.New)+ }++ // log.Println("Content after replacements: " + content)+ } else if streamedType == "file" {+ content = streamed.Content} else {- // log.Printf("Note section. Writing to file path '%s'\n", chunk.Path)- writeToPath = filepath.Join(PlanFilesDir, chunk.Path)+ err = fmt.Errorf("unknown streamed type: %s", streamedType)+ log.Println(err)+ return false, err}- // log.Printf("Writing to file or section path '%s'\n", writeToPath)err := os.MkdirAll(filepath.Dir(writeToPath), os.ModePerm)if err != nil {log.Printf("failed to create directory: %s\n", err)return false, fmt.Errorf("failed to create directory: %s\n", err)}- file, err := os.OpenFile(writeToPath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY,- 0644)- if err != nil {- log.Printf("failed to open plan file '%s': %v\n", writeToPath, err)- return false, fmt.Errorf("failed to open plan file '%s': %v\n", writeToPath,- err)- }- defer file.Close()- _, err = file.WriteString(streamed.Content)+ err = os.WriteFile(writeToPath, []byte(content), 0644)if err != nil {log.Printf("failed to write plan file '%s': %v\n", writeToPath, err)return false, fmt.Errorf("failed to write plan file '%s': %v\n", writeToPath, err)@@ -93,8 +164,6 @@ func receiveFileChunk(params *receiveFileChunkParams) (bool, error) {return false, fmt.Errorf("failed to write token counts: %s\n", err)}- // fmt.Println("Wrote to file " + filePath)-finishedByPath[chunk.Path] = truereturn true, nil@@ -173,133 +242,3 @@ func loadCurrentPlanTokensByFilePath() (map[string]int, error) {return currentPlanTokensByFilePath, nil}--func writeFilesFromSections(apiReq *shared.PromptRequest, finishedByPath map[string]bool) error {- log.Println("Starting writeFilesFromSections...")-- var filePaths []string-- for path := range finishedByPath {- filePath, sectionNum, err := shared.SplitSectionPath(path)- if err != nil {- return fmt.Errorf("error parsing section number: %v", err)- }- if sectionNum >= 0 {- filePaths = append(filePaths, filePath)- }- }-- log.Printf("File paths to process: %v\n", filePaths)-- errCh := make(chan error)- doneCh := make(chan bool)- numWritten := 0-- for _, filePath := range filePaths {- go func(filePath string) {- log.Printf("Processing file: %s\n", filePath)-- origPath := filepath.Join(".", filePath)- planFilesPath := filepath.Join(PlanFilesDir, filePath)-- // read the original file- origBytes, err := os.ReadFile(origPath)- if err != nil {- log.Printf("failed to read original file '%s': %v\n", origPath, err)- errCh <- fmt.Errorf("failed to read original file '%s': %v\n", origPath, err)- return- }- origContent := string(origBytes)-- // get the full sections from the original file- var contextPart *shared.ModelContextPart- for _, part := range apiReq.ModelContext {- if part.FilePath == filePath {- contextPart = &part- break- }- }- if contextPart == nil {- log.Printf("failed to find context part for file '%s'\n", filePath)- errCh <- fmt.Errorf("failed to find context part for file '%s'\n", filePath)- return- }- origSections := shared.GetFullSections(origContent, contextPart.SectionEnds)- fileContent := origContent-- // list existing section files for this file path- sectionsDir := filepath.Dir(filepath.Join(PlanSectionsDir, filePath))- sectionFiles, err := os.ReadDir(sectionsDir)- if err != nil {- log.Printf("failed to read section files for '%s': %v\n", filePath, err)- errCh <- fmt.Errorf("failed to read section files for '%s': %v\n", filePath, err)- return- }- for _, sectionFile := range sectionFiles {- name := sectionFile.Name()- sectionPath := filepath.Join(filepath.Dir(filePath), name)-- _, sectionNum, err := shared.SplitSectionPath(sectionPath)- if err != nil || sectionNum < 0 {- log.Printf("failed to parse section number for '%s': %v\n", sectionPath, err)- errCh <- fmt.Errorf("failed to parse section number for '%s': %v\n", sectionPath, err)- return- }-- if sectionNum >= len(origSections) {- log.Printf("failed to find section %d in file '%s'\n", sectionNum, filePath)- errCh <- fmt.Errorf("failed to find section %d in file '%s'\n", sectionNum, filePath)- return- }-- origSection := origSections[sectionNum]-- // read the section file- sectionBytes, err := os.ReadFile(filepath.Join(sectionsDir, name))- if err != nil {- log.Printf("failed to read section file '%s': %v\n", sectionPath, err)- errCh <- fmt.Errorf("failed to read section file '%s': %v\n", sectionPath, err)- return- }-- sectionContent := string(sectionBytes)-- // replace the section in the original file- fileContent = strings.Replace(fileContent, origSection, sectionContent, 1)- }-- // ensure directory exists- err = os.MkdirAll(filepath.Dir(planFilesPath), os.ModePerm)- if err != nil {- log.Printf("failed to create directory: %s\n", err)- errCh <- fmt.Errorf("failed to create directory: %s\n", err)- return- }-- // write the file- err = os.WriteFile(planFilesPath, []byte(fileContent), 0644)- if err != nil {- log.Printf("failed to write file '%s': %v\n", planFilesPath, err)- errCh <- fmt.Errorf("failed to write file '%s': %v\n", planFilesPath, err)- return- }-- // log.Printf("File written successfully: %s\n", planFilesPath)- doneCh <- true- }(filePath)- }-- for numWritten < len(filePaths) {- select {- case err := <-errCh:- return err- case <-doneCh:- numWritten++- // log.Printf("Number of files written: %d\n", numWritten)- }- }-- // log.Println("Completed writeFilesFromSections.")-- return nil-}diff --git a/server/model/proposal/confirm.go b/server/model/proposal/confirm.goindex 62dd12b9..e32f3d27 100644--- a/server/model/proposal/confirm.go+++ b/server/model/proposal/confirm.go@@ -15,6 +15,148 @@ import ("github.com/sashabaranov/go-openai/jsonschema")+const systemPrompt = `+[YOUR INSTRUCTIONS]++You apply changes from a plan to a given code file. You can either us the 'writeEntireFile' function to write the entire file, or the 'writeReplacements' function to write a list of replacements to apply to the file.++If the current state of the file within the plan is included, apply your changes to the current state of the file.++Decide whether it is more efficient to rewrite the entire file or a list of replacements. Do whichever will use fewer tokens to update the file. 'writeReplacement' is more efficient if you are only changing a small amount of text. 'writeEntireFile' is more efficient if you are changing a large amount of text.++A. If you are using the 'writeEntireFile' function, call it with the full content of the file as raw text, including any updates from the previous response. Ouput the entire updated file.++B. If you are using the 'writeReplacements' function, call it with a list of replacements to apply to the file. Each replacement is an object with two properties: 'old' and 'new'. 'old' is the old text to replace, and 'new' is the new text to replace it with. You can include as many replacements as you want. You must include at least one replacement.++- The 'new' text must include the full text of the replacement without any placeholders or references to the original file.+- The 'old' text must be a substring of the current file.+- The 'old' text must not overlap with any other 'old' text in the list of replacements.++Replacement examples below. Note: >>> and <<< indicate the start and end of an example response.++1.)+If the current file is:+` + "```" + `+package main++import "fmt"++func main() {+ fmt.Println("Hello, world!")+}+` + "```" + `++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:++writeReplacements({+ replacements: [+ {+ old: "import \"fmt\"",+ new: "import (\n\t\"fmt\"\n\t\"time\"\n)"+ },+ {+ old: "fmt.Println(\"Hello, world!\")",+ new: "fmt.Println(time.Now())"+ }+ }+})++2.)+If the current file is:+` + "```" + `+package helpers++func Add(a, b int) int {+ return a + b+}+` + "```" + `++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:++writeReplacements({+ replacements: [+ {+ old: "\n}",+ new: "\n}\n\nfunc Subtract(a, b int) int {\n\treturn a - b\n}"+ }+ ]+})++3.)+If the current file is:+` + "```" + `+package main++import "fmt"++func main() {+ fmt.Println("Hello, world!")+}+` + "```" + `++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:++writeReplacements({+ replacements: [+ {+ old: "fmt.Println(\"Hello, world!\")",+ new: "fmt.Println(\"Hello, world!\")\n\tfmt.Println(\"I love you!\")"+ }+ ]+})++[END INSTRUCTIONS]`+func confirmProposal(proposalId string, onStream types.OnStreamFunc) error {goEnv := os.Getenv("GOENV")if goEnv == "test" {@@ -66,25 +208,22 @@ func confirmProposal(proposalId string, onStream types.OnStreamFunc) error {}}- fmtStr := ""- fmtArgs := []interface{}{}-- if fileContext != nil {- fmtStr += "Original %s:\n```\n%s\n```"- fmtArgs = []interface{}{filePath, fileContext.Body}- }+ fmtStr := "\nCurrent state of %s:\n```\n%s\n```"+ fmtArgs := []interface{}{filePath}currentState := proposal.Request.CurrentPlan.Files[filePath]+ fmtStr += "\nCurrent state of %s:\n```\n%s\n```"if currentState != "" {- fmtStr += "\nCurrent state of %s in the plan:\n```\n%s\n```"- fmtArgs = append(fmtArgs, filePath, currentState)+ fmtArgs = append(fmtArgs, currentState)+ } else if fileContext != nil {+ fmtArgs = append(fmtArgs, fileContext.Body)}fileMessages := []openai.ChatCompletionMessage{}if fileContext != nil || currentState != "" {fileMessages = append(fileMessages, openai.ChatCompletionMessage{Role: openai.ChatMessageRoleSystem,- Content: fmt.Sprintf(fmtStr, fmtArgs...),+ Content: systemPrompt + "\n\n" + fmt.Sprintf(fmtStr, fmtArgs...),})}@@ -95,8 +234,8 @@ func confirmProposal(proposalId string, onStream types.OnStreamFunc) error {openai.ChatCompletionMessage{Role: openai.ChatMessageRoleUser,Content: fmt.Sprintf(`- Based on your previous response, call the 'write' function with the full content of the file or file section %s as raw text, including any updates. If the current state of the file+section within the plan is included above, apply your changes to the *current file+section*, not the original file+section. If there is no current file+section, apply your changes to the original file+section. You must include the entire file+section and not leave anything out, even if it is already present the original file+section. Do not include any placeholders or references to the original file+section. Output the updated entire file. Only call the 'write' function in your reponse. Don't call any other function.- `, filePath),+ Based on your instructions, apply the changes from the plan to %s. You must call either the 'writeReplacements' function or the 'writeEntireFile' function, depending on which is a more efficient way to apply the changes. Don't call any other function.+ `, filePath),})fmt.Println("Calling model for file: " + filePath)@@ -107,17 +246,43 @@ func confirmProposal(proposalId string, onStream types.OnStreamFunc) error {modelReq := openai.ChatCompletionRequest{Model: openai.GPT4,Functions: []openai.FunctionDefinition{{- Name: "write",+ Name: "writeEntireFile",Parameters: &jsonschema.Definition{Type: jsonschema.Object,Properties: map[string]jsonschema.Definition{"content": {Type: jsonschema.String,- Description: "The full content of the file+section, including any updates from the previous response, as raw text",+ Description: "The full content of the file, including any updates from the previous response, as raw text",},},Required: []string{"content"},},+ }, {+ Name: "writeReplacements",+ Parameters: &jsonschema.Definition{+ Type: jsonschema.Object,+ Properties: map[string]jsonschema.Definition{+ "replacements": {+ Type: jsonschema.Array,+ Description: "A list of replacements to apply to the file",+ Items: &jsonschema.Definition{+ Type: jsonschema.Object,+ Properties: map[string]jsonschema.Definition{+ "old": {+ Type: jsonschema.String,+ Description: "The old text to replace",+ },+ "new": {+ Type: jsonschema.String,+ Description: "The new text to replace it with",+ },+ },+ Required: []string{"old", "new"},+ },+ },+ },+ Required: []string{"replacements"},+ },}},Messages: fileMessages,}@@ -187,18 +352,16 @@ func confirmProposal(proposalId string, onStream types.OnStreamFunc) error {}} else {- onError(fmt.Errorf("Stream finished without 'write' function call. Reason: %s", choice.FinishReason))+ onError(fmt.Errorf("Stream finished without a function call. Reason: %s", choice.FinishReason))return}-- return}var content stringdelta := response.Choices[0].Deltaif delta.FunctionCall == nil {- fmt.Printf("\nStream received data not for 'write' function call")+ fmt.Printf("\nStream received data not for a function call")continue} else {content = delta.FunctionCall.Arguments@@ -221,8 +384,10 @@ func confirmProposal(proposalId string, onStream types.OnStreamFunc) error {}onStream(string(chunkJson), nil)}+}}()+}(filePath)}diff --git a/server/model/proposal/create.go b/server/model/proposal/create.goindex 9cf72618..73d2fb7f 100644--- a/server/model/proposal/create.go+++ b/server/model/proposal/create.go@@ -28,17 +28,17 @@ const systemMessageHead = `You are Plandex, an AI programming and system adminis- Ask the user for more information or context and stop there.2. Decide whether this task is small enough to be completed in a single response.- a. If so, write out the code to complete the task. Precede the code block with the file path + section like this '- file_path-section_num:'--for example:- - src/main.rs-1:- - lib/utils.go-2:- - main.py-8:- File+section paths should always come *before* the opening triple backticks of a code block. They should *not* be included in the code block itself.- File+section paths should appear *immediately* before the opening triple backticks of a code block. There should be *no other lines* between the file path and the code block. Any explanations should come either *before the file path or after the code block.*+ a. If so, write out the code to complete the task. Precede the code block with the file path like this '- file_path:'--for example:+ - src/main.rs:+ - lib/utils.go:+ - main.py:+ File paths should always come *before* the opening triple backticks of a code block. They should *not* be included in the code block itself.+ File paths should appear *immediately* before the opening triple backticks of a code block. There should be *no other lines* between the file path and the code block. Any explanations should come either *before the file path or after the code block.*b. If not:- Explicitly say "I will break this large task into subtasks."- Divide the task into smaller subtasks and list them in a numbered list. Stop there.- Always precede code blocks the file path+section as described above in 2a. Code must *always* be labelled with the path+section.+ Always precede code blocks the file path as described above in 2a. Code must *always* be labelled with the path.Every file you reference should either exist in the context directly or be a new file that will be created in the same base directory a file in the context. For example, if there is a file in context at path 'lib/utils.go', you can create a new file at path 'lib/utils_test.go' but *not* at path 'src/lib/utils.go'.@@ -46,7 +46,7 @@ const systemMessageHead = `You are Plandex, an AI programming and system adminisDon't include unnecessary comments in code. Lean towards no comments as much as you can. If you must include a comment to make the code understandable, be sure it is concise. Don't use comments to communicate with the user.- An exception to the above instructions on comments are if a file+section block is empty because you removed everything in it. In that case, leave a brief one-line comment starting with 'Plandex: removed' that says what was removed so that the file+section block isn't empty.+ An exception to the above instructions on comments are if a file block is empty because you removed everything in it. In that case, leave a brief one-line comment starting with 'Plandex: removed' that says what was removed so that the file block isn't empty.At the end of a plan, you can suggest additional iterations to make the plan better. You can also ask the user to load more files or information into context if it would help you make a better plan.` +"\n```\n\n" +@@ -54,7 +54,7 @@ const systemMessageHead = `You are Plandex, an AI programming and system adminisvar systemHeadNumTokens = shared.GetNumTokens(systemMessageHead)-const promptWrapperFormatStr = "The user's latest prompt:\n```\n%s\n```\n\nPlease respond according to the 'Your instructions' section above. Remember to precede code blocks with the file path+section *exactly* as described in 2a. Do not use any other formatting for file paths or file sections."+const promptWrapperFormatStr = "The user's latest prompt:\n```\n%s\n```\n\nPlease respond according to the 'Your instructions' section above. Remember to precede code blocks with the file path *exactly* as described in 2a. Do not use any other formatting for file paths."var promptWrapperTokens = shared.GetNumTokens(fmt.Sprintf(promptWrapperFormatStr, ""))diff --git a/server/model/sectionize.go b/server/model/sectionize.goindex 519a9476..d2f02500 100644--- a/server/model/sectionize.go+++ b/server/model/sectionize.go@@ -49,12 +49,12 @@ func Sectionize(text string) ([]byte, error) {1a. If the text is code, try to group together related operations.1b. If the text is natural language, try to group together related ideas.- 2. Call the 'sectionized' function with the the 'sections' parameter. For each section, provide a string containing *just the first line that begins the section.*+ 2. Call the 'sectionized' function with the the 'sections' parameter. For each section, provide a string containing *just the first several distinguishing tokens that begin the section.*When breaking up the text into sections, follow these guidelines.- Sections should be roughly 50-100 lines in size.- - A file should be broken up into no more than 5-10 sections.- - For a short file, it's good to have a small number of sections, like 2-3 sections.+ - A long file should be broken up into no more than 5-7 sections.+ - A short file should have 2-3 sections.- Sections should be understandable in isolation.- If in doubt, lean towards fewer sections rather than more sections.- Blocks of code that are commented out should be given their own sections.diff --git a/shared/stream.go b/shared/stream.goindex 522bbb37..71494bb8 100644--- a/shared/stream.go+++ b/shared/stream.go@@ -48,3 +48,12 @@ func NewPlanStreamState() *fsm.FSM {type StreamedFile struct {Content string `json:"content"`}++type Replacement struct {+ Old string `json:"old"`+ New string `json:"new"`+}++type StreamedReplacements struct {+ Replacements []Replacement `json:"replacements"`+}diff --git a/shared/types.go b/shared/types.goindex d36eab1e..f639155a 100644--- a/shared/types.go+++ b/shared/types.go@@ -64,7 +64,6 @@ type ModelContextState struct {}type PlanChunk struct {- Type string `json:"type"`Path string `json:"path"`Content string `json:"content"`}