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
Enhance git operations with improved file state handling and rewind functionality
Dane Schneider9305d326d5f0
diff --git a/app/cli/lib/apply.go b/app/cli/lib/apply.goindex 5a91b201..acd70871 100644--- a/app/cli/lib/apply.go+++ b/app/cli/lib/apply.go@@ -180,7 +180,7 @@ func MustApplyPlanAttempt(term.ResumeSpinner()}- updatedFiles, toRollback, err = applyFiles(toApply, toRemove)+ updatedFiles, toRollback, err = ApplyFiles(toApply, toRemove)if err != nil {onErr("failed to apply files: %s", err)@@ -269,7 +269,6 @@ func handleApplyScript(confirmed = true} else {confirmed, err = term.ConfirmYesNo("Execute now?")-if err != nil {onErr("failed to get confirmation user input: %s", err)}@@ -480,7 +479,6 @@ func execApplyScript(fmt.Println("✅ Commands succeeded")onSuccess()}-}func apiApplyPlan(planId, branch string) (string, error) {@@ -520,9 +518,7 @@ func commitApplied(autoCommit bool, commitSummary string, updatedFiles []string,fmt.Println()// fmt.Println("ℹ️ Only the files that Plandex is updating will be included the commit. Any other changes, staged or unstaged, will remain exactly as they are.")// fmt.Println()-confirmed, err = term.ConfirmYesNo("Commit Plandex updates now?")-if err != nil {return fmt.Errorf("failed to get confirmation user input: %s", err)}@@ -531,12 +527,9 @@ func commitApplied(autoCommit bool, commitSummary string, updatedFiles []string,if confirmed {// Commit the changesmsg := currentPlanState.PendingChangesSummaryForApply(commitSummary)-// log.Println("Committing changes with message:")// log.Println(msg)-// spew.Dump(currentPlanState)-err = GitAddAndCommitPaths(fs.ProjectRoot, msg, updatedFiles, true)if err != nil {return fmt.Errorf("failed to commit changes: %s", err.Error())@@ -546,7 +539,7 @@ func commitApplied(autoCommit bool, commitSummary string, updatedFiles []string,return nil}-func applyFiles(toApply map[string]string, toRemove map[string]bool) ([]string, *types.ApplyRollbackPlan, error) {+func ApplyFiles(toApply map[string]string, toRemove map[string]bool) ([]string, *types.ApplyRollbackPlan, error) {var updatedFiles []stringtoRevert := map[string]types.ApplyReversion{}var toRemoveOnRollback []string@@ -561,12 +554,10 @@ func applyFiles(toApply map[string]string, toRemove map[string]bool) ([]string,errCh <- nilcontinue}-go func(path, content string) {// Compute destination pathdstPath := filepath.Join(fs.ProjectRoot, path)content = strings.ReplaceAll(content, "\\`\\`\\`", "```")-// Check if the file existsvar exists boolvar mode os.FileMode@@ -586,12 +577,10 @@ func applyFiles(toApply map[string]string, toRemove map[string]bool) ([]string,if exists {// read file contentbytes, err := os.ReadFile(dstPath)-if err != nil {errCh <- fmt.Errorf("failed to read %s: %s", dstPath, err.Error())return}-// Check if the file has changedif string(bytes) == content {// log.Println("File is unchanged, skipping")@@ -608,7 +597,6 @@ func applyFiles(toApply map[string]string, toRemove map[string]bool) ([]string,updatedFiles = append(updatedFiles, path)toRemoveOnRollback = append(toRemoveOnRollback, dstPath)mu.Unlock()-// Create the directory if it doesn't existerr := os.MkdirAll(filepath.Dir(dstPath), 0755)if err != nil {@@ -616,14 +604,12 @@ func applyFiles(toApply map[string]string, toRemove map[string]bool) ([]string,return}}-// Write the fileerr = os.WriteFile(dstPath, []byte(content), 0644)if err != nil {errCh <- fmt.Errorf("failed to write %s: %s", dstPath, err.Error())return}-errCh <- nil}(path, content)}@@ -636,7 +622,6 @@ func applyFiles(toApply map[string]string, toRemove map[string]bool) ([]string,}// Compute destination pathdstPath := filepath.Join(fs.ProjectRoot, path)-// Check if the file existsvar exists boolvar mode os.FileMode@@ -652,25 +637,21 @@ func applyFiles(toApply map[string]string, toRemove map[string]bool) ([]string,return}}-if exists {content, err := os.ReadFile(dstPath)if err != nil {errCh <- fmt.Errorf("failed to read %s: %s", dstPath, err.Error())return}-err = os.Remove(dstPath)if err != nil && !os.IsNotExist(err) {errCh <- fmt.Errorf("failed to remove %s: %s", dstPath, err.Error())return}-mu.Lock()toRevert[dstPath] = types.ApplyReversion{Content: string(content), Mode: mode}mu.Unlock()}-errCh <- nil}(path, remove)}@@ -700,7 +681,6 @@ func applyFiles(toApply map[string]string, toRemove map[string]bool) ([]string,func Rollback(rollbackPlan *types.ApplyRollbackPlan, msg bool) error {errCh := make(chan error, len(rollbackPlan.ToRevert)+len(rollbackPlan.ToRemove))-for path, revert := range rollbackPlan.ToRevert {go func(path string, revert types.ApplyReversion) {err := os.WriteFile(path, []byte(revert.Content), revert.Mode)@@ -711,7 +691,6 @@ func Rollback(rollbackPlan *types.ApplyRollbackPlan, msg bool) error {errCh <- nil}(path, revert)}-for _, path := range rollbackPlan.ToRemove {go func(path string) {err := os.Remove(path)@@ -722,30 +701,25 @@ func Rollback(rollbackPlan *types.ApplyRollbackPlan, msg bool) error {errCh <- nil}(path)}-go func() {var err errorprojectPaths, err := fs.GetProjectPaths(fs.ProjectRoot)if err != nil {errCh <- fmt.Errorf("failed to get project paths: %v", err)}-var toRemove []stringfor path := range projectPaths.ActivePaths {if _, ok := rollbackPlan.PreviousProjectPaths.ActivePaths[path]; !ok {toRemove = append(toRemove, path)}}-pathsErrCh := make(chan error, len(toRemove))-for _, path := range toRemove {go func(path string) {err := os.Remove(path)pathsErrCh <- err}(path)}-for range toRemove {err := <-pathsErrChif err != nil {@@ -753,26 +727,20 @@ func Rollback(rollbackPlan *types.ApplyRollbackPlan, msg bool) error {return}}-errCh <- nil}()-errs := []error{}-for i := 0; i < len(rollbackPlan.ToRevert)+len(rollbackPlan.ToRemove)+1; i++ {err := <-errChif err != nil {errs = append(errs, err)}}-if len(errs) > 0 {return fmt.Errorf("failed to rollback: %s", errs)}-if msg {fmt.Println("🚫 Rolled back all changes")}-return nil}diff --git a/app/cli/lib/git.go b/app/cli/lib/git.goindex 579e14de..75d8107a 100644--- a/app/cli/lib/git.go+++ b/app/cli/lib/git.go@@ -4,8 +4,10 @@ import ("fmt""log""os/exec"+ "regexp""strings""sync"+ "time")var gitMutex sync.Mutex@@ -212,6 +214,19 @@ func GitCheckoutFile(path string) error {return nil}+const GitLogTimestampFormat = "Mon Jan 2, 2006 | 3:04:05pm"++var GitLogTimestampRegex = regexp.MustCompile(`\w{3} \w{3} \d{1,2}, \d{4} \| \d{1,2}:\d{2}:\d{2}(am|pm) UTC`)++func GetGitLogTimestamp(log string) (time.Time, error) {+ matches := GitLogTimestampRegex.FindStringSubmatch(log)+ if len(matches) < 2 {+ return time.Time{}, fmt.Errorf("no timestamp found in log")+ }++ return time.Parse(GitLogTimestampFormat, strings.TrimSuffix(matches[0], " UTC"))+}+func parseConflictFiles(gitOutput string) []string {var conflictFiles []stringlines := strings.Split(gitOutput, "\n")diff --git a/app/cli/lib/rewind.go b/app/cli/lib/rewind.gonew file mode 100644index 00000000..c727486d--- /dev/null+++ b/app/cli/lib/rewind.go@@ -0,0 +1,318 @@+package lib++import (+ "fmt"+ "os"+ "path/filepath"+ "plandex-cli/fs"+ shared "plandex-shared"+ "sort"+ "sync"+ "time"+)++// GetUndonePlanApplies returns the list of PlanApplies that will be undone by rewinding to targetSHA.+// An apply is considered "undone" if its timestamp is after OR equal to the target SHA's timestamp,+// since we want to revert to the state before the target SHA.+func GetUndonePlanApplies(currentState *shared.CurrentPlanState, timestamp time.Time) []*shared.PlanApply {+ if currentState == nil {+ return nil+ }++ var undoneApplies []*shared.PlanApply+ for _, apply := range currentState.PlanApplies {+ // Include applies after OR equal to target time+ if !apply.CreatedAt.Before(timestamp) {+ undoneApplies = append(undoneApplies, apply)+ }+ }++ // Sort by creation time ascending to ensure proper order+ sort.Slice(undoneApplies, func(i, j int) bool {+ return undoneApplies[i].CreatedAt.Before(undoneApplies[j].CreatedAt)+ })++ return undoneApplies+}++// GetAffectedFilePaths extracts the set of file paths that were modified by the given PlanApplies.+// It looks up each PlanFileResultId in the current state to get the actual file paths.+func GetAffectedFilePaths(currentState *shared.CurrentPlanState, applies []*shared.PlanApply) map[string]bool {+ if currentState == nil || currentState.PlanResult == nil {+ return nil+ }++ // First collect all file result IDs+ fileResultIds := make(map[string]bool)+ for _, apply := range applies {+ if apply == nil {+ continue+ }+ for _, fileId := range apply.PlanFileResultIds {+ if fileId != "" {+ fileResultIds[fileId] = true+ }+ }+ }++ // Then get the actual file paths from the plan result+ affectedPaths := make(map[string]bool)+ for _, result := range currentState.PlanResult.Results {+ if result == nil {+ continue+ }++ // Skip if this result wasn't part of an undone apply+ if !fileResultIds[result.Id] {+ continue+ }++ // Skip if the result was rejected+ if result.RejectedAt != nil {+ continue+ }++ // Skip if the result was never applied+ if result.AppliedAt == nil {+ continue+ }++ // Validate path+ if result.Path == "" {+ continue+ }++ // Check if path is in plan context+ if currentState.ContextsByPath[result.Path] == nil {+ continue+ }++ affectedPaths[result.Path] = true+ }++ return affectedPaths+}++// RewindAnalysis captures all the information about a potential rewind operation+type RewindAnalysis struct {+ // Files that need to be modified when rewinding from current plan state to target plan state+ RequiredChanges map[string]string+ // Files that have been modified on disk relative to current plan state (potential conflicts)+ Conflicts map[string]bool+}++// AnalyzeRewind examines the three states (disk, current plan, target plan) to determine:+// 1. What files need to be changed to reach target state+// 2. Which of those changes would conflict with user modifications+func AnalyzeRewind(targetState, currentState *shared.CurrentPlanState) (*RewindAnalysis, error) {+ if targetState == nil || currentState == nil {+ return nil, fmt.Errorf("both target and current states must be provided")+ }++ // First determine what files need to be changed between current and target plan states+ requiredChanges := make(map[string]string)++ // Track all paths we need to examine for either changes or conflicts+ allPaths := make(map[string]bool)++ // Add paths from both states+ for path, context := range targetState.ContextsByPath {+ if context.ContextType != shared.ContextFileType {+ continue+ }+ allPaths[path] = true+ }+ for path, context := range currentState.ContextsByPath {+ if context.ContextType != shared.ContextFileType {+ continue+ }+ allPaths[path] = true+ }++ // For each path, check if content differs between current and target states+ for path := range allPaths {+ targetContent := ""+ if ctx := targetState.ContextsByPath[path]; ctx != nil {+ targetContent = ctx.Body+ }++ currentContent := ""+ if ctx := currentState.ContextsByPath[path]; ctx != nil {+ currentContent = ctx.Body+ }++ // If content differs between plan states, this is a required change+ if targetContent != currentContent {+ if targetContent == "" {+ // File should be removed+ requiredChanges[path] = ""+ } else {+ // File should be added or modified+ requiredChanges[path] = targetContent+ }+ }+ }++ // Now check for conflicts by comparing disk state with current plan state+ // A conflict exists if a file that needs to be changed has been modified on disk+ conflicts := make(map[string]bool)++ var mu sync.Mutex+ errCh := make(chan error, len(requiredChanges))++ for path := range requiredChanges {+ go func(path string) {+ var outErr error+ defer func() { errCh <- outErr }()++ // Get the content from current plan state+ currentContent := ""+ if ctx := currentState.ContextsByPath[path]; ctx != nil {+ currentContent = ctx.Body+ }++ // Get the actual file content from disk+ dstPath := filepath.Join(fs.ProjectRoot, path)+ diskContent, err := os.ReadFile(dstPath)+ if err != nil {+ if os.IsNotExist(err) {+ // If file doesn't exist on disk and current state has no content,+ // there's no conflict+ if currentContent == "" {+ return+ }+ // Otherwise it's a conflict because file was deleted+ mu.Lock()+ conflicts[path] = true+ mu.Unlock()+ return+ }+ outErr = fmt.Errorf("failed to read %s: %w", path, err)+ return+ }++ // If disk content differs from current plan state, we have a conflict+ if string(diskContent) != currentContent {+ mu.Lock()+ conflicts[path] = true+ mu.Unlock()+ }+ }(path)+ }++ // Collect any errors from goroutines+ for i := 0; i < len(requiredChanges); i++ {+ if err := <-errCh; err != nil {+ return nil, err+ }+ }++ return &RewindAnalysis{+ RequiredChanges: requiredChanges,+ Conflicts: conflicts,+ }, nil+}++// RemoveEmptyDirs recursively removes empty directories starting from the given path+func RemoveEmptyDirs(path string, baseDir string) error {+ // Check if the path is a directory+ info, err := os.Stat(path)+ if err != nil {+ if os.IsNotExist(err) {+ return nil+ }+ return err+ }+ if !info.IsDir() {+ return nil+ }++ // List directory contents+ entries, err := os.ReadDir(path)+ if err != nil {+ return err+ }++ // If directory has contents, leave it alone+ if len(entries) > 0 {+ return nil+ }++ // Directory is empty, remove it if it's not the base dir+ if path != baseDir {+ if err := os.Remove(path); err != nil {+ return err+ }+ }++ // Recursively check parent directory+ parent := filepath.Dir(path)+ if parent != baseDir && parent != path {+ return RemoveEmptyDirs(parent, baseDir)+ }++ return nil+}++// ApplyRewindChanges updates files on disk to match target state+func ApplyRewindChanges(requiredChanges map[string]string) error {+ if len(requiredChanges) == 0 {+ return nil+ }++ // Track directories that might need cleanup+ dirsToCheck := make(map[string]bool)++ errCh := make(chan error, len(requiredChanges))++ for path, content := range requiredChanges {+ go func(path, content string) {+ dstPath := filepath.Join(fs.ProjectRoot, path)++ if content == "" {+ // Remove the file+ err := os.Remove(dstPath)+ if err != nil && !os.IsNotExist(err) {+ errCh <- fmt.Errorf("failed to remove %s: %w", path, err)+ return+ }+ // Mark parent directory for cleanup+ parentDir := filepath.Dir(dstPath)+ dirsToCheck[parentDir] = true+ errCh <- nil+ return+ }++ // Ensure directory exists+ if err := os.MkdirAll(filepath.Dir(dstPath), 0755); err != nil {+ errCh <- fmt.Errorf("failed to create directory for %s: %w", path, err)+ return+ }++ // Write the file+ if err := os.WriteFile(dstPath, []byte(content), 0644); err != nil {+ errCh <- fmt.Errorf("failed to write %s: %w", path, err)+ return+ }++ errCh <- nil+ }(path, content)+ }++ // Collect any errors+ for i := 0; i < len(requiredChanges); i++ {+ if err := <-errCh; err != nil {+ return err+ }+ }++ // Clean up empty directories+ for dir := range dirsToCheck {+ if err := RemoveEmptyDirs(dir, fs.ProjectRoot); err != nil {+ // Log but don't fail the operation for directory cleanup errors+ fmt.Printf("Warning: failed to clean up directory %s: %v\n", dir, err)+ }+ }++ return nil+}diff --git a/app/server/db/git.go b/app/server/db/git.goindex c509c321..0fdd836c 100644--- a/app/server/db/git.go+++ b/app/server/db/git.go@@ -7,6 +7,7 @@ import ("os""os/exec""path/filepath"+ "runtime/debug""strconv""strings""time"@@ -51,9 +52,14 @@ func initGitRepo(dir string) error {}func GitAddAndCommit(orgId, planId, branch, message string) error {+ err := assertWriteOrRootLockSet(planId, branch)+ if err != nil {+ return err+ }+dir := getPlanDir(orgId, planId)- err := gitWriteOperation(func() error {+ err = gitWriteOperation(func() error {return gitAdd(dir, ".")}, fmt.Sprintf("GitAddAndCommit > gitAdd: plan=%s branch=%s", planId, branch))if err != nil {@@ -71,9 +77,14 @@ func GitAddAndCommit(orgId, planId, branch, message string) error {}func GitRewindToSha(orgId, planId, branch, sha string) error {+ err := assertWriteOrRootLockSet(planId, branch)+ if err != nil {+ return err+ }+dir := getPlanDir(orgId, planId)- err := gitWriteOperation(func() error {+ err = gitWriteOperation(func() error {return gitRewindToSha(dir, sha)}, fmt.Sprintf("GitRewindToSha > gitRewindToSha: plan=%s branch=%s", planId, branch))if err != nil {@@ -84,6 +95,11 @@ func GitRewindToSha(orgId, planId, branch, sha string) error {}func GetCurrentCommitSha(orgId, planId string) (sha string, err error) {+ err = assertAnyPlanLockSet(planId, "")+ if err != nil {+ return "", err+ }+dir := getPlanDir(orgId, planId)cmd := exec.Command("git", "-C", dir, "rev-parse", "HEAD")@@ -96,10 +112,41 @@ func GetCurrentCommitSha(orgId, planId string) (sha string, err error) {return sha, nil}+func GetCommitTime(orgId, planId, branch, ref string) (time.Time, error) {+ err := assertAnyPlanLockSet(planId, branch)+ if err != nil {+ return time.Time{}, err+ }++ dir := getPlanDir(orgId, planId)++ // Use git show to get the commit timestamp+ cmd := exec.Command("git", "-C", dir, "show", "-s", "--format=%ct", ref)+ output, err := cmd.Output()+ if err != nil {+ return time.Time{}, fmt.Errorf("error getting commit time for ref %s: %v", ref, err)+ }++ // Parse the Unix timestamp+ timestamp, err := strconv.ParseInt(strings.TrimSpace(string(output)), 10, 64)+ if err != nil {+ return time.Time{}, fmt.Errorf("error parsing commit timestamp for ref %s: %v", ref, err)+ }++ // Convert Unix timestamp to time.Time+ commitTime := time.Unix(timestamp, 0)+ return commitTime, nil+}+func GitResetToSha(orgId, planId, sha string) error {+ err := assertWriteOrRootLockSet(planId, "")+ if err != nil {+ return err+ }+dir := getPlanDir(orgId, planId)- err := gitWriteOperation(func() error {+ err = gitWriteOperation(func() error {cmd := exec.Command("git", "-C", dir, "reset", "--hard", sha)_, err := cmd.Output()if err != nil {@@ -116,7 +163,37 @@ func GitResetToSha(orgId, planId, sha string) error {return nil}+func GitCheckoutSha(orgId, planId, sha string) error {+ err := assertWriteOrRootLockSet(planId, "")+ if err != nil {+ return err+ }++ dir := getPlanDir(orgId, planId)++ err = gitWriteOperation(func() error {+ cmd := exec.Command("git", "-C", dir, "checkout", sha)+ _, err := cmd.Output()+ if err != nil {+ return fmt.Errorf("error checking out git repository at SHA for dir: %s, sha: %s, err: %v", dir, sha, err)+ }++ return nil+ }, fmt.Sprintf("GitCheckoutSha > gitCheckout: plan=%s sha=%s", planId, sha))++ if err != nil {+ return fmt.Errorf("error checking out git repository at SHA for dir: %s, sha: %s, err: %v", dir, sha, err)+ }++ return nil+}+func GetGitCommitHistory(orgId, planId, branch string) (body string, shas []string, err error) {+ err = assertAnyPlanLockSet(planId, branch)+ if err != nil {+ return "", nil, err+ }+dir := getPlanDir(orgId, planId)body, shas, err = getGitCommitHistory(dir)@@ -128,6 +205,11 @@ func GetGitCommitHistory(orgId, planId, branch string) (body string, shas []stri}func GetLatestCommit(orgId, planId, branch string) (sha, body string, err error) {+ err = assertAnyPlanLockSet(planId, branch)+ if err != nil {+ return "", "", err+ }+dir := getPlanDir(orgId, planId)sha, body, err = getLatestCommit(dir)@@ -139,6 +221,11 @@ func GetLatestCommit(orgId, planId, branch string) (sha, body string, err error)}func GetLatestCommitShaBeforeTime(orgId, planId, branch string, before time.Time) (sha string, err error) {+ err = assertAnyPlanLockSet(planId, branch)+ if err != nil {+ return "", err+ }+dir := getPlanDir(orgId, planId)log.Printf("ADMIN - GetLatestCommitShaBeforeTime - dir: %s, before: %s", dir, before.Format("2006-01-02T15:04:05Z"))@@ -176,13 +263,18 @@ func GetLatestCommitShaBeforeTime(orgId, planId, branch string, before time.Time}func GitListBranches(orgId, planId string) ([]string, error) {+ err := assertAnyPlanLockSet(planId, "")+ if err != nil {+ return nil, err+ }+dir := getPlanDir(orgId, planId)var out bytes.Buffercmd := exec.Command("git", "branch", "--format=%(refname:short)")cmd.Dir = dircmd.Stdout = &out- err := cmd.Run()+ err = cmd.Run()if err != nil {return nil, fmt.Errorf("error getting git branches for dir: %s, err: %v", dir, err)}@@ -197,9 +289,14 @@ func GitListBranches(orgId, planId string) ([]string, error) {}func GitCreateBranch(orgId, planId, newBranch string) error {+ err := assertWriteOrRootLockSet(planId, "")+ if err != nil {+ return err+ }+dir := getPlanDir(orgId, planId)- err := gitWriteOperation(func() error {+ err = gitWriteOperation(func() error {res, err := exec.Command("git", "-C", dir, "checkout", "-b", newBranch).CombinedOutput()if err != nil {return fmt.Errorf("error creating git branch for dir: %s, err: %v, output: %s", dir, err, string(res))@@ -216,9 +313,14 @@ func GitCreateBranch(orgId, planId, newBranch string) error {}func GitDeleteBranch(orgId, planId, branchName string) error {+ err := assertWriteOrRootLockSet(planId, "")+ if err != nil {+ return err+ }+dir := getPlanDir(orgId, planId)- err := gitWriteOperation(func() error {+ err = gitWriteOperation(func() error {res, err := exec.Command("git", "-C", dir, "branch", "-D", branchName).CombinedOutput()if err != nil {return fmt.Errorf("error deleting git branch for dir: %s, err: %v, output: %s", dir, err, string(res))@@ -234,10 +336,15 @@ func GitDeleteBranch(orgId, planId, branchName string) error {return nil}-func GitClearUncommittedChanges(orgId, planId string) error {+func GitClearUncommittedChanges(orgId, planId, branch string) error {+ err := assertWriteOrRootLockSet(planId, branch)+ if err != nil {+ return err+ }+dir := getPlanDir(orgId, planId)- err := gitWriteOperation(func() error {+ err = gitWriteOperation(func() error {// Reset staged changesres, err := exec.Command("git", "-C", dir, "reset", "--hard").CombinedOutput()if err != nil {@@ -263,15 +370,16 @@ func GitClearUncommittedChanges(orgId, planId string) error {return err}-// Not used currently but may be good to handle these errors specifically later if locking can't fully prevent them-//-// func isLockFileError(output string) bool {-// return strings.Contains(output, "fatal: Unable to create") && strings.Contains output, ".git/index.lock': File exists")-// }func GitCheckoutBranch(orgId, planId, branch string) error {+ // even though we use 'gitWriteOperation' below, we also check out a branch for reads, so we just need to assert that any lock is set+ err := assertAnyPlanLockSet(planId, branch)+ if err != nil {+ return err+ }+dir := getPlanDir(orgId, planId)- err := gitWriteOperation(func() error {+ err = gitWriteOperation(func() error {return gitCheckoutBranch(dir, branch)}, fmt.Sprintf("GitCheckoutBranch > gitCheckout: plan=%s branch=%s", planId, branch))@@ -578,3 +686,54 @@ func gitWriteOperation(operation func() error, label string) error {}return fmt.Errorf("operation %s failed after %d attempts: %v", label, maxGitRetries, err)}++func assertWriteOrRootLockSet(planId, branch string) error {+ planLocksMu.Lock()+ defer planLocksMu.Unlock()++ lock, ok := planLocks[planId]+ if !ok || lock.currentBranch != branch || (!lock.hasWriter && lock.currentBranch != "") {+ stack := debug.Stack()++ if !ok {+ log.Printf("Plan %s branch %s NO LOCK SET for git repo write operation\n%s", planId, branch, formatStackTraceLong(stack))++ return fmt.Errorf("plan %s branch %s NO LOCK SET for git repo write operation", planId, branch)+ } else if lock.currentBranch != branch {+ log.Printf("lock.currentBranch: %s, branch: %s", lock.currentBranch, branch)+ log.Printf("Plan %s branch %s WRONG LOCK SET for git repo write operation\n%s", planId, branch, formatStackTraceLong(stack))++ return fmt.Errorf("plan %s branch %s WRONG LOCK SET for git repo write operation", planId, branch)+ } else if !lock.hasWriter {+ log.Printf("lock.hasWriter: %t", lock.hasWriter)+ log.Printf("Plan %s branch %s NO WRITER LOCK SET for git repo write operation\n%s", planId, branch, formatStackTraceLong(stack))++ return fmt.Errorf("plan %s branch %s NO WRITER LOCK SET for git repo write operation", planId, branch)+ }++ }++ return nil+}++func assertAnyPlanLockSet(planId, branch string) error {+ planLocksMu.Lock()+ defer planLocksMu.Unlock()++ lock, ok := planLocks[planId]+ if !ok {+ stack := debug.Stack()+ log.Printf("Plan %s branch %s NO LOCK SET for git repo operation\n%s", planId, branch, formatStackTraceLong(stack))+ return fmt.Errorf("plan %s NO LOCK SET", planId)+ }++ // if the lock is set on a branch rather than a plan lock, require the branch to match+ if lock.currentBranch != "" && lock.currentBranch != branch {+ stack := debug.Stack()+ log.Printf("Plan %s branch %s WRONG LOCK SET for git repo operation\n%s", planId, branch, formatStackTraceLong(stack))+ return fmt.Errorf("plan %s WRONG LOCK SET", planId)+ }++ // otherwise it's a root plan lock, so we allow any branch+ return nil+}diff --git a/app/server/db/result_helpers.go b/app/server/db/result_helpers.goindex d302f7b3..5bdd1224 100644--- a/app/server/db/result_helpers.go+++ b/app/server/db/result_helpers.go@@ -9,6 +9,7 @@ import ("path/filepath""sort""strings"+ "sync""time"shared "plandex-shared"@@ -58,6 +59,61 @@ type CurrentPlanStateParams struct {Contexts []*Context}+func GetFullCurrentPlanStateParams(orgId, planId string) (CurrentPlanStateParams, error) {+ errCh := make(chan error)++ var results []*PlanFileResult+ var convoMessageDescriptions []*ConvoMessageDescription+ var contexts []*Context++ go func() {+ res, err := GetPlanFileResults(orgId, planId)+ if err != nil {+ errCh <- fmt.Errorf("error getting plan file results: %v", err)+ return+ }+ results = res+ errCh <- nil+ }()++ go func() {+ res, err := GetConvoMessageDescriptions(orgId, planId)+ if err != nil {+ errCh <- fmt.Errorf("error getting latest plan build description: %v", err)+ return+ }+ convoMessageDescriptions = res+ errCh <- nil+ }()++ go func() {+ res, err := GetPlanContexts(orgId, planId, true, false)+ if err != nil {+ errCh <- fmt.Errorf("error getting contexts: %v", err)+ return+ }++ contexts = res++ errCh <- nil+ }()++ for i := 0; i < 3; i++ {+ err := <-errCh+ if err != nil {+ return CurrentPlanStateParams{}, err+ }+ }++ return CurrentPlanStateParams{+ OrgId: orgId,+ PlanId: planId,+ PlanFileResults: results,+ ConvoMessageDescriptions: convoMessageDescriptions,+ Contexts: contexts,+ }, nil+}+func GetCurrentPlanState(params CurrentPlanStateParams) (*shared.CurrentPlanState, error) {orgId := params.OrgIdplanId := params.PlanId@@ -65,6 +121,7 @@ func GetCurrentPlanState(params CurrentPlanStateParams) (*shared.CurrentPlanStatvar dbPlanFileResults []*PlanFileResultvar convoMessageDescriptions []*shared.ConvoMessageDescriptioncontextsByPath := map[string]*Context{}+ planApplies := []*shared.PlanApply{}errCh := make(chan error)go func() {@@ -127,7 +184,21 @@ func GetCurrentPlanState(params CurrentPlanStateParams) (*shared.CurrentPlanStaterrCh <- nil}()- for i := 0; i < 3; i++ {+ go func() {+ res, err := GetPlanApplies(orgId, planId)+ if err != nil {+ errCh <- fmt.Errorf("error getting plan applies: %v", err)+ return+ }++ for _, apply := range res {+ planApplies = append(planApplies, apply.ToApi())+ }++ errCh <- nil+ }()++ for i := 0; i < 4; i++ {err := <-errChif err != nil {return nil, err@@ -169,6 +240,7 @@ func GetCurrentPlanState(params CurrentPlanStateParams) (*shared.CurrentPlanStatPlanResult: planResult,ConvoMessageDescriptions: convoMessageDescriptions,ContextsByPath: pendingContextsByPath,+ PlanApplies: planApplies,}currentPlanFiles, err := planState.GetFiles()@@ -358,65 +430,40 @@ func GetPlanResult(planFileResults []*shared.PlanFileResult) *shared.PlanResult}}-func ApplyPlan(ctx context.Context, orgId, userId, branchName string, plan *Plan) (*shared.CurrentPlanState, error) {- planId := plan.Id+type ApplyPlanParams struct {+ OrgId string+ UserId string+ BranchName string+ Plan *Plan+ CurrentPlanState *shared.CurrentPlanState+ CurrentPlanStateParams *CurrentPlanStateParams+ CommitMsg string+}+func ApplyPlan(ctx context.Context, params ApplyPlanParams) error {+ orgId := params.OrgId+ userId := params.UserId+ branchName := params.BranchName+ plan := params.Plan+ currentPlanState := params.CurrentPlanState+ currentPlanParams := params.CurrentPlanStateParams+ planId := plan.IdresultsDir := getPlanResultsDir(orgId, planId)- errCh := make(chan error)-- var results []*PlanFileResult- var convoMessageDescriptions []*ConvoMessageDescription- contextsById := make(map[string]*Context)- contextsByPath := make(map[string]*Context)-- go func() {- res, err := GetPlanFileResults(orgId, planId)- if err != nil {- errCh <- fmt.Errorf("error getting plan file results: %v", err)- return- }- results = res- errCh <- nil- }()-- go func() {- res, err := GetConvoMessageDescriptions(orgId, planId)- if err != nil {- errCh <- fmt.Errorf("error getting latest plan build description: %v", err)- return- }- convoMessageDescriptions = res- errCh <- nil- }()-- go func() {- res, err := GetPlanContexts(orgId, planId, false, false)- if err != nil {- errCh <- fmt.Errorf("error getting contexts: %v", err)- return- }-- for _, context := range res {- contextsById[context.Id] = context- if context.FilePath != "" {- contextsByPath[context.FilePath] = context- }- }+ var pendingDbResults []*PlanFileResult- errCh <- nil- }()+ planFileResults := currentPlanParams.PlanFileResults+ convoMessageDescriptions := currentPlanParams.ConvoMessageDescriptions+ contexts := currentPlanParams.Contexts- for i := 0; i < 3; i++ {- err := <-errCh- if err != nil {- return nil, err+ contextsByPath := make(map[string]*Context)+ for _, context := range contexts {+ if context.FilePath != "" {+ contextsByPath[context.FilePath] = context}}- var pendingDbResults []*PlanFileResult-- for _, result := range results {+ for _, result := range planFileResults {apiResult := result.ToApi()if apiResult.IsPending() {pendingDbResults = append(pendingDbResults, result)@@ -442,23 +489,7 @@ func ApplyPlan(ctx context.Context, orgId, userId, branchName string, plan *Planvar loadContextRes *shared.LoadContextResponsevar updateContextRes *shared.UpdateContextResponse- var currentPlanState *shared.CurrentPlanState- if len(pendingNewFilesSet) > 0 || len(pendingUpdatedFilesSet) > 0 {- res, err := GetCurrentPlanState(CurrentPlanStateParams{- OrgId: orgId,- PlanId: plan.Id,- PlanFileResults: results,- ConvoMessageDescriptions: convoMessageDescriptions,- })-- if err != nil {- return nil, fmt.Errorf("error getting current plan state: %v", err)- }-- currentPlanState = res- }-- errCh = make(chan error)+ errCh := make(chan error)now := time.Now()for _, result := range pendingDbResults {@@ -521,6 +552,7 @@ func ApplyPlan(ctx context.Context, orgId, userId, branchName string, plan *PlanBranchName: branchName,Req: &loadReq,SkipConflictInvalidation: true, // no need to invalidate conflicts when applying plan--and fixes race condition since invalidation check loads description+ AutoLoaded: true,},)@@ -583,10 +615,54 @@ func ApplyPlan(ctx context.Context, orgId, userId, branchName string, plan *Planfor i := 0; i < numRoutines; i++ {err := <-errChif err != nil {- return nil, fmt.Errorf("error applying plan: %v", err)+ return fmt.Errorf("error applying plan: %v", err)}}+ // Store the PlanApply record+ planApply := &PlanApply{+ Id: uuid.New().String(),+ OrgId: orgId,+ PlanId: planId,+ UserId: userId,+ CommitMsg: params.CommitMsg,+ CreatedAt: now,+ }++ // Collect the IDs from the pending results and descriptions+ var resultIds []string+ var descriptionIds []string+ var messageIds []string++ for _, result := range pendingDbResults {+ resultIds = append(resultIds, result.Id)+ }+ for _, desc := range convoMessageDescriptions {+ descriptionIds = append(descriptionIds, desc.Id)+ messageIds = append(messageIds, desc.ConvoMessageId)+ }++ planApply.PlanFileResultIds = resultIds+ planApply.ConvoMessageDescriptionIds = descriptionIds+ planApply.ConvoMessageIds = messageIds++ // Store the PlanApply object+ bytes, err := json.MarshalIndent(planApply, "", " ")+ if err != nil {+ return fmt.Errorf("error marshalling plan apply: %v", err)+ }++ appliesDir := getPlanAppliesDir(orgId, planId)+ err = os.MkdirAll(appliesDir, 0755)+ if err != nil {+ return fmt.Errorf("error creating applies dir: %v", err)+ }++ err = os.WriteFile(filepath.Join(appliesDir, planApply.Id+".json"), bytes, 0644)+ if err != nil {+ return fmt.Errorf("error writing plan apply file: %v", err)+ }+msg := "✅ Marked pending results as applied"currentFiles := currentPlanState.CurrentPlanFiles.Files@@ -598,6 +674,7 @@ func ApplyPlan(ctx context.Context, orgId, userId, branchName string, plan *Planfor _, path := range sortedFiles {msg += fmt.Sprintf("\n • 📄 %s", path)}+ msg += "\n" + "✏️ " + params.CommitMsgif loadContextRes != nil && !loadContextRes.MaxTokensExceeded {msg += "\n\n" + loadContextRes.Msg@@ -607,13 +684,13 @@ func ApplyPlan(ctx context.Context, orgId, userId, branchName string, plan *Planmsg += "\n\n" + updateContextRes.Msg}- err := GitAddAndCommit(orgId, plan.Id, branchName, msg)+ err = GitAddAndCommit(orgId, plan.Id, branchName, msg)if err != nil {- return nil, fmt.Errorf("error committing plan: %v", err)+ return fmt.Errorf("error committing plan: %v", err)}- return currentPlanState, nil+ return nil}func RejectAllResults(orgId, planId string) error {@@ -826,3 +903,55 @@ func RejectReplacement(orgId, planId, resultId, replacementId string) error {return nil}++func GetPlanApplies(orgId, planId string) ([]*PlanApply, error) {+ appliesDir := getPlanAppliesDir(orgId, planId)+ files, err := os.ReadDir(appliesDir)++ if err != nil {+ if os.IsNotExist(err) {+ return nil, nil+ }++ return nil, fmt.Errorf("error reading applies dir: %v", err)+ }++ planApplies := []*PlanApply{}+ var mu sync.Mutex++ errCh := make(chan error, len(files))++ for _, file := range files {+ go func(file os.DirEntry) {+ bytes, err := os.ReadFile(filepath.Join(appliesDir, file.Name()))++ if err != nil {+ errCh <- fmt.Errorf("error reading apply file: %v", err)+ return+ }++ var apply PlanApply+ err = json.Unmarshal(bytes, &apply)++ if err != nil {+ errCh <- fmt.Errorf("error unmarshalling apply file: %v", err)+ return+ }++ mu.Lock()+ planApplies = append(planApplies, &apply)+ mu.Unlock()++ errCh <- nil+ }(file)+ }++ for i := 0; i < len(files); i++ {+ err := <-errCh+ if err != nil {+ return nil, fmt.Errorf("error getting plan applies: %v", err)+ }+ }++ return planApplies, nil+}