Skip to content

Open source AI coding agent. Designed for large projects and real world tasks.

fixes for incorrect reference comment generation; auto-verification step for plans that update files or generate more than a few files; a 'debug' command; auto-confirm and auto-apply flags for tell/continue

Dane Schneiderd4c183862b56
diff --git a/app/cli/changes_tui/run.go b/app/cli/changes_tui/run.go
index 9cf5314f..7e77c806 100644
--- a/app/cli/changes_tui/run.go
+++ b/app/cli/changes_tui/run.go
@@ -38,7 +38,7 @@ func StartChangesUI(currentPlan *shared.CurrentPlanState) error {
}
if mod.shouldApplyAll {
- lib.MustApplyPlan(lib.CurrentPlanId, lib.CurrentBranch, false)
+ lib.MustApplyPlan(lib.CurrentPlanId, lib.CurrentBranch, false, false, false)
}
if mod.rejectFileErr != nil {
diff --git a/app/cli/cmd/apply.go b/app/cli/cmd/apply.go
index a04977a6..87b6a5d8 100644
--- a/app/cli/cmd/apply.go
+++ b/app/cli/cmd/apply.go
@@ -8,11 +8,12 @@ import (
"github.com/spf13/cobra"
)
-var autoConfirm bool
+var autoConfirm, autoCommit, noCommit bool
func init() {
applyCmd.Flags().BoolVarP(&autoConfirm, "yes", "y", false, "Automatically confirm unless plan is outdated")
-
+ applyCmd.Flags().BoolVarP(&autoCommit, "commit", "c", false, "Commit changes to git")
+ applyCmd.Flags().BoolVarP(&noCommit, "no-commit", "n", false, "Do not commit changes to git")
RootCmd.AddCommand(applyCmd)
}
@@ -31,5 +32,5 @@ func apply(cmd *cobra.Command, args []string) {
term.OutputNoCurrentPlanErrorAndExit()
}
- lib.MustApplyPlan(lib.CurrentPlanId, lib.CurrentBranch, autoConfirm)
+ lib.MustApplyPlan(lib.CurrentPlanId, lib.CurrentBranch, autoConfirm, autoCommit, noCommit)
}
diff --git a/app/cli/cmd/build.go b/app/cli/cmd/build.go
index 78fd19b1..becf46b6 100644
--- a/app/cli/cmd/build.go
+++ b/app/cli/cmd/build.go
@@ -25,6 +25,7 @@ var buildCmd = &cobra.Command{
func init() {
RootCmd.AddCommand(buildCmd)
buildCmd.Flags().BoolVar(&buildBg, "bg", false, "Execute autonomously in the background")
+ buildCmd.Flags().BoolVarP(&autoConfirm, "yes", "y", false, "Automatically confirm context updates")
}
func build(cmd *cobra.Command, args []string) {
@@ -45,7 +46,7 @@ func build(cmd *cobra.Command, args []string) {
CurrentBranch: lib.CurrentBranch,
ApiKeys: apiKeys,
CheckOutdatedContext: func(maybeContexts []*shared.Context) (bool, bool, error) {
- return lib.CheckOutdatedContextWithOutput(false, maybeContexts)
+ return lib.CheckOutdatedContextWithOutput(false, autoConfirm, maybeContexts)
},
}, buildBg)
diff --git a/app/cli/cmd/changes.go b/app/cli/cmd/changes.go
index 0f6a32e4..13593101 100644
--- a/app/cli/cmd/changes.go
+++ b/app/cli/cmd/changes.go
@@ -85,7 +85,7 @@ func changes(cmd *cobra.Command, args []string) {
CurrentBranch: lib.CurrentBranch,
ApiKeys: apiKeys,
CheckOutdatedContext: func(maybeContexts []*shared.Context) (bool, bool, error) {
- return lib.CheckOutdatedContextWithOutput(true, maybeContexts)
+ return lib.CheckOutdatedContextWithOutput(true, false, maybeContexts)
},
}, false)
diff --git a/app/cli/cmd/continue.go b/app/cli/cmd/continue.go
index 38db8b60..44560301 100644
--- a/app/cli/cmd/continue.go
+++ b/app/cli/cmd/continue.go
@@ -23,6 +23,10 @@ func init() {
continueCmd.Flags().BoolVarP(&tellStop, "stop", "s", false, "Stop after a single reply")
continueCmd.Flags().BoolVarP(&tellNoBuild, "no-build", "n", false, "Don't build files")
continueCmd.Flags().BoolVar(&tellBg, "bg", false, "Execute autonomously in the background")
+
+ continueCmd.Flags().BoolVarP(&autoConfirm, "yes", "y", false, "Automatically confirm context updates")
+ continueCmd.Flags().BoolVarP(&tellAutoApply, "apply", "a", false, "Automatically apply changes (and confirm context updates)")
+ continueCmd.Flags().BoolVarP(&autoCommit, "commit", "c", false, "Commit changes to git when --apply/-a is passed")
}
func doContinue(cmd *cobra.Command, args []string) {
@@ -43,7 +47,11 @@ func doContinue(cmd *cobra.Command, args []string) {
CurrentBranch: lib.CurrentBranch,
ApiKeys: apiKeys,
CheckOutdatedContext: func(maybeContexts []*shared.Context) (bool, bool, error) {
- return lib.CheckOutdatedContextWithOutput(false, maybeContexts)
+ return lib.CheckOutdatedContextWithOutput(false, autoConfirm || tellAutoApply, maybeContexts)
},
- }, "", tellBg, tellStop, tellNoBuild, true)
+ }, "", tellBg, tellStop, tellNoBuild, true, false, false)
+
+ if tellAutoApply {
+ lib.MustApplyPlan(lib.CurrentPlanId, lib.CurrentBranch, true, autoCommit, !autoCommit)
+ }
}
diff --git a/app/cli/cmd/debug.go b/app/cli/cmd/debug.go
new file mode 100644
index 00000000..3621883c
--- /dev/null
+++ b/app/cli/cmd/debug.go
@@ -0,0 +1,131 @@
+package cmd
+
+import (
+ "fmt"
+ "os"
+ "os/exec"
+ "plandex/auth"
+ "plandex/lib"
+ "plandex/plan_exec"
+ "plandex/term"
+ "strconv"
+ "strings"
+
+ "github.com/fatih/color"
+ "github.com/plandex/plandex/shared"
+ "github.com/spf13/cobra"
+)
+
+const DebugDefaultTries = 5
+
+var debugCmd = &cobra.Command{
+ Use: "debug [tries] <cmd>",
+ Short: "Debug a failing command with Plandex",
+ Args: cobra.MinimumNArgs(1),
+ Run: doDebug,
+}
+
+func init() {
+ RootCmd.AddCommand(debugCmd)
+ debugCmd.Flags().BoolVarP(&autoCommit, "commit", "c", false, "Commit changes to git on each try")
+}
+
+func doDebug(cmd *cobra.Command, args []string) {
+ auth.MustResolveAuthWithOrg()
+ lib.MustResolveProject()
+
+ if lib.CurrentPlanId == "" {
+ term.OutputNoCurrentPlanErrorAndExit()
+ }
+
+ // Parse tries and command
+ tries := DebugDefaultTries
+ cmdArgs := args
+
+ // Check if first arg is tries count
+ if val, err := strconv.Atoi(args[0]); err == nil {
+ if val <= 0 {
+ term.OutputErrorAndExit("Tries must be greater than 0")
+ }
+ tries = val
+ cmdArgs = args[1:]
+ if len(cmdArgs) == 0 {
+ term.OutputErrorAndExit("No command specified")
+ }
+ }
+
+ var apiKeys map[string]string
+ if !auth.Current.IntegratedModelsMode {
+ apiKeys = lib.MustVerifyApiKeys()
+ }
+
+ // Get current working directory
+ cwd, err := os.Getwd()
+ if err != nil {
+ term.OutputErrorAndExit("Failed to get working directory: %v", err)
+ }
+
+ cmdStr := strings.Join(cmdArgs, " ")
+
+ // Execute command and handle retries
+ for attempt := 0; attempt < tries; attempt++ {
+ term.StartSpinner("")
+ // Use shell to handle operators like && and |
+ execCmd := exec.Command("sh", "-c", cmdStr)
+ execCmd.Dir = cwd
+ execCmd.Env = os.Environ()
+
+ output, err := execCmd.CombinedOutput()
+
+ term.StopSpinner()
+
+ outputStr := string(output)
+ if outputStr == "" && err != nil {
+ // If no output but error occurred, include error in output
+ outputStr = err.Error()
+ }
+
+ if outputStr != "" {
+ fmt.Println(outputStr)
+ }
+
+ if err == nil {
+ if attempt == 0 {
+ fmt.Printf("✅ Command %s succeeded on first try\n", color.New(color.Bold, term.ColorHiCyan).Sprintf(cmdStr))
+ } else {
+ lbl := "attempts"
+ if attempt == 1 {
+ lbl = "attempt"
+ }
+ fmt.Printf("✅ Command %s succeeded after %d fix %s\n", color.New(color.Bold, term.ColorHiCyan).Sprintf(cmdStr), attempt, lbl)
+ }
+ return
+ }
+
+ if attempt == tries-1 {
+ fmt.Printf("Command failed after %d tries\n", tries)
+ os.Exit(1)
+ }
+
+ // Prepare prompt for TellPlan
+ exitErr, ok := err.(*exec.ExitError)
+ status := -1
+ if ok {
+ status = exitErr.ExitCode()
+ }
+
+ prompt := fmt.Sprintf("'%s' failed with exit status %d. Output:\n\n%s\n\n--\n\n",
+ strings.Join(cmdArgs, " "), status, string(output))
+
+ plan_exec.TellPlan(plan_exec.ExecParams{
+ CurrentPlanId: lib.CurrentPlanId,
+ CurrentBranch: lib.CurrentBranch,
+ ApiKeys: apiKeys,
+ CheckOutdatedContext: func(maybeContexts []*shared.Context) (bool, bool, error) {
+ return lib.CheckOutdatedContextWithOutput(false, true, maybeContexts)
+ },
+ }, prompt, false, false, false, false, true, false)
+
+ lib.MustApplyPlan(lib.CurrentPlanId, lib.CurrentBranch, true, autoCommit, !autoCommit)
+ }
+}
diff --git a/app/cli/cmd/tell.go b/app/cli/cmd/tell.go
index 5ba0421a..0d5d383c 100644
--- a/app/cli/cmd/tell.go
+++ b/app/cli/cmd/tell.go
@@ -25,6 +25,7 @@ var tellPromptFile string
var tellBg bool
var tellStop bool
var tellNoBuild bool
+var tellAutoApply bool
// tellCmd represents the prompt command
var tellCmd = &cobra.Command{
@@ -43,6 +44,11 @@ func init() {
tellCmd.Flags().BoolVarP(&tellStop, "stop", "s", false, "Stop after a single reply")
tellCmd.Flags().BoolVarP(&tellNoBuild, "no-build", "n", false, "Don't build files")
tellCmd.Flags().BoolVar(&tellBg, "bg", false, "Execute autonomously in the background")
+
+ tellCmd.Flags().BoolVarP(&autoConfirm, "yes", "y", false, "Automatically confirm context updates")
+ tellCmd.Flags().BoolVar(&tellAutoApply, "apply", false, "Automatically apply changes (and confirm context updates)")
+ tellCmd.Flags().BoolVarP(&autoCommit, "commit", "c", false, "Commit changes to git when --apply/-a is passed")
+
}
func doTell(cmd *cobra.Command, args []string) {
@@ -106,9 +112,13 @@ func doTell(cmd *cobra.Command, args []string) {
CurrentBranch: lib.CurrentBranch,
ApiKeys: apiKeys,
CheckOutdatedContext: func(maybeContexts []*shared.Context) (bool, bool, error) {
- return lib.CheckOutdatedContextWithOutput(false, maybeContexts)
+ return lib.CheckOutdatedContextWithOutput(false, autoConfirm || tellAutoApply, maybeContexts)
},
- }, prompt, tellBg, tellStop, tellNoBuild, false)
+ }, prompt, tellBg, tellStop, tellNoBuild, false, false, false)
+
+ if tellAutoApply {
+ lib.MustApplyPlan(lib.CurrentPlanId, lib.CurrentBranch, true, autoCommit, !autoCommit)
+ }
}
func prepareEditorCommand(editor string, filename string) *exec.Cmd {
diff --git a/app/cli/lib/apply.go b/app/cli/lib/apply.go
index 86aac677..3b989a6d 100644
--- a/app/cli/lib/apply.go
+++ b/app/cli/lib/apply.go
@@ -13,7 +13,7 @@ import (
"github.com/plandex/plandex/shared"
)
-func MustApplyPlan(planId, branch string, autoConfirm bool) {
+func MustApplyPlan(planId, branch string, autoConfirm, autoCommit, noCommit bool) {
term.StartSpinner("")
currentPlanState, apiErr := api.Client.GetCurrentPlanState(planId, branch)
@@ -56,14 +56,14 @@ func MustApplyPlan(planId, branch string, autoConfirm bool) {
os.Exit(0)
}
- _, err = buildPlanInlineFn(nil)
+ _, err = buildPlanInlineFn(autoConfirm, nil)
if err != nil {
term.OutputErrorAndExit("failed to build plan: %v", err)
}
}
- anyOutdated, didUpdate, err := CheckOutdatedContextWithOutput(true, nil)
+ anyOutdated, didUpdate, err := CheckOutdatedContextWithOutput(true, autoConfirm, nil)
if err != nil {
term.OutputErrorAndExit("error checking outdated context: %v", err)
@@ -200,16 +200,19 @@ func MustApplyPlan(planId, branch string, autoConfirm bool) {
fmt.Println("✅ Applied changes, but no files were updated")
return
} else {
- if isRepo {
- fmt.Println("✏️ Plandex can commit these updates with an automatically generated message.")
- 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()
+ if isRepo && !noCommit {
+ confirmed := autoCommit
+ if !autoCommit {
+ fmt.Println("✏️ Plandex can commit these updates with an automatically generated message.")
+ 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?")
+ confirmed, err = term.ConfirmYesNo("Commit Plandex updates now?")
- if err != nil {
- onErr("failed to get confirmation user input: %s", err)
+ if err != nil {
+ onErr("failed to get confirmation user input: %s", err)
+ }
}
if confirmed {
diff --git a/app/cli/lib/build.go b/app/cli/lib/build.go
index 975d8291..6d0a541d 100644
--- a/app/cli/lib/build.go
+++ b/app/cli/lib/build.go
@@ -2,8 +2,8 @@ package lib
import "github.com/plandex/plandex/shared"
-var buildPlanInlineFn func(maybeContexts []*shared.Context) (bool, error)
+var buildPlanInlineFn func(autoConfirm bool, maybeContexts []*shared.Context) (bool, error)
-func SetBuildPlanInlineFn(fn func(maybeContexts []*shared.Context) (bool, error)) {
+func SetBuildPlanInlineFn(fn func(autoConfirm bool, maybeContexts []*shared.Context) (bool, error)) {
buildPlanInlineFn = fn
}
diff --git a/app/cli/lib/context_load.go b/app/cli/lib/context_load.go
index 092e0bf3..75e74351 100644
--- a/app/cli/lib/context_load.go
+++ b/app/cli/lib/context_load.go
@@ -413,7 +413,7 @@ func MustLoadContext(resources []string, params *types.LoadContextParams) {
if hasConflicts {
term.StartSpinner("🏗️ Starting build...")
- _, err := buildPlanInlineFn(nil)
+ _, err := buildPlanInlineFn(false, nil)
if err != nil {
onErr(fmt.Errorf("failed to build plan: %v", err))
diff --git a/app/cli/lib/context_update.go b/app/cli/lib/context_update.go
index 20074dd9..eda558f4 100644
--- a/app/cli/lib/context_update.go
+++ b/app/cli/lib/context_update.go
@@ -20,7 +20,7 @@ import (
"github.com/plandex/plandex/shared"
)
-func CheckOutdatedContextWithOutput(quiet bool, maybeContexts []*shared.Context) (contextOutdated, updated bool, err error) {
+func CheckOutdatedContextWithOutput(quiet, autoConfirm bool, maybeContexts []*shared.Context) (contextOutdated, updated bool, err error) {
if !quiet {
term.StartSpinner("🔬 Checking context...")
}
@@ -133,12 +133,14 @@ func CheckOutdatedContextWithOutput(quiet bool, maybeContexts []*shared.Context)
fmt.Println(tableString)
}
- var confirmed bool
+ confirmed := autoConfirm
- confirmed, err = term.ConfirmYesNo("Update context now?")
+ if !autoConfirm {
+ confirmed, err = term.ConfirmYesNo("Update context now?")
- if err != nil {
- term.OutputErrorAndExit("failed to get user input: %s", err)
+ if err != nil {
+ term.OutputErrorAndExit("failed to get user input: %s", err)
+ }
}
if confirmed {
@@ -452,7 +454,7 @@ func checkOutdatedAndMaybeUpdateContext(doUpdate bool, maybeContexts []*shared.C
if hasConflicts {
term.StartSpinner("🏗️ Starting build...")
- _, err := buildPlanInlineFn(nil) // don't pass in outdated contexts -- nil value causes them to be refetched, which is what we want since they were just updated
+ _, err := buildPlanInlineFn(false, nil) // don't pass in outdated contexts -- nil value causes them to be refetched, which is what we want since they were just updated
if err != nil {
return nil, fmt.Errorf("failed to build plan: %v", err)
diff --git a/app/cli/main.go b/app/cli/main.go
index 17f07925..40ee3ef6 100644
--- a/app/cli/main.go
+++ b/app/cli/main.go
@@ -27,7 +27,7 @@ func init() {
term.SetOpenUnauthenticatedCloudURLFn(ui.OpenUnauthenticatedCloudURL)
term.SetConvertTrialFn(auth.ConvertTrial)
- lib.SetBuildPlanInlineFn(func(maybeContexts []*shared.Context) (bool, error) {
+ lib.SetBuildPlanInlineFn(func(autoConfirm bool, maybeContexts []*shared.Context) (bool, error) {
var apiKeys map[string]string
if !auth.Current.IntegratedModelsMode {
apiKeys = lib.MustVerifyApiKeys()
@@ -37,7 +37,7 @@ func init() {
CurrentBranch: lib.CurrentBranch,
ApiKeys: apiKeys,
CheckOutdatedContext: func(maybeContexts []*shared.Context) (bool, bool, error) {
- return lib.CheckOutdatedContextWithOutput(true, maybeContexts)
+ return lib.CheckOutdatedContextWithOutput(true, autoConfirm, maybeContexts)
},
}, false)
})
diff --git a/app/cli/plan_exec/tell.go b/app/cli/plan_exec/tell.go
index ecf4a49e..67a3af16 100644
--- a/app/cli/plan_exec/tell.go
+++ b/app/cli/plan_exec/tell.go
@@ -21,8 +21,11 @@ func TellPlan(
tellBg,
tellStop,
tellNoBuild,
- isUserContinue bool,
+ isUserContinue,
+ isDebugCmd,
+ isChatOnly bool,
) {
+ done := make(chan struct{})
outputPromptIfTell := func() {
if isUserContinue || prompt == "" {
@@ -108,6 +111,7 @@ func TellPlan(
ProjectPaths: paths.ActivePaths,
BuildMode: buildMode,
IsUserContinue: isUserContinue,
+ IsUserDebug: isDebugCmd,
ApiKey: legacyApiKey, // deprecated
Endpoint: openAIBase, // deprecated
ApiKeys: params.ApiKeys,
@@ -160,10 +164,10 @@ func TellPlan(
if tellStop {
term.PrintCmds("", "continue", "diff", "diff --ui", "apply", "reject", "log", "rewind")
- } else {
+ } else if !isDebugCmd {
term.PrintCmds("", "diff", "diff --ui", "apply", "reject", "log", "rewind")
}
- os.Exit(0)
+ close(done)
}()
}
@@ -181,7 +185,6 @@ func TellPlan(
fmt.Println()
term.PrintCmds("", "ps", "connect", "stop")
} else {
- // Wait for stream UI to quit
- select {}
+ <-done
}
}
diff --git a/app/cli/stream_tui/update.go b/app/cli/stream_tui/update.go
index d9ef107b..24d3cf0d 100644
--- a/app/cli/stream_tui/update.go
+++ b/app/cli/stream_tui/update.go
@@ -303,6 +303,7 @@ func (m *streamUIModel) streamUpdate(msg *shared.StreamMessage, deferUIUpdate bo
}
if m.processing {
+ log.Println("Message reply, setting processing to false")
m.processing = false
if m.promptedMissingFile {
m.promptedMissingFile = false
@@ -353,6 +354,7 @@ func (m *streamUIModel) streamUpdate(msg *shared.StreamMessage, deferUIUpdate bo
return m, tea.Batch(cmds...)
case shared.StreamMessageDescribing:
+ log.Println("Message describing, setting processing to true")
m.processing = true
cmds := []tea.Cmd{m.spinner.Tick}
@@ -377,6 +379,7 @@ func (m *streamUIModel) streamUpdate(msg *shared.StreamMessage, deferUIUpdate bo
return m, tea.Quit
case shared.StreamMessageRepliesFinished:
+ log.Println("Replies finished, setting processing to false")
m.processing = false
if m.building {
diff --git a/app/server/model/plan/build_exec.go b/app/server/model/plan/build_exec.go
index 1544c637..cef5622b 100644
--- a/app/server/model/plan/build_exec.go
+++ b/app/server/model/plan/build_exec.go
@@ -280,6 +280,7 @@ func (fileState *activeBuildStreamFileState) buildFile() {
log.Printf("Current state num tokens: %d\n", currentNumTokens)
activeBuild.CurrentFileTokens = currentNumTokens
+ activePlan.DidEditFiles = true
}
if fileState.parser != nil && !fileState.preBuildStateSyntaxInvalid {
diff --git a/app/server/model/plan/build_structured_edits.go b/app/server/model/plan/build_structured_edits.go
index 982b5c5f..4cc12fc4 100644
--- a/app/server/model/plan/build_structured_edits.go
+++ b/app/server/model/plan/build_structured_edits.go
@@ -40,10 +40,13 @@ func (fileState *activeBuildStreamFileState) buildStructuredEdits() {
if activePlan == nil {
log.Printf("Active plan not found for plan ID %s and branch %s\n", planId, branch)
- fileState.onBuildFileError(fmt.Errorf("active plan not found for plan ID %s and branch %s\n", planId, branch))
+ fileState.onBuildFileError(fmt.Errorf("active plan not found for plan ID %s and branch %s", planId, branch))
return
}
+ proposedContentLines := strings.Split(activeBuild.FileContent, "\n")
+ originalContentLines := strings.Split(originalFile, "\n")
+
log.Println("buildStructuredEdits - getting references prompt")
anchorsSysPrompt := prompts.GetSemanticAnchorsPrompt(filePath, originalFile, activeBuild.FileContent, activeBuild.FileDescription)
@@ -186,7 +189,12 @@ func (fileState *activeBuildStreamFileState) buildStructuredEdits() {
return
}
- anchorLines[proposedLine] = originalLine
+ proposedContent := proposedContentLines[proposedLine-1]
+ originalContent := originalContentLines[originalLine-1]
+
+ if proposedContent != originalContent {
+ anchorLines[proposedLine] = originalLine
+ }
}
fileContentLines := strings.Split(activeBuild.FileContent, "\n")
@@ -272,7 +280,7 @@ func (fileState *activeBuildStreamFileState) structuredEditRetryOrError(err erro
if fileState.structuredEditNumRetry < MaxBuildErrorRetries {
fileState.structuredEditNumRetry++
- log.Printf("buildStructuredEdits - retrying expand refs file '%s' due to error: %v\n", fileState.filePath, err)
+ log.Printf("buildStructuredEdits - retrying structured edits file '%s' due to error: %v\n", fileState.filePath, err)
activePlan := GetActivePlan(fileState.plan.Id, fileState.branch)
diff --git a/app/server/model/plan/exec_status.go b/app/server/model/plan/exec_status.go
index 15837f5d..b25cc411 100644
--- a/app/server/model/plan/exec_status.go
+++ b/app/server/model/plan/exec_status.go
@@ -219,7 +219,8 @@ func (state *activeTellStreamState) execStatusShouldContinue(message string, lat
return false, "", nil
}
- log.Printf("Plan exec status response: %v\n", res)
+ log.Println("Plan exec status response:")
+ log.Println(spew.Sdump(res))
return res.ShouldContinue, res.Reasoning, nil
}
diff --git a/app/server/model/plan/tell_exec.go b/app/server/model/plan/tell_exec.go
index f8cf2dfb..99deeeb3 100644
--- a/app/server/model/plan/tell_exec.go
+++ b/app/server/model/plan/tell_exec.go
@@ -320,7 +320,12 @@ func execTellPlan(
} else {
var prompt string
if iteration == 0 {
- prompt = req.Prompt
+ if req.IsUserDebug {
+ prompt = prompts.DebugPrompt + req.Prompt
+ state.totalRequestTokens += prompts.DebugPromptTokens
+ } else {
+ prompt = req.Prompt
+ }
} else if verifyDiffs != "" {
prompt = prompts.VerifyDiffsPrompt + verifyDiffs
diff --git a/app/server/model/plan/tell_stream.go b/app/server/model/plan/tell_stream.go
index ed0c2a83..afe42215 100644
--- a/app/server/model/plan/tell_stream.go
+++ b/app/server/model/plan/tell_stream.go
@@ -410,6 +410,7 @@ mainLoop:
if active.ShouldVerifyDiff() {
// If we're going to verify the diffs when build finishes, then replies aren't finished yet so we'll just continue here
+ log.Println("Replies aren't finished yet—waiting on verify diff step")
continue mainLoop
} else {
log.Println("Updating status to building")
diff --git a/app/server/model/prompts/build_update.go b/app/server/model/prompts/build_update.go
index 95e9a51d..84bbece6 100644
--- a/app/server/model/prompts/build_update.go
+++ b/app/server/model/prompts/build_update.go
@@ -14,7 +14,7 @@ func GetSemanticAnchorsPrompt(filePath, preBuildState, changesFile, changesDesc
s += fmt.Sprintf("Proposed updates:\n%s\n```\n%s\n```", changesDesc, changesWithLineNums)
- fmt.Printf("SemanticAnchorsPrompt: %s\n", s)
+ // fmt.Printf("SemanticAnchorsPrompt: %s\n", s)
return s
}
diff --git a/app/server/model/prompts/create.go b/app/server/model/prompts/create.go
index 6c78944a..4d77be41 100644
--- a/app/server/model/prompts/create.go
+++ b/app/server/model/prompts/create.go
@@ -85,7 +85,7 @@ const SysCreate = Identity + ` A plan is a set of files with an attached context
When you are updating an existing file in context: include the *minimum amount of code* necessary in code blocks to describe the suggested changes. Include only lines that are changing and lines that make it clear where the change should be applied. When updating an existing file in context, you can use the *reference comment* "// ... existing code ..." (with the appropriate comment symbol for the programming language) instead of including large sections from the original file in order to make it clear where changes should be applied. You *must not* include more lines from the original file than are absolutely necessary to make the location, structure, and order of suggested changes clear.
- Instead, show only the code that is changing and the immediately surrounding code that is necessary to understand the changes. Use the comment "// ... existing code ..." (with the appropriate comment symbol for the programming language) to replace sections of code from the original file and denote where the existing code should be placed. Again, 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 NOT use the comment "// ... existing code ..." (or any equivalent) when creating a new file.
+ Instead, show only the code that is changing and the immediately surrounding code that is necessary to understand the changes. Use the comment "// ... existing code ..." (with the appropriate comment symbol for the programming language) to replace sections of code from the original file and denote where the existing code should be placed. Again, 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 NOT use the comment "// ... existing code ..." (or any equivalent) when creating a new file.
` + UpdateFormatPrompt + `
@@ -137,9 +137,11 @@ const SysCreate = Identity + ` A plan is a set of files with an attached context
You are able to create and update files, but you are not able to execute code or commands. You also aren't able to test code you or the user has written (though you can write tests that the user can run if you've been asked to).
- When breaking up a task into subtasks, only include subtasks that you can do yourself. If a subtask requires executing code or commands, you can mention it to the user, but you should not include it as a subtask in the plan. Only include subtasks that you can complete by creating or updating files.
+ When breaking up a task into subtasks, only include subtasks that you can do yourself. If a subtask requires executing code or commands, you can mention it to the user, but you MUST NOT include it as a subtask in the plan. Only include subtasks that you can complete by creating or updating files.
- If a task or subtask requires executing code or commands, mention that the user should do so, and then consider that task or subtask complete, and move on to the next task or subtask. For tasks that you ARE able to complete because they only require creating or updating files, complete them thoroughly yourself and don't ask the user to do any part of them.
+ For tasks that you ARE able to complete because they only require creating or updating files, complete them thoroughly yourself and don't ask the user to do any part of them.
+
+ You MUST consider the plan complete if the only remaining tasks must be completed by the user. Explicitly state when this is the case.
Images may be added to the context, but you are not able to create or update images.
@@ -165,7 +167,7 @@ const SysCreate = Identity + ` A plan is a set of files with an attached context
- If any summaries of the plan have been included in the conversation that list all the subtasks and mark each one 'Implemented' or 'Not implemented', consider only the *latest* summary. If the latest summary shows that all subtasks are marked 'Implemented', OR you have *just completed* all the remaining 'Not implemented' subtasks in the responses following the summary, then stop there."
Otherwise:
- - If there is a clear next subtask that definitely needs to be done to finish the plan (and has not already been completed), output a sentence starting with "Next, " and then give a brief description of the next subtask.
+ - If there is a clear next subtask that definitely needs to be done to finish the plan (and has not already been completed), output a sentence starting with "Next, " and then give a brief description of the next subtask.
- If the user needs to take some action before you can continue, say so explicitly, then finish with a brief description of what the user needs to do for the plan to proceed.
- You must not output any other text after this final paragraph. It *must* be the last thing in your response
@@ -176,6 +178,8 @@ const SysCreate = Identity + ` A plan is a set of files with an attached context
- If you think the plan is done, say so, but remember that you don't have the final word on the matter. Explain why you think the plan is done.
+ - If you think the plan is done and any file blocks have been used in the plan: unless the diffs for the plan have been supplied to you in the prompt for you to verify, state that you think the plan is done (as described above), but that you will proceed to verify the generated files before the plan is fully complete.
+
## EXTREMELY IMPORTANT Rules for responses
You *must never respond with just a single paragraph.* Every response should include at least a few paragraphs that try to move a plan forward. You *especially must never* reply with just a single paragraph that begins with "Next,".
@@ -240,6 +244,8 @@ Only list out subtasks once for the plan--after that, do not list or describe a
Do not ask the user to do anything that you can do yourself with a code block. Do not say a task is too large or complex for you to complete--do your best to break down the task and complete it even if it's very large or complex.
+You can ONLY create or update files. You cannot execute code or commands. If a task or subtask requires executing code or commands, mention that the user should do so and move on. You MUST consider the plan complete if the only remaining tasks must be completed by the user. Explicitly state when this is the case.
+
Do not implement a task partially and then give up even if it's very large or complex--do your best to implement each task and subtask **fully**.
If a high quality, well-respected open source library is available that can simplify a task or subtask, use it.
@@ -282,9 +288,9 @@ const SkippedPathsPrompt = "\n\nSome files have been skipped by the user and *mu
const VerifyDiffsPrompt = `Below are the diffs for the plan you've created. Based on the diffs, evaluate whether the plan has been completed correctly or whether there are problems to address. Pay particular attention to syntax errors, code that has been incorrectly removed, or code that has been incorrectlyduplicated.
-Do not additional features or functionality to the plan. Your job at this stage is to check your work and ensure that the diffs have been generated correctly based on the existing plan, not to increase the scope of the plan or add new tasks beyond fixing any problems in the diffs.
+You MUST NOT add additional features or functionality to the plan. Your job at this stage is to check your work and ensure that the diffs have been generated correctly based on the existing plan, not to increase the scope of the plan or add new tasks beyond fixing any problems in the diffs.
-If there are no problems, state in your own words that the plan appears to have been generated correctly and is now complete.
+If there are no problems, state in your own words that the plan appears to have been generated correctly and is now complete. If there are no problems, be very succinct. Don't summarize the plan or the diffs, or add additional detail. Just state in a few words that the plan is complete.
If there are problems, explain the problems and make a plan to fix them. You can use multiple responses to fix all the problems if necessary. If you've identified problems, don't skip any—fix them all thoroughly and don't stop until the plan is correct.
@@ -294,6 +300,17 @@ Here are the diffs:
var VerifyDiffsPromptTokens int
+const DebugPrompt = `You are debugging a failing shell command. Focus only on fixing this issue so that the command runs successfully; don't make other changes.
+
+Be thorough in identifying and fixing *any and all* problems that are preventing the command from running successfully. If there are multiple problems, identify and fix all of them.
+
+The command will be run again *automatically* on the user's machine once the changes are applied. DO NOT consider running the command to be a subtask of the plan. Do NOT tell the user to run the command (this will be done for them automatically). Just make the necessary changes and then stop there.
+
+Command details:
+`
+
+var DebugPromptTokens int
+
func init() {
var err error
CreateSysMsgNumTokens, err = shared.GetNumTokens(SysCreate)
@@ -319,6 +336,12 @@ func init() {
if err != nil {
panic(fmt.Sprintf("Error getting number of tokens for verify diffs prompt: %v", err))
}
+
+ DebugPromptTokens, err = shared.GetNumTokens(DebugPrompt)
+
+ if err != nil {
+ panic(fmt.Sprintf("Error getting number of tokens for debug prompt: %v", err))
+ }
}
const UpdateFormatPrompt = `
@@ -384,7 +407,7 @@ class FooBar {
ALWAYS use the above format when updating a file. You MUST NEVER UNDER ANY CIRCUMSTANCES leave out an "... existing code ..." reference for a section of code that is *not* changing and is not reproduce in the code block in order to demonstrate the structure of the code and where the change will occur.
-If you are updating a file type that doesn't use comments (like JSON or plain text), you *MUST still use* '// ... existing code ...' to denote where the reference should be placed. It's ok if // is not a comment in the file type or if these references break the syntax of the file type, since they will be replaced by the correct code from the original file. You MUST still use "// ... existing code ..." references regardless of the file type. Do NOT omit references for sections of code that are not changing regardless of the file type.
+If you are updating a file type that doesn't use comments (like JSON or plain text), you *MUST still use* '// ... existing code ...' to denote where the reference should be placed. It's ok if // is not a comment in the file type or if these references break the syntax of the file type, since they will be replaced by the correct code from the original file. You MUST still use "// ... existing code ..." references regardless of the file type. Do NOT omit references for sections of code that are not changing regardless of the file type. Remember, this *ONLY* applies to files that don't use comments. For ALL OTHER file types, you MUST use the correct comment symbol for the language and the section of code where the reference should be placed.
For example, in a JSON file:
@@ -943,4 +966,10 @@ func main() {
---
Now the code before and after the change is accounted for.
+
+*
+
+When writing an "... existing code ..." comment, you MUST use the correct comment symbol for the programming language. For example, if you are writing a plan in Python, Ruby, or Bash, you MUST use '# ... existing code ...' instead of '// ... existing code ...'. If you're writing HTML, you MUST use '<!-- ... existing code ... -->'. If you're writing jsx, tsx, svelte, or another language where the correct comment symbol(s) depend on where in the code you are, use the appropriate comment symbol(s) for where that comment is placed in the file. If you're in a javascript block of a jsx file, use '// ... existing code ...'. If you're in a markup block of a jsx file, use '{/* ... existing code ... */}'.
+
+Again, if you are writing a plan in a language that does not use '//' for comments, you absolutely must always use the appropriate comment symbol or symbols for that language instead of '//'. It is critically important that comments are ALWAYS written correctly for the language you are writing in.
`
diff --git a/app/server/model/prompts/exec_status.go b/app/server/model/prompts/exec_status.go
index 6e2c3f41..bbeb1c66 100644
--- a/app/server/model/prompts/exec_status.go
+++ b/app/server/model/prompts/exec_status.go
@@ -19,6 +19,8 @@ If any new subtasks have been added to plan that haven't been implemented yet, e
If A1 1 has indicated that the plan is complete, but there are still subtasks remaining that have not been implemented, the plan should continue despite AI 1's statement that the plan is complete. The plan should only be considered complete if all tasks and subtasks have been fully implemented.
+If AI 1 mentions that it has verified the plan's diffs, and either that there were no problems to fix or that it fixed all the problems, the plan must *NOT* continue, regardless of any other criteria. If AI 1 mentions that it has verified the plan's diffs, but there are still problems remaining to be fixed, the plan should continue.
+
DO NOT only go by the latest summary when considering whether subtasks are complete. You MUST also consider the latest message from AI 1 and the previous message from AI 1 if it is provided. If the latest or previous message from AI 1 has new subtasks that have not been implemented, the plan should continue. If the latest or previous message from AI 1 has *finished* subtasks that are not marked as implemented in the summary, you MUST consider them as implemented.
If no subtasks are remaining to be implemented:
@@ -42,6 +44,8 @@ Between all of these sources, explain whether all subtasks have been implemented
If there are any todo placeholders in the 'comments' array, list them ALL in 'reasoning'.
+If all the steps remaining are for the *user* to complete, you MUST state that the plan is complete in 'reasoning'. AI 1 can only create or update files. It cannot execute commands, run tests, or do anything else that requires user action. The task must only continue if there are still steps remaining that aren't yet completed and that AI 1 can do.
+
If the plan should continue, you MUST state what the immediate next step should be in 'reasoning'. You MUST NOT state any subtasks that have been marked implemented in the summary or completed in the latest message or previous message from AI 1. You MUST only state what the next unimplemented subtask is and that should be done next. Subtasks MUST ALWAYS be completed in order. If subtask 3 was just completed in the latest message, and subtask 4 is the next unimplemented subtask in numerical order, you MUST state that subtask 4 should be done next. You MUST NOT skip any subtasks. You MUST NOT repeat any subtasks that have already been completed, either in the summary or in the latest or previous message from AI 1. If there is no immediate next subtask, you MUST state that the plan is complete.
Set 'shouldContinue' to true if the plan should automatically continue based on your instructions above, or false otherwise.
diff --git a/app/server/syntax/comments.go b/app/server/syntax/comments.go
index a8a5a8fe..b6131c05 100644
--- a/app/server/syntax/comments.go
+++ b/app/server/syntax/comments.go
@@ -58,3 +58,24 @@ func findCommentNodes(node *tree_sitter.Node) []*tree_sitter.Node {
return commentNodes
}
+
+func GetCommentSymbols(lang string) (string, string) {
+ switch lang {
+ case "c", "cpp", "csharp", "java", "javascript", "go", "rust", "swift", "kotlin", "groovy", "scala", "typescript", "php":
+ return "//", ""
+ case "bash", "dockerfile", "elixir", "hcl", "python", "ruby", "toml", "yaml":
+ return "#", ""
+ case "lua", "elm":
+ return "--", ""
+ case "css":
+ return "/*", "*/"
+ case "html":
+ return "<!--", "-->"
+ case "ocaml":
+ return "(*", "*)"
+ case "svelte", "jsx", "tsx", "json":
+ return "", "" // comments are either not allowed or correct symbols depend on the context
+ }
+
+ return "", ""
+}
diff --git a/app/server/syntax/structural_edits.go b/app/server/syntax/structural_edits.go
index c00ff068..57f2ec02 100644
--- a/app/server/syntax/structural_edits.go
+++ b/app/server/syntax/structural_edits.go
@@ -65,22 +65,24 @@ func ApplyChanges(
originalLines := strings.Split(original, "\n")
proposedLines := strings.Split(proposed, "\n")
- // if language == "json" {
- // for i, line := range proposedLines {
- // // keep indentation for syntax parsing
- // content := strings.TrimSpace(line)
- // if removalsByLine[Removal(i+1)] {
- // proposedLines[i] = strings.Replace(line, content, "", 1)
- // } else if refsByLine[Reference(i+1)] {
- // proposedLines[i] = strings.Replace(line, content, "", 1)
- // }
- // }
- // }
-
- proposedWithoutRemovals := strings.Join(proposedLines, "\n")
+ // normalize comments in case the wrong comment symbols were used
+ openingCommentSymbol, closingCommentSymbol := GetCommentSymbols(language)
+ if openingCommentSymbol != "" {
+ for i, line := range proposedLines {
+ // keep indentation for syntax parsing
+ content := strings.TrimSpace(line)
+
+ if removalsByLine[Removal(i+1)] || refsByLine[Reference(i+1)] {
+ comment := openingCommentSymbol + " ref " + closingCommentSymbol
+ proposedLines[i] = strings.Replace(line, content, comment, 1)
+ }
+ }
+ }
+
+ proposedWithNormalizedComments := strings.Join(proposedLines, "\n")
originalBytes := []byte(original)
- proposedBytes := []byte(proposedWithoutRemovals)
+ proposedBytes := []byte(proposedWithNormalizedComments)
originalTree, err := parser.ParseCtx(ctx, nil, originalBytes)
if err != nil {
diff --git a/app/server/types/active_plan.go b/app/server/types/active_plan.go
index d928285e..3dc1a419 100644
--- a/app/server/types/active_plan.go
+++ b/app/server/types/active_plan.go
@@ -79,6 +79,7 @@ type ActivePlan struct {
AllowOverwritePaths map[string]bool
SkippedPaths map[string]bool
StoredReplyIds []string
+ DidEditFiles bool
DidVerifyDiff bool
subscriptions map[string]*subscription
@@ -355,7 +356,17 @@ func (sub *subscription) enqueueMessage(msg string) {
}
func (ap *ActivePlan) ShouldVerifyDiff() bool {
- return !ap.BuildOnly && !ap.DidVerifyDiff && len(ap.BuiltFiles) > 0
+ // log.Printf("ShouldVerifyDiff: buildOnly=%v, didVerifyDiff=%v, numBuiltFiles=%d, didEditFiles=%v, hasMultipleBuiltFiles=%v",
+ // !ap.BuildOnly,
+ // !ap.DidVerifyDiff,
+ // len(ap.BuiltFiles),
+ // ap.DidEditFiles,
+ // len(ap.BuiltFiles) > 3)
+
+ return !ap.BuildOnly &&
+ !ap.DidVerifyDiff &&
+ (len(ap.BuiltFiles) > 0 || len(ap.IsBuildingByPath) > 0) &&
+ (ap.DidEditFiles || len(ap.BuiltFiles) > 3) // verify diff if we edited any files or built more than 3 new files—unlikely to have errors otherwise
}
func (ap *ActivePlan) Finish() {
diff --git a/app/server/types/anchors.go b/app/server/types/anchors.go
index e96004cb..f9ffc45d 100644
--- a/app/server/types/anchors.go
+++ b/app/server/types/anchors.go
@@ -8,7 +8,7 @@ type SemanticAnchorsTag struct {
}
type AnchorTag struct {
- Reasoning string `xml:"reasoning,attr"`
+ // Reasoning string `xml:"reasoning,attr"` // better to leave this out since it can cause problems with unmarshalling and isn't used after parsing
ProposedLine string `xml:"proposedLine,attr"`
OriginalLine string `xml:"originalLine,attr"`
}
diff --git a/app/shared/req_res.go b/app/shared/req_res.go
index ec4f01af..018acbc7 100644
--- a/app/shared/req_res.go
+++ b/app/shared/req_res.go
@@ -120,6 +120,8 @@ type TellPlanRequest struct {
ConnectStream bool `json:"connectStream"`
AutoContinue bool `json:"autoContinue"`
IsUserContinue bool `json:"isUserContinue"`
+ IsUserDebug bool `json:"isUserDebug"`
+ IsChatOnly bool `json:"isChatOnly"`
ApiKey string `json:"apiKey"` // deprecated
Endpoint string `json:"endpoint"` // deprecated
ApiKeys map[string]string `json:"apiKeys"`