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
some updates for locking/branches, db helpers, sort results fix, and experimenting with a new build approach
Dane Schneidera86ccc286ebe
diff --git a/app/server/db/branch_helpers.go b/app/server/db/branch_helpers.goindex d53b3cc2..e3555df6 100644--- a/app/server/db/branch_helpers.go+++ b/app/server/db/branch_helpers.go@@ -80,12 +80,12 @@ func CreateBranch(plan *Plan, parentBranch *Branch, name string, tx *sqlx.Tx) (*// Create the git branch (except for main, which is created by default on repo init)if name != "main" {- parentBranchName := "main"- if parentBranch != nil {- parentBranchName = parentBranch.Name- }+ // parentBranchName := "main"+ // if parentBranch != nil {+ // parentBranchName = parentBranch.Name+ // }- err = GitCreateBranch(plan.OrgId, plan.Id, parentBranchName, name)+ err = GitCreateBranch(plan.OrgId, plan.Id, name)if err != nil {return nil, fmt.Errorf("error creating git branch: %v", err)diff --git a/app/server/db/convo_helpers.go b/app/server/db/convo_helpers.goindex c9983d67..780096a0 100644--- a/app/server/db/convo_helpers.go+++ b/app/server/db/convo_helpers.go@@ -67,6 +67,25 @@ func GetPlanConvo(orgId, planId string) ([]*ConvoMessage, error) {return convo, nil}+func GetConvoMessage(orgId, planId, messageId string) (*ConvoMessage, error) {+ convoDir := getPlanConversationDir(orgId, planId)++ filePath := filepath.Join(convoDir, messageId+".json")++ bytes, err := os.ReadFile(filePath)+ if err != nil {+ return nil, fmt.Errorf("error reading convo message: %v", err)+ }++ var convoMessage ConvoMessage+ err = json.Unmarshal(bytes, &convoMessage)+ if err != nil {+ return nil, fmt.Errorf("error unmarshalling convo message: %v", err)+ }++ return &convoMessage, nil+}+func StoreConvoMessage(message *ConvoMessage, currentUserId, branch string, commit bool) (string, error) {convoDir := getPlanConversationDir(message.OrgId, message.PlanId)diff --git a/app/server/db/data_models.go b/app/server/db/data_models.goindex 1b45d8ca..a7ff51b9 100644--- a/app/server/db/data_models.go+++ b/app/server/db/data_models.go@@ -280,7 +280,7 @@ const (type repoLock struct {Id string `db:"id"`- OrgId *string `db:"org_id"`+ OrgId string `db:"org_id"`UserId *string `db:"user_id"`PlanId string `db:"plan_id"`Scope LockScope `db:"scope"`diff --git a/app/server/db/git.go b/app/server/db/git.goindex a2cd7ef4..0d3fdd22 100644--- a/app/server/db/git.go+++ b/app/server/db/git.go@@ -103,6 +103,43 @@ func GetLatestCommit(orgId, planId, branch string) (sha, body string, err error)return sha, body, nil}+func GetLatestCommitShaBeforeTime(orgId, planId, branch string, before time.Time) (sha string, err error) {+ dir := getPlanDir(orgId, planId)++ log.Printf("ADMIN - GetLatestCommitShaBeforeTime - dir: %s, before: %s", dir, before.Format("2006-01-02T15:04:05Z"))++ // Round up to the next second+ // roundedTime := before.Add(time.Second).Truncate(time.Second)++ gitFormattedTime := before.Format("2006-01-02 15:04:05+0000")++ // log.Printf("ADMIN - Git formatted time: %s", gitFormattedTime)++ cmd := exec.Command("git", "-C", dir, "log", "-n", "1",+ "--before="+gitFormattedTime,+ "--pretty=%h@@|@@%B@>>>@")+ log.Printf("ADMIN - Executing command: %s", cmd.String())+ res, err := cmd.CombinedOutput()+ if err != nil {+ return "", fmt.Errorf("error getting latest commit before time for dir: %s, err: %v, output: %s", dir, err, string(res))+ }++ // log.Printf("ADMIN - git log res: %s", string(res))++ output := strings.TrimSpace(string(res))++ // history := processGitHistoryOutput(strings.TrimSpace(string(res)))++ // log.Printf("ADMIN - History: %v", history)++ if output == "" {+ return "", fmt.Errorf("no commits found before time: %s", before.Format("2006-01-02T15:04:05Z"))+ }++ sha = strings.Split(output, "@@|@@")[0]+ return sha, nil+}+func GitListBranches(orgId, planId string) ([]string, error) {dir := getPlanDir(orgId, planId)@@ -124,7 +161,7 @@ func GitListBranches(orgId, planId string) ([]string, error) {return branches, nil}-func GitCreateBranch(orgId, planId, branch, newBranch string) error {+func GitCreateBranch(orgId, planId, newBranch string) error {dir := getPlanDir(orgId, planId)res, err := exec.Command("git", "-C", dir, "checkout", "-b", newBranch).CombinedOutput()@@ -174,9 +211,14 @@ func GitClearUncommittedChanges(orgId, planId string) error {}// Not used currently but may be good to handle these errors specifically later if locking can't fully prevent them-// func isLockFileError(output string) bool {-// return strings.Contains(output, "fatal: Unable to create") && strings.Contains output, ".git/index.lock': File exists")-// }+//+// func isLockFileError(output string) bool {+// return strings.Contains(output, "fatal: Unable to create") && strings.Contains output, ".git/index.lock': File exists")+// }+func GitCheckoutBranch(orgId, planId, branch string) error {+ dir := getPlanDir(orgId, planId)+ return gitCheckoutBranch(dir, branch)+}func gitCheckoutBranch(repoDir, branch string) error {// get current branch and only checkout if it's not the same@@ -186,6 +228,9 @@ func gitCheckoutBranch(repoDir, branch string) error {cmd.Stdout = &outerr := cmd.Run()if err != nil {+ // log output+ log.Printf("error getting current git branch for dir: %s, err: %v, output: %s", repoDir, err, out.String())+return fmt.Errorf("error getting current git branch for dir: %s, err: %v", repoDir, err)}diff --git a/app/server/db/locks.go b/app/server/db/locks.goindex 1059fa59..a775d76a 100644--- a/app/server/db/locks.go+++ b/app/server/db/locks.go@@ -48,6 +48,16 @@ func lockRepo(params LockRepoParams, numRetry int) (string, error) {ctx := params.CtxcancelFn := params.CancelFn+ if orgId == "" {+ return "", fmt.Errorf("orgId is required")+ }+ if planId == "" {+ return "", fmt.Errorf("planId is required")+ }+ if scope != LockScopeRead && scope != LockScopeWrite {+ return "", fmt.Errorf("invalid lock scope: %s", scope)+ }+tx, err := Conn.BeginTxx(ctx, &sql.TxOptions{Isolation: sql.LevelRepeatableRead})if err != nil {return "", fmt.Errorf("error starting transaction: %v", err)@@ -193,14 +203,12 @@ func lockRepo(params LockRepoParams, numRetry int) (string, error) {newLock := &repoLock{PlanId: planId,+ OrgId: orgId,PlanBuildId: lockPlanBuildId,Scope: scope,Branch: lockBranch,}- if orgId != "" {- newLock.OrgId = &orgId- }if userId != "" {newLock.UserId = &userId}diff --git a/app/server/db/result_helpers.go b/app/server/db/result_helpers.goindex 0f9d50cd..6e9c1154 100644--- a/app/server/db/result_helpers.go+++ b/app/server/db/result_helpers.go@@ -162,7 +162,7 @@ func GetCurrentPlanState(params CurrentPlanStateParams) (*shared.CurrentPlanStatpendingContextsByPath[path] = context.ToApi()}- log.Println("Pending contexts by path:", len(pendingContextsByPath))+ // log.Println("Pending contexts by path:", len(pendingContextsByPath))planState := &shared.CurrentPlanState{PlanResult: planResult,diff --git a/app/server/handlers/fs_helper.go b/app/server/handlers/fs_helper.goindex 4ccc603f..d0349757 100644--- a/app/server/handlers/fs_helper.go+++ b/app/server/handlers/fs_helper.go@@ -23,17 +23,37 @@ func LockRepo(w http.ResponseWriter, r *http.Request, auth *types.ServerAuth, screturn nil}- repoLockId, err := db.LockRepo(- db.LockRepoParams{- OrgId: auth.OrgId,- UserId: auth.User.Id,- PlanId: planId,- Branch: branch,- Scope: scope,- Ctx: ctx,- CancelFn: cancelFn,- },- )+ return lockRepo(w, r, auth, scope, ctx, cancelFn, planId, branch)+}++func LockRepoForBranch(w http.ResponseWriter, r *http.Request, auth *types.ServerAuth, scope db.LockScope, ctx context.Context, cancelFn context.CancelFunc, branch string) *func(err error) {+ vars := mux.Vars(r)+ planId := vars["planId"]++ return lockRepo(w, r, auth, scope, ctx, cancelFn, planId, branch)+}++func lockRepo(w http.ResponseWriter, r *http.Request, auth *types.ServerAuth, scope db.LockScope, ctx context.Context, cancelFn context.CancelFunc, planId, branch string) *func(err error) {+ params := db.LockRepoParams{+ PlanId: planId,+ Branch: branch,+ Scope: scope,+ Ctx: ctx,+ CancelFn: cancelFn,+ }+ if auth == nil {+ // error out+ log.Println("Auth required")+ http.Error(w, "Auth required", http.StatusInternalServerError)+ return nil+ } else {+ params.OrgId = auth.OrgId+ if auth.User != nil {+ params.UserId = auth.User.Id+ }+ }++ repoLockId, err := db.LockRepo(params)if err != nil {log.Printf("Error locking repo: %v\n", err)diff --git a/app/server/migrations/2024100900_update_locks.down.sql b/app/server/migrations/2024100900_update_locks.down.sqlindex 28d38c67..9379da54 100644--- a/app/server/migrations/2024100900_update_locks.down.sql+++ b/app/server/migrations/2024100900_update_locks.down.sql@@ -1,13 +1,12 @@--- Revert user_id and org_id to NOT NULL if no NULL values exist+-- Revert user_id to NOT NULL if no NULL values existDO $$BEGIN- -- Check for NULL values in user_id and org_id- IF EXISTS (SELECT 1 FROM repo_locks WHERE user_id IS NULL OR org_id IS NULL) THEN- RAISE EXCEPTION 'Cannot revert to NOT NULL, as there are rows with NULL values in user_id or org_id.';+ -- Check for NULL values in user_id+ IF EXISTS (SELECT 1 FROM repo_locks WHERE user_id IS NULL) THEN+ RAISE EXCEPTION 'Cannot revert to NOT NULL, as there are rows with NULL values in user_id.';ELSE-- Proceed with setting the columns to NOT NULLALTER TABLE repo_locks- ALTER COLUMN user_id SET NOT NULL,- ALTER COLUMN org_id SET NOT NULL;+ ALTER COLUMN user_id SET NOT NULL;END IF;END $$;diff --git a/app/server/migrations/2024100900_update_locks.up.sql b/app/server/migrations/2024100900_update_locks.up.sqlindex 880a0b4a..ab8d070f 100644--- a/app/server/migrations/2024100900_update_locks.up.sql+++ b/app/server/migrations/2024100900_update_locks.up.sql@@ -1,3 +1,2 @@ALTER TABLE repo_locks- ALTER COLUMN user_id DROP NOT NULL,- ALTER COLUMN org_id DROP NOT NULL;+ ALTER COLUMN user_id DROP NOT NULL;diff --git a/app/server/model/plan/build_result.go b/app/server/model/plan/build_result.goindex cdabce0d..9e220867 100644--- a/app/server/model/plan/build_result.go+++ b/app/server/model/plan/build_result.go@@ -250,7 +250,7 @@ func (fileState *activeBuildStreamFileState) onBuildResult(res types.ChangesWithConvoMessageId: build.ConvoMessageId,FilePath: filePath,PreBuildState: preBuildState,- ChangesWithLineNums: res.Changes,+ ChangesWithLineNums: sorted,OverlapStrategy: overlapStrategy,CheckSyntax: false,},diff --git a/app/server/model/prompts/build_update.go b/app/server/model/prompts/build_update.gonew file mode 100644index 00000000..f8afdb3c--- /dev/null+++ b/app/server/model/prompts/build_update.go@@ -0,0 +1,206 @@+package prompts++import (+ "fmt"++ "github.com/plandex/plandex/shared"+)++func GetUpdatedBuildPrompt(filePath, preBuildState, changesFile, changesDesc string) string {+ preBuildStateWithLineNums := shared.AddLineNums(preBuildState)+ changesWithLineNums := shared.AddLineNums(changesFile)++ s := UpdatedBuildPrompt + "\n\n" + getPreBuildStatePrompt(filePath, preBuildStateWithLineNums) + "\n\n"++ s += fmt.Sprintf("Proposed updates:\n%s\n```\n%s\n```", changesDesc, changesWithLineNums)++ return s+}++var UpdatedBuildPrompt = `+ You are an AI that takes a file and a set of proposed changes to that file and determines exactly how the changes should be applied in order to produce a valid result. To do this you will produce a map of the resulting file, showing which sections remain unchanged from the original file and which sections will be updated by the proposed changes.++ In order to do this, you will go through the following process:++ **1.** Identify all *anchors* in the proposed changes and list them all. An anchor a line or group of lines from the proposed changes that can be unambigulously matched with a line or group of lines in the pre-change file. Anchors must be exact matches between the proposed changes and the original file.++ For each anchor:+ - Briefly identify it with a description+ - Output the starting line number prefixed by 'pdx-' in the proposed changes. If the anchor spans multiple lines, also output the ending line number prefixed by 'pdx-'.+ - Output the starting line number in the original file that corresponds to the anchor's starting line number in the proposed changes. If the anchor spans multiple lines, also output the ending line number in the original file prefixed by 'pdx-' that corresponds to the anchor's ending line number in the proposed changes.++ Example:++ ---+ ## Anchors++ 1. Signature and opening brace of the 'update' function+ Changes pdx-5 to pdx-6 > Original pdx-456 to pdx-457++ 2. 'Commit db transaction' comment+ Changes pdx-10 > Original pdx-456++ 3. Closing brace of the 'update' function+ Changes pdx-7 > Original pdx-458++ ---++ **2.** Identify all *references* in the proposed changes. A reference is a comment like:++ - "// ... existing code..."+ - "# Existing code..."+ - "/* ... */"+ - "// Rest of the function..."+ - "<!-- rest of div tag -->"+ - "// ... rest of function ..."+ - "// rest of component..."+ - "# other methods..."+ - "// ... rest of init code..."+ - "// rest of the class..."+ - "// other properties"+ - "// other methods"++ These are examples of reference comments, but there are many other variations a reference could take. Identify all reference comments based on the context of the change. Use your judgement to determine what is a reference. A reference must clearly be intented to reference code in the original file for the purpose of making it clear where a change should be applied.++ For each reference:+ - Briefly identify it with a description+ - Output the line number of the reference prefixed by 'pdx-'+ - Output the starting line number prefixed by 'pdx-' in the original file that the reference is referring to. If the reference spans multiple lines, also output the ending line number prefixed by 'pdx-' in the original file that the reference is referring to.++ Ensure no *anchors* are included in the list of references. The referenced section of the original file must not overlap with any lines that are present in the proposed updates. For example, if there's a reference immediately after an opening brace in the proposed changes, the line with the opening brace must *NOT* be included in the referenced section of the original file. Similarly if there's a reference immediately before a closing brace in the proposed changes, the line with the closing brace must *NOT* be included in the referenced section of the original file since this would produce overlap.++ Example:++ ---+ ## References++ 1. "// ... existing imports..." reference to import statements in original file+ Changes pdx-3 > Original pdx-1 to pdx-10++ 2. "// ... rest of the function..." reference to code after the addition of the conditional statment in the 'update' function+ Changes pdx-10 > Original pdx-456 to pdx-460++ ---++ **3.** Identify insertions in the proposed changes. An insertion is code from the proposed changes that should be added to the original file *and doesn't replace any existing code in the original file*. Insertions are for *new code*. They are *not* for changes to existing code. They are also *not* for deletions of existing code.++ For each insertion:+ - Briefly identify it with a description+ - Output the starting line of the code that will be insert in the proposed changes prefixed by 'pdx-'. If the insertion spans multiple lines, also output the ending line of the code that will be inserted in the proposed changes prefixed by 'pdx-'.+ - Output the line number in the original file that the new code should be inserted *after* prefixed by 'pdx-'. If the new code should be prepended to the original file, output 'pdx-0'. If the new code should be appended to the original file, output 'pdx-n' where n is the last line of the original file.++ Example:++ ---+ ## Insertions++ 1. New imports+ Changes pdx-10 to pdx-15 > Original pdx-0++ 2. New validation check+ Changes pdx-30 to pdx-35 > Original pdx-323++ ---++ **4.** Identify replacements in the proposed changes. A replacement is code from the proposed changes that should replace code in the original file. Replacements are for *changes* to existing code that must overwrite existing code in the original file. They are *not* for new code that does not replace any existing code in the original file. They are also *not* for deletions of existing code.++ For each replacement:+ - Briefly identify it with a description+ - Output the starting line of the code that will be replaced in the proposed changes prefixed by 'pdx-'. If the replacement spans multiple lines, also output the ending line of the code that will be replaced in the proposed changes prefixed by 'pdx-'.+ - Output the starting line number in the original file that the replacement is replacing. If the replacement spans multiple lines, also output the ending line number in the original file prefixed by 'pdx-' that the replacement is replacing.++ Example:++ ---+ ## Replacements++ 1. Update the db transaction commit+ Changes pdx-10 to pdx-15 > Original pdx-456 to pdx-461++ 2. Improve the validation check+ Changes pdx-30 to pdx-40 > Original pdx-323 to pdx-328++ ---++ **5.** Identify deletions in the proposed changes. A deletion is code that should be removed from the original file. They are marked by comments like:+ - "// Remove the validation check"+ - "# Remove the 'update' function"+ - "<!-- Remove the header -->"+ - "// Remove the footer"++ Deletions are for *deletions* of existing code. They are *not* for changes to existing code. They are also *not* for new code that does not replace any existing code in the original file.++ Use *deletions* for these kinds of comments rather than replacements so that the deletion comment does not end up in the result.++ For each deletion:+ - Briefly identify it with a description+ - Output the line number of the deletion in the proposed changes prefixed by 'pdx-'+ - Output the starting line number in the original file that the deletion is deleting. If the deletion spans multiple lines, also output the ending line number in the original file prefixed by 'pdx-' that the deletion is deleting.++ Example:++ ---+ ## Deletions++ 1. Remove the old validation check+ Changes pdx-30 > Original pdx-323 to pdx-328++ 2. Remove the 'update' function+ Changes pdx-10 > Original pdx-456 to pdx-461++ ---++ **6.** Now that you've identified all the anchors, references, insertions, replacements, and deletions in the proposed changes, you will output a map of the ENTIRE resulting file as a series of sections that refer to either the original file or the proposed changes. Take into account anchors, references, insertions, replacements, and deletions when building the map.++ Use xml tags for the sections with these attributes:+ - 'type': 'original' or 'proposed'+ - 'description': a brief description of the section. Be clear, precise, and unambiguous about where the section begins and ends.+ - 'anchor': optional anchor number from step 1. Do NOT repeat an anchor number in multiple sections—each anchor should be unique.+ - 'reference': optional reference number from step 2. Do NOT repeat a reference number in multiple sections—each reference should be unique.+ - 'insertion': optional insertion number from step 3. Do NOT repeat an insertion number in multiple sections—each insertion should be unique.+ - 'replacement': optional replacement number from step 4. Do NOT repeat a replacement number in multiple sections—each replacement should be unique.+ - 'start': the starting line number in the original file or proposed changes+ - 'end': the ending line number in the original file or proposed changes. If the section is a single line, the start and end should be the same.+ - 'newlineBefore': optional boolean. Set to 'true' if a newline should be added *before* the section to preserve the original file's formatting. Omit this if the section already includes all necessary newlines.+ - 'newlineAfter': optional boolean. Set to 'true' if a newline should be added *after* the section to preserve the original file's formatting. Omit this if the section already includes all necessary newlines.++ Follow these rules for the map:+ - Always give anchors, references, inserts, replacements, and deletions their *own sections* in the map. Do not include multiple anchors, references, inserts, replacements, and deletions in a single section.+ - Anchors should always have type "proposed". Even though they are present in both the original file and the proposed changes, always include them as "proposed" sections in the map for consistency. Anchors that are added as "proposed" sections must *NOT* be included in the map as "original" sections.+ - References should always have type "original".+ - Insertions should always have type "proposed".+ - Replacements should always have type "proposed".+ - Lines that have been *deleted* in the 'deletions' list must *NOT* be included in the map.+ - Lines that have been *replaces* in the 'replacements' list must have a corresponding section in the map with type "proposed", and the lines from the original file that have been replaced must *NOT* be included in the map.+ - Lines that have been *inserted* in the 'insertions' list must have a corresponding section in the map with type "proposed".+ - Every anchor, reference, insertion, and replacement *must* have a corresponding section in the map. 'deletion' sections must *NOT* be included in the map.+ - Do not include the same line of code in multiple sections. Each line should be assigned to *only one* section.+ - Be precise about section boundaries and DO NOT incorrectly duplicate or omit a single line of code.+ - The map, when assembled from all the sections *must* include the *complete* update file with all changes correctly applied, no change omitted, and no references incorrectly included.+ - When producing the map, do not change or omit any lines from the original file unless they are explicitly delete or replaced. This includes comments, whitespace, and newlines.+ - You MUST NOT omit any sections from the original file that were not *explictly* deleted or replaced in the proposed changes.+ - You MUST ensure newlines are preserved from both the original file and the proposed changes. Do NOT add or remove newlines unless it is explicitly intended by the proposed changes. Even if there is a large block of newlines in the original file, you MUST NOT omit them unless they are explicitly deleted in the proposed changes.+ - The start and end of each section *must* be the same line if the section is a single line.+ - The start and end of each section *must* be a line that exists in the original file or proposed changes.+ - The end line of each section must always be equal to or greater than the start line.++ Example:++ ---+ ## Result map++ <result>+ <section type="original" description="unchanged import statements prior to the newly added imports" start="pdx-1" end="pdx-10" />+ <section type="proposed" description="new imports" insertion="1" start="pdx-2" end="pdx-10" />+ <section type="original" description="unchanged code before the 'update' function" start="pdx-11" end="pdx-300" newlineBefore="true" />+ <section type="proposed" description="function signature and opening brace of the 'update' function" start="pdx-301" end="pdx-302" anchor="1" newlineAfter="true" />+ <section type="proposed" description="new code added to the 'update' function" insertion="2" start="pdx-1" end="pdx-5" />+ <section type="proposed" description="changes to the loop body in the 'update' function" replacement="1" start="pdx-6" end="pdx-10" />+ <section type="original" description="rest of the unchanged 'update' function" reference="1" start="pdx-11" end="pdx-300" />+ <section type="proposed" description="closing brace of the 'update' function" start="pdx-301" end="pdx-302" anchor="2" newlineBefore="true" />+ <section type="original" description="unchanged code following the 'update' function" reference="2" start="pdx-303" end="pdx-620" />+ </result>+ ---++ Do not include any additional text in your final output. Only output the process sections and the result map.+`diff --git a/app/server/model/prompts/create.go b/app/server/model/prompts/create.goindex 316d1340..d8fa2292 100644--- a/app/server/model/prompts/create.go+++ b/app/server/model/prompts/create.go@@ -73,7 +73,7 @@ const SysCreate = Identity + ` A plan is a set of files with an attached contextYou MUST NOT use the labelled file block format followed by triple backticks for **any purpose** other than creating or updating a file in the plan. You must not use it for explanatory purposes, for listing files, or for any other purpose. If you need to label a section or a list of files, use a markdown section header instead like this: '## Files to update'.- If code is being removed from a file, the removal must be shown in a labelled file block according to your instructions. Use a comment within the file block to denote the removal like '// Plandex: removed the fooBar function' or '// Plandex: removed the loop'. Do NOT use any other formatting apart from a labelled file block to denote the removal.+ If code is being removed from a file, the removal must be shown in a labelled file block according to your instructions. Use a comment within the file block to denote the removal like '// Remove the fooBar function' or '// Remove the loop'. Do NOT use any other formatting apart from a labelled file block to denote the removal. Ensure the comment denoting the removal is clear and unambiguously describes the code that is being removed.If a change is related to code in an existing file in context, make the change as an update to the existing file. Do NOT create a new file for a change that applies to an existing file in context. For example, if there is an 'Page.tsx' file in the existing context and the user has asked you to update the structure of the page component, make the change in the existing 'Page.tsx' file. Do NOT create a new file like 'page.tsx' or 'NewPage.tsx' for the change. If the user has specifically asked you to apply a change to a new file, then you can create a new file. If there is no existing file that makes sense to apply a change to, then you can create a new file.@@ -83,9 +83,7 @@ const SysCreate = Identity + ` A plan is a set of files with an attached contextDon'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.- An exception to the above instructions on comments are if a file block is empty because you removed everything in it. In that case, leave a brief one-line comment starting with 'Plandex: removed' that says what was removed so that the file block isn't empty.--+ An exception to the above instructions on comments are if a file block is empty because you removed everything in it. In that case, leave a brief one-line comment starting with 'Removed' that describes unambiguously what was removed so that the file block isn't empty.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 comment "// ... existing code ..." (adapted 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 large sections of the original file unless it is absolutely necessary to make the 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 ..." (adapted 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.diff --git a/app/server/syntax/comments.go b/app/server/syntax/comments.gonew file mode 100644index 00000000..69a4e242--- /dev/null+++ b/app/server/syntax/comments.go@@ -0,0 +1,60 @@+package syntax++import (+ "context"+ "fmt"+ "path/filepath"+ "sort"++ tree_sitter "github.com/smacker/go-tree-sitter"+)++// StripComments removes all comments from the given source code using the appropriate parser+func StripComments(ctx context.Context, path, source string) (string, error) {+ ext := filepath.Ext(path)+ parser, _, _, _ := getParserForExt(ext)++ // If no parser is available, return the source as is+ if parser == nil {+ return source, nil+ }++ ctx, cancel := context.WithTimeout(ctx, parserTimeout)+ defer cancel()++ tree, err := parser.ParseCtx(ctx, nil, []byte(source))+ if err != nil {+ return source, fmt.Errorf("failed to parse the content: %v", err)+ }+ defer tree.Close()++ root := tree.RootNode()+ commentNodes := findCommentNodes(root)++ // Sort comment nodes in reverse order to avoid shifting positions+ sort.Slice(commentNodes, func(i, j int) bool {+ return commentNodes[i].StartByte() > commentNodes[j].StartByte()+ })++ // Remove comments from the source+ result := []byte(source)+ for _, node := range commentNodes {+ start := node.StartByte()+ end := node.EndByte()+ result = append(result[:start], result[end:]...)+ }++ return string(result), nil+}++func findCommentNodes(node *tree_sitter.Node) []*tree_sitter.Node {+ var commentNodes []*tree_sitter.Node++ visitNodes(node, func(n *tree_sitter.Node) {+ if n.Type() == "comment" {+ commentNodes = append(commentNodes, n)+ }+ })++ return commentNodes+}diff --git a/app/shared/plan_result_replacements.go b/app/shared/plan_result_replacements.goindex 5788dc13..41f4c648 100644--- a/app/shared/plan_result_replacements.go+++ b/app/shared/plan_result_replacements.go@@ -11,7 +11,11 @@ import (func ApplyReplacements(content string, replacements []*Replacement, setFailed bool) (string, bool) {apply := func(replacements []*Replacement) (string, int) {+ // log.Println("Applying replacements")+ // log.Println("original content:\n", content)+updated := content+lastInsertedIdx := 0for i, replacement := range replacements {@@ -43,8 +47,8 @@ func ApplyReplacements(content string, replacements []*Replacement, setFailed bo}log.Println("Replacement failed at index:", i)- // log.Println("Replacement:")- // log.Println(spew.Sdump(replacement))+ log.Println("replacement.Old:")+ log.Println(replacement.Old)// log.Println("Updated:")// log.Println(updated)@@ -170,7 +174,7 @@ func (planState *CurrentPlanState) GetFilesBeforeReplacement(updated = context.Bodyshas[path] = context.Sha- log.Println("setting updated content to context body")+ // log.Println("setting updated content to context body")// log.Println(updated)}diff --git a/app/shared/streamed_change.go b/app/shared/streamed_change.goindex de72c7ef..560ed83e 100644--- a/app/shared/streamed_change.go+++ b/app/shared/streamed_change.go@@ -48,7 +48,7 @@ func (streamedChange StreamedChangeWithLineNums) GetLines() (int, int, error) {if streamedChange.Old.StartLineString == "" {startLine = streamedChange.Old.StartLine} else {- startLine, err = extractLineNumber(streamedChange.Old.StartLineString)+ startLine, err = ExtractLineNumber(streamedChange.Old.StartLineString)if err != nil {log.Printf("Error extracting start line number: %v\n", err)@@ -63,7 +63,7 @@ func (streamedChange StreamedChangeWithLineNums) GetLines() (int, int, error) {endLine = startLine}} else {- endLine, err = extractLineNumber(streamedChange.Old.EndLineString)+ endLine, err = ExtractLineNumber(streamedChange.Old.EndLineString)if err != nil {log.Printf("Error extracting end line number: %v\n", err)@@ -84,12 +84,9 @@ func (streamedChange StreamedChangeWithLineNums) GetLines() (int, int, error) {return startLine, endLine, nil}-func extractLineNumber(line string) (int, error) {+func ExtractLineNumber(line string) (int, error) {// Split the line at the first space to isolate the line numberparts := strings.SplitN(line, " ", 2)- if len(parts) < 2 {- return 0, fmt.Errorf("invalid line format")- }// Remove the colon from the line number partlineNumberStr := strings.TrimSuffix(parts[0], ":")