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
work on file ops (wip, still need to fix bug(s)), some reorg, apply rollbacks
Dane Schneider4807601963bb
diff --git a/app/cli/lib/apply.go b/app/cli/lib/apply.goindex 5a95c6ea..6313b4a9 100644--- a/app/cli/lib/apply.go+++ b/app/cli/lib/apply.go@@ -118,6 +118,7 @@ func MustApplyPlanAttempt(isRepo := fs.ProjectRootIsGitRepo()toApply := currentPlanFiles.Files+ toRemove := currentPlanFiles.RemovedhasExec := currentPlanFiles.Files["_apply.sh"] != ""log.Printf("Files to apply: %d, Has exec script: %v", len(toApply), hasExec)@@ -136,7 +137,7 @@ func MustApplyPlanAttempt(onErr := func(errMsg string, errArgs ...interface{}) {term.StopSpinner()if toRollback != nil && toRollback.HasChanges() {- toRollback.Rollback(true)+ Rollback(toRollback, true)}term.OutputErrorAndExit(errMsg, errArgs...)}@@ -178,7 +179,7 @@ func MustApplyPlanAttempt(term.ResumeSpinner()}- updatedFiles, toRollback, err = applyFiles(toApply)+ updatedFiles, toRollback, err = applyFiles(toApply, toRemove)if err != nil {onErr("failed to apply files: %s", err)@@ -277,7 +278,7 @@ func handleApplyScript(}if res == string(types.ApplyRollbackOptionRollback) {- toRollback.Rollback(true)+ Rollback(toRollback, true)} else {onSuccess()}@@ -394,7 +395,7 @@ func execApplyScript(}if res == string(types.ApplyRollbackOptionRollback) {- toRollback.Rollback(true)+ Rollback(toRollback, true)} else {onSuccess()}@@ -504,13 +505,14 @@ func commitApplied(autoCommit bool, commitSummary string, updatedFiles []string,return nil}-func applyFiles(toApply map[string]string) ([]string, *types.ApplyRollbackPlan, error) {+func applyFiles(toApply map[string]string, toRemove map[string]bool) ([]string, *types.ApplyRollbackPlan, error) {var updatedFiles []stringvar toRevert map[string]types.ApplyReversion- var toRemove []string+ var toRemoveOnRollback []string+ var projectPaths *types.ProjectPathsvar mu sync.Mutex- errCh := make(chan error, len(toApply))+ errCh := make(chan error, len(toApply)+len(toRemove))for path, content := range toApply {if path == "_apply.sh" {@@ -562,7 +564,7 @@ func applyFiles(toApply map[string]string) ([]string, *types.ApplyRollbackPlan,} else {mu.Lock()updatedFiles = append(updatedFiles, path)- toRemove = append(toRemove, dstPath)+ toRemoveOnRollback = append(toRemoveOnRollback, dstPath)mu.Unlock()// Create the directory if it doesn't exist@@ -584,7 +586,62 @@ func applyFiles(toApply map[string]string) ([]string, *types.ApplyRollbackPlan,}(path, content)}- for range toApply {+ for path, remove := range toRemove {+ go func(path string, remove bool) {+ if !remove {+ errCh <- nil+ return+ }+ // Compute destination path+ dstPath := filepath.Join(fs.ProjectRoot, path)++ // Check if the file exists+ var exists bool+ var mode os.FileMode+ info, err := os.Stat(dstPath)+ if err == nil {+ exists = true+ mode = info.Mode()+ } else {+ if os.IsNotExist(err) {+ exists = false+ } else {+ errCh <- fmt.Errorf("failed to check if %s exists: %s", dstPath, err.Error())+ 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)+ }++ go func() {+ var err error+ projectPaths, err = fs.GetProjectPaths(fs.ProjectRoot)+ if err != nil {+ errCh <- fmt.Errorf("failed to get project paths: %v", err)+ }+ }()++ for i := 0; i < len(toApply)+len(toRemove)+1; i++ {err := <-errChif err != nil {return nil, nil, err@@ -592,7 +649,87 @@ func applyFiles(toApply map[string]string) ([]string, *types.ApplyRollbackPlan,}return updatedFiles, &types.ApplyRollbackPlan{- ToRevert: toRevert,- ToRemove: toRemove,+ PreviousProjectPaths: projectPaths,+ ToRevert: toRevert,+ ToRemove: toRemoveOnRollback,}, nil}++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)+ if err != nil {+ errCh <- fmt.Errorf("failed to write %s: %s", path, err.Error())+ return+ }+ errCh <- nil+ }(path, revert)+ }++ for _, path := range rollbackPlan.ToRemove {+ go func(path string) {+ err := os.Remove(path)+ if err != nil {+ errCh <- fmt.Errorf("failed to remove %s: %s", path, err.Error())+ return+ }+ errCh <- nil+ }(path)+ }++ go func() {+ var err error+ projectPaths, err := fs.GetProjectPaths(fs.ProjectRoot)+ if err != nil {+ errCh <- fmt.Errorf("failed to get project paths: %v", err)+ }++ var toRemove []string+ for 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 := <-pathsErrCh+ if err != nil {+ errCh <- fmt.Errorf("failed to remove %s: %s", toRemove, err.Error())+ return+ }+ }++ errCh <- nil+ }()++ errs := []error{}++ for i := 0; i < len(rollbackPlan.ToRevert)+len(rollbackPlan.ToRemove)+1; i++ {+ err := <-errCh+ if 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/plan_exec/apply_exec.go b/app/cli/plan_exec/apply_exec.goindex 21efaa97..abd4df75 100644--- a/app/cli/plan_exec/apply_exec.go+++ b/app/cli/plan_exec/apply_exec.go@@ -41,7 +41,7 @@ func GetOnApplyExecFail(flags lib.ApplyFlags) types.OnApplyExecFailFn {if proceed {if toRollback != nil && toRollback.HasChanges() {- toRollback.Rollback(true)+ lib.Rollback(toRollback, true)}var apiKeys map[string]string@@ -71,7 +71,7 @@ func GetOnApplyExecFail(flags lib.ApplyFlags) types.OnApplyExecFailFn {}if res == string(types.ApplyRollbackOptionRollback) {- toRollback.Rollback(true)+ lib.Rollback(toRollback, true)} else {onSuccess()}diff --git a/app/cli/stream_tui/model.go b/app/cli/stream_tui/model.goindex 96e76b0e..fede4069 100644--- a/app/cli/stream_tui/model.go+++ b/app/cli/stream_tui/model.go@@ -48,6 +48,7 @@ type streamUIModel struct {building booltokensByPath map[string]intfinishedByPath map[string]bool+ removedByPath map[string]boolready boolwidth int@@ -167,6 +168,7 @@ func initialModel(prestartReply, prompt string, buildOnly bool) *streamUIModel {tokensByPath: make(map[string]int),finishedByPath: make(map[string]bool),+ removedByPath: make(map[string]bool),spinner: s,buildSpinner: buildSpinner,sharedTicker: sharedTicker,diff --git a/app/cli/stream_tui/update.go b/app/cli/stream_tui/update.goindex 81356d57..d7062d25 100644--- a/app/cli/stream_tui/update.go+++ b/app/cli/stream_tui/update.go@@ -309,6 +309,12 @@ func (m *streamUIModel) streamUpdate(msg *shared.StreamMessage, deferUIUpdate bowasFinished := m.finishedByPath[msg.BuildInfo.Path]nowFinished := msg.BuildInfo.Finished+ if msg.BuildInfo.Removed {+ m.removedByPath[msg.BuildInfo.Path] = true+ } else {+ m.removedByPath[msg.BuildInfo.Path] = false+ }+if msg.BuildInfo.Finished {m.tokensByPath[msg.BuildInfo.Path] = 0m.finishedByPath[msg.BuildInfo.Path] = truediff --git a/app/cli/stream_tui/view.go b/app/cli/stream_tui/view.goindex 157c5731..e296f957 100644--- a/app/cli/stream_tui/view.go+++ b/app/cli/stream_tui/view.go@@ -135,6 +135,7 @@ func (m streamUIModel) getRows(static bool) []string {for _, filePath := range filePaths {tokens := m.tokensByPath[filePath]finished := m.finished || m.finishedByPath[filePath] || built+ removed := m.removedByPath[filePath]icon := "📄"label := filePathif filePath == "_apply.sh" {@@ -142,7 +143,9 @@ func (m streamUIModel) getRows(static bool) []string {}block := fmt.Sprintf("%s %s", icon, label)- if finished {+ if removed {+ block += " ❌"+ } else if finished {block += " ✅"} else if tokens > 0 {block += fmt.Sprintf(" %d 🪙", tokens)diff --git a/app/cli/types/apply.go b/app/cli/types/apply.goindex 8d1a783d..2ac3ddeb 100644--- a/app/cli/types/apply.go+++ b/app/cli/types/apply.go@@ -1,7 +1,6 @@package typesimport (- "fmt""os")@@ -28,48 +27,3 @@ type ApplyRollbackPlan struct {func (r *ApplyRollbackPlan) HasChanges() bool {return len(r.ToRevert) > 0 || len(r.ToRemove) > 0}--func (r *ApplyRollbackPlan) Rollback(msg bool) error {- errCh := make(chan error, len(r.ToRevert)+len(r.ToRemove))-- for path, revert := range r.ToRevert {- go func(path string, revert ApplyReversion) {- err := os.WriteFile(path, []byte(revert.Content), revert.Mode)- if err != nil {- errCh <- fmt.Errorf("failed to write %s: %s", path, err.Error())- return- }- errCh <- nil- }(path, revert)- }-- for _, path := range r.ToRemove {- go func(path string) {- err := os.RemoveAll(path)- if err != nil {- errCh <- fmt.Errorf("failed to remove %s: %s", path, err.Error())- return- }- errCh <- nil- }(path)- }-- errs := []error{}-- for i := 0; i < len(r.ToRevert)+len(r.ToRemove); i++ {- err := <-errCh- if 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/server/db/data_models.go b/app/server/db/data_models.goindex e2caf031..0961d00e 100644--- a/app/server/db/data_models.go+++ b/app/server/db/data_models.go@@ -492,6 +492,8 @@ type PlanFileResult struct {Replacements []*shared.Replacement `json:"replacements"`+ RemovedFile bool `json:"removedFile"`+AnyFailed bool `json:"anyFailed"`Error string `json:"error"`@@ -527,6 +529,7 @@ func (res *PlanFileResult) ToApi() *shared.PlanFileResult {AppliedAt: res.AppliedAt,RejectedAt: res.RejectedAt,Replacements: res.Replacements,+ RemovedFile: res.RemovedFile,CanVerify: res.CanVerify,RanVerifyAt: res.RanVerifyAt,VerifyPassed: res.VerifyPassed,diff --git a/app/server/db/db.go b/app/server/db/db.goindex fe50d2d9..93185b6f 100644--- a/app/server/db/db.go+++ b/app/server/db/db.go@@ -44,11 +44,11 @@ func Connect() error {log.Println("connected to database")if os.Getenv("GOENV") == "production" {- Conn.SetMaxOpenConns(100) // Allow up to 100 concurrent connections per task- Conn.SetMaxIdleConns(100) // Keep up to 100 idle connections for reuse+ Conn.SetMaxOpenConns(500)+ Conn.SetMaxIdleConns(100)} else {- Conn.SetMaxOpenConns(20) // Allow up to 20 concurrent connections per task- Conn.SetMaxIdleConns(20) // Keep up to 20 idle connections for reuse+ Conn.SetMaxOpenConns(250)+ Conn.SetMaxIdleConns(50)}_, err = Conn.Exec("SET TIMEZONE='UTC';")diff --git a/app/server/model/parse/file_ops.go b/app/server/model/parse/file_ops.gonew file mode 100644index 00000000..1fdce930--- /dev/null+++ b/app/server/model/parse/file_ops.go@@ -0,0 +1,126 @@+package parse++import (+ "strings"+)++type FileMove struct {+ Source string+ Destination string+}++// ParseMoveFiles parses the "### Move Files" section and returns a list of source/destination pairs+func ParseMoveFiles(content string) []FileMove {+ split := strings.Split(content, "### Move Files")+ if len(split) < 2 {+ return nil+ }++ var moves []FileMove+ lines := strings.Split(split[1], "\n")++ for _, line := range lines {+ line = strings.TrimSpace(line)+ if !strings.HasPrefix(line, "-") {+ continue+ }++ // Remove the leading dash and trim+ line = strings.TrimPrefix(line, "-")+ line = strings.TrimSpace(line)++ // Split on arrow, requiring backticks+ parts := strings.Split(line, "→")+ if len(parts) != 2 {+ continue+ }++ src := strings.TrimSpace(parts[0])+ dst := strings.TrimSpace(parts[1])++ // Remove backticks+ src = strings.Trim(src, "`")+ dst = strings.Trim(dst, "`")++ if src != "" && dst != "" {+ moves = append(moves, FileMove{+ Source: src,+ Destination: dst,+ })+ }+ }++ return moves+}++// ParseRemoveFiles parses the "### Remove Files" section and returns a list of files to remove+func ParseRemoveFiles(content string) []string {+ split := strings.Split(content, "### Remove Files")+ if len(split) < 2 {+ return nil+ }++ var files []string+ lines := strings.Split(split[1], "\n")++ for _, line := range lines {+ line = strings.TrimSpace(line)+ if !strings.HasPrefix(line, "-") {+ continue+ }++ // Remove the leading dash and trim+ line = strings.TrimPrefix(line, "-")+ line = strings.TrimSpace(line)++ // Check for proper backtick format+ if !strings.HasPrefix(line, "`") || !strings.HasSuffix(line, "`") {+ continue+ }++ // Remove backticks+ line = strings.Trim(line, "`")++ if line != "" {+ files = append(files, line)+ }+ }++ return files+}++// ParseResetChanges parses the "### Reset Changes" section and returns a list of files to reset+func ParseResetChanges(content string) []string {+ split := strings.Split(content, "### Reset Changes")+ if len(split) < 2 {+ return nil+ }++ var files []string+ lines := strings.Split(split[1], "\n")++ for _, line := range lines {+ line = strings.TrimSpace(line)+ if !strings.HasPrefix(line, "-") {+ continue+ }++ // Remove the leading dash and trim+ line = strings.TrimPrefix(line, "-")+ line = strings.TrimSpace(line)++ // Check for proper backtick format+ if !strings.HasPrefix(line, "`") || !strings.HasSuffix(line, "`") {+ continue+ }++ // Remove backticks+ line = strings.Trim(line, "`")++ if line != "" {+ files = append(files, line)+ }+ }++ return files+}diff --git a/app/server/model/parse/file_ops_test.go b/app/server/model/parse/file_ops_test.gonew file mode 100644index 00000000..0de9781c--- /dev/null+++ b/app/server/model/parse/file_ops_test.go@@ -0,0 +1,181 @@+package parse++import (+ "testing"+)++func TestParseMoveFiles(t *testing.T) {+ tests := []struct {+ name string+ input string+ expected []FileMove+ }{+ {+ name: "empty input",+ input: "",+ expected: nil,+ },+ {+ name: "single move",+ input: `### Move Files+- ` + "`source/file.ts` → `dest/file.ts`",+ expected: []FileMove{+ {Source: "source/file.ts", Destination: "dest/file.ts"},+ },+ },+ {+ name: "multiple moves",+ input: `### Move Files+- ` + "`src/components/button.tsx` → `components/button.tsx`" + `+- ` + "`old/utils.ts` → `utils/index.ts`",+ expected: []FileMove{+ {Source: "src/components/button.tsx", Destination: "components/button.tsx"},+ {Source: "old/utils.ts", Destination: "utils/index.ts"},+ },+ },+ {+ name: "ignores invalid lines",+ input: `### Move Files+- ` + "`valid/source.ts` → `valid/dest.ts`" + `+- not properly formatted+- ` + "`missing/arrow`" + `+Some other content`,+ expected: []FileMove{+ {Source: "valid/source.ts", Destination: "valid/dest.ts"},+ },+ },+ {+ name: "handles empty lines",+ input: `### Move Files+- ` + "`src/file1.ts` → `dest/file1.ts`" + `++- ` + "`src/file2.ts` → `dest/file2.ts`",+ expected: []FileMove{+ {Source: "src/file1.ts", Destination: "dest/file1.ts"},+ {Source: "src/file2.ts", Destination: "dest/file2.ts"},+ },+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := ParseMoveFiles(tt.input)+ if len(got) != len(tt.expected) {+ t.Errorf("ParseMoveFiles() returned %d moves, want %d", len(got), len(tt.expected))+ return+ }+ for i := range got {+ if got[i].Source != tt.expected[i].Source {+ t.Errorf("Move[%d].Source = %q, want %q", i, got[i].Source, tt.expected[i].Source)+ }+ if got[i].Destination != tt.expected[i].Destination {+ t.Errorf("Move[%d].Destination = %q, want %q", i, got[i].Destination, tt.expected[i].Destination)+ }+ }+ })+ }+}++func TestParseRemoveFiles(t *testing.T) {+ tests := []struct {+ name string+ input string+ expected []string+ }{+ {+ name: "empty input",+ input: "",+ expected: nil,+ },+ {+ name: "single file",+ input: `### Remove Files+- ` + "`components/button.tsx`",+ expected: []string{"components/button.tsx"},+ },+ {+ name: "multiple files",+ input: `### Remove Files+- ` + "`src/file1.ts`" + `+- ` + "`src/file2.ts`",+ expected: []string{"src/file1.ts", "src/file2.ts"},+ },+ {+ name: "ignores invalid lines",+ input: `### Remove Files+- ` + "`valid/file.ts`" + `+- missing backticks+Some other content`,+ expected: []string{"valid/file.ts"},+ },+ {+ name: "handles empty lines",+ input: `### Remove Files+- ` + "`file1.ts`" + `++- ` + "`file2.ts`",+ expected: []string{"file1.ts", "file2.ts"},+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := ParseRemoveFiles(tt.input)+ if !sliceEqual(got, tt.expected) {+ t.Errorf("ParseRemoveFiles() = %v, want %v", got, tt.expected)+ }+ })+ }+}++func TestParseResetChanges(t *testing.T) {+ tests := []struct {+ name string+ input string+ expected []string+ }{+ {+ name: "empty input",+ input: "",+ expected: nil,+ },+ {+ name: "single file",+ input: `### Reset Changes+- ` + "`components/button.tsx`",+ expected: []string{"components/button.tsx"},+ },+ {+ name: "multiple files",+ input: `### Reset Changes+- ` + "`src/file1.ts`" + `+- ` + "`src/file2.ts`",+ expected: []string{"src/file1.ts", "src/file2.ts"},+ },+ {+ name: "ignores invalid lines",+ input: `### Reset Changes+- ` + "`valid/file.ts`" + `+- missing backticks+Some other content`,+ expected: []string{"valid/file.ts"},+ },+ {+ name: "handles empty lines",+ input: `### Reset Changes+- ` + "`file1.ts`" + `++- ` + "`file2.ts`",+ expected: []string{"file1.ts", "file2.ts"},+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := ParseResetChanges(tt.input)+ if !sliceEqual(got, tt.expected) {+ t.Errorf("ParseResetChanges() = %v, want %v", got, tt.expected)+ }+ })+ }+}diff --git a/app/server/model/subtasks.go b/app/server/model/parse/subtasks.gosimilarity index 99%rename from app/server/model/subtasks.gorename to app/server/model/parse/subtasks.goindex 3f46f08a..619f8931 100644--- a/app/server/model/subtasks.go+++ b/app/server/model/parse/subtasks.go@@ -1,4 +1,4 @@-package model+package parseimport ("plandex-server/db"diff --git a/app/server/model/subtasks_test.go b/app/server/model/parse/subtasks_test.gosimilarity index 99%rename from app/server/model/subtasks_test.gorename to app/server/model/parse/subtasks_test.goindex 559ae52b..a4c8ff06 100644--- a/app/server/model/subtasks_test.go+++ b/app/server/model/parse/subtasks_test.go@@ -1,4 +1,4 @@-package model+package parseimport ("plandex-server/db"diff --git a/app/server/model/plan/build_exec.go b/app/server/model/plan/build_exec.goindex 3f7539ef..76740de8 100644--- a/app/server/model/plan/build_exec.go+++ b/app/server/model/plan/build_exec.go@@ -225,6 +225,100 @@ func (fileState *activeBuildStreamFileState) buildFile() {// log.Println("\n\nCurrent state:\n", currentState, "\n\n")}+ if activeBuild.IsMoveOp {+ log.Printf("File %s is a move operation. Moving to %s\n", filePath, activeBuild.MoveDestination)+ log.Println("Will remove this path and then queue another build for the new path with the current file's content")++ fileState.queueBuilds([]*types.ActiveBuild{+ {+ ReplyId: activeBuild.ReplyId,+ Idx: activeBuild.Idx,+ Path: activeBuild.Path,+ IsRemoveOp: true,+ },+ {+ ReplyId: activeBuild.ReplyId,+ Idx: activeBuild.Idx,+ Path: activeBuild.MoveDestination,+ FileContent: currentState,+ FileContentTokens: 0,+ },+ })++ return+ }++ if activeBuild.IsRemoveOp {+ log.Printf("File %s is a remove operation. Removing file.\n", filePath)++ buildInfo := &shared.BuildInfo{+ Path: filePath,+ NumTokens: 0,+ Removed: true,+ Finished: true,+ }++ activePlan.Stream(shared.StreamMessage{+ Type: shared.StreamMessageBuildInfo,+ BuildInfo: buildInfo,+ })++ planRes := &db.PlanFileResult{+ OrgId: currentOrgId,+ PlanId: planId,+ PlanBuildId: build.Id,+ ConvoMessageId: build.ConvoMessageId,+ Path: filePath,+ Content: "",+ RemovedFile: true,+ }+ fileState.onFinishBuildFile(planRes, "")+ return+ }++ if activeBuild.IsResetOp {+ log.Printf("File %s is a reset operation. Resetting file.\n", filePath)++ if contextPart == nil {+ log.Printf("File %s not found in model context. Removing pending file.\n", filePath)++ fileState.queueBuilds([]*types.ActiveBuild{+ {+ ReplyId: activeBuild.ReplyId,+ Idx: activeBuild.Idx,+ Path: activeBuild.Path,+ IsRemoveOp: true,+ },+ })++ return+ } else {+ log.Printf("File %s found in model context. Using context state.\n", filePath)++ buildInfo := &shared.BuildInfo{+ Path: filePath,+ NumTokens: 0,+ Finished: true,+ }++ activePlan.Stream(shared.StreamMessage{+ Type: shared.StreamMessageBuildInfo,+ BuildInfo: buildInfo,+ })++ planRes := &db.PlanFileResult{+ OrgId: currentOrgId,+ PlanId: planId,+ PlanBuildId: build.Id,+ ConvoMessageId: build.ConvoMessageId,+ Path: filePath,+ Content: contextPart.Body,+ }+ fileState.onFinishBuildFile(planRes, "")+ return+ }+ }+fileState.preBuildState = currentStateif currentState == "" {@@ -285,17 +379,9 @@ func (fileState *activeBuildStreamFileState) buildFile() {activePlan.DidEditFiles = true}- if fileState.parser != nil && !fileState.preBuildStateSyntaxInvalid {- log.Println("buildFile - building structured edits")-- fileState.buildStructuredEdits()- } else {- log.Println("buildFile - building expand references")- log.Printf("fileState.parser == nil: %v\n", fileState.parser == nil)- log.Printf("fileState.preBuildStateSyntaxInvalid: %v\n", fileState.preBuildStateSyntaxInvalid)-- fileState.buildExpandReferences()- }+ // build structured edits strategy now works regardless of language/tree-sitter support+ log.Println("buildFile - building structured edits")+ fileState.buildStructuredEdits()}func (fileState *activeBuildStreamFileState) buildFileLineNums() {diff --git a/app/server/model/plan/tell_context.go b/app/server/model/plan/tell_context.goindex b5e7c586..89c7c58a 100644--- a/app/server/model/plan/tell_context.go+++ b/app/server/model/plan/tell_context.go@@ -100,6 +100,14 @@ func (state *activeTellStreamState) formatModelContext(includeMaps, includeTrees}}+ if len(state.currentPlanState.CurrentPlanFiles.Removed) > 0 {+ contextMessages = append(contextMessages, "*Removed files:*\n")+ for path := range state.currentPlanState.CurrentPlanFiles.Removed {+ contextMessages = append(contextMessages, fmt.Sprintf("- %s", path))+ }+ contextMessages = append(contextMessages, "These files have been *removed* and are no longer in the plan. If you want to re-add them to the plan, you must explicitly create them again.")+ }+if execEnabled {contextMessages = append(contextMessages, state.currentPlanState.ExecHistory())@@ -114,3 +122,54 @@ func (state *activeTellStreamState) formatModelContext(includeMaps, includeTreesreturn strings.Join(contextMessages, "\n### END OF CONTEXT ###\n"), numTokens, nil}++func (state *activeTellStreamState) checkAutoLoadContext() []string {+ activePlan := GetActivePlan(state.plan.Id, state.branch)++ if activePlan == nil {+ return nil+ }++ if !activePlan.AutoContext {+ return nil+ }++ if state.req.IsUserContinue {+ return nil+ }++ // only load context on the first iteration of a non-continue prompt+ if state.iteration > 0 {+ return nil+ }++ split := strings.Split(activePlan.CurrentReplyContent, "### Load Context")++ if len(split) < 2 {+ return nil+ }++ req := state.req++ list := strings.Split(split[1], "\n")+ files := []string{}++ for _, line := range list {+ trimmed := strings.TrimSpace(line)+ if trimmed == "" {+ continue+ }++ if strings.HasPrefix(trimmed, "-") {+ trimmed = strings.TrimPrefix(trimmed, "-")+ trimmed = strings.ReplaceAll(trimmed, "`", "")+ trimmed = strings.TrimSpace(trimmed)++ if req.ProjectPaths[trimmed] {+ files = append(files, trimmed)+ }+ }+ }++ return files+}diff --git a/app/server/model/plan/tell_file_ops.go b/app/server/model/plan/tell_file_ops.gonew file mode 100644index 00000000..0c7e987d--- /dev/null+++ b/app/server/model/plan/tell_file_ops.go@@ -0,0 +1,41 @@+package plan++import (+ "plandex-server/model/parse"+)++func (state *activeTellStreamState) checkMoveFileOps() []parse.FileMove {+ activePlan := GetActivePlan(state.plan.Id, state.branch)++ if activePlan == nil {+ return nil+ }++ moveFiles := parse.ParseMoveFiles(activePlan.CurrentReplyContent)++ return moveFiles+}++func (state *activeTellStreamState) checkRemoveFileOps() []string {+ activePlan := GetActivePlan(state.plan.Id, state.branch)++ if activePlan == nil {+ return nil+ }++ removeFiles := parse.ParseRemoveFiles(activePlan.CurrentReplyContent)++ return removeFiles+}++func (state *activeTellStreamState) checkResetFileOps() []string {+ activePlan := GetActivePlan(state.plan.Id, state.branch)++ if activePlan == nil {+ return nil+ }++ resetFiles := parse.ParseResetChanges(activePlan.CurrentReplyContent)++ return resetFiles+}diff --git a/app/server/model/plan/tell_stream.go b/app/server/model/plan/tell_stream.goindex 61822f0e..6018bd3c 100644--- a/app/server/model/plan/tell_stream.go+++ b/app/server/model/plan/tell_stream.go@@ -214,8 +214,71 @@ mainLoop:autoLoadContextFiles := state.checkAutoLoadContext()hasNewSubtasks := state.checkNewSubtasks()+ moveFiles := state.checkMoveFileOps()+ removeFiles := state.checkRemoveFileOps()+ resetFiles := state.checkResetFileOps()var allSubtasksFinished bool+ if req.BuildMode == shared.BuildModeAuto {+ getBuildState := func() *activeBuildStreamState {+ return &activeBuildStreamState{+ tellState: state,+ clients: clients,+ auth: auth,+ currentOrgId: currentOrgId,+ currentUserId: currentUserId,+ plan: plan,+ branch: branch,+ settings: settings,+ modelContext: state.modelContext,+ }+ }++ if len(moveFiles) > 0 {+ log.Println("Detected move files, queuing builds")+ for i, moveFile := range moveFiles {+ getBuildState().queueBuilds([]*types.ActiveBuild{+ {+ ReplyId: replyId,+ Idx: i,+ Path: moveFile.Source,+ IsMoveOp: true,+ MoveDestination: moveFile.Destination,+ },+ })+ }+ }++ if len(removeFiles) > 0 {+ log.Println("Detected remove files, queuing builds")+ for i, removeFile := range removeFiles {+ getBuildState().queueBuilds([]*types.ActiveBuild{+ {+ ReplyId: replyId,+ Idx: i,+ Path: removeFile,+ IsRemoveOp: true,+ },+ })+ }+ }++ if len(resetFiles) > 0 {+ log.Println("Detected reset files, queuing builds")++ for i, resetFile := range resetFiles {+ getBuildState().queueBuilds([]*types.ActiveBuild{+ {+ ReplyId: replyId,+ Idx: i,+ Path: resetFile,+ IsResetOp: true,+ },+ })+ }+ }+ }+var errCh = make(chan error, 2)go func() {@@ -744,11 +807,6 @@ mainLoop:log.Printf("Detected file: %s\n", file)- if file == "_pending.sh" {- // TODO: extract and queue commands from _pending.sh- continue- }-if req.BuildMode == shared.BuildModeAuto {log.Printf("Queuing build for %s\n", file)// log.Println("Content:")@@ -842,126 +900,6 @@ func (state *activeTellStreamState) storeAssistantReply() (*db.ConvoMessage, strreturn &assistantMsg, commitMsg, err}-func (state *activeTellStreamState) checkAutoLoadContext() []string {- activePlan := GetActivePlan(state.plan.Id, state.branch)-- if activePlan == nil {- return nil- }-- if !activePlan.AutoContext {- return nil- }-- if state.req.IsUserContinue {- return nil- }-- // only load context on the first iteration of a non-continue prompt- if state.iteration > 0 {- return nil- }-- split := strings.Split(activePlan.CurrentReplyContent, "### Load Context")-- if len(split) < 2 {- return nil- }-- req := state.req-- list := strings.Split(split[1], "\n")- files := []string{}-- for _, line := range list {- trimmed := strings.TrimSpace(line)- if trimmed == "" {- continue- }-- if strings.HasPrefix(trimmed, "-") {- trimmed = strings.TrimPrefix(trimmed, "-")- trimmed = strings.ReplaceAll(trimmed, "`", "")- trimmed = strings.TrimSpace(trimmed)-- if req.ProjectPaths[trimmed] {- files = append(files, trimmed)- }- }- }-- return files-}--func (state *activeTellStreamState) checkNewSubtasks() bool {- activePlan := GetActivePlan(state.plan.Id, state.branch)-- if activePlan == nil {- return false- }-- content := activePlan.CurrentReplyContent-- subtasks := model.ParseSubtasks(content)-- if len(subtasks) == 0 {- return false- }-- log.Println("Found new subtasks:")- spew.Dump(subtasks)-- subtasksByName := map[string]*db.Subtask{}-- for _, subtask := range state.subtasks {- subtasksByName[subtask.Title] = subtask- }-- var newSubtasks []*db.Subtask-- for _, subtask := range state.subtasks {- if subtask.IsFinished {- newSubtasks = append(newSubtasks, subtask)- }- }-- for _, subtask := range subtasks {- if subtasksByName[subtask.Title] == nil {- newSubtasks = append(newSubtasks, subtask)- }- }-- state.subtasks = newSubtasks-- var currentSubtaskName string- if state.currentSubtask != nil {- currentSubtaskName = state.currentSubtask.Title- }-- found := false- for _, subtask := range state.subtasks {- if subtask.Title == currentSubtaskName {- found = true- state.currentSubtask = subtask- break- }- }- if !found {- state.currentSubtask = nil- }-- if state.currentSubtask == nil {- for _, subtask := range state.subtasks {- if !subtask.IsFinished {- state.currentSubtask = subtask- break- }- }- }-- return true-}-func (state *activeTellStreamState) onError(streamErr error, storeDesc bool, convoMessageId, commitMsg string) {log.Printf("\nStream error: %v\n", streamErr)diff --git a/app/server/model/plan/tell_subtasks.go b/app/server/model/plan/tell_subtasks.goindex 71452011..282465ce 100644--- a/app/server/model/plan/tell_subtasks.go+++ b/app/server/model/plan/tell_subtasks.go@@ -2,8 +2,12 @@ package planimport ("fmt"+ "log"+ "plandex-server/db"+ "plandex-server/model/parse""strings"+ "github.com/davecgh/go-spew/spew""github.com/plandex/plandex/shared")@@ -47,3 +51,72 @@ func (state *activeTellStreamState) formatSubtasks() (string, int, error) {return subtasksText, numTokens, nil}++func (state *activeTellStreamState) checkNewSubtasks() bool {+ activePlan := GetActivePlan(state.plan.Id, state.branch)++ if activePlan == nil {+ return false+ }++ content := activePlan.CurrentReplyContent++ subtasks := parse.ParseSubtasks(content)++ if len(subtasks) == 0 {+ return false+ }++ log.Println("Found new subtasks:")+ spew.Dump(subtasks)++ subtasksByName := map[string]*db.Subtask{}++ for _, subtask := range state.subtasks {+ subtasksByName[subtask.Title] = subtask+ }++ var newSubtasks []*db.Subtask++ for _, subtask := range state.subtasks {+ if subtask.IsFinished {+ newSubtasks = append(newSubtasks, subtask)+ }+ }++ for _, subtask := range subtasks {+ if subtasksByName[subtask.Title] == nil {+ newSubtasks = append(newSubtasks, subtask)+ }+ }++ state.subtasks = newSubtasks++ var currentSubtaskName string+ if state.currentSubtask != nil {+ currentSubtaskName = state.currentSubtask.Title+ }++ found := false+ for _, subtask := range state.subtasks {+ if subtask.Title == currentSubtaskName {+ found = true+ state.currentSubtask = subtask+ break+ }+ }+ if !found {+ state.currentSubtask = nil+ }++ if state.currentSubtask == nil {+ for _, subtask := range state.subtasks {+ if !subtask.IsFinished {+ state.currentSubtask = subtask+ break+ }+ }+ }++ return true+}diff --git a/app/server/model/prompts/apply_exec.go b/app/server/model/prompts/apply_exec.goindex d9ea401f..a4829a34 100644--- a/app/server/model/prompts/apply_exec.go+++ b/app/server/model/prompts/apply_exec.go@@ -29,7 +29,7 @@ const ApplyScriptPrompt = `**Execution mode is enabled.**-In addition to creating and updating files, you can also execute commands on the user's machine by writing to a another *special path*: ` + "_apply.sh" + `+In addition to creating and updating files with code blocks, you can also execute commands on the user's machine by writing to a another *special path*: ` + "_apply.sh" + `This file allows you to execute commands in the context of the *user's machine*, not the Plandex server, when the user applies the changes from the plan to their project. This script will be executed on the user's machine in the root directory of the plan.@@ -37,9 +37,7 @@ Use this to run any necessary commands *after* all the pending files from the plDO NOT use the _apply.sh script to move, remove, or reset changes to files that are in context or have pending changes—use one of the special file operation sections instead: '### Move Files', '### Remove Files', or '### Reset Changes' if you need to do that, and follow the instructions for those sections.-DO NOT use the _apply.sh script to create directory paths for files that are in context or pending. Any required directories will be created automatically when the plan is applied.--You can use the _apply.sh script for file operations on files that are *not* in context or pending, but be careful and conservative—only do so when it is strictly necessary to implement the plan. Do NOT use it for file operations on files that are in context or pending, and do NOT use it to create directories or files—any required directories will be created automatically when the plan is applied, and files must be created by code blocks within the plan, not in _apply.sh.+You ABSOLUTELY MUST NOT use the _apply.sh script to create files or directories. Use code blocks within the plan to create files and directories. When you create a new file with a code block, the necessary directories will be created automatically, so DO NOT create directories in _apply.sh.Use the appropriate commands for the user's operating system and shell, which will be supplied to you in the prompt.@@ -69,6 +67,8 @@ If appropriate, also include a command to run the actual program in _apply.sh. FIf it's appropriate, include a subtask for writing to the _apply.sh script when you break up a task into subtasks. Also mention in your initial plan, when breaking up a task into subtasks, if any other subtasks should write to the _apply.sh script (in addition to any other actions in that subtask).+When breaking up a task into subtasks, remember that you MUST NOT use the _apply.sh script to create files or directories. This must be done by code blocks within the plan, not in _apply.sh. Do NOT create a subtask for writing to the _apply.sh script unless there are other commands that need to be run—NOT just to create files or directories.+When running commands in _apply.sh, DO NOT hide or filter the output of the commands in any way. For example, do not do something like this:` + "```bash" + `@@ -165,7 +165,7 @@ Key instructions for _apply.sh:- The script runs on the user's machine after plan files are created/updated- DO NOT use _apply.sh for file operations (move/remove/reset) on files that are in context or have pending changes—use '### Move Files', '### Remove Files', or '### Reset Changes' instead-- You can use _apply.sh for file operations on files that are not in context or pending, but be careful and conservative—only do so when it is strictly necessary to implement the plan+- DO NOT use _apply.sh to create files or directories—use code blocks within the plan to create files and directories. When you create a new file with a code block, the necessary directories will be created automatically, so DO NOT create directories in _apply.sh.- Include ALL necessary commands unless they are risky/dangerous- Prefer local changes over global system changes- Check for required tools before using themdiff --git a/app/server/model/prompts/file_ops.go b/app/server/model/prompts/file_ops.goindex 61902920..b5a7d938 100644--- a/app/server/model/prompts/file_ops.go+++ b/app/server/model/prompts/file_ops.go@@ -5,60 +5,52 @@ const FileOpsPrompt = `You can perform file operations using special sections in your response. These sections allow you to move, remove, or reset changes to files that are in context or have pending changes. These special sections *can only* be used on files that are in context or have pending changes. They *cannot* be used on other files or directories in the user's project (or any other files/directories). *ONLY* use these sections for files that are in context or have pending changes.-Move Files Section:+*Move Files Section:*-Use the '### Move Files' section to move or rename files and directories:+Use the '### Move Files' section to move or rename files:### Move Files- ` + "`source/path.tsx` → `dest/path.tsx`" + `-- ` + "`src/components/` → `components/`" + `+- ` + "`components/button.tsx` → `pages/button.tsx`" + `Rules for the Move Files section:- Each line must start with a dash (-)-- Source and destination paths must be wrapped in backticks (` + "`" + `)+- Source and destination paths must be wrapped in backticks (` + "`" + `)- Paths must be separated by → (Unicode arrow, NOT ->)-- Can move individual files or entire directories-- Directories must have a trailing slash-- All paths MUST match a path in context or that has pending changes+- Can only move individual files (not directories)+- All source paths MUST match a path in context or that has pending changes- Destination path must be in the same base directory as files in context+- Destination path MUST NOT already exist in context or pending files—i.e. you cannot move a file to a path that is *already* in context or pending (and would therefore overwrite the existing file)+- You CAN move a file to a directory that does not exist yet—it will be created as needed automatically-## Remove Files Section+*Remove Files Section:*-Use the '### Remove Files' section to remove/delete files and directories:+Use the '### Remove Files' section to remove/delete files:### Remove Files- ` + "`components/page.tsx`" + `-- ` + "`sections/`" + `-- ` + "`lib/**/*.ts`" + `+- ` + "`layouts/header.tsx`" + `Rules for the Remove Files section:- Each line must start with a dash (-)-- Paths must be wrapped in backticks (` + "`" + `)-- Can remove individual files, directories, or glob patterns-- Directories must have a trailing slash+- Paths must be wrapped in backticks (` + "`" + `)+- Can only remove individual files (not directories)- All paths MUST match a path in context or that has pending changes-- All paths must be relative (no absolute paths starting with /)-- Can only remove files that are in context or have pending changes-- Glob patterns (like ` + "`**/*.ts`" + `) are allowed- Each path must be on its own line-## Reset Changes Section+*Reset Changes Section:*Use the '### Reset Changes' section to clear pending changes for files:### Reset Changes- ` + "`components/page.tsx`" + `-- ` + "`src/components/`" + `-- ` + "`lib/**/*.ts`" + `-+- ` + "`layouts/header.tsx`" + `Rules for the Reset Changes section:- Each line must start with a dash (-)-- Paths must be wrapped in backticks (` + "`" + `)-- Can reset individual files, directories, or glob patterns+- Paths must be wrapped in backticks (` + "`" + `)+- Can only reset individual files (not directories)- Can only reset files that have pending changes-- Glob patterns (like ` + "`**/*.ts`" + `) are allowed-- Directories must have a trailing slash- Each path must be on its own line## Important Notes@@ -73,10 +65,11 @@ Rules for the Reset Changes section:- Move, remove, or reset files that aren't in context or pending- Create new directories (they will be created as needed by the operations)- Include comments or additional text within these sections+ - Move a file to a path that is *already* in context or pending (and would therefore overwrite the existing file)3. Format Rules:- Section headers must be exactly as shown (### Move Files, ### Remove Files, ### Reset Changes)- - All file paths must be wrapped in backticks (` + "`" + `)+ - All file paths must be wrapped in backticks (` + "`" + `)- Move operations must use the → arrow character (Unicode arrow, NOT ->)- Each operation must be on its own line starting with a dash (-)- Empty lines between operations are allowed@@ -85,6 +78,10 @@ Rules for the Reset Changes section:4. Ending Response- Immediately after outputting one of these sections, you ABSOLUTELY MUST *immediately end the response* and output nothing else. DO NOT output any additional text or comments after a '### Move Files', '### Remove Files', or '### Reset Changes' section.+5. Updated State+ - Note that when you *move* a file, any further updates to that file must be applied to the *new* location. The context in your prompt will be updated to reflect the new location. Ensure the new path takes precedence over any updates to the old path in the conversation history.+ - Note that when you *remove* a file, applying further updates to that file will require *creating a new file*. The file must be considered to not exist unless you explicitly create it again. The context in your prompt will be updated to reflect the file's removal. Ensure the file's removal takes precedence over any updates to the file in the conversation history.+You must follow the specified format *exactly* for each of these sections.These special sections are *not* used when initially implementing a plan, since in that case you are only creating files and updating them, and possibly writing to the _apply.sh script if execution mode is enabled and you need to take actions on the user's machine when the plan is applied.@@ -106,13 +103,12 @@ Key instructions for file operations:- '### Reset Changes' (using backtick paths)- Every path MUST be wrapped in backticks (` + "`" + `)- Every line MUST start with a dash (-)-- Directories MUST have trailing slash+- Can ONLY operate on individual files (not directories)- DO NOT UNDER ANY CIRCUMSTANCES:- Include comments or additional text in these sections- Use on files not in context or pending- Continue the response after using these sections- These sections are for REVISING plans, not initial implementation-- Can use glob patterns (like ` + "`**/*.ts`" + `) in Remove and Reset sections- Must end response IMMEDIATELY after using any of these sections- When making changes, choose between:- Iterating on current pending changesdiff --git a/app/server/model/prompts/implement.go b/app/server/model/prompts/implement.goindex d7b7d317..87be0991 100644--- a/app/server/model/prompts/implement.go+++ b/app/server/model/prompts/implement.go@@ -68,6 +68,8 @@ For code in markdown blocks, always include the language name after the openingIf there are triple backticks within any file in context, they will be escaped with backslashes like this '` + "\\`\\`\\`" + `'. If you are outputting triple backticks in a code block, you MUST escape them in exactly the same way.+DO NOT create directories independently of files, whether in _apply.sh or in code blocks by adding a '.gitkeep' file in any other way. Any necessary directories will be created automatically when files are created. You MUST NOT create directories independently of files.+Don'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 or explain what you're doing unless it's absolutely necessary to make the code understandable.When updating an existing file in context, use the *reference comment* "// ... existing code ..." (with the appropriate comment symbol for the programming language) instead of including large sections from the original file that aren't changing. Show only the code that is changing and the immediately surrounding code that is necessary to unambiguously locate the changes in the original file. This only applies when you are *updating* an *existing file* in context. It does *not* apply when you are creating a new file. You MUST NEVER use the comment "// ... existing code ..." (or any equivalent) when creating a new file.diff --git a/app/server/model/prompts/user_prompt.go b/app/server/model/prompts/user_prompt.goindex a117a052..6670dfcc 100644--- a/app/server/model/prompts/user_prompt.go+++ b/app/server/model/prompts/user_prompt.go@@ -56,16 +56,7 @@ ALWAYS complete subtasks in order and never go backwards in the list of subtasksIf you break up a task into subtasks, only include subtasks that can be implemented directly in code by creating or updating files. Do not include subtasks that require executing code or commands. Do not include subtasks that require user testing, deployment, or other tasks that go beyond coding.-If you need to *move* or *rename* a file that is in context or pending, use the special ` + "`move`" + ` command in the _pending.sh script. Do NOT use a file block to move a file to another path.--If you need to *copy* a file that is in context or pending, use the special ` + "`copy`" + ` command in the _pending.sh script. Do NOT use a file block to copy a file to another path.--If you need to reject/revert all the changes you've made to a file that is in context or pending, use the special ` + "`reject`" + ` command in the _pending.sh script. Do NOT use a file block to reject/revert changes to a file.--If you need to *remove* a file that is in context or pending, use the special ` + "`remove`" + ` command in the _pending.sh script. Do NOT use a file block to remove a file.--DO NOT include comments or any other commands in the _pending.sh script. It MUST ONLY include special commands and their arguments. Do NOT create directories in the _pending.sh script—the special commands will create directories as needed.-`+` + FileOpsPromptSummaryvar ImplementationPromptWrapperTokens intdiff --git a/app/server/types/active_plan.go b/app/server/types/active_plan.goindex a49f5281..9ac22ff2 100644--- a/app/server/types/active_plan.go+++ b/app/server/types/active_plan.go@@ -33,6 +33,10 @@ type ActiveBuild struct {Error errorIsVerification boolToVerifyUpdatedState string+ IsMoveOp bool+ MoveDestination string+ IsRemoveOp bool+ IsResetOp bool}type subscription struct {diff --git a/app/server/types/active_plan_pending_builds.go b/app/server/types/active_plan_pending_builds.goindex e19189f6..db73d9c8 100644--- a/app/server/types/active_plan_pending_builds.go+++ b/app/server/types/active_plan_pending_builds.go@@ -4,6 +4,7 @@ import ("fmt""log""plandex-server/db"+ "plandex-server/model/parse""github.com/plandex/plandex/shared")@@ -55,6 +56,7 @@ func (ap *ActivePlan) PendingBuildsByPath(orgId, userId string, convoMessagesArgreplyParser.AddChunk(convoMessage.Message, false)parserRes := replyParser.FinishAndRead()+ numAdded := 0for i, file := range desc.Files {if desc.DidBuild && !desc.BuildPathsInvalidated[file] {@@ -83,6 +85,47 @@ func (ap *ActivePlan) PendingBuildsByPath(orgId, userId string, convoMessagesArgPath: file,FileDescription: fileDesc,})+ numAdded+++ }++ moveFiles := parse.ParseMoveFiles(convoMessage.Message)+ if len(moveFiles) > 0 {+ for i, moveFile := range moveFiles {+ src := moveFile.Source+ dest := moveFile.Destination++ activeBuildsByPath[dest] = append(activeBuildsByPath[dest], &ActiveBuild{+ ReplyId: desc.ConvoMessageId,+ Idx: numAdded + i,+ Path: src,+ IsMoveOp: true,+ MoveDestination: dest,+ })+ }+ }++ removeFiles := parse.ParseRemoveFiles(convoMessage.Message)+ if len(removeFiles) > 0 {+ for i, removeFile := range removeFiles {+ activeBuildsByPath[removeFile] = append(activeBuildsByPath[removeFile], &ActiveBuild{+ ReplyId: desc.ConvoMessageId,+ Idx: numAdded + i,+ Path: removeFile,+ IsRemoveOp: true,+ })+ }+ }++ resetFiles := parse.ParseResetChanges(convoMessage.Message)+ if len(resetFiles) > 0 {+ for i, resetFile := range resetFiles {+ activeBuildsByPath[resetFile] = append(activeBuildsByPath[resetFile], &ActiveBuild{+ ReplyId: desc.ConvoMessageId,+ Idx: numAdded + i,+ Path: resetFile,+ IsResetOp: true,+ })+ }}}}diff --git a/app/shared/data_models.go b/app/shared/data_models.goindex b0ca5b0f..6aadeefd 100644--- a/app/shared/data_models.go+++ b/app/shared/data_models.go@@ -194,6 +194,8 @@ type PlanFileResult struct {RejectedAt *time.Time `json:"rejectedAt,omitempty"`Replacements []*Replacement `json:"replacements"`+ RemovedFile bool `json:"removedFile"`+CanVerify bool `json:"canVerify"`RanVerifyAt *time.Time `json:"ranVerifyAt,omitempty"`VerifyPassed bool `json:"verifyPassed"`@@ -208,6 +210,7 @@ type PlanFileResult struct {type CurrentPlanFiles struct {Files map[string]string `json:"files"`+ Removed map[string]bool `json:"removedByPath"`UpdatedAtByPath map[string]time.Time `json:"updatedAtByPath"`}diff --git a/app/shared/plan_result_replacements.go b/app/shared/plan_result_replacements.goindex 4d0d1ae2..bc381a04 100644--- a/app/shared/plan_result_replacements.go+++ b/app/shared/plan_result_replacements.go@@ -150,6 +150,7 @@ func (planState *CurrentPlanState) GetFilesBeforeReplacement(files := make(map[string]string)shas := make(map[string]string)updatedAtByPath := make(map[string]time.Time)+ removedByPath := make(map[string]bool)for path, planResults := range planRes.FileResultsByPath {updated := files[path]@@ -169,6 +170,15 @@ func (planState *CurrentPlanState) GetFilesBeforeReplacement(continue}+ if planRes.RemovedFile {+ updated = ""+ delete(files, path)+ delete(shas, path)+ delete(updatedAtByPath, path)+ removedByPath[path] = true+ continue+ }+if len(planRes.Replacements) == 0 {if updated != "" {return nil, fmt.Errorf("plan updates out of order: %s", path)@@ -177,6 +187,7 @@ func (planState *CurrentPlanState) GetFilesBeforeReplacement(updated = planRes.Contentfiles[path] = updatedupdatedAtByPath[path] = planRes.CreatedAt+ delete(removedByPath, path)continue} else if updated == "" {@@ -252,39 +263,5 @@ func (planState *CurrentPlanState) GetFilesBeforeReplacement(files[path] = updated}- return &CurrentPlanFiles{Files: files, UpdatedAtByPath: updatedAtByPath}, nil+ return &CurrentPlanFiles{Files: files, UpdatedAtByPath: updatedAtByPath, Removed: removedByPath}, nil}--// func getUniqueFuzzyIndex(doc, s string) int {-// words := strings.Fields(s)-// if len(words) < 2 {-// return -1-// }--// searchStart := regexp.QuoteMeta(words[0])-// searchEnd := regexp.QuoteMeta(words[len(words)-1])--// // Loop to expand search pattern gradually from both ends towards the center-// for i := 0; i < len(words)/2; i++ { // Ensure we do not go out of bounds-// // Construct the regex pattern-// regexPattern := fmt.Sprintf("%s.*%s", searchStart, searchEnd)-// re, err := regexp.Compile(regexPattern)-// if err != nil {-// return -1 // Handle regex compilation error-// }--// // Find all matches of the pattern in the document-// matches := re.FindAllStringIndex(doc, -1)-// if len(matches) == 1 {-// return matches[0][0] // Return the start index of the unique match-// }--// // Update search strings if possible-// if i+1 < len(words)/2 {-// searchStart += " " + regexp.QuoteMeta(words[i+1])-// searchEnd = regexp.QuoteMeta(words[len(words)-i-2]) + " " + searchEnd-// }-// }--// return -1-// }diff --git a/app/shared/stream.go b/app/shared/stream.goindex 934e3d19..71a13816 100644--- a/app/shared/stream.go+++ b/app/shared/stream.go@@ -6,6 +6,7 @@ type BuildInfo struct {Path string `json:"path"`NumTokens int `json:"numTokens"`Finished bool `json:"finished"`+ Removed bool `json:"removed,omitempty"`}type StreamMessageType string