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
Fix for handling files that are loaded into context and later deleted from the file system, fixes #47
Dane Schneider5036d0238ff2
diff --git a/app/cli/fs/fs.go b/app/cli/fs/fs.goindex b604df29..8fd858c3 100644--- a/app/cli/fs/fs.go+++ b/app/cli/fs/fs.go@@ -156,7 +156,47 @@ func GetPaths(baseDir, currentDir string) (*ProjectPaths, error) {var mu sync.MutexnumRoutines := 0+ deletedFiles := map[string]bool{}+if isGitRepo {++ // Use git status to find deleted files+ numRoutines+++ go func() {+ cmd := exec.Command("git", "rev-parse", "--show-toplevel")+ output, err := cmd.Output()+ if err != nil {+ errCh <- fmt.Errorf("error getting git root: %s", err)+ return+ }+ repoRoot := strings.TrimSpace(string(output))++ cmd = exec.Command("git", "status", "--porcelain")+ cmd.Dir = baseDir+ out, err := cmd.Output()+ if err != nil {+ errCh <- fmt.Errorf("error getting git status: %s", err)+ }++ lines := strings.Split(string(out), "\n")++ for _, line := range lines {+ line = strings.TrimSpace(line)+ if strings.HasPrefix(line, "D ") {+ path := strings.TrimSpace(line[2:])+ absPath := filepath.Join(repoRoot, path)+ relPath, err := filepath.Rel(currentDir, absPath)+ if err != nil {+ errCh <- fmt.Errorf("error getting relative path: %s", err)+ return+ }+ deletedFiles[relPath] = true+ }+ }++ errCh <- nil+ }()+// combine `git ls-files` and `git ls-files --others --exclude-standard`// to get all files in the repo@@ -320,6 +360,11 @@ func GetPaths(baseDir, currentDir string) (*ProjectPaths, error) {activePaths[dir] = true}+ // remove deleted files from active paths+ for path := range deletedFiles {+ delete(activePaths, path)+ }+ignoredPaths := map[string]string{}for path := range allPaths {if _, ok := activePaths[path]; !ok {diff --git a/app/cli/lib/context_update.go b/app/cli/lib/context_update.goindex 2e6bdea9..3efdd0b7 100644--- a/app/cli/lib/context_update.go+++ b/app/cli/lib/context_update.go@@ -4,6 +4,7 @@ import ("crypto/sha256""encoding/hex""fmt"+ "log""os""plandex/api""plandex/fs"@@ -32,61 +33,105 @@ func MustCheckOutdatedContext(quiet bool, maybeContexts []*shared.Context) (contterm.StopSpinner()- if len(outdatedRes.UpdatedContexts) == 0 {+ if len(outdatedRes.UpdatedContexts) == 0 && len(outdatedRes.RemovedContexts) == 0 {if !quiet {fmt.Println("β Context is up to date")}return false, false}- types := []string{}- if outdatedRes.NumFiles > 0 {- lbl := "file"- if outdatedRes.NumFiles > 1 {- lbl = "files"+ if len(outdatedRes.UpdatedContexts) > 0 {+ types := []string{}+ if outdatedRes.NumFiles > 0 {+ lbl := "file"+ if outdatedRes.NumFiles > 1 {+ lbl = "files"+ }+ lbl = strconv.Itoa(outdatedRes.NumFiles) + " " + lbl+ types = append(types, lbl)}- lbl = strconv.Itoa(outdatedRes.NumFiles) + " " + lbl- types = append(types, lbl)- }- if outdatedRes.NumUrls > 0 {- lbl := "url"- if outdatedRes.NumUrls > 1 {- lbl = "urls"+ if outdatedRes.NumUrls > 0 {+ lbl := "url"+ if outdatedRes.NumUrls > 1 {+ lbl = "urls"+ }+ lbl = strconv.Itoa(outdatedRes.NumUrls) + " " + lbl+ types = append(types, lbl)}- lbl = strconv.Itoa(outdatedRes.NumUrls) + " " + lbl- types = append(types, lbl)- }- if outdatedRes.NumTrees > 0 {- lbl := "directory tree"- if outdatedRes.NumTrees > 1 {- lbl = "directory trees"+ if outdatedRes.NumTrees > 0 {+ lbl := "directory tree"+ if outdatedRes.NumTrees > 1 {+ lbl = "directory trees"+ }+ lbl = strconv.Itoa(outdatedRes.NumTrees) + " " + lbl+ types = append(types, lbl)}- lbl = strconv.Itoa(outdatedRes.NumTrees) + " " + lbl- types = append(types, lbl)- }- var msg string- if len(types) <= 2 {- msg += strings.Join(types, " and ")- } else {- for i, add := range types {- if i == len(types)-1 {- msg += ", and " + add- } else {- msg += ", " + add+ var msg string+ if len(types) <= 2 {+ msg += strings.Join(types, " and ")+ } else {+ for i, add := range types {+ if i == len(types)-1 {+ msg += ", and " + add+ } else {+ msg += ", " + add+ }}}- }- phrase := "have been"- if len(outdatedRes.UpdatedContexts) == 1 {- phrase = "has been"+ phrase := "have been"+ if len(outdatedRes.UpdatedContexts) == 1 {+ phrase = "has been"+ }++ color.New(term.ColorHiCyan, color.Bold).Printf("%s in context %s modified π\n\n", msg, phrase)++ tableString := tableForContextOutdated(outdatedRes.UpdatedContexts, outdatedRes.TokenDiffsById)+ fmt.Println(tableString)}- color.New(term.ColorHiCyan, color.Bold).Printf("%s in context %s modified π\n\n", msg, phrase)- tableString := tableForContextOutdated(outdatedRes)- fmt.Println(tableString)+ if len(outdatedRes.RemovedContexts) > 0 {+ types := []string{}+ if outdatedRes.NumFilesRemoved > 0 {+ lbl := "file"+ if outdatedRes.NumFilesRemoved > 1 {+ lbl = "files"+ }+ lbl = strconv.Itoa(outdatedRes.NumFilesRemoved) + " " + lbl+ types = append(types, lbl)+ }+ if outdatedRes.NumTreesRemoved > 0 {+ lbl := "directory tree"+ if outdatedRes.NumTreesRemoved > 1 {+ lbl = "directory trees"+ }+ lbl = strconv.Itoa(outdatedRes.NumTreesRemoved) + " " + lbl+ types = append(types, lbl)+ }- fmt.Println()+ var msg string+ if len(types) <= 2 {+ msg += strings.Join(types, " and ")+ } else {+ for i, add := range types {+ if i == len(types)-1 {+ msg += ", and " + add+ } else {+ msg += ", " + add+ }+ }+ }++ phrase := "have been"+ if len(outdatedRes.RemovedContexts) == 1 {+ phrase = "has been"+ }++ color.New(term.ColorHiCyan, color.Bold).Printf("%s in context %s removed π\n\n", msg, phrase)++ tableString := tableForContextOutdated(outdatedRes.RemovedContexts, outdatedRes.TokenDiffsById)+ fmt.Println(tableString)+ }var confirmed bool@@ -105,10 +150,10 @@ func MustCheckOutdatedContext(quiet bool, maybeContexts []*shared.Context) (cont}-func MustUpdateContext(maybeContexts []*shared.Context) {+func MustUpdateContext(maybeUpdateContexts []*shared.Context) {term.StartSpinner("π Updating context...")- updateRes, err := UpdateContext(maybeContexts)+ updateRes, err := UpdateContext(maybeUpdateContexts)if err != nil {term.StopSpinner()@@ -132,6 +177,8 @@ func CheckOutdatedContext(maybeContexts []*shared.Context) (*types.ContextOutdatfunc checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.Context) (*types.ContextOutdatedResult, error) {var contexts []*shared.Context+ log.Println("Checking outdated context")+if maybeContexts == nil {var apiErr *shared.ApiErrorcontexts, apiErr = api.Client.ListContext(CurrentPlanId, CurrentBranch)@@ -150,6 +197,8 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.Cvar numFiles intvar numUrls intvar numTrees int+ var numFilesRemoved int+ var numTreesRemoved intvar mu sync.Mutexvar wg sync.WaitGroupcontextsById := map[string]*shared.Context{}@@ -181,12 +230,14 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.Cwg.Add(1)go func(context *shared.Context) {defer wg.Done()-+mu.Lock()defer mu.Unlock()if _, err := os.Stat(context.FilePath); os.IsNotExist(err) {deleteIds[context.Id] = true+ numFilesRemoved+++ tokenDiffsById[context.Id] = -context.NumTokensreturn}@@ -223,6 +274,17 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.Cwg.Add(1)go func(context *shared.Context) {defer wg.Done()++ // check if the directory tree exists+ if _, err := os.Stat(context.FilePath); os.IsNotExist(err) {+ mu.Lock()+ defer mu.Unlock()+ deleteIds[context.Id] = true+ numTreesRemoved+++ tokenDiffsById[context.Id] = -context.NumTokens+ return+ }+flattenedPaths, err := ParseInputPaths([]string{context.FilePath}, &types.LoadContextParams{NamesOnly: true,ForceSkipIgnore: context.ForceSkipIgnore,@@ -318,7 +380,8 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.Cvar msg stringvar hasConflicts bool- if len(req) == 0 && len(deleteIds) == 0{+ if len(req) == 0 && len(deleteIds) == 0 {+ log.Println("return context is up to date res")return &types.ContextOutdatedResult{Msg: "Context is up to date",}, nil@@ -330,6 +393,12 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.CfilesToLoad[context.FilePath] = context.Body}}+ for id := range deleteIds {+ context := contextsById[id]+ if context.ContextType == shared.ContextFileType {+ filesToLoad[context.FilePath] = ""+ }+ }var err errorhasConflicts, err = checkContextConflicts(filesToLoad)@@ -344,7 +413,7 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.C}msg = res.Msg}-+if len(deleteIds) > 0 {req, apiErr := api.Client.DeleteContext(CurrentPlanId, CurrentBranch, shared.DeleteContextRequest{Ids: deleteIds,@@ -367,20 +436,25 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.Cfmt.Println()}+ var removedContexts []*shared.Context+ for id := range deleteIds {+ removedContexts = append(removedContexts, contextsById[id])+ }+return &types.ContextOutdatedResult{Msg: msg,UpdatedContexts: updatedContexts,+ RemovedContexts: removedContexts,TokenDiffsById: tokenDiffsById,NumFiles: numFiles,NumUrls: numUrls,NumTrees: numTrees,+ NumFilesRemoved: numFilesRemoved,+ NumTreesRemoved: numTreesRemoved,}, nil}-func tableForContextOutdated(updateRes *types.ContextOutdatedResult) string {- updatedContexts := updateRes.UpdatedContexts- tokenDiffsById := updateRes.TokenDiffsById-+func tableForContextOutdated(updatedContexts []*shared.Context, tokenDiffsById map[string]int) string {if len(updatedContexts) == 0 {return ""}diff --git a/app/cli/types/types.go b/app/cli/types/types.goindex bf530029..9922e8f5 100644--- a/app/cli/types/types.go+++ b/app/cli/types/types.go@@ -28,10 +28,13 @@ type LoadContextParams struct {type ContextOutdatedResult struct {Msg stringUpdatedContexts []*shared.Context+ RemovedContexts []*shared.ContextTokenDiffsById map[string]intNumFiles intNumUrls intNumTrees int+ NumFilesRemoved int+ NumTreesRemoved int}const (diff --git a/app/server/db/context_helpers.go b/app/server/db/context_helpers.goindex 5500c773..34b7f416 100644--- a/app/server/db/context_helpers.go+++ b/app/server/db/context_helpers.go@@ -98,13 +98,16 @@ func GetContext(orgId, planId, contextId string, includeBody bool) (*Context, erreturn &context, nil}-func ContextRemove(contexts []*Context) error {+func ContextRemove(orgId, planId string, contexts []*Context) error {// remove filesnumFiles := len(contexts) * 2+ filesToUpdate := make(map[string]string)+errCh := make(chan error, numFiles)for _, context := range contexts {- contextDir := getPlanContextDir(context.OrgId, context.PlanId)+ filesToUpdate[context.FilePath] = ""+ contextDir := getPlanContextDir(orgId, planId)for _, ext := range []string{".meta", ".body"} {go func(context *Context, dir, ext string) {errCh <- os.Remove(filepath.Join(dir, context.Id+ext))@@ -119,6 +122,11 @@ func ContextRemove(contexts []*Context) error {}}+ err := invalidateConflictedResults(orgId, planId, filesToUpdate)+ if err != nil {+ return fmt.Errorf("error invalidating conflicted results: %v", err)+ }+return nil}@@ -497,7 +505,7 @@ func UpdateContexts(params UpdateContextsParams) (*shared.UpdateContextResponse,}, nil}-func invalidateConflictedResults(orgId, planId string, filesToLoad map[string]string) error {+func invalidateConflictedResults(orgId, planId string, filesToUpdate map[string]string) error {descriptions, err := GetConvoMessageDescriptions(orgId, planId)if err != nil {return fmt.Errorf("error getting pending build descriptions: %v", err)@@ -513,7 +521,7 @@ func invalidateConflictedResults(orgId, planId string, filesToLoad map[string]streturn fmt.Errorf("error getting current plan state: %v", err)}- conflictPaths := currentPlan.PlanResult.FileResultsByPath.ConflictedPaths(filesToLoad)+ conflictPaths := currentPlan.PlanResult.FileResultsByPath.ConflictedPaths(filesToUpdate)// log.Println("invalidateConflictedResults - Conflicted paths:", conflictPaths)diff --git a/app/server/handlers/plans_context.go b/app/server/handlers/plans_context.goindex 585b4f18..597eb04c 100644--- a/app/server/handlers/plans_context.go+++ b/app/server/handlers/plans_context.go@@ -277,7 +277,7 @@ func DeleteContextHandler(w http.ResponseWriter, r *http.Request) {}}- err = db.ContextRemove(toRemove)+ err = db.ContextRemove(auth.OrgId, planId, toRemove)if err != nil {log.Printf("Error deleting contexts: %v\n", err)diff --git a/app/server/model/plan/build_exec.go b/app/server/model/plan/build_exec.goindex 43854560..ec29f241 100644--- a/app/server/model/plan/build_exec.go+++ b/app/server/model/plan/build_exec.go@@ -128,6 +128,7 @@ func (buildState *activeBuildStreamState) execPlanBuild(activeBuild *types.Activ}// stream initial status to client+ log.Printf("streaming initial build info for file %s\n", filePath)buildInfo := &shared.BuildInfo{Path: filePath,NumTokens: 0,diff --git a/app/server/model/plan/tell_exec.go b/app/server/model/plan/tell_exec.goindex 68044c9b..b56188af 100644--- a/app/server/model/plan/tell_exec.go+++ b/app/server/model/plan/tell_exec.go@@ -380,6 +380,9 @@ func execTellPlan(return}+ log.Printf("Tell plan: found %d pending builds\n", len(pendingBuildsByPath))+ // spew.Dump(pendingBuildsByPath)x+buildState := &activeBuildStreamState{client: client,auth: auth,diff --git a/releases/server/versions/0.8.4.md b/releases/server/versions/0.8.4.mdindex ecfb33a8..9ed64182 100644--- a/releases/server/versions/0.8.4.md+++ b/releases/server/versions/0.8.4.md@@ -1 +1,2 @@-- Add support for new OpenAI models: `gpt-4-turbo` and `gpt-4-turbo-2024-04-09` -- these models haven't been set as defaults yet since they need more testing, but can be used with the `set-model` command\ No newline at end of file+- Add support for new OpenAI models: `gpt-4-turbo` and `gpt-4-turbo-2024-04-09` -- these models haven't been set as defaults yet since they need more testing, but can be used with the `set-model` command+- Fix for handling files that are loaded into context and later deleted from the file system (https://github.com/plandex-ai/plandex/issues/47)\ No newline at end of file