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
rewind command
Dane Schneider2448c6c7f1c9
diff --git a/cli/api/methods.go b/cli/api/methods.goindex 9302ec15..f96b111b 100644--- a/cli/api/methods.go+++ b/cli/api/methods.go@@ -644,3 +644,37 @@ func (a *Api) ListLogs(planId string) (*shared.LogResponse, error) {return &logs, nil}++func (a *Api) RewindPlan(planId string, req shared.RewindPlanRequest) (*shared.RewindPlanResponse, error) {+ serverUrl := fmt.Sprintf("%s/plans/%s/rewind", apiHost, planId)+ reqBytes, err := json.Marshal(req)+ if err != nil {+ return nil, fmt.Errorf("error marshalling request: %v", err)+ }++ request, err := http.NewRequest(http.MethodPatch, serverUrl, bytes.NewBuffer(reqBytes))+ if err != nil {+ return nil, fmt.Errorf("error creating request: %v", err)+ }+ request.Header.Set("Content-Type", "application/json")++ resp, err := http.DefaultClient.Do(request)+ if err != nil {+ return nil, fmt.Errorf("error sending request: %v", err)+ }++ defer resp.Body.Close()++ if resp.StatusCode >= 400 {+ errorBody, _ := io.ReadAll(resp.Body)+ return nil, fmt.Errorf("error rewinding plan: %d - %s", resp.StatusCode, string(errorBody))+ }++ var rewindPlanResponse shared.RewindPlanResponse+ err = json.NewDecoder(resp.Body).Decode(&rewindPlanResponse)+ if err != nil {+ return nil, fmt.Errorf("error decoding response: %v", err)+ }++ return &rewindPlanResponse, nil+}diff --git a/cli/api/types.go b/cli/api/types.goindex fbabaef8..dc638218 100644--- a/cli/api/types.go+++ b/cli/api/types.go@@ -48,4 +48,5 @@ type ApiClient interface {ListConvo(planId string) ([]*shared.ConvoMessage, error)ListLogs(planId string) (*shared.LogResponse, error)+ RewindPlan(planId string, req shared.RewindPlanRequest) (*shared.RewindPlanResponse, error)}diff --git a/cli/cmd/log.go b/cli/cmd/log.goindex 126944c3..47e04b15 100644--- a/cli/cmd/log.go+++ b/cli/cmd/log.go@@ -11,7 +11,7 @@ import (// logCmd represents the log commandvar logCmd = &cobra.Command{- Use: "log [scope]",+ Use: "log",Aliases: []string{"history"},Short: "Show plan history",Long: `Show plan history.`,diff --git a/cli/cmd/rewind.go b/cli/cmd/rewind.goindex e3b66e4b..bf8ae89b 100644--- a/cli/cmd/rewind.go+++ b/cli/cmd/rewind.go@@ -3,22 +3,24 @@ package cmdimport ("fmt""os"+ "plandex/api""plandex/lib""strconv"+ "github.com/plandex/plandex/shared""github.com/spf13/cobra")// rewindCmd represents the rewind commandvar rewindCmd = &cobra.Command{- Use: "rewind [scope] [steps-or-sha]",+ Use: "rewind [steps-or-sha]",Aliases: []string{"rw"},Short: "Rewind the plan to an earlier state",- Long: `Rewind the plan to an earlier state. Pass an optional scope to rewind only a specific part of the plan. Valid scopes are "convo", "context", and "draft". If no scope is passed, the entire plan is rewound.+ Long: `Rewind the plan to an earlier state.- You can also optionally pass a "steps" number or commit sha. If a steps number is passed, the plan will be rewound that many steps. If a commit sha is passed, the plan will be rewound to that commit. If neither a steps number nor a commit sha is passed, the target scope will be rewound by 1 step.+ You can pass a "steps" number or a commit sha. If a steps number is passed, the plan will be rewound that many steps. If a commit sha is passed, the plan will be rewound to that commit. If neither a steps number nor a commit sha is passed, the target scope will be rewound by 1 step.`,- Args: cobra.MaximumNArgs(2),+ Args: cobra.MaximumNArgs(1),Run: rewind,}@@ -33,66 +35,44 @@ func init() {}func rewind(cmd *cobra.Command, args []string) {- var dir string- scope := "all"- if len(args) > 0 {- scope = args[0]- }-- switch scope {- case "convo":- dir = lib.ConversationSubdir- case "context":- dir = lib.ContextSubdir- case "draft":- dir = lib.ResultsSubdir- default:- dir = lib.CurrentPlanDir // Rewind the whole plan by default- }// Check if either steps or sha is provided and not both- stepsOrSHA := ""+ stepsOrSha := ""if len(args) > 1 {- stepsOrSHA = args[1]+ stepsOrSha = args[1]+ }++ logsRes, err := api.Client.ListLogs(lib.CurrentPlanId)++ if err != nil {+ fmt.Printf("Error getting logs: %v\n", err)+ return}- if steps, err := strconv.Atoi(stepsOrSHA); err == nil && steps > 0 {+ var targetSha string++ if steps, err := strconv.Atoi(stepsOrSha); err == nil && steps > 0 {// Rewind by the specified number of steps- if err := lib.GitRewindSteps(dir, steps, scope == "all"); err != nil {- fmt.Fprintln(os.Stderr, "Error rewinding steps:", err)- os.Exit(1)- }- } else if sha := stepsOrSHA; sha != "" {- // Rewind to the specified SHA- if err := lib.GitRewindToSHA(dir, sha, scope == "all"); err != nil {- fmt.Fprintln(os.Stderr, "Error rewinding to SHA:", err)- os.Exit(1)- }- } else if stepsOrSHA == "" {- // No steps or SHA provided, rewind by 1 step by default- if err := lib.GitRewindSteps(dir, 1, scope == "all"); err != nil {- fmt.Fprintln(os.Stderr, "Error rewinding 1 step:", err)- os.Exit(1)- }+ targetSha = logsRes.Shas[steps]+ } else if sha := stepsOrSha; sha != "" {+ // Rewind to the specified Sha+ targetSha = sha+ } else if stepsOrSha == "" {+ // Rewind by 1 step+ targetSha = logsRes.Shas[1]} else {- fmt.Fprintln(os.Stderr, "Invalid steps or SHA. Steps must be a positive integer, and SHA must be a valid commit hash.")+ fmt.Fprintln(os.Stderr, "Invalid steps or sha. Steps must be a positive integer, and sha must be a valid commit hash.")os.Exit(1)}- latestCommitSha, latestCommitMsg, err := lib.GetLatestCommit(dir)- if err != nil {- fmt.Fprintln(os.Stderr, "Error getting latest commit:", err)- os.Exit(1)- }+ // Rewind to the target sha+ rwRes, err := api.Client.RewindPlan(lib.CurrentPlanId, shared.RewindPlanRequest{Sha: targetSha})msg := "✅ Rewound "- if scope != "all" {- msg += scope + " "- }- msg += "to " + latestCommitSha+ msg += "to " + targetShafmt.Println(msg)fmt.Println()- fmt.Println(latestCommitMsg)+ fmt.Println(rwRes.LatestCommit)}diff --git a/server/db/git.go b/server/db/git.goindex 42528def..19562ae5 100644--- a/server/db/git.go+++ b/server/db/git.go@@ -46,10 +46,10 @@ func GitAddAndCommit(orgId, planId, message string) error {return nil}-func GitRewindToSHA(orgId, planId, sha string) error {+func GitRewindToSha(orgId, planId, sha string) error {dir := getPlanDir(orgId, planId)- err := gitRewindToSHA(dir, sha)+ err := gitRewindToSha(dir, sha)if err != nil {return fmt.Errorf("error rewinding git repository for dir: %s, err: %v", dir, err)}@@ -57,29 +57,29 @@ func GitRewindToSHA(orgId, planId, sha string) error {return nil}-func GetGitCommitHistory(orgId, planId string) (string, error) {+func GetGitCommitHistory(orgId, planId string) (body string, shas []string, err error) {dir := getPlanDir(orgId, planId)- history, err := getGitCommitHistory(dir)+ body, shas, err = getGitCommitHistory(dir)if err != nil {- return "", fmt.Errorf("error getting git history for dir: %s, err: %v", dir, err)+ return "", nil, fmt.Errorf("error getting git history for dir: %s, err: %v", dir, err)}- return history, nil+ return body, shas, nil}-func GetLatestCommit(orgId, planId string) (string, string, error) {+func GetLatestCommit(orgId, planId string) (sha, body string, err error) {dir := getPlanDir(orgId, planId)- sha, timestamp, err := getLatestCommit(dir)+ sha, body, err = getLatestCommit(dir)if err != nil {return "", "", fmt.Errorf("error getting latest commit for dir: %s, err: %v", dir, err)}- return sha, timestamp, nil+ return sha, body, nil}-func gitRewindToSHA(repoDir, sha string) error {+func gitRewindToSha(repoDir, sha string) error {res, err := exec.Command("git", "-C", repoDir, "reset", "--hard",sha).CombinedOutput()@@ -90,12 +90,12 @@ func gitRewindToSHA(repoDir, sha string) error {return nil}-func getLatestCommit(dir string) (string, string, error) {+func getLatestCommit(dir string) (sha, body string, err error) {var out bytes.Buffercmd := exec.Command("git", "log", "--pretty=%h@@|@@%at@@|@@%B@>>>@")cmd.Dir = dircmd.Stdout = &out- err := cmd.Run()+ err = cmd.Run()if err != nil {return "", "", fmt.Errorf("error getting git history for dir: %s, err: %v",dir, err)@@ -106,17 +106,20 @@ func getLatestCommit(dir string) (string, string, error) {first := history[0]- return first[0], first[1], nil+ sha = first[0]+ body = first[1]++ return sha, body, nil}-func getGitCommitHistory(dir string) (string, error) {+func getGitCommitHistory(dir string) (body string, shas []string, err error) {var out bytes.Buffercmd := exec.Command("git", "log", "--pretty=%h@@|@@%at@@|@@%B@>>>@")cmd.Dir = dircmd.Stdout = &out- err := cmd.Run()+ err = cmd.Run()if err != nil {- return "", fmt.Errorf("error getting git history for dir: %s, err: %v",+ return "", nil, fmt.Errorf("error getting git history for dir: %s, err: %v",dir, err)}@@ -125,10 +128,11 @@ func getGitCommitHistory(dir string) (string, error) {var output []stringfor _, el := range history {+ shas = append(shas, el[0])output = append(output, el[1])}- return strings.Join(output, "\n\n"), nil+ return strings.Join(output, "\n\n"), shas, nil}// processGitHistoryOutput processes the raw output from the git log command and returns a formatted string.@@ -165,7 +169,7 @@ func processGitHistoryOutput(raw string) [][2]string {headerColor := color.New(color.FgCyan, color.Bold)dateColor := color.New(color.FgCyan)- // Combine SHA, formatted timestamp, and message header into one string.+ // Combine sha, formatted timestamp, and message header into one string.header := fmt.Sprintf("%s | %s", headerColor.Sprintf("📝 Update %s", sha), dateColor.Sprintf("%s", formattedTs))// Combine header and message with a newline only if the message is not empty.diff --git a/server/handlers/plans_versions.go b/server/handlers/plans_versions.goindex 4d642fa4..73e7293f 100644--- a/server/handlers/plans_versions.go+++ b/server/handlers/plans_versions.go@@ -2,6 +2,7 @@ package handlersimport ("encoding/json"+ "io""log""net/http""plandex-server/db"@@ -21,7 +22,7 @@ func ListLogsHandler(w http.ResponseWriter, r *http.Request) {log.Println("planId: ", planId)- body, err := db.GetGitCommitHistory(currentOrgId, planId)+ body, shas, err := db.GetGitCommitHistory(currentOrgId, planId)if err != nil {log.Println("Error getting logs: ", err)@@ -31,6 +32,7 @@ func ListLogsHandler(w http.ResponseWriter, r *http.Request) {res := shared.LogResponse{Body: body,+ Shas: shas,}bytes, err := json.Marshal(res)@@ -49,9 +51,60 @@ func ListLogsHandler(w http.ResponseWriter, r *http.Request) {func RewindPlanHandler(w http.ResponseWriter, r *http.Request) {log.Println("Received request for RewindPlanHandler")+ // TODO: get from auth when implemented+ currentOrgId := "org1"+vars := mux.Vars(r)planId := vars["planId"]log.Println("planId: ", planId)+ // read the request body+ body, err := io.ReadAll(r.Body)+ if err != nil {+ log.Printf("Error reading request body: %v\n", err)+ http.Error(w, "Error reading request body", http.StatusInternalServerError)+ return+ }+ defer r.Body.Close()++ var requestBody shared.RewindPlanRequest+ if err := json.Unmarshal(body, &requestBody); err != nil {+ log.Printf("Error parsing request body: %v\n", err)+ http.Error(w, "Error parsing request body", http.StatusBadRequest)+ return+ }++ err = db.GitRewindToSha(currentOrgId, planId, requestBody.Sha)++ if err != nil {+ log.Println("Error rewinding plan: ", err)+ w.WriteHeader(http.StatusInternalServerError)+ return+ }++ sha, latest, err := db.GetLatestCommit(currentOrgId, planId)++ if err != nil {+ log.Println("Error getting latest commit: ", err)+ w.WriteHeader(http.StatusInternalServerError)+ return+ }++ res := shared.RewindPlanResponse{+ LatestSha: sha,+ LatestCommit: latest,+ }++ bytes, err := json.Marshal(res)++ if err != nil {+ log.Println("Error marshalling response: ", err)+ w.WriteHeader(http.StatusInternalServerError)+ return+ }++ w.Write(bytes)++ log.Println("Successfully processed request for RewindPlanHandler")}diff --git a/shared/req_res.go b/shared/req_res.goindex de40ca61..8067b6c1 100644--- a/shared/req_res.go+++ b/shared/req_res.go@@ -69,8 +69,14 @@ type RewindPlanRequest struct {Sha string `json:"sha"`}+type RewindPlanResponse struct {+ LatestSha string `json:"latestSha"`+ LatestCommit string `json:"latestCommit"`+}+type LogResponse struct {- Body string `json:"body"`+ Shas []string `json:"shas"`+ Body string `json:"body"`}type PlanTokenCount struct {