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
switch to reference expansion build strategy
Dane Schneidere0449e99d493
diff --git a/app/server/db/data_models.go b/app/server/db/data_models.goindex a7ff51b9..d1f5f937 100644--- a/app/server/db/data_models.go+++ b/app/server/db/data_models.go@@ -471,18 +471,20 @@ func (desc *ConvoMessageDescription) ToApi() *shared.ConvoMessageDescription {}type PlanFileResult struct {- Id string `json:"id"`- TypeVersion int `json:"typeVersion"`- ReplaceWithLineNums bool `json:"replaceWithLineNums"`- OrgId string `json:"orgId"`- PlanId string `json:"planId"`- ConvoMessageId string `json:"convoMessageId"`- PlanBuildId string `json:"planBuildId"`- Path string `json:"path"`- Content string `json:"content,omitempty"`- Replacements []*shared.Replacement `json:"replacements"`- AnyFailed bool `json:"anyFailed"`- Error string `json:"error"`+ Id string `json:"id"`+ TypeVersion int `json:"typeVersion"`+ ReplaceWithLineNums bool `json:"replaceWithLineNums"`+ OrgId string `json:"orgId"`+ PlanId string `json:"planId"`+ ConvoMessageId string `json:"convoMessageId"`+ PlanBuildId string `json:"planBuildId"`+ Path string `json:"path"`+ Content string `json:"content,omitempty"`++ Replacements []*shared.Replacement `json:"replacements"`++ AnyFailed bool `json:"anyFailed"`+ Error string `json:"error"`CanVerify bool `json:"canVerify"`RanVerifyAt *time.Time `json:"ranVerifyAt,omitempty"`diff --git a/app/server/external/diff/LICENSE b/app/server/external/diff/LICENSEnew file mode 100644index 00000000..54ce0710--- /dev/null+++ b/app/server/external/diff/LICENSE@@ -0,0 +1,27 @@+Copyright 2009 The Go Authors.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are+met:++ * Redistributions of source code must retain the above copyright+notice, this list of conditions and the following disclaimer.+ * Redistributions in binary form must reproduce the above+copyright notice, this list of conditions and the following disclaimer+in the documentation and/or other materials provided with the+distribution.+ * Neither the name of Google LLC nor the names of its+contributors may be used to endorse or promote products derived from+this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\ No newline at end of filediff --git a/app/server/external/diff/NOTICE.txt b/app/server/external/diff/NOTICE.txtnew file mode 100644index 00000000..9e4e738c--- /dev/null+++ b/app/server/external/diff/NOTICE.txt@@ -0,0 +1,3 @@+This package is copied from https://github.com/golang/tools/tree/master/internal/diff++Unneeded code has been removed. License is included in the LICENSE file of this directory.\ No newline at end of filediff --git a/app/server/external/diff/diff.go b/app/server/external/diff/diff.gonew file mode 100644index 00000000..a13547b7--- /dev/null+++ b/app/server/external/diff/diff.go@@ -0,0 +1,176 @@+// Copyright 2019 The Go Authors. All rights reserved.+// Use of this source code is governed by a BSD-style+// license that can be found in the LICENSE file.++// Package diff computes differences between text files or strings.+package diff++import (+ "fmt"+ "sort"+ "strings"+)++// An Edit describes the replacement of a portion of a text file.+type Edit struct {+ Start, End int // byte offsets of the region to replace+ New string // the replacement+}++func (e Edit) String() string {+ return fmt.Sprintf("{Start:%d,End:%d,New:%q}", e.Start, e.End, e.New)+}++// Apply applies a sequence of edits to the src buffer and returns the+// result. Edits are applied in order of start offset; edits with the+// same start offset are applied in they order they were provided.+//+// Apply returns an error if any edit is out of bounds,+// or if any pair of edits is overlapping.+func Apply(src string, edits []Edit) (string, error) {+ edits, size, err := validate(src, edits)+ if err != nil {+ return "", err+ }++ // Apply edits.+ out := make([]byte, 0, size)+ lastEnd := 0+ for _, edit := range edits {+ if lastEnd < edit.Start {+ out = append(out, src[lastEnd:edit.Start]...)+ }+ out = append(out, edit.New...)+ lastEnd = edit.End+ }+ out = append(out, src[lastEnd:]...)++ if len(out) != size {+ panic("wrong size")+ }++ return string(out), nil+}++// ApplyBytes is like Apply, but it accepts a byte slice.+// The result is always a new array.+func ApplyBytes(src []byte, edits []Edit) ([]byte, error) {+ res, err := Apply(string(src), edits)+ return []byte(res), err+}++// validate checks that edits are consistent with src,+// and returns the size of the patched output.+// It may return a different slice.+func validate(src string, edits []Edit) ([]Edit, int, error) {+ if !sort.IsSorted(editsSort(edits)) {+ edits = append([]Edit(nil), edits...)+ SortEdits(edits)+ }++ // Check validity of edits and compute final size.+ size := len(src)+ lastEnd := 0+ for _, edit := range edits {+ if !(0 <= edit.Start && edit.Start <= edit.End && edit.End <= len(src)) {+ return nil, 0, fmt.Errorf("diff has out-of-bounds edits")+ }+ if edit.Start < lastEnd {+ return nil, 0, fmt.Errorf("diff has overlapping edits")+ }+ size += len(edit.New) + edit.Start - edit.End+ lastEnd = edit.End+ }++ return edits, size, nil+}++// SortEdits orders a slice of Edits by (start, end) offset.+// This ordering puts insertions (end = start) before deletions+// (end > start) at the same point, but uses a stable sort to preserve+// the order of multiple insertions at the same point.+// (Apply detects multiple deletions at the same point as an error.)+func SortEdits(edits []Edit) {+ sort.Stable(editsSort(edits))+}++type editsSort []Edit++func (a editsSort) Len() int { return len(a) }+func (a editsSort) Less(i, j int) bool {+ if cmp := a[i].Start - a[j].Start; cmp != 0 {+ return cmp < 0+ }+ return a[i].End < a[j].End+}+func (a editsSort) Swap(i, j int) { a[i], a[j] = a[j], a[i] }++// lineEdits expands and merges a sequence of edits so that each+// resulting edit replaces one or more complete lines.+// See ApplyEdits for preconditions.+func lineEdits(src string, edits []Edit) ([]Edit, error) {+ edits, _, err := validate(src, edits)+ if err != nil {+ return nil, err+ }++ // Do all deletions begin and end at the start of a line,+ // and all insertions end with a newline?+ // (This is merely a fast path.)+ for _, edit := range edits {+ if edit.Start >= len(src) || // insertion at EOF+ edit.Start > 0 && src[edit.Start-1] != '\n' || // not at line start+ edit.End > 0 && src[edit.End-1] != '\n' || // not at line start+ edit.New != "" && edit.New[len(edit.New)-1] != '\n' { // partial insert+ goto expand // slow path+ }+ }+ return edits, nil // aligned++expand:+ if len(edits) == 0 {+ return edits, nil // no edits (unreachable due to fast path)+ }+ expanded := make([]Edit, 0, len(edits)) // a guess+ prev := edits[0]+ // TODO(adonovan): opt: start from the first misaligned edit.+ // TODO(adonovan): opt: avoid quadratic cost of string += string.+ for _, edit := range edits[1:] {+ between := src[prev.End:edit.Start]+ if !strings.Contains(between, "\n") {+ // overlapping lines: combine with previous edit.+ prev.New += between + edit.New+ prev.End = edit.End+ } else {+ // non-overlapping lines: flush previous edit.+ expanded = append(expanded, expandEdit(prev, src))+ prev = edit+ }+ }+ return append(expanded, expandEdit(prev, src)), nil // flush final edit+}++// expandEdit returns edit expanded to complete whole lines.+func expandEdit(edit Edit, src string) Edit {+ // Expand start left to start of line.+ // (delta is the zero-based column number of start.)+ start := edit.Start+ if delta := start - 1 - strings.LastIndex(src[:start], "\n"); delta > 0 {+ edit.Start -= delta+ edit.New = src[start-delta:start] + edit.New+ }++ // Expand end right to end of line.+ end := edit.End+ if end > 0 && src[end-1] != '\n' ||+ edit.New != "" && edit.New[len(edit.New)-1] != '\n' {+ if nl := strings.IndexByte(src[end:], '\n'); nl < 0 {+ edit.End = len(src) // extend to EOF+ } else {+ edit.End = end + nl + 1 // extend beyond \n+ }+ }+ edit.New += src[end:edit.End]++ return edit+}diff --git a/app/server/external/diff/lcs/common.go b/app/server/external/diff/lcs/common.gonew file mode 100644index 00000000..c3e82dd2--- /dev/null+++ b/app/server/external/diff/lcs/common.go@@ -0,0 +1,179 @@+// Copyright 2022 The Go Authors. All rights reserved.+// Use of this source code is governed by a BSD-style+// license that can be found in the LICENSE file.++package lcs++import (+ "log"+ "sort"+)++// lcs is a longest common sequence+type lcs []diag++// A diag is a piece of the edit graph where A[X+i] == B[Y+i], for 0<=i<Len.+// All computed diagonals are parts of a longest common subsequence.+type diag struct {+ X, Y int+ Len int+}++// sort sorts in place, by lowest X, and if tied, inversely by Len+func (l lcs) sort() lcs {+ sort.Slice(l, func(i, j int) bool {+ if l[i].X != l[j].X {+ return l[i].X < l[j].X+ }+ return l[i].Len > l[j].Len+ })+ return l+}++// validate that the elements of the lcs do not overlap+// (can only happen when the two-sided algorithm ends early)+// expects the lcs to be sorted+func (l lcs) valid() bool {+ for i := 1; i < len(l); i++ {+ if l[i-1].X+l[i-1].Len > l[i].X {+ return false+ }+ if l[i-1].Y+l[i-1].Len > l[i].Y {+ return false+ }+ }+ return true+}++// repair overlapping lcs+// only called if two-sided stops early+func (l lcs) fix() lcs {+ // from the set of diagonals in l, find a maximal non-conflicting set+ // this problem may be NP-complete, but we use a greedy heuristic,+ // which is quadratic, but with a better data structure, could be D log D.+ // indepedent is not enough: {0,3,1} and {3,0,2} can't both occur in an lcs+ // which has to have monotone x and y+ if len(l) == 0 {+ return nil+ }+ sort.Slice(l, func(i, j int) bool { return l[i].Len > l[j].Len })+ tmp := make(lcs, 0, len(l))+ tmp = append(tmp, l[0])+ for i := 1; i < len(l); i++ {+ var dir direction+ nxt := l[i]+ for _, in := range tmp {+ if dir, nxt = overlap(in, nxt); dir == empty || dir == bad {+ break+ }+ }+ if nxt.Len > 0 && dir != bad {+ tmp = append(tmp, nxt)+ }+ }+ tmp.sort()+ if false && !tmp.valid() { // debug checking+ log.Fatalf("here %d", len(tmp))+ }+ return tmp+}++type direction int++const (+ empty direction = iota // diag is empty (so not in lcs)+ leftdown // proposed acceptably to the left and below+ rightup // proposed diag is acceptably to the right and above+ bad // proposed diag is inconsistent with the lcs so far+)++// overlap trims the proposed diag prop so it doesn't overlap with+// the existing diag that has already been added to the lcs.+func overlap(exist, prop diag) (direction, diag) {+ if prop.X <= exist.X && exist.X < prop.X+prop.Len {+ // remove the end of prop where it overlaps with the X end of exist+ delta := prop.X + prop.Len - exist.X+ prop.Len -= delta+ if prop.Len <= 0 {+ return empty, prop+ }+ }+ if exist.X <= prop.X && prop.X < exist.X+exist.Len {+ // remove the beginning of prop where overlaps with exist+ delta := exist.X + exist.Len - prop.X+ prop.Len -= delta+ if prop.Len <= 0 {+ return empty, prop+ }+ prop.X += delta+ prop.Y += delta+ }+ if prop.Y <= exist.Y && exist.Y < prop.Y+prop.Len {+ // remove the end of prop that overlaps (in Y) with exist+ delta := prop.Y + prop.Len - exist.Y+ prop.Len -= delta+ if prop.Len <= 0 {+ return empty, prop+ }+ }+ if exist.Y <= prop.Y && prop.Y < exist.Y+exist.Len {+ // remove the beginning of peop that overlaps with exist+ delta := exist.Y + exist.Len - prop.Y+ prop.Len -= delta+ if prop.Len <= 0 {+ return empty, prop+ }+ prop.X += delta // no test reaches this code+ prop.Y += delta+ }+ if prop.X+prop.Len <= exist.X && prop.Y+prop.Len <= exist.Y {+ return leftdown, prop+ }+ if exist.X+exist.Len <= prop.X && exist.Y+exist.Len <= prop.Y {+ return rightup, prop+ }+ // prop can't be in an lcs that contains exist+ return bad, prop+}++// manipulating Diag and lcs++// prepend a diagonal (x,y)-(x+1,y+1) segment either to an empty lcs+// or to its first Diag. prepend is only called to extend diagonals+// the backward direction.+func (lcs lcs) prepend(x, y int) lcs {+ if len(lcs) > 0 {+ d := &lcs[0]+ if int(d.X) == x+1 && int(d.Y) == y+1 {+ // extend the diagonal down and to the left+ d.X, d.Y = int(x), int(y)+ d.Len+++ return lcs+ }+ }++ r := diag{X: int(x), Y: int(y), Len: 1}+ lcs = append([]diag{r}, lcs...)+ return lcs+}++// append appends a diagonal, or extends the existing one.+// by adding the edge (x,y)-(x+1.y+1). append is only called+// to extend diagonals in the forward direction.+func (lcs lcs) append(x, y int) lcs {+ if len(lcs) > 0 {+ last := &lcs[len(lcs)-1]+ // Expand last element if adjoining.+ if last.X+last.Len == x && last.Y+last.Len == y {+ last.Len+++ return lcs+ }+ }++ return append(lcs, diag{X: x, Y: y, Len: 1})+}++// enforce constraint on d, k+func ok(d, k int) bool {+ return d >= 0 && -d <= k && k <= d+}diff --git a/app/server/external/diff/lcs/doc.go b/app/server/external/diff/lcs/doc.gonew file mode 100644index 00000000..9029dd20--- /dev/null+++ b/app/server/external/diff/lcs/doc.go@@ -0,0 +1,156 @@+// Copyright 2022 The Go Authors. All rights reserved.+// Use of this source code is governed by a BSD-style+// license that can be found in the LICENSE file.++// package lcs contains code to find longest-common-subsequences+// (and diffs)+package lcs++/*+Compute longest-common-subsequences of two slices A, B using+algorithms from Myers' paper. A longest-common-subsequence+(LCS from now on) of A and B is a maximal set of lexically increasing+pairs of subscripts (x,y) with A[x]==B[y]. There may be many LCS, but+they all have the same length. An LCS determines a sequence of edits+that changes A into B.++The key concept is the edit graph of A and B.+If A has length N and B has length M, then the edit graph has+vertices v[i][j] for 0 <= i <= N, 0 <= j <= M. There is a+horizontal edge from v[i][j] to v[i+1][j] whenever both are in+the graph, and a vertical edge from v[i][j] to f[i][j+1] similarly.+When A[i] == B[j] there is a diagonal edge from v[i][j] to v[i+1][j+1].++A path between in the graph between (0,0) and (N,M) determines a sequence+of edits converting A into B: each horizontal edge corresponds to removing+an element of A, and each vertical edge corresponds to inserting an+element of B.++A vertex (x,y) is on (forward) diagonal k if x-y=k. A path in the graph+is of length D if it has D non-diagonal edges. The algorithms generate+forward paths (in which at least one of x,y increases at each edge),+or backward paths (in which at least one of x,y decreases at each edge),+or a combination. (Note that the orientation is the traditional mathematical one,+with the origin in the lower-left corner.)++Here is the edit graph for A:"aabbaa", B:"aacaba". (I know the diagonals look weird.)+ ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙+ a | ___/‾‾‾ | ___/‾‾‾ | | | ___/‾‾‾ | ___/‾‾‾ |+ ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙+ b | | | ___/‾‾‾ | ___/‾‾‾ | | |+ ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙+ a | ___/‾‾‾ | ___/‾‾‾ | | | ___/‾‾‾ | ___/‾‾‾ |+ ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙+ c | | | | | | |+ ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙+ a | ___/‾‾‾ | ___/‾‾‾ | | | ___/‾‾‾ | ___/‾‾‾ |+ ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙+ a | ___/‾‾‾ | ___/‾‾‾ | | | ___/‾‾‾ | ___/‾‾‾ |+ ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙+ a a b b a a+++The algorithm labels a vertex (x,y) with D,k if it is on diagonal k and at+the end of a maximal path of length D. (Because x-y=k it suffices to remember+only the x coordinate of the vertex.)++The forward algorithm: Find the longest diagonal starting at (0,0) and+label its end with D=0,k=0. From that vertex take a vertical step and+then follow the longest diagonal (up and to the right), and label that vertex+with D=1,k=-1. From the D=0,k=0 point take a horizontal step and the follow+the longest diagonal (up and to the right) and label that vertex+D=1,k=1. In the same way, having labelled all the D vertices,+from a vertex labelled D,k find two vertices+tentatively labelled D+1,k-1 and D+1,k+1. There may be two on the same+diagonal, in which case take the one with the larger x.++Eventually the path gets to (N,M), and the diagonals on it are the LCS.++Here is the edit graph with the ends of D-paths labelled. (So, for instance,+0/2,2 indicates that x=2,y=2 is labelled with 0, as it should be, since the first+step is to go up the longest diagonal from (0,0).)+A:"aabbaa", B:"aacaba"+ ⊙ ------- ⊙ ------- ⊙ -------(3/3,6)------- ⊙ -------(3/5,6)-------(4/6,6)+ a | ___/‾‾‾ | ___/‾‾‾ | | | ___/‾‾‾ | ___/‾‾‾ |+ ⊙ ------- ⊙ ------- ⊙ -------(2/3,5)------- ⊙ ------- ⊙ ------- ⊙+ b | | | ___/‾‾‾ | ___/‾‾‾ | | |+ ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ -------(3/5,4)------- ⊙+ a | ___/‾‾‾ | ___/‾‾‾ | | | ___/‾‾‾ | ___/‾‾‾ |+ ⊙ ------- ⊙ -------(1/2,3)-------(2/3,3)------- ⊙ ------- ⊙ ------- ⊙+ c | | | | | | |+ ⊙ ------- ⊙ -------(0/2,2)-------(1/3,2)-------(2/4,2)-------(3/5,2)-------(4/6,2)+ a | ___/‾‾‾ | ___/‾‾‾ | | | ___/‾‾‾ | ___/‾‾‾ |+ ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙+ a | ___/‾‾‾ | ___/‾‾‾ | | | ___/‾‾‾ | ___/‾‾‾ |+ ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙ ------- ⊙+ a a b b a a++The 4-path is reconstructed starting at (4/6,6), horizontal to (3/5,6), diagonal to (3,4), vertical+to (2/3,3), horizontal to (1/2,3), vertical to (0/2,2), and diagonal to (0,0). As expected,+there are 4 non-diagonal steps, and the diagonals form an LCS.++There is a symmetric backward algorithm, which gives (backwards labels are prefixed with a colon):+A:"aabbaa", B:"aacaba"+ ⊙ -------- ⊙ -------- ⊙ -------- ⊙ -------- ⊙ -------- ⊙ -------- ⊙+ a | ____/‾‾‾ | ____/‾‾‾ | | | ____/‾‾‾ | ____/‾‾‾ |+ ⊙ -------- ⊙ -------- ⊙ -------- ⊙ -------- ⊙ --------(:0/5,5)-------- ⊙+ b | | | ____/‾‾‾ | ____/‾‾‾ | | |+ ⊙ -------- ⊙ -------- ⊙ --------(:1/3,4)-------- ⊙ -------- ⊙ -------- ⊙+ a | ____/‾‾‾ | ____/‾‾‾ | | | ____/‾‾‾ | ____/‾‾‾ |+ (:3/0,3)--------(:2/1,3)-------- ⊙ --------(:2/3,3)--------(:1/4,3)-------- ⊙ -------- ⊙+ c | | | | | | |+ ⊙ -------- ⊙ -------- ⊙ --------(:3/3,2)--------(:2/4,2)-------- ⊙ -------- ⊙+ a | ____/‾‾‾ | ____/‾‾‾ | | | ____/‾‾‾ | ____/‾‾‾ |+ (:3/0,1)-------- ⊙ -------- ⊙ -------- ⊙ --------(:3/4,1)-------- ⊙ -------- ⊙+ a | ____/‾‾‾ | ____/‾‾‾ | | | ____/‾‾‾ | ____/‾‾‾ |+ (:4/0,0)-------- ⊙ -------- ⊙ -------- ⊙ --------(:4/4,0)-------- ⊙ -------- ⊙+ a a b b a a++Neither of these is ideal for use in an editor, where it is undesirable to send very long diffs to the+front end. It's tricky to decide exactly what 'very long diffs' means, as "replace A by B" is very short.+We want to control how big D can be, by stopping when it gets too large. The forward algorithm then+privileges common prefixes, and the backward algorithm privileges common suffixes. Either is an undesirable+asymmetry.++Fortunately there is a two-sided algorithm, implied by results in Myers' paper. Here's what the labels in+the edit graph look like.+A:"aabbaa", B:"aacaba"+ ⊙ --------- ⊙ --------- ⊙ --------- ⊙ --------- ⊙ --------- ⊙ --------- ⊙+ a | ____/‾‾‾‾ | ____/‾‾‾‾ | | | ____/‾‾‾‾ | ____/‾‾‾‾ |+ ⊙ --------- ⊙ --------- ⊙ --------- (2/3,5) --------- ⊙ --------- (:0/5,5)--------- ⊙+ b | | | ____/‾‾‾‾ | ____/‾‾‾‾ | | |+ ⊙ --------- ⊙ --------- ⊙ --------- (:1/3,4)--------- ⊙ --------- ⊙ --------- ⊙+ a | ____/‾‾‾‾ | ____/‾‾‾‾ | | | ____/‾‾‾‾ | ____/‾‾‾‾ |+ ⊙ --------- (:2/1,3)--------- (1/2,3) ---------(2:2/3,3)--------- (:1/4,3)--------- ⊙ --------- ⊙+ c | | | | | | |+ ⊙ --------- ⊙ --------- (0/2,2) --------- (1/3,2) ---------(2:2/4,2)--------- ⊙ --------- ⊙+ a | ____/‾‾‾‾ | ____/‾‾‾‾ | | | ____/‾‾‾‾ | ____/‾‾‾‾ |+ ⊙ --------- ⊙ --------- ⊙ --------- ⊙ --------- ⊙ --------- ⊙ --------- ⊙+ a | ____/‾‾‾‾ | ____/‾‾‾‾ | | | ____/‾‾‾‾ | ____/‾‾‾‾ |+ ⊙ --------- ⊙ --------- ⊙ --------- ⊙ --------- ⊙ --------- ⊙ --------- ⊙+ a a b b a a++The algorithm stopped when it saw the backwards 2-path ending at (1,3) and the forwards 2-path ending at (3,5). The criterion+is a backwards path ending at (u,v) and a forward path ending at (x,y), where u <= x and the two points are on the same+diagonal. (Here the edgegraph has a diagonal, but the criterion is x-y=u-v.) Myers proves there is a forward+2-path from (0,0) to (1,3), and that together with the backwards 2-path ending at (1,3) gives the expected 4-path.+Unfortunately the forward path has to be constructed by another run of the forward algorithm; it can't be found from the+computed labels. That is the worst case. Had the code noticed (x,y)=(u,v)=(3,3) the whole path could be reconstructed+from the edgegraph. The implementation looks for a number of special cases to try to avoid computing an extra forward path.++If the two-sided algorithm has stop early (because D has become too large) it will have found a forward LCS and a+backwards LCS. Ideally these go with disjoint prefixes and suffixes of A and B, but disjointness may fail and the two+computed LCS may conflict. (An easy example is where A is a suffix of B, and shares a short prefix. The backwards LCS+is all of A, and the forward LCS is a prefix of A.) The algorithm combines the two+to form a best-effort LCS. In the worst case the forward partial LCS may have to+be recomputed.+*/++/* Eugene Myers paper is titled+"An O(ND) Difference Algorithm and Its Variations"+and can be found at+http://www.xmailserver.org/diff2.pdf++(There is a generic implementation of the algorithm the repository with git hash+b9ad7e4ade3a686d608e44475390ad428e60e7fc)+*/diff --git a/app/server/external/diff/lcs/labels.go b/app/server/external/diff/lcs/labels.gonew file mode 100644index 00000000..504913d1--- /dev/null+++ b/app/server/external/diff/lcs/labels.go@@ -0,0 +1,55 @@+// Copyright 2022 The Go Authors. All rights reserved.+// Use of this source code is governed by a BSD-style+// license that can be found in the LICENSE file.++package lcs++import (+ "fmt"+)++// For each D, vec[D] has length D+1,+// and the label for (D, k) is stored in vec[D][(D+k)/2].+type label struct {+ vec [][]int+}++// Temporary checking DO NOT COMMIT true TO PRODUCTION CODE+const debug = false++// debugging. check that the (d,k) pair is valid+// (that is, -d<=k<=d and d+k even)+func checkDK(D, k int) {+ if k >= -D && k <= D && (D+k)%2 == 0 {+ return+ }+ panic(fmt.Sprintf("out of range, d=%d,k=%d", D, k))+}++func (t *label) set(D, k, x int) {+ if debug {+ checkDK(D, k)+ }+ for len(t.vec) <= D {+ t.vec = append(t.vec, nil)+ }+ if t.vec[D] == nil {+ t.vec[D] = make([]int, D+1)+ }+ t.vec[D][(D+k)/2] = x // known that D+k is even+}++func (t *label) get(d, k int) int {+ if debug {+ checkDK(d, k)+ }+ return int(t.vec[d][(d+k)/2])+}++func newtriang(limit int) label {+ if limit < 100 {+ // Preallocate if limit is not large.+ return label{vec: make([][]int, limit)}+ }+ return label{}+}diff --git a/app/server/external/diff/lcs/old.go b/app/server/external/diff/lcs/old.gonew file mode 100644index 00000000..4353da15--- /dev/null+++ b/app/server/external/diff/lcs/old.go@@ -0,0 +1,480 @@+// Copyright 2022 The Go Authors. All rights reserved.+// Use of this source code is governed by a BSD-style+// license that can be found in the LICENSE file.++package lcs++// TODO(adonovan): remove unclear references to "old" in this package.++import (+ "fmt"+)++// A Diff is a replacement of a portion of A by a portion of B.+type Diff struct {+ Start, End int // offsets of portion to delete in A+ ReplStart, ReplEnd int // offset of replacement text in B+}++// DiffStrings returns the differences between two strings.+// It does not respect rune boundaries.+func DiffStrings(a, b string) []Diff { return diff(stringSeqs{a, b}) }++// DiffBytes returns the differences between two byte sequences.+// It does not respect rune boundaries.+func DiffBytes(a, b []byte) []Diff { return diff(bytesSeqs{a, b}) }++// DiffRunes returns the differences between two rune sequences.+func DiffRunes(a, b []rune) []Diff { return diff(runesSeqs{a, b}) }++func diff(seqs sequences) []Diff {+ // A limit on how deeply the LCS algorithm should search. The value is just a guess.+ const maxDiffs = 100+ diff, _ := compute(seqs, twosided, maxDiffs/2)+ return diff+}++// compute computes the list of differences between two sequences,+// along with the LCS. It is exercised directly by tests.+// The algorithm is one of {forward, backward, twosided}.+func compute(seqs sequences, algo func(*editGraph) lcs, limit int) ([]Diff, lcs) {+ if limit <= 0 {+ limit = 1 << 25 // effectively infinity+ }+ alen, blen := seqs.lengths()+ g := &editGraph{+ seqs: seqs,+ vf: newtriang(limit),+ vb: newtriang(limit),+ limit: limit,+ ux: alen,+ uy: blen,+ delta: alen - blen,+ }+ lcs := algo(g)+ diffs := lcs.toDiffs(alen, blen)+ return diffs, lcs+}++// editGraph carries the information for computing the lcs of two sequences.+type editGraph struct {+ seqs sequences+ vf, vb label // forward and backward labels++ limit int // maximal value of D+ // the bounding rectangle of the current edit graph+ lx, ly, ux, uy int+ delta int // common subexpression: (ux-lx)-(uy-ly)+}++// toDiffs converts an LCS to a list of edits.+func (lcs lcs) toDiffs(alen, blen int) []Diff {+ var diffs []Diff+ var pa, pb int // offsets in a, b+ for _, l := range lcs {+ if pa < l.X || pb < l.Y {+ diffs = append(diffs, Diff{pa, l.X, pb, l.Y})+ }+ pa = l.X + l.Len+ pb = l.Y + l.Len+ }+ if pa < alen || pb < blen {+ diffs = append(diffs, Diff{pa, alen, pb, blen})+ }+ return diffs+}++// --- FORWARD ---++// fdone decides if the forward path has reached the upper right+// corner of the rectangle. If so, it also returns the computed lcs.+func (e *editGraph) fdone(D, k int) (bool, lcs) {+ // x, y, k are relative to the rectangle+ x := e.vf.get(D, k)+ y := x - k+ if x == e.ux && y == e.uy {+ return true, e.forwardlcs(D, k)+ }+ return false, nil+}++// run the forward algorithm, until success or up to the limit on D.+func forward(e *editGraph) lcs {+ e.setForward(0, 0, e.lx)+ if ok, ans := e.fdone(0, 0); ok {+ return ans+ }+ // from D to D+1+ for D := 0; D < e.limit; D++ {+ e.setForward(D+1, -(D + 1), e.getForward(D, -D))+ if ok, ans := e.fdone(D+1, -(D + 1)); ok {+ return ans+ }+ e.setForward(D+1, D+1, e.getForward(D, D)+1)+ if ok, ans := e.fdone(D+1, D+1); ok {+ return ans+ }+ for k := -D + 1; k <= D-1; k += 2 {+ // these are tricky and easy to get backwards+ lookv := e.lookForward(k, e.getForward(D, k-1)+1)+ lookh := e.lookForward(k, e.getForward(D, k+1))+ if lookv > lookh {+ e.setForward(D+1, k, lookv)+ } else {+ e.setForward(D+1, k, lookh)+ }+ if ok, ans := e.fdone(D+1, k); ok {+ return ans+ }+ }+ }+ // D is too large+ // find the D path with maximal x+y inside the rectangle and+ // use that to compute the found part of the lcs+ kmax := -e.limit - 1+ diagmax := -1+ for k := -e.limit; k <= e.limit; k += 2 {+ x := e.getForward(e.limit, k)+ y := x - k+ if x+y > diagmax && x <= e.ux && y <= e.uy {+ diagmax, kmax = x+y, k+ }+ }+ return e.forwardlcs(e.limit, kmax)+}++// recover the lcs by backtracking from the farthest point reached+func (e *editGraph) forwardlcs(D, k int) lcs {+ var ans lcs+ for x := e.getForward(D, k); x != 0 || x-k != 0; {+ if ok(D-1, k-1) && x-1 == e.getForward(D-1, k-1) {+ // if (x-1,y) is labelled D-1, x--,D--,k--,continue+ D, k, x = D-1, k-1, x-1+ continue+ } else if ok(D-1, k+1) && x == e.getForward(D-1, k+1) {+ // if (x,y-1) is labelled D-1, x, D--,k++, continue+ D, k = D-1, k+1+ continue+ }+ // if (x-1,y-1)--(x,y) is a diagonal, prepend,x--,y--, continue+ y := x - k+ ans = ans.prepend(x+e.lx-1, y+e.ly-1)+ x--+ }+ return ans+}++// start at (x,y), go up the diagonal as far as possible,+// and label the result with d+func (e *editGraph) lookForward(k, relx int) int {+ rely := relx - k+ x, y := relx+e.lx, rely+e.ly+ if x < e.ux && y < e.uy {+ x += e.seqs.commonPrefixLen(x, e.ux, y, e.uy)+ }+ return x+}++func (e *editGraph) setForward(d, k, relx int) {+ x := e.lookForward(k, relx)+ e.vf.set(d, k, x-e.lx)+}++func (e *editGraph) getForward(d, k int) int {+ x := e.vf.get(d, k)+ return x+}++// --- BACKWARD ---++// bdone decides if the backward path has reached the lower left corner+func (e *editGraph) bdone(D, k int) (bool, lcs) {+ // x, y, k are relative to the rectangle+ x := e.vb.get(D, k)+ y := x - (k + e.delta)+ if x == 0 && y == 0 {+ return true, e.backwardlcs(D, k)+ }+ return false, nil+}++// run the backward algorithm, until success or up to the limit on D.+func backward(e *editGraph) lcs {+ e.setBackward(0, 0, e.ux)+ if ok, ans := e.bdone(0, 0); ok {+ return ans+ }+ // from D to D+1+ for D := 0; D < e.limit; D++ {+ e.setBackward(D+1, -(D + 1), e.getBackward(D, -D)-1)+ if ok, ans := e.bdone(D+1, -(D + 1)); ok {+ return ans+ }+ e.setBackward(D+1, D+1, e.getBackward(D, D))+ if ok, ans := e.bdone(D+1, D+1); ok {+ return ans+ }+ for k := -D + 1; k <= D-1; k += 2 {+ // these are tricky and easy to get wrong+ lookv := e.lookBackward(k, e.getBackward(D, k-1))+ lookh := e.lookBackward(k, e.getBackward(D, k+1)-1)+ if lookv < lookh {+ e.setBackward(D+1, k, lookv)+ } else {+ e.setBackward(D+1, k, lookh)+ }+ if ok, ans := e.bdone(D+1, k); ok {+ return ans+ }+ }+ }++ // D is too large+ // find the D path with minimal x+y inside the rectangle and+ // use that to compute the part of the lcs found+ kmax := -e.limit - 1+ diagmin := 1 << 25+ for k := -e.limit; k <= e.limit; k += 2 {+ x := e.getBackward(e.limit, k)+ y := x - (k + e.delta)+ if x+y < diagmin && x >= 0 && y >= 0 {+ diagmin, kmax = x+y, k+ }+ }+ if kmax < -e.limit {+ panic(fmt.Sprintf("no paths when limit=%d?", e.limit))+ }+ return e.backwardlcs(e.limit, kmax)+}++// recover the lcs by backtracking+func (e *editGraph) backwardlcs(D, k int) lcs {+ var ans lcs+ for x := e.getBackward(D, k); x != e.ux || x-(k+e.delta) != e.uy; {+ if ok(D-1, k-1) && x == e.getBackward(D-1, k-1) {+ // D--, k--, x unchanged+ D, k = D-1, k-1+ continue+ } else if ok(D-1, k+1) && x+1 == e.getBackward(D-1, k+1) {+ // D--, k++, x+++ D, k, x = D-1, k+1, x+1+ continue+ }+ y := x - (k + e.delta)+ ans = ans.append(x+e.lx, y+e.ly)+ x+++ }+ return ans+}++// start at (x,y), go down the diagonal as far as possible,+func (e *editGraph) lookBackward(k, relx int) int {+ rely := relx - (k + e.delta) // forward k = k + e.delta+ x, y := relx+e.lx, rely+e.ly+ if x > 0 && y > 0 {+ x -= e.seqs.commonSuffixLen(0, x, 0, y)+ }+ return x+}++// convert to rectangle, and label the result with d+func (e *editGraph) setBackward(d, k, relx int) {+ x := e.lookBackward(k, relx)+ e.vb.set(d, k, x-e.lx)+}++func (e *editGraph) getBackward(d, k int) int {+ x := e.vb.get(d, k)+ return x+}++// -- TWOSIDED ---++func twosided(e *editGraph) lcs {+ // The termination condition could be improved, as either the forward+ // or backward pass could succeed before Myers' Lemma applies.+ // Aside from questions of efficiency (is the extra testing cost-effective)+ // this is more likely to matter when e.limit is reached.+ e.setForward(0, 0, e.lx)+ e.setBackward(0, 0, e.ux)++ // from D to D+1+ for D := 0; D < e.limit; D++ {+ // just finished a backwards pass, so check+ if got, ok := e.twoDone(D, D); ok {+ return e.twolcs(D, D, got)+ }+ // do a forwards pass (D to D+1)+ e.setForward(D+1, -(D + 1), e.getForward(D, -D))+ e.setForward(D+1, D+1, e.getForward(D, D)+1)+ for k := -D + 1; k <= D-1; k += 2 {+ // these are tricky and easy to get backwards+ lookv := e.lookForward(k, e.getForward(D, k-1)+1)+ lookh := e.lookForward(k, e.getForward(D, k+1))+ if lookv > lookh {+ e.setForward(D+1, k, lookv)+ } else {+ e.setForward(D+1, k, lookh)+ }+ }+ // just did a forward pass, so check+ if got, ok := e.twoDone(D+1, D); ok {+ return e.twolcs(D+1, D, got)+ }+ // do a backward pass, D to D+1+ e.setBackward(D+1, -(D + 1), e.getBackward(D, -D)-1)+ e.setBackward(D+1, D+1, e.getBackward(D, D))+ for k := -D + 1; k <= D-1; k += 2 {+ // these are tricky and easy to get wrong+ lookv := e.lookBackward(k, e.getBackward(D, k-1))+ lookh := e.lookBackward(k, e.getBackward(D, k+1)-1)+ if lookv < lookh {+ e.setBackward(D+1, k, lookv)+ } else {+ e.setBackward(D+1, k, lookh)+ }+ }+ }++ // D too large. combine a forward and backward partial lcs+ // first, a forward one+ kmax := -e.limit - 1+ diagmax := -1+ for k := -e.limit; k <= e.limit; k += 2 {+ x := e.getForward(e.limit, k)+ y := x - k+ if x+y > diagmax && x <= e.ux && y <= e.uy {+ diagmax, kmax = x+y, k+ }+ }+ if kmax < -e.limit {+ panic(fmt.Sprintf("no forward paths when limit=%d?", e.limit))+ }+ lcs := e.forwardlcs(e.limit, kmax)+ // now a backward one+ // find the D path with minimal x+y inside the rectangle and+ // use that to compute the lcs+ diagmin := 1 << 25 // infinity+ for k := -e.limit; k <= e.limit; k += 2 {+ x := e.getBackward(e.limit, k)+ y := x - (k + e.delta)+ if x+y < diagmin && x >= 0 && y >= 0 {+ diagmin, kmax = x+y, k+ }+ }+ if kmax < -e.limit {+ panic(fmt.Sprintf("no backward paths when limit=%d?", e.limit))+ }+ lcs = append(lcs, e.backwardlcs(e.limit, kmax)...)+ // These may overlap (e.forwardlcs and e.backwardlcs return sorted lcs)+ ans := lcs.fix()+ return ans+}++// Does Myers' Lemma apply?+func (e *editGraph) twoDone(df, db int) (int, bool) {+ if (df+db+e.delta)%2 != 0 {+ return 0, false // diagonals cannot overlap+ }+ kmin := -db + e.delta+ if -df > kmin {+ kmin = -df+ }+ kmax := db + e.delta+ if df < kmax {+ kmax = df+ }+ for k := kmin; k <= kmax; k += 2 {+ x := e.vf.get(df, k)+ u := e.vb.get(db, k-e.delta)+ if u <= x {+ // is it worth looking at all the other k?+ for l := k; l <= kmax; l += 2 {+ x := e.vf.get(df, l)+ y := x - l+ u := e.vb.get(db, l-e.delta)+ v := u - l+ if x == u || u == 0 || v == 0 || y == e.uy || x == e.ux {+ return l, true+ }+ }+ return k, true+ }+ }+ return 0, false+}++func (e *editGraph) twolcs(df, db, kf int) lcs {+ // db==df || db+1==df+ x := e.vf.get(df, kf)+ y := x - kf+ kb := kf - e.delta+ u := e.vb.get(db, kb)+ v := u - kf++ // Myers proved there is a df-path from (0,0) to (u,v)+ // and a db-path from (x,y) to (N,M).+ // In the first case the overall path is the forward path+ // to (u,v) followed by the backward path to (N,M).+ // In the second case the path is the backward path to (x,y)+ // followed by the forward path to (x,y) from (0,0).++ // Look for some special cases to avoid computing either of these paths.+ if x == u {+ // "babaab" "cccaba"+ // already patched together+ lcs := e.forwardlcs(df, kf)+ lcs = append(lcs, e.backwardlcs(db, kb)...)+ return lcs.sort()+ }++ // is (u-1,v) or (u,v-1) labelled df-1?+ // if so, that forward df-1-path plus a horizontal or vertical edge+ // is the df-path to (u,v), then plus the db-path to (N,M)+ if u > 0 && ok(df-1, u-1-v) && e.vf.get(df-1, u-1-v) == u-1 {+ // "aabbab" "cbcabc"+ lcs := e.forwardlcs(df-1, u-1-v)+ lcs = append(lcs, e.backwardlcs(db, kb)...)+ return lcs.sort()+ }+ if v > 0 && ok(df-1, (u-(v-1))) && e.vf.get(df-1, u-(v-1)) == u {+ // "abaabb" "bcacab"+ lcs := e.forwardlcs(df-1, u-(v-1))+ lcs = append(lcs, e.backwardlcs(db, kb)...)+ return lcs.sort()+ }++ // The path can't possibly contribute to the lcs because it+ // is all horizontal or vertical edges+ if u == 0 || v == 0 || x == e.ux || y == e.uy {+ // "abaabb" "abaaaa"+ if u == 0 || v == 0 {+ return e.backwardlcs(db, kb)+ }+ return e.forwardlcs(df, kf)+ }++ // is (x+1,y) or (x,y+1) labelled db-1?+ if x+1 <= e.ux && ok(db-1, x+1-y-e.delta) && e.vb.get(db-1, x+1-y-e.delta) == x+1 {+ // "bababb" "baaabb"+ lcs := e.backwardlcs(db-1, kb+1)+ lcs = append(lcs, e.forwardlcs(df, kf)...)+ return lcs.sort()+ }+ if y+1 <= e.uy && ok(db-1, x-(y+1)-e.delta) && e.vb.get(db-1, x-(y+1)-e.delta) == x {+ // "abbbaa" "cabacc"+ lcs := e.backwardlcs(db-1, kb-1)+ lcs = append(lcs, e.forwardlcs(df, kf)...)+ return lcs.sort()+ }++ // need to compute another path+ // "aabbaa" "aacaba"+ lcs := e.backwardlcs(db, kb)+ oldx, oldy := e.ux, e.uy+ e.ux = u+ e.uy = v+ lcs = append(lcs, forward(e)...)+ e.ux, e.uy = oldx, oldy+ return lcs.sort()+}diff --git a/app/server/external/diff/lcs/sequence.go b/app/server/external/diff/lcs/sequence.gonew file mode 100644index 00000000..2d72d263--- /dev/null+++ b/app/server/external/diff/lcs/sequence.go@@ -0,0 +1,113 @@+// Copyright 2022 The Go Authors. All rights reserved.+// Use of this source code is governed by a BSD-style+// license that can be found in the LICENSE file.++package lcs++// This file defines the abstract sequence over which the LCS algorithm operates.++// sequences abstracts a pair of sequences, A and B.+type sequences interface {+ lengths() (int, int) // len(A), len(B)+ commonPrefixLen(ai, aj, bi, bj int) int // len(commonPrefix(A[ai:aj], B[bi:bj]))+ commonSuffixLen(ai, aj, bi, bj int) int // len(commonSuffix(A[ai:aj], B[bi:bj]))+}++type stringSeqs struct{ a, b string }++func (s stringSeqs) lengths() (int, int) { return len(s.a), len(s.b) }+func (s stringSeqs) commonPrefixLen(ai, aj, bi, bj int) int {+ return commonPrefixLenString(s.a[ai:aj], s.b[bi:bj])+}+func (s stringSeqs) commonSuffixLen(ai, aj, bi, bj int) int {+ return commonSuffixLenString(s.a[ai:aj], s.b[bi:bj])+}++// The explicit capacity in s[i:j:j] leads to more efficient code.++type bytesSeqs struct{ a, b []byte }++func (s bytesSeqs) lengths() (int, int) { return len(s.a), len(s.b) }+func (s bytesSeqs) commonPrefixLen(ai, aj, bi, bj int) int {+ return commonPrefixLenBytes(s.a[ai:aj:aj], s.b[bi:bj:bj])+}+func (s bytesSeqs) commonSuffixLen(ai, aj, bi, bj int) int {+ return commonSuffixLenBytes(s.a[ai:aj:aj], s.b[bi:bj:bj])+}++type runesSeqs struct{ a, b []rune }++func (s runesSeqs) lengths() (int, int) { return len(s.a), len(s.b) }+func (s runesSeqs) commonPrefixLen(ai, aj, bi, bj int) int {+ return commonPrefixLenRunes(s.a[ai:aj:aj], s.b[bi:bj:bj])+}+func (s runesSeqs) commonSuffixLen(ai, aj, bi, bj int) int {+ return commonSuffixLenRunes(s.a[ai:aj:aj], s.b[bi:bj:bj])+}++// TODO(adonovan): optimize these functions using ideas from:+// - https://go.dev/cl/408116 common.go+// - https://go.dev/cl/421435 xor_generic.go++// TODO(adonovan): factor using generics when available,+// but measure performance impact.++// commonPrefixLen* returns the length of the common prefix of a[ai:aj] and b[bi:bj].+func commonPrefixLenBytes(a, b []byte) int {+ n := min(len(a), len(b))+ i := 0+ for i < n && a[i] == b[i] {+ i+++ }+ return i+}+func commonPrefixLenRunes(a, b []rune) int {+ n := min(len(a), len(b))+ i := 0+ for i < n && a[i] == b[i] {+ i+++ }+ return i+}+func commonPrefixLenString(a, b string) int {+ n := min(len(a), len(b))+ i := 0+ for i < n && a[i] == b[i] {+ i+++ }+ return i+}++// commonSuffixLen* returns the length of the common suffix of a[ai:aj] and b[bi:bj].+func commonSuffixLenBytes(a, b []byte) int {+ n := min(len(a), len(b))+ i := 0+ for i < n && a[len(a)-1-i] == b[len(b)-1-i] {+ i+++ }+ return i+}+func commonSuffixLenRunes(a, b []rune) int {+ n := min(len(a), len(b))+ i := 0+ for i < n && a[len(a)-1-i] == b[len(b)-1-i] {+ i+++ }+ return i+}+func commonSuffixLenString(a, b string) int {+ n := min(len(a), len(b))+ i := 0+ for i < n && a[len(a)-1-i] == b[len(b)-1-i] {+ i+++ }+ return i+}++func min(x, y int) int {+ if x < y {+ return x+ } else {+ return y+ }+}diff --git a/app/server/external/diff/ndiff.go b/app/server/external/diff/ndiff.gonew file mode 100644index 00000000..c65b02a8--- /dev/null+++ b/app/server/external/diff/ndiff.go@@ -0,0 +1,99 @@+// Copyright 2022 The Go Authors. All rights reserved.+// Use of this source code is governed by a BSD-style+// license that can be found in the LICENSE file.++package diff++import (+ "bytes"+ "unicode/utf8"++ "plandex-server/external/diff/lcs"+)++// Strings computes the differences between two strings.+// The resulting edits respect rune boundaries.+func Strings(before, after string) []Edit {+ if before == after {+ return nil // common case+ }++ if isASCII(before) && isASCII(after) {+ // TODO(adonovan): opt: specialize diffASCII for strings.+ return diffASCII([]byte(before), []byte(after))+ }+ return diffRunes([]rune(before), []rune(after))+}++// Bytes computes the differences between two byte slices.+// The resulting edits respect rune boundaries.+func Bytes(before, after []byte) []Edit {+ if bytes.Equal(before, after) {+ return nil // common case+ }++ if isASCII(before) && isASCII(after) {+ return diffASCII(before, after)+ }+ return diffRunes(runes(before), runes(after))+}++func diffASCII(before, after []byte) []Edit {+ diffs := lcs.DiffBytes(before, after)++ // Convert from LCS diffs.+ res := make([]Edit, len(diffs))+ for i, d := range diffs {+ res[i] = Edit{d.Start, d.End, string(after[d.ReplStart:d.ReplEnd])}+ }+ return res+}++func diffRunes(before, after []rune) []Edit {+ diffs := lcs.DiffRunes(before, after)++ // The diffs returned by the lcs package use indexes+ // into whatever slice was passed in.+ // Convert rune offsets to byte offsets.+ res := make([]Edit, len(diffs))+ lastEnd := 0+ utf8Len := 0+ for i, d := range diffs {+ utf8Len += runesLen(before[lastEnd:d.Start]) // text between edits+ start := utf8Len+ utf8Len += runesLen(before[d.Start:d.End]) // text deleted by this edit+ res[i] = Edit{start, utf8Len, string(after[d.ReplStart:d.ReplEnd])}+ lastEnd = d.End+ }+ return res+}++// runes is like []rune(string(bytes)) without the duplicate allocation.+func runes(bytes []byte) []rune {+ n := utf8.RuneCount(bytes)+ runes := make([]rune, n)+ for i := 0; i < n; i++ {+ r, sz := utf8.DecodeRune(bytes)+ bytes = bytes[sz:]+ runes[i] = r+ }+ return runes+}++// runesLen returns the length in bytes of the UTF-8 encoding of runes.+func runesLen(runes []rune) (len int) {+ for _, r := range runes {+ len += utf8.RuneLen(r)+ }+ return len+}++// isASCII reports whether s contains only ASCII.+func isASCII[S string | []byte](s S) bool {+ for i := 0; i < len(s); i++ {+ if s[i] >= utf8.RuneSelf {+ return false+ }+ }+ return true+}diff --git a/app/server/external/diff/unified.go b/app/server/external/diff/unified.gonew file mode 100644index 00000000..cfbda610--- /dev/null+++ b/app/server/external/diff/unified.go@@ -0,0 +1,251 @@+// Copyright 2019 The Go Authors. All rights reserved.+// Use of this source code is governed by a BSD-style+// license that can be found in the LICENSE file.++package diff++import (+ "fmt"+ "log"+ "strings"+)++// DefaultContextLines is the number of unchanged lines of surrounding+// context displayed by Unified. Use ToUnified to specify a different value.+const DefaultContextLines = 3++// Unified returns a unified diff of the old and new strings.+// The old and new labels are the names of the old and new files.+// If the strings are equal, it returns the empty string.+func Unified(oldLabel, newLabel, old, new string) string {+ edits := Strings(old, new)+ unified, err := ToUnified(oldLabel, newLabel, old, edits, DefaultContextLines)+ if err != nil {+ // Can't happen: edits are consistent.+ log.Fatalf("internal error in diff.Unified: %v", err)+ }+ return unified+}++// ToUnified applies the edits to content and returns a unified diff,+// with contextLines lines of (unchanged) context around each diff hunk.+// The old and new labels are the names of the content and result files.+// It returns an error if the edits are inconsistent; see ApplyEdits.+func ToUnified(oldLabel, newLabel, content string, edits []Edit, contextLines int) (string, error) {+ u, err := toUnified(oldLabel, newLabel, content, edits, contextLines)+ if err != nil {+ return "", err+ }+ return u.String(), nil+}++// unified represents a set of edits as a unified diff.+type unified struct {+ // from is the name of the original file.+ from string+ // to is the name of the modified file.+ to string+ // hunks is the set of edit hunks needed to transform the file content.+ hunks []*hunk+}++// Hunk represents a contiguous set of line edits to apply.+type hunk struct {+ // The line in the original source where the hunk starts.+ fromLine int+ // The line in the original source where the hunk finishes.+ toLine int+ // The set of line based edits to apply.+ lines []line+}++// Line represents a single line operation to apply as part of a Hunk.+type line struct {+ // kind is the type of line this represents, deletion, insertion or copy.+ kind opKind+ // content is the content of this line.+ // For deletion it is the line being removed, for all others it is the line+ // to put in the output.+ content string+}++// opKind is used to denote the type of operation a line represents.+type opKind int++const (+ // opDelete is the operation kind for a line that is present in the input+ // but not in the output.+ opDelete opKind = iota+ // opInsert is the operation kind for a line that is new in the output.+ opInsert+ // opEqual is the operation kind for a line that is the same in the input and+ // output, often used to provide context around edited lines.+ opEqual+)++// String returns a human readable representation of an OpKind. It is not+// intended for machine processing.+func (k opKind) String() string {+ switch k {+ case opDelete:+ return "delete"+ case opInsert:+ return "insert"+ case opEqual:+ return "equal"+ default:+ panic("unknown operation kind")+ }+}++// toUnified takes a file contents and a sequence of edits, and calculates+// a unified diff that represents those edits.+func toUnified(fromName, toName string, content string, edits []Edit, contextLines int) (unified, error) {+ gap := contextLines * 2+ u := unified{+ from: fromName,+ to: toName,+ }+ if len(edits) == 0 {+ return u, nil+ }+ var err error+ edits, err = lineEdits(content, edits) // expand to whole lines+ if err != nil {+ return u, err+ }+ lines := splitLines(content)+ var h *hunk+ last := 0+ toLine := 0+ for _, edit := range edits {+ // Compute the zero-based line numbers of the edit start and end.+ // TODO(adonovan): opt: compute incrementally, avoid O(n^2).+ start := strings.Count(content[:edit.Start], "\n")+ end := strings.Count(content[:edit.End], "\n")+ if edit.End == len(content) && len(content) > 0 && content[len(content)-1] != '\n' {+ end++ // EOF counts as an implicit newline+ }++ switch {+ case h != nil && start == last:+ //direct extension+ case h != nil && start <= last+gap:+ //within range of previous lines, add the joiners+ addEqualLines(h, lines, last, start)+ default:+ //need to start a new hunk+ if h != nil {+ // add the edge to the previous hunk+ addEqualLines(h, lines, last, last+contextLines)+ u.hunks = append(u.hunks, h)+ }+ toLine += start - last+ h = &hunk{+ fromLine: start + 1,+ toLine: toLine + 1,+ }+ // add the edge to the new hunk+ delta := addEqualLines(h, lines, start-contextLines, start)+ h.fromLine -= delta+ h.toLine -= delta+ }+ last = start+ for i := start; i < end; i++ {+ h.lines = append(h.lines, line{kind: opDelete, content: lines[i]})+ last+++ }+ if edit.New != "" {+ for _, content := range splitLines(edit.New) {+ h.lines = append(h.lines, line{kind: opInsert, content: content})+ toLine+++ }+ }+ }+ if h != nil {+ // add the edge to the final hunk+ addEqualLines(h, lines, last, last+contextLines)+ u.hunks = append(u.hunks, h)+ }+ return u, nil+}++func splitLines(text string) []string {+ lines := strings.SplitAfter(text, "\n")+ if lines[len(lines)-1] == "" {+ lines = lines[:len(lines)-1]+ }+ return lines+}++func addEqualLines(h *hunk, lines []string, start, end int) int {+ delta := 0+ for i := start; i < end; i++ {+ if i < 0 {+ continue+ }+ if i >= len(lines) {+ return delta+ }+ h.lines = append(h.lines, line{kind: opEqual, content: lines[i]})+ delta+++ }+ return delta+}++// String converts a unified diff to the standard textual form for that diff.+// The output of this function can be passed to tools like patch.+func (u unified) String() string {+ if len(u.hunks) == 0 {+ return ""+ }+ b := new(strings.Builder)+ fmt.Fprintf(b, "--- %s\n", u.from)+ fmt.Fprintf(b, "+++ %s\n", u.to)+ for _, hunk := range u.hunks {+ fromCount, toCount := 0, 0+ for _, l := range hunk.lines {+ switch l.kind {+ case opDelete:+ fromCount+++ case opInsert:+ toCount+++ default:+ fromCount+++ toCount+++ }+ }+ fmt.Fprint(b, "@@")+ if fromCount > 1 {+ fmt.Fprintf(b, " -%d,%d", hunk.fromLine, fromCount)+ } else if hunk.fromLine == 1 && fromCount == 0 {+ // Match odd GNU diff -u behavior adding to empty file.+ fmt.Fprintf(b, " -0,0")+ } else {+ fmt.Fprintf(b, " -%d", hunk.fromLine)+ }+ if toCount > 1 {+ fmt.Fprintf(b, " +%d,%d", hunk.toLine, toCount)+ } else if hunk.toLine == 1 && toCount == 0 {+ // Match odd GNU diff -u behavior adding to empty file.+ fmt.Fprintf(b, " +0,0")+ } else {+ fmt.Fprintf(b, " +%d", hunk.toLine)+ }+ fmt.Fprint(b, " @@\n")+ for _, l := range hunk.lines {+ switch l.kind {+ case opDelete:+ fmt.Fprintf(b, "-%s", l.content)+ case opInsert:+ fmt.Fprintf(b, "+%s", l.content)+ default:+ fmt.Fprintf(b, " %s", l.content)+ }+ if !strings.HasSuffix(l.content, "\n") {+ fmt.Fprintf(b, "\n\\ No newline at end of file\n")+ }+ }+ }+ return b.String()+}diff --git a/app/server/go.mod b/app/server/go.modindex b354b93c..e164e314 100644--- a/app/server/go.mod+++ b/app/server/go.mod@@ -29,6 +29,7 @@ require (github.com/tadvi/systray v0.0.0-20190226123456-11a2b8fa57af // indirectgo.uber.org/atomic v1.11.0 // indirectgolang.org/x/image v0.19.0 // indirect+ golang.org/x/mod v0.11.0 // indirectgolang.org/x/sys v0.24.0 // indirect)@@ -42,6 +43,7 @@ require (github.com/lib/pq v1.10.9github.com/rs/cors v1.11.0github.com/smacker/go-tree-sitter v0.0.0-20240625050157-a31a98a7c0f6+ golang.org/x/tools v0.10.0)replace github.com/plandex/plandex/shared => ../shareddiff --git a/app/server/model/plan/build_exec.go b/app/server/model/plan/build_exec.goindex 0bc39d15..6fbd271b 100644--- a/app/server/model/plan/build_exec.go+++ b/app/server/model/plan/build_exec.go@@ -374,15 +374,16 @@ func (fileState *activeBuildStreamFileState) buildFileLineNums() {Temperature: config.Temperature,TopP: config.TopP,ResponseFormat: responseFormat,- StreamOptions: &openai.StreamOptions{- IncludeUsage: true,- },}envVar := config.BaseModelConfig.ApiKeyEnvVarclient := clients[envVar]if config.BaseModelConfig.HasStreamingFunctionCalls {+ modelReq.StreamOptions = &openai.StreamOptions{+ IncludeUsage: true,+ }+stream, err := model.CreateChatCompletionStreamWithRetries(client, activePlan.Ctx, modelReq)if err != nil {log.Printf("Error creating plan file stream for path '%s': %v\n", filePath, err)@@ -390,7 +391,6 @@ func (fileState *activeBuildStreamFileState) buildFileLineNums() {return}- log.Printf("File %s: calling listenStreamChangesWithLineNums\n", filePath)go fileState.listenStreamChangesWithLineNums(stream)} else {@@ -405,6 +405,28 @@ func (fileState *activeBuildStreamFileState) buildFileLineNums() {return}+ log.Println("buildFileLineNums - usage:")+ spew.Dump(resp.Usage)++ _, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{+ Auth: auth,+ Plan: fileState.plan,+ DidSendModelRequestParams: &hooks.DidSendModelRequestParams{+ InputTokens: resp.Usage.PromptTokens,+ OutputTokens: resp.Usage.CompletionTokens,+ ModelName: fileState.settings.ModelPack.Builder.BaseModelConfig.ModelName,+ ModelProvider: fileState.settings.ModelPack.Builder.BaseModelConfig.Provider,+ ModelPackName: fileState.settings.ModelPack.Name,+ ModelRole: shared.ModelRoleBuilder,+ Purpose: "Generated file update (ref expansion)",+ },+ })++ if apiErr != nil {+ activePlan.StreamDoneCh <- apiErr+ return+ }+var s stringvar res types.ChangesWithLineNums@@ -419,7 +441,7 @@ func (fileState *activeBuildStreamFileState) buildFileLineNums() {if s == "" {log.Println("no ListReplacements function call found in response")- fileState.lineNumsRetryOrError(fmt.Errorf("No ListReplacements function call found in response. This usually means the model failed to generate a valid response."))+ fileState.lineNumsRetryOrError(fmt.Errorf("no ListReplacements function call found in response"))return}@@ -428,14 +450,10 @@ func (fileState *activeBuildStreamFileState) buildFileLineNums() {err = json.Unmarshal(bytes, &res)if err != nil {log.Printf("Error unmarshalling build response: %v\n", err)- fileState.lineNumsRetryOrError(fmt.Errorf("Error unmarshalling build response: %v | This usually means the model failed to generate valid JSON.", err))+ fileState.lineNumsRetryOrError(fmt.Errorf("error unmarshalling build response: %v", err))return}- // log the file path- log.Printf("File %s: calling onBuildResult after non-streaming build\n", filePath)-- fileState.onBuildResult(res)+ fileState.onLineNumsBuildResult(res)}-}diff --git a/app/server/model/plan/build_refs.go b/app/server/model/plan/build_refs.gonew file mode 100644index 00000000..c5cb3178--- /dev/null+++ b/app/server/model/plan/build_refs.go@@ -0,0 +1,289 @@+package plan++import (+ "encoding/xml"+ "fmt"+ "log"+ "math/rand"+ "plandex-server/db"+ "plandex-server/external/diff"+ "plandex-server/hooks"+ "plandex-server/model"+ "plandex-server/model/prompts"+ "plandex-server/syntax"+ "strings"+ "time"++ "github.com/davecgh/go-spew/spew"+ "github.com/plandex/plandex/shared"+ "github.com/sashabaranov/go-openai"+)++type Reference struct {+ Comment string `xml:"comment,attr"`+ Description string `xml:"description,attr"`+ ProposedLine string `xml:"proposedLine,attr"`+ OriginalStart string `xml:"originalStart,attr"`+ OriginalEnd string `xml:"originalEnd,attr"`+}++type References struct {+ XMLName xml.Name `xml:"references"`+ References []Reference `xml:"reference"`+}++const ExpandRefsRetries = 1++func (fileState *activeBuildStreamFileState) buildExpandReferences() {+ auth := fileState.auth+ filePath := fileState.filePath+ activeBuild := fileState.activeBuild+ clients := fileState.clients+ planId := fileState.plan.Id+ branch := fileState.branch+ config := fileState.settings.ModelPack.Builder+ originalFile := fileState.preBuildState++ activePlan := GetActivePlan(planId, branch)++ if activePlan == nil {+ log.Printf("Active plan not found for plan ID %s and branch %s\n", planId, branch)+ return+ }++ log.Println("buildExpandReferences - getting references prompt")++ refsSysPrompt := prompts.GetReferencesPrompt(filePath, originalFile, activeBuild.FileContent, activeBuild.FileDescription)++ refsFileMessages := []openai.ChatCompletionMessage{+ {+ Role: openai.ChatMessageRoleSystem,+ Content: refsSysPrompt,+ },+ }++ promptTokens, err := shared.GetNumTokens(refsSysPrompt)++ if err != nil {+ log.Printf("buildExpandReferences - error getting num tokens for prompt: %v\n", err)+ fileState.onBuildFileError(fmt.Errorf("error getting num tokens for prompt: %v", err))+ return+ }++ inputTokens := prompts.ExtraTokensPerRequest + prompts.ExtraTokensPerMessage + promptTokens++ fileState.inputTokens = inputTokens++ _, apiErr := hooks.ExecHook(hooks.WillSendModelRequest, hooks.HookParams{+ Auth: auth,+ Plan: fileState.plan,+ WillSendModelRequestParams: &hooks.WillSendModelRequestParams{+ InputTokens: inputTokens,+ OutputTokens: shared.AvailableModelsByName[fileState.settings.ModelPack.Builder.BaseModelConfig.ModelName].DefaultReservedOutputTokens,+ ModelName: fileState.settings.ModelPack.Builder.BaseModelConfig.ModelName,+ },+ })+ if apiErr != nil {+ activePlan.StreamDoneCh <- apiErr+ return+ }++ log.Println("buildExpandReferences - calling model for references")++ modelReq := openai.ChatCompletionRequest{+ Model: config.BaseModelConfig.ModelName,+ Messages: refsFileMessages,+ Temperature: config.Temperature,+ TopP: config.TopP,+ }++ envVar := config.BaseModelConfig.ApiKeyEnvVar+ client := clients[envVar]++ resp, err := model.CreateChatCompletionWithRetries(client, activePlan.Ctx, modelReq)++ if err != nil {+ log.Printf("buildExpandReferences - error calling model: %v\n", err)+ fileState.expandRefsRetryOrError(fmt.Errorf("error calling model: %v", err))+ return+ }++ log.Println("buildExpandReferences - usage:")+ spew.Dump(resp.Usage)++ _, apiErr = hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{+ Auth: auth,+ Plan: fileState.plan,+ DidSendModelRequestParams: &hooks.DidSendModelRequestParams{+ InputTokens: resp.Usage.PromptTokens,+ OutputTokens: resp.Usage.CompletionTokens,+ ModelName: fileState.settings.ModelPack.Builder.BaseModelConfig.ModelName,+ ModelProvider: fileState.settings.ModelPack.Builder.BaseModelConfig.Provider,+ ModelPackName: fileState.settings.ModelPack.Name,+ ModelRole: shared.ModelRoleBuilder,+ Purpose: "Generated file update (ref expansion)",+ },+ })++ if apiErr != nil {+ activePlan.StreamDoneCh <- apiErr+ return+ }++ if len(resp.Choices) == 0 {+ log.Printf("buildExpandReferences - no choices in response\n")+ fileState.expandRefsRetryOrError(fmt.Errorf("no choices in response"))+ return+ }++ refsChoice := resp.Choices[0]+ refsXml := refsChoice.Message.Content++ refsSplit := strings.Split(refsXml, "<references>")+ if len(refsSplit) != 2 {+ log.Printf("buildExpandReferences - error processing references xml\n")+ fileState.expandRefsRetryOrError(fmt.Errorf("error processing references xml"))+ return+ }++ processedXml := "<references>" + refsSplit[1]+ processedXml = EscapeInvalidXMLAttributeCharacters(processedXml)+ refsXml = processedXml++ var refs References++ err = xml.Unmarshal([]byte(processedXml), &refs)+ if err != nil {+ log.Printf("buildExpandReferences - error unmarshalling xml: %v\n", err)+ fileState.expandRefsRetryOrError(fmt.Errorf("error unmarshalling xml: %v", err))+ return+ }++ log.Printf("buildExpandReferences - got %d references\n", len(refs.References))++ fileContentLines := strings.Split(activeBuild.FileContent, "\n")+ inputTextLines := strings.Split(originalFile, "\n")++ for _, ref := range refs.References {+ var proposedLine, originalStart, originalEnd int++ proposedLine, err = shared.ExtractLineNumberWithPrefix(ref.ProposedLine, "pdx-new-")+ if err != nil {+ log.Printf("Error extracting line number from proposed line: %v", err)+ fileState.expandRefsRetryOrError(fmt.Errorf("error extracting line number from proposed line: %v", err))+ return+ }++ originalStart, err = shared.ExtractLineNumberWithPrefix(ref.OriginalStart, "pdx-")+ if err != nil {+ log.Printf("Error extracting line number from start: %v", err)+ fileState.expandRefsRetryOrError(fmt.Errorf("error extracting line number from start: %v", err))+ return+ }+ originalEnd, err = shared.ExtractLineNumberWithPrefix(ref.OriginalEnd, "pdx-")+ if err != nil {+ log.Printf("Error extracting line number from end: %v", err)+ fileState.expandRefsRetryOrError(fmt.Errorf("error extracting line number from end: %v", err))+ return+ }++ if originalStart > originalEnd {+ originalStart, originalEnd = originalEnd, originalStart+ }++ if originalEnd > len(inputTextLines) {+ log.Printf("Start line is greater than end line or end line is greater than the number of lines in the file: %d > %d", originalStart, originalEnd)+ fileState.expandRefsRetryOrError(fmt.Errorf("start line is greater than end line or end line is greater than the number of lines in the file: %d > %d", originalStart, originalEnd))+ return+ }++ // Replace the proposed line with the referenced section from inputTextLines+ referencedSection := inputTextLines[originalStart-1 : originalEnd]++ if proposedLine-1 >= 0 && proposedLine-1 < len(fileContentLines) {+ fileContentLines[proposedLine-1] = strings.Join(referencedSection, "\n")+ } else {+ log.Printf("Proposed line is out of bounds: %d", proposedLine)+ fileState.expandRefsRetryOrError(fmt.Errorf("proposed line is out of bounds: %d", proposedLine))+ return+ }+ }++ updatedFile := strings.Join(fileContentLines, "\n")++ buildInfo := &shared.BuildInfo{+ Path: filePath,+ NumTokens: 0,+ Finished: true,+ }+ activePlan.Stream(shared.StreamMessage{+ Type: shared.StreamMessageBuildInfo,+ BuildInfo: buildInfo,+ })+ time.Sleep(50 * time.Millisecond)++ fileState.updated = updatedFile++ edits := diff.Strings(originalFile, updatedFile)+ replacements := []*shared.Replacement{}+ for _, edit := range edits {+ old := originalFile[edit.Start:edit.End]+ replacements = append(replacements, &shared.Replacement{+ Old: old,+ New: edit.New,+ })+ }++ res := db.PlanFileResult{+ TypeVersion: 1,+ OrgId: fileState.plan.OrgId,+ PlanId: fileState.plan.Id,+ PlanBuildId: fileState.build.Id,+ ConvoMessageId: fileState.convoMessageId,+ Content: "",+ Path: filePath,+ Replacements: replacements,+ CanVerify: true,+ }++ validationRes, err := syntax.Validate(activePlan.Ctx, filePath, updatedFile)+ if err != nil {+ log.Printf("buildExpandReferences - error validating syntax: %v\n", err)+ fileState.expandRefsRetryOrError(fmt.Errorf("error validating syntax: %v", err))+ return+ }++ res.WillCheckSyntax = validationRes.HasParser && !validationRes.TimedOut+ res.SyntaxValid = validationRes.Valid+ res.SyntaxErrors = validationRes.Errors++ fileState.onFinishBuildFile(&res, updatedFile)+}++func (fileState *activeBuildStreamFileState) expandRefsRetryOrError(err error) {+ if fileState.expandRefsNumRetry < ExpandRefsRetries {+ fileState.expandRefsNumRetry++++ log.Printf("buildExpandReferences - retrying expand refs file '%s' due to error: %v\n", fileState.filePath, err)++ activePlan := GetActivePlan(fileState.plan.Id, fileState.branch)++ if activePlan == nil {+ log.Printf("buildExpandReferences - active plan not found for plan ID %s and branch %s\n", fileState.plan.Id, fileState.branch)+ return+ }++ select {+ case <-activePlan.Ctx.Done():+ log.Printf("buildExpandReferences - context canceled\n")+ return+ case <-time.After(time.Duration(fileState.expandRefsNumRetry*fileState.expandRefsNumRetry)*200*time.Millisecond + time.Duration(rand.Intn(500))*time.Millisecond):+ break+ }++ fileState.buildExpandReferences()+ } else {+ fileState.onBuildFileError(err)+ }++}diff --git a/app/server/model/plan/build_result.go b/app/server/model/plan/build_result.goindex d75a17e8..9ce46b75 100644--- a/app/server/model/plan/build_result.go+++ b/app/server/model/plan/build_result.go@@ -339,8 +339,8 @@ func GetPlanResultUpdated(ctx context.Context, params PlanResultParamsUpdated) (return &res, updated, allSucceeded, nil}-func (fileState *activeBuildStreamFileState) onBuildResult(res types.ChangesWithLineNums) {- log.Printf("onBuildResult - File: %s\n", fileState.filePath)+func (fileState *activeBuildStreamFileState) onLineNumsBuildResult(res types.ChangesWithLineNums) {+ log.Printf("onLineNumsBuildResult - File: %s\n", fileState.filePath)filePath := fileState.filePathbuild := fileState.build@@ -352,7 +352,7 @@ func (fileState *activeBuildStreamFileState) onBuildResult(res types.ChangesWithactivePlan := GetActivePlan(planId, branch)if activePlan == nil {- log.Printf("onBuildResult - File %s: Active plan not found for plan ID %s on branch %s\n", filePath, planId, branch)+ log.Printf("onLineNumsBuildResult - File %s: Active plan not found for plan ID %s on branch %s\n", filePath, planId, branch)return}@@ -372,24 +372,24 @@ func (fileState *activeBuildStreamFileState) onBuildResult(res types.ChangesWithiStartLine, _, err := sorted[i].Old.GetLines()if err != nil {- log.Printf("onBuildResult - File %s: Error getting start line for change %v: %v\n", filePath, sorted[i], err)- fileState.lineNumsRetryOrError(fmt.Errorf("onBuildResult - error getting start line for change %v: %v", sorted[i], err))+ log.Printf("onLineNumsBuildResult - File %s: Error getting start line for change %v: %v\n", filePath, sorted[i], err)+ fileState.lineNumsRetryOrError(fmt.Errorf("onLineNumsBuildResult - error getting start line for change %v: %v", sorted[i], err))return false}jStartLine, _, err = sorted[j].Old.GetLines()if err != nil {- log.Printf("onBuildResult - File %s: Error getting start line for change %v: %v\n", filePath, sorted[j], err)- fileState.lineNumsRetryOrError(fmt.Errorf("onBuildResult - error getting start line for change %v: %v", sorted[j], err))+ log.Printf("onLineNumsBuildResult - File %s: Error getting start line for change %v: %v\n", filePath, sorted[j], err)+ fileState.lineNumsRetryOrError(fmt.Errorf("onLineNumsBuildResult - error getting start line for change %v: %v", sorted[j], err))return false}return iStartLine < jStartLine})- log.Printf("onBuildResult - File %s: fileState.streamedChangesWithLineNums = sorted\n", filePath)- log.Printf("onBuildResult - File %s: num changes: %d\n", filePath, len(sorted))+ log.Printf("onLineNumsBuildResult - File %s: fileState.streamedChangesWithLineNums = sorted\n", filePath)+ log.Printf("onLineNumsBuildResult - File %s: num changes: %d\n", filePath, len(sorted))fileState.streamedChangesWithLineNums = sorted@@ -414,20 +414,20 @@ func (fileState *activeBuildStreamFileState) onBuildResult(res types.ChangesWith)if err != nil {- log.Printf("onBuildResult - File %s: Error getting plan result: %v\n", filePath, err)- fileState.lineNumsRetryOrError(fmt.Errorf("onBuildResult - error getting plan result for file '%s': %v", filePath, err))+ log.Printf("onLineNumsBuildResult - File %s: Error getting plan result: %v\n", filePath, err)+ fileState.lineNumsRetryOrError(fmt.Errorf("onLineNumsBuildResult - error getting plan result for file '%s': %v", filePath, err))return}if !allSucceeded {- log.Printf("onBuildResult - File %s: Failed replacements:\n", filePath)+ log.Printf("onLineNumsBuildResult - File %s: Failed replacements:\n", filePath)for _, replacement := range planFileResult.Replacements {if replacement.Failed {spew.Dump(replacement)}}- fileState.onBuildFileError(fmt.Errorf("onBuildResult - replacements failed for file '%s'", filePath))+ fileState.onBuildFileError(fmt.Errorf("onLineNumsBuildResult - replacements failed for file '%s'", filePath))return}@@ -444,8 +444,8 @@ func (fileState *activeBuildStreamFileState) onBuildResult(res types.ChangesWithfileState.updated = updatedFile- log.Printf("onBuildResult - File %s: Plan file result: %v\n", filePath, planFileResult != nil)- log.Printf("onBuildResult - File %s: updatedFile exists: %v\n", filePath, updatedFile != "")+ log.Printf("onLineNumsBuildResult - File %s: Plan file result: %v\n", filePath, planFileResult != nil)+ log.Printf("onLineNumsBuildResult - File %s: updatedFile exists: %v\n", filePath, updatedFile != "")fileState.onFinishBuildFile(planFileResult, updatedFile)}diff --git a/app/server/model/plan/build_state.go b/app/server/model/plan/build_state.goindex 3ec6487b..249fce0d 100644--- a/app/server/model/plan/build_state.go+++ b/app/server/model/plan/build_state.go@@ -27,12 +27,14 @@ type activeBuildStreamState struct {type activeBuildStreamFileState struct {*activeBuildStreamState- filePath string- convoMessageId string- build *db.PlanBuild- currentPlanState *shared.CurrentPlanState- activeBuild *types.ActiveBuild- preBuildState string+ filePath string+ convoMessageId string+ build *db.PlanBuild+ currentPlanState *shared.CurrentPlanState+ activeBuild *types.ActiveBuild+ preBuildState string++ expandRefsNumRetry intlineNumsNumRetry intverifyFileNumRetry intfixFileNumRetry intdiff --git a/app/server/model/plan/build_stream_line_nums.go b/app/server/model/plan/build_stream_line_nums.goindex 25eb368d..65ff8939 100644--- a/app/server/model/plan/build_stream_line_nums.go+++ b/app/server/model/plan/build_stream_line_nums.go@@ -51,7 +51,7 @@ func (fileState *activeBuildStreamFileState) listenStreamChangesWithLineNums(strModelProvider: fileState.settings.ModelPack.Builder.BaseModelConfig.Provider,ModelPackName: fileState.settings.ModelPack.Name,ModelRole: shared.ModelRoleBuilder,- Purpose: "Generated file update",+ Purpose: "Generated file update (line numbers)",},})@@ -219,8 +219,8 @@ func (fileState *activeBuildStreamFileState) listenStreamChangesWithLineNums(strstreamFinished = true // Stream finished successfully- log.Printf("listenStream - File %s: calling onBuildResult\n", filePath)- fileState.onBuildResult(streamed)+ log.Printf("listenStream - File %s: calling onLineNumsBuildResult\n", filePath)+ fileState.onLineNumsBuildResult(streamed)// Reset the timer for the usage chunkif !timer.Stop() {diff --git a/app/server/model/plan/build_verify.go b/app/server/model/plan/build_verify.goindex 9fe33cca..51aa1a61 100644--- a/app/server/model/plan/build_verify.go+++ b/app/server/model/plan/build_verify.go@@ -56,7 +56,7 @@ func (fileState *activeBuildStreamFileState) verifyFileBuild() {var diff stringif verifyState.preBuildFileState != "" {- diff, err = db.GetDiffsForBuild(verifyState.preBuildFileState, updated)+ diff, err = db.GetDiffs(verifyState.preBuildFileState, updated)if err != nil {log.Printf("Error getting diffs for file '%s': %v\n", filePath, err)diff --git a/app/server/model/plan/build_verify_stream.go b/app/server/model/plan/build_verify_stream.goindex 8ed35d3b..d0635af8 100644--- a/app/server/model/plan/build_verify_stream.go+++ b/app/server/model/plan/build_verify_stream.go@@ -115,7 +115,7 @@ func (fileState *activeBuildStreamFileState) listenStreamVerifyOutput(stream *opif len(response.Choices) == 0 {if response.Usage != nil {- log.Println("Fix stream usage:")+ log.Println("Verify stream usage:")spew.Dump(response.Usage)_, apiErr := hooks.ExecHook(hooks.DidSendModelRequest, hooks.HookParams{diff --git a/app/server/model/plan/xml.go b/app/server/model/plan/xml.gonew file mode 100644index 00000000..a0e9ab80--- /dev/null+++ b/app/server/model/plan/xml.go@@ -0,0 +1,35 @@+package plan++import (+ "regexp"+ "strings"+)++func EscapeInvalidXMLAttributeCharacters(xmlString string) string {+ // Regular expression to match content inside double quotes, but not the quotes themselves+ re := regexp.MustCompile(`"([^"]*?)"`)+ return re.ReplaceAllStringFunc(xmlString, func(attrValue string) string {+ // Extract the content inside the quotes (removing the enclosing quotes)+ content := attrValue[1 : len(attrValue)-1]++ // Escape the content inside the quotes+ escaped := strings.ReplaceAll(content, "&", "&")+ escaped = strings.ReplaceAll(escaped, "<", "<")+ escaped = strings.ReplaceAll(escaped, ">", ">")+ escaped = strings.ReplaceAll(escaped, `"`, """)+ escaped = strings.ReplaceAll(escaped, "'", "'")++ // Re-wrap the escaped content in quotes+ return `"` + escaped + `"`+ })+}++func EscapeCdata(xmlString string) string {+ escaped := strings.ReplaceAll(xmlString, "]]>", "PDX_ESCAPED_CDATA_END")+ return escaped+}++func UnescapeCdata(xmlString string) string {+ escaped := strings.ReplaceAll(xmlString, "PDX_ESCAPED_CDATA_END", "]]>")+ return escaped+}diff --git a/app/server/model/prompts/build.go b/app/server/model/prompts/build.goindex 5dfbebd3..2260d445 100644--- a/app/server/model/prompts/build.go+++ b/app/server/model/prompts/build.go@@ -143,7 +143,25 @@ The 'summary' property is a brief summary of the change.The 'newReasoning' property evaluates what needs to be included in the 'new' section to ensure that *ALL* the code from the *proposed changes* are correctly applied to the resulting file. Carefully consider whether the code from the *proposed updates* contain code structures that need to be properly closed in the resulting file. For example, "the <Route> tag needs to be closed properly in the resulting file, so the 'new' section should end on the closing tag at pdx-new-10: </Route>".-The 'structureReasoning' property list the code structures that are involved in the change. Explain what kind of change should be used to ensure that the code structures are closed properly. For example, if a new method should be added to the end of a class, explain that the change should use the 'insertBefore' property in order to ensure that the method is added *before* the closing brace of the class so that the method stays inside the class and both the method and the class are closed properly.+The 'structureReasoning' property is an object with 2 properties: 'old' and 'new'.++ The 'old' property is an object with 3 properties: 'structure', 'structureOpens', and 'structureCloses'.++ 'structure' is the *code structure* (e.g. 'function', 'class', 'loop', 'conditional', etc.) that this change is contained by. If the change is not contained within a code structure and is instead at the top level of the file, output 'top level'. This must be the MOST specific, deeply nested code structure that contains the change. You must output only a single structure or 'top level'. Identify the structure unambiguously. If a structure is being *replaced*, the 'structure' property must identify the exact structure that is being replaced. If new code is being added to a structure, the 'structure' property must identify the structure that the new code is being added to.++ 'structureOpens' is the entire line from the *original file* that contains the opening symbol of the code structure identified in the 'structure' property, including the line number prefixed with 'pdx-'. Empty if the code structure is 'top level'.++ 'structureCloses' is the entire line from the *original file* that contains the closing symbol of the code structure identified in the 'structure' property, including the line number prefixed with 'pdx-'. Empty if the code structure is 'top level'.++ When determining 'structureOpens' and 'structureCloses' properties for 'old', evaluate both the *original file* AND the *proposed updates* to help you identify the correct closing symbol.++ The 'new' property is an object with 3 properties: 'structure', 'structureOpens', and 'structureCloses'.++ 'structure' is the *code structure* (e.g. 'function', 'class', 'loop', 'conditional', etc.) in the *proposed updates* that should be inserted. If the code that should be inserted is 'flat' and not contained within a code structure, either because the *proposed updates* themselves are 'flat' or because surrounding code structures in the *proposed updates* are already contained by the *original file*, output 'flat'. If you output a structure and not 'flat', it must be the MOST specific, deeply nested code structure that contains the new code to be inserted. You must output only a single structure or 'flat'. Identify the structure unambiguously.++ 'structureOpens' is the entire line from the *proposed updates* that contains the opening symbol of the code structure identified in the 'structure' property, including the line number prefixed with 'pdx-new-'. Must be an EXACT MATCH to a line from the *proposed updates*. Empty if the code structure is 'flat'.++ 'structureCloses' is the entire line from the *proposed updates* that contains the closing symbol of the code structure identified in the 'structure' property, including the line number prefixed with 'pdx-new-'. Must be an EXACT MATCH to a line from the *proposed updates*. Empty if the code structure is 'flat'.If you are adding new code to the *end* of an existing code structure (and not replacing any existing code), you must use the 'insertBefore' property to add the new code before the closing symbol of the existing code structure.@@ -241,7 +259,7 @@ Expand the lines the 'new' property refers to in the *proposed updates* where neIf the code from the 'new' section should fully replace the code from the 'old' property, say "Fully replace" and stop.-If the 'old' section spans multiple lines of the *original file*, say "Multiple lins, don't include." and stop.+If the 'old' section spans multiple lines of the *original file*, say "Multiple lines, don't include." and stop.Otherwise, if the code from the 'old' property is a *single line* and it's not in the *proposed updates*, state this. In that case, proceed to evaluate whether the code from the old property makes more sense at the beginning or end of the change from the new property. State which makes more sense and why. For example, "The closing </Routes> tag should be included in the final result. It should be added *after* the 'new' code from the *proposed updates*.@@ -303,7 +321,7 @@ You MUST also explicitly state the *order* that all the changes you've listed wi`const originalSectionsPrompt = `-The 'originalSections' key is an array of objects with four properties: 'description', 'reasoning', 'sectionStartLine', 'sectionEndLine', 'shouldChange', and 'shouldRemove'. In the 'originalSections' key you must logically divide the *original file* into sections based on functionality, logic, code structure, and general organization.+The 'originalSections' key is an array of objects with four properties: 'description', 'structure', 'reasoning', 'sectionStartLine', 'sectionEndLine', 'shouldChange', and 'shouldRemove'. In the 'originalSections' key you must logically divide the *original file* into sections based on functionality, logic, code structure, and general organization.You must list every section that exists in the *original file*. When large sections of the *original file* are not changing, combine them into a single section. Only include sections from the *original file*. Do NOT include sections from the *proposed updates*.@@ -311,13 +329,20 @@ Don't make the sections overly small and granular unless there is a clear semant'description' is a brief summary of the section and its purpose.-'reasoning' is a brief evaluation of how this section relates to the *proposed updates*, and whether all or any part of it will be changed, removed, or preserved as is. If only part of the section should be changed, explain which part(s) will change and which will remain the same, and further explain how you will avoid incorrectly removing or overwriting code that should not be removed.+'structure' is an object with three properties: 'structure', 'structureOpens', and 'structureCloses'.+ 'structure' is the OUTERMOST code structure (namespace, class, function, etc.) of the section. State whether the full structure is contained within the section or whether the section only contains part of the structure. If the seciton is not contained within a structure, output 'top level'.++ 'structureOpens' is the entire line from the *original file* that contains the opening symbol of the code structure identified in the 'structure' property, including the line number prefixed with 'pdx-'. Empty if the code structure is 'top level'. Empty if the the section does not contain the opening symbol of the identified structure. If the section clearly contains an entire structure, like "SomeClass definition", then the 'structureOpens' property must be set and must be the line that opens the structure.++ 'structureCloses' is the entire line from the *original file* that contains the closing symbol of the code structure identified in the 'structure' property, including the line number prefixed with 'pdx-'. Empty if the code structure is 'top level'. Empty if the the section does not contain the closing symbol of the identified structure. If the secton clearly contains an entire structure, like "SomeClass definition", then the 'structureCloses' property must be set and must be the line that closes the structure.++'reasoning' is a brief evaluation of how this section relates to the *proposed updates*, and whether all or any part of it will be changed, removed, or preserved as is. If only part of the section should be changed, explain which part(s) will change and which parts will remain the same, and further explain how you will avoid incorrectly removing or overwriting code that should not be removed.Anytime there is a partial change to a section, it is CRITICAL that you explain BOTH which parts of the section should be *changed* and which parts will be *preserved* and how you will ensure this when generating changes below. You MUST include this explanation in the 'reasoning' key when there's a partial change. It must begin with "To avoid removing". If new code is being added, note *where* in the section it will be added, and include line numbers prefixed with 'pdx-'. For example, "To avoid removing any existing imports, the new imports will be added after the existing imports, which end on pdx-5." or "To avoid removing any existing init code, the new code for checking the GOENV environment variable will be added before the existing init code, which starts on pdx-10."-'sectionStartLine' is the line number, prefixed with 'pdx-', where the section begins in the *original file*. Include only the line number, not the line itself.+'sectionStartLine' is the line number, prefixed with 'pdx-', where the section begins in the *original file*. Include only the line number, not the line itself. If 'structure.structureOpens' is not empty, 'sectionStartLine' MUST be the same as 'structure.structureOpens'.-'sectionEndLine' is the line number, prefixed with 'pdx-', where the section ends in the *original file*. Include only the line number, not the line itself.+'sectionEndLine' is the line number, prefixed with 'pdx-', where the section ends in the *original file*. Include only the line number, not the line itself. If 'structure.structureCloses' is not empty, 'sectionEndLine' MUST be the same as 'structure.structureCloses'.'shouldChange' is a boolean that indicates whether the section should be changed.diff --git a/app/server/model/prompts/build_update.go b/app/server/model/prompts/build_update.goindex 003adb2d..2141b8d9 100644--- a/app/server/model/prompts/build_update.go+++ b/app/server/model/prompts/build_update.go@@ -19,11 +19,9 @@ func GetReferencesPrompt(filePath, preBuildState, changesFile, changesDesc strinreturn s}-var ReferencesPrompt = `-You are an AI that analyzes an *original file* and *proposed updates* to that file and then identifies *all* *reference comments* present in the *proposed updates*.-+var ExampleReferences = `A reference comment is a comment that references code in the *original file* for the purpose of making it clear where a change should be applied. Examples of reference comments include:-+- // ... existing code...- # Existing code...- /* ... */@@ -37,7 +35,13 @@ A reference comment is a comment that references code in the *original file* for- // other properties- // other methods- Comments often won't exactly match one of the above examples, but they will always be referencing a block of code from the *original file* that is left out of the *proposed updates* for the sake of focusing on the specific change that is being made.+Reference comments often won't exactly match one of the above examples, but they will always be referencing a block of code from the *original file* that is left out of the *proposed updates* for the sake of focusing on the specific change that is being made.+`++var ReferencesPrompt = `+You are an AI that analyzes an *original file* and *proposed updates* to that file and then identifies *all* *reference comments* present in the *proposed updates*.++` + ExampleReferences + `*NOT EVERY COMMENT IS A REFERENCE.* If a comment refers to code that is present in the *proposed updates* then it is *not* a reference. Similarly, if a comment explains something about the change being made in the *proposed updates*, it is also *not* a reference.@@ -83,6 +87,9 @@ A reference comment is a comment that references code in the *original file* forcomment="// ... existing code..."description="Code after the addition of the conditional statement in the 'update' function"proposedLine="pdx-new-10"+ structure="'update' function"+ structureOpens="opening '{' on pdx-455"+ structureCloses="closing '}' on pdx-461"originalStart="pdx-456"originalEnd="pdx-460"/>@@ -96,7 +103,13 @@ A reference comment is a comment that references code in the *original file* for**proposedLine**: The line number, prefixed by 'pdx-new-', in the *proposed updates* that the reference is referring to. MUST be a line that exists in the *proposed updates* and contains the reference comment in 'comment' attribute.- **originalStart**: The starting line number, prefixed by 'pdx-', in the *original file* that the reference is referring to. MUST be less than or equal to the 'originalEnd' line number and MUST be greater than or equal to 1.+ **structure**: The *code structure* (e.g. 'function', 'class', 'loop', 'conditional', etc.) that this reference is contained within. If it's not contained within a code structure and is instead at the top level of the file, output 'top level'. This must be the MOST specific, deeply nested code structure that contains the reference. You must output only a single structure or 'top level'. Identify the structure unambiguously.++ **structureOpens**: The entire line from the *original file*, prefixed by 'pdx-', that contains the opening symbol of the code structure identified in the 'structure' property.++ **structureCloses**: The entire line from the *original file*, prefixed by 'pdx-', that contains the closing symbol of the code structure identified in the 'structure' property.++ **originalStart**: The starting line number, prefixed by 'pdx-', in the *original file* that the reference is referring to. MUST be less than or equal to the 'originalEnd' line number and MUST be greater than or equal to 1.**originalEnd**: The ending line number, prefixed by 'pdx-', in the *original file* that the reference is referring to. If the referenced code in the *original file* is a single line, the originalStart and originalEnd must be the same. 'originalEnd' MUST be greater than or equal to 'originalStart' and MUST be less than or equal to the last line number in the *original file*.@@ -151,6 +164,9 @@ A reference comment is a comment that references code in the *original file* forcomment="// ... existing code to start transaction ..."description="Code for starting database transaction"proposedLine="pdx-new-2"+ structure="'update' function"+ structureOpens="opening '{' on pdx-1"+ structureCloses="closing '}' on pdx-18"originalStart="pdx-2"originalEnd="pdx-3"/>@@ -158,6 +174,9 @@ A reference comment is a comment that references code in the *original file* forcomment="// ... existing update code ..."description="Code inside the canUpdate() conditional for updating the user"proposedLine="pdx-new-6"+ structure="'update' function"+ structureOpens="opening '{' on pdx-1"+ structureCloses="closing '}' on pdx-18"originalStart="pdx-5"originalEnd="pdx-6"/>@@ -165,6 +184,9 @@ A reference comment is a comment that references code in the *original file* forcomment="// ... existing code to commit db transaction..."description="Code for committing the database transaction and handling errors"proposedLine="pdx-new-9"+ structure="'update' function"+ structureOpens="opening '{' on pdx-1"+ structureCloses="closing '}' on pdx-18"originalStart="pdx-8"originalEnd="pdx-17"/>@@ -180,15 +202,63 @@ A reference comment is a comment that references code in the *original file* forYou MUST carefully consider code structures when determining the 'originalStart' and 'originalEnd' lines for a reference. If a reference looks like this:- pdx-1: class MyClass {- pdx-2: constructor() {- pdx-3: this.initialize();- pdx-4: }- pdx-5:- pdx-6: // ... existing code ...- pdx-7: }+ pdx-new-1: class MyClass {+ pdx-new-2: constructor() {+ pdx-new-3: this.initialize();+ pdx-new-4: }+ pdx-new-5:+ pdx-new-6: // ... existing code ...+ pdx-new-7: }++ The the reference ONLY refers to the code within the 'MyClass' class. If there is additional code before or after the 'MyClass' class, it must not be included. The same applies to other code structures, like functions, loops, conditionals, etc.++ When setting the 'originalStart' and 'originalEnd' lines for a reference, it is critically important that the code referenced in the *original file* falls COMPLETELY *within* the code structure specified in the 'structure' attribute. Do NOT include the lines that open or close the code structure in the 'originalStart' and 'originalEnd' lines, since these already exist in the *proposed updates*. Only the lines that *do not already exist* in the *proposed updates* can be included in the reference.++ If a reference comes at the beginning of a structure, followed by new or changed code, like this:++ pdx-new-1: class MyClass {+ pdx-new-2: // ... existing code ...+ pdx-new-3:+ pdx-new-4: function update() {+ pdx-new-5: const conn = await getConnection();+ pdx-new-6: const res = await execUpdate(conn);+ pdx-new-7: }+ pdx-new-8: }++ Then the '// ... existing code ...' reference must include ALL code from the *original file* inside the 'MyClass' structure. The 'originalStart' must be one line *after* the 'structureOpens' line and the 'originalEnd' must be one line *before* the 'structureCloses' line.++ Similarly, if a reference comes at the end of a structure, preceded by new or changed code, like this:++ pdx-new-1: class MyClass {+ pdx-new-2: function update() {+ pdx-new-3: const conn = await getConnection();+ pdx-new-4: const res = await execUpdate(conn);+ pdx-new-5: }+ pdx-new-6: // ... existing code ...+ pdx-new-7: }++ Then the '// ... existing code ...' reference must include ALL code from the *original file* inside the 'MyClass' structure. The 'originalStart' must be one line *after* the 'structureOpens' line and the 'originalEnd' must be one line *before* the 'structureCloses' line.++ If a structure has references at both the beginning and the end, with new or changed code in between, like this:++ pdx-new-1: class MyClass {+ pdx-new-2: // ... existing code ...+ pdx-new-3:+ pdx-new-4: function update() {+ pdx-new-5: const conn = await getConnection();+ pdx-new-6: const res = await execUpdate(conn);+ pdx-new-7: }+ pdx-new-8:+ pdx-new-9: // ... existing code ...+ pdx-new-10: }++ Then you must use your judgement to determine the location that the new code should be inserted in the final results. Based on where the new code is inserted, the first "pdx-new-2: // ... existing code ..." reference must include ALL code from the *original file* inside the 'MyClass' structure that should come *before* the new code. The 'originalStart' of the first reference must be one line *after* the 'structureOpens' line.++ The last "pdx-new-9: // ... existing code ..." reference must include ALL code from the *original file* inside the 'MyClass' structure that should come *after* the new code. The 'originalEnd' of the last reference must be one line *before* the 'structureCloses' line.++ In cases like this with multiple references within the same structure, you MUST NOT duplicate code in any of the references. Taken together, the references must cover the entire 'MyClass' structure with no code from the *original file* repeated or left out.- The the reference ONLY refers to the code within the 'MyClass' class. If there is additional code before or after the 'MyClass' class, it must not be included. The same applies to other code structures, like functions, loops, conditionals, etc.+ If there are commented out lines that still logically belong to a section that is referenced, you MUST include those lines in the reference.Do not include any additional text in your final output. Only output the references.`@@ -209,6 +279,20 @@ var UpdatedListReplacementsFn = openai.FunctionDefinition{"description": {Type: jsonschema.String,},+ "structure": {+ Type: jsonschema.Object,+ Properties: map[string]jsonschema.Definition{+ "structure": {+ Type: jsonschema.String,+ },+ "structureOpens": {+ Type: jsonschema.String,+ },+ "structureCloses": {+ Type: jsonschema.String,+ },+ },+ },"reasoning": {Type: jsonschema.String,},@@ -227,6 +311,7 @@ var UpdatedListReplacementsFn = openai.FunctionDefinition{},Required: []string{"description",+ "structure","reasoning","sectionStartLine","sectionEndLine",@@ -259,10 +344,39 @@ var UpdatedListReplacementsFn = openai.FunctionDefinition{Type: jsonschema.String,},"structureReasoning": {- Type: jsonschema.String,- },- "closingSyntaxReasoning": {- Type: jsonschema.String,+ Type: jsonschema.Object,+ Properties: map[string]jsonschema.Definition{+ "old": {+ Type: jsonschema.Object,+ Properties: map[string]jsonschema.Definition{+ "structure": {+ Type: jsonschema.String,+ },+ "structureOpens": {+ Type: jsonschema.String,+ },+ "structureCloses": {+ Type: jsonschema.String,+ },+ },+ Required: []string{"structure", "structureOpens", "structureCloses"},+ },+ "new": {+ Type: jsonschema.Object,+ Properties: map[string]jsonschema.Definition{+ "structure": {+ Type: jsonschema.String,+ },+ "structureOpens": {+ Type: jsonschema.String,+ },+ "structureCloses": {+ Type: jsonschema.String,+ },+ },+ Required: []string{"structure", "structureOpens", "structureCloses"},+ },+ },},"orderReasoning": {Type: jsonschema.String,@@ -324,7 +438,6 @@ var UpdatedListReplacementsFn = openai.FunctionDefinition{"summary","newReasoning","structureReasoning",- "closingSyntaxReasoning","orderReasoning","hasChange","insertBefore",@@ -338,3 +451,276 @@ var UpdatedListReplacementsFn = openai.FunctionDefinition{Required: []string{"originalSections", "entireFileReasoning", "entireFile", "problems", "changes"},},}++func AddImplicitReferencesPrompt(filePath, preBuildState, changesFile, changesDesc string) string {+ preBuildStateWithLineNums := shared.AddLineNums(preBuildState)++ s := ImplicitReferencesPrompt + "\n\n" + getPreBuildStatePrompt(filePath, preBuildStateWithLineNums) + "\n\n"++ s += fmt.Sprintf("Proposed updates:\n%s\n```\n%s\n```", changesDesc, changesFile)++ return s+}++var ImplicitReferencesPrompt = `+You are an AI that analyzes an *original file* and *proposed updates* to that file and then rewrites the *proposed updates* to fit this general format:++<ProposedUpdatesWithReferences>+// ... existing code ...++[code that is being changed]++// ... existing code ...++[code that is being added]++// ... existing code ...+</ProposedUpdatesWithReferences>++There will not *always* be a need for an "... existing code ..." comment before or after the code that is being changed or added. Only add it if there is a clear semantic reason to do so.++The *proposed updates* will often already include comments similar to "... existing code ...". If so, leave these in place and do not duplicate them. Only add the "... existing code ..." comment if there is a clear semantic reason to do so that is not already accomplished by existing "... existing code ..." (or similar) comments in the *proposed updates*.++In other words, sometimes the *proposed updates* will already have followed this format correctly. In that case, simply repeat the *proposed updates* verbatim inside the <ProposedUpdatesWithReferences> element.++Other times, there will be missing "... existing code ..." comments that you need to add. In that case, add them as necessary inside the <ProposedUpdatesWithReferences> element.++Inside the <ProposedUpdatesWithReferences> element, include nothing but the code for the *proposed updates* with the addition of any "... existing code ..." comments that you are adding. Don't include any other text. Don't include triple backticks or any other formatting.+`++// var ImplicitReferencesPrompt = `+// You are an AI that analyzes an *original file* and *proposed updates* to that file and then:++// *Sections*: Divides the *original file* into sections based on functionality, logic, code structure, and general organization.+// *Section Reasoning*: Evaluates each section to determine which sections should be *changed* and which sections should be *preserved* as is.+// *Implicit References*: Rewrites the *proposed updates* to add *reference comments* for any sections from the *original file* that should be *preserved* in the final output if there is not already a *reference comment* for that section in the *proposed updates*.++// Now I'll provide more detail and examples for each step.++// *Sections*: Divides the *original file* into sections based on functionality, logic, code structure, and general organization.++// You must list every section that exists in the *original file*. When large sections of the *original file* are not changing, combine them into a single section. Only include sections from the *original file*. Do NOT include sections from the *proposed updates*.++// Don't make the sections overly small and granular unless there is a clear semantic reason to do so. For example, if there are many small functions in a file, don't create a section for each section. Sections should be larger than that and instead reflect the general structure of a file, rather than being a long list of every top-level code structure.++// For each section, give it a name and a brief description of what it does. At this point, don't yet assess whether the section should be *changed* or *preserved*, just focus on describing the section as it relates to the rest of the *original file*.++// Example:++// ---++// Sections:++// 1 - Import statements+// 2 - initialize() function+// 3 - main() function++// ---++// *Section Reasoning*: Evaluates each section to determine which sections should be *changed* and which sections should be *preserved*.++// For each section listed in 1, list it again by name and evaluate whether it should be *changed* or *preserved* based on the *proposed updates*. Give your reasoning: a brief evaluation of how this section relates to the *proposed updates*, and whether all or any part of it will be changed, removed, or preserved as is. If only part of the section should be changed, explain which part(s) will change and which will remain the same.++// Anytime there is a partial change to a section, it is CRITICAL that you explain BOTH which parts of the section should be *changed* and which parts will be *preserved*. Be very specific and precise.++// At the end of your reasoning, output 'shouldChange' followed by a boolean value (true or false).++// If 'shouldChange' is true, add a 'changeDescription' attribute that describes which parts of the section will be changed and which will remain the same. Set a 'preservePart' attribute under the 'changeDescription'. If part of the section will remain the same, set 'preservePart' attribute to 'true', otherwise 'false'. If 'preservePart' is true, set a 'referenceCovers' attribute that whether the code that is being preserved is covered by a reference comment in the *proposed updates*. Describe in words which *reference comment* covers the preserved code. Otherwise, set 'referenceCovers' to 'false'.++// After the 'shouldChange', add a 'shouldRemove' followed by a boolean value (true or false).++// Then add a 'shouldPreserve' followed by a boolean value (true or false).++// 'shouldChange' should be true if any part of the section should be changed.++// 'shouldRemove' should be true if the entire section should be removed.++// 'shouldPreserve' should be true if the entire section should be preserved as is.++// If 'shouldPreserve' is true, set a 'referenceCovers' attribute that whether the code that is being preserved is covered by a reference comment in the *proposed updates*. Describe in words which *reference comment* covers the preserved code. Otherwise, set 'referenceCovers' to 'false'.++// Only one of "shouldChange", "shouldRemove", or "shouldPreserve" can be true. The other two must be false. One of these three must be true.++// A section is 'covered' by a *reference comment* if *any* existing *reference comment* in the *proposed updates* references that code. If the code that is being preserved is at the beginning of a code structure in the *original file* and there's a *reference comment* like "// ... existing code ..." at the *beginning* of the code structure in the *proposed updates*, then the section is covered by that reference comment. Example:++// [ORIGINAL FILE]++// function update(name string, id string) {+// const client = getClient();+// const tx = await client.startTransaction();+// const logStatement = prepLogStatement('some-app');+// await sendLogStatement(logStatement);+// await doUpdate(name, id);+// }++// [/END ORIGINAL FILE]++// [PROPOSED UPDATES]++// function update(name string, id string) {+// // ... existing code ...++// if (canUpdate(name, id)) {+// await doUpdate(name, id);+// }+// }++// [/END PROPOSED UPDATES]++// In the case above, all the code before 'await doUpdate();' is covered by the reference comment "// ... existing code ..." at the start of the 'update' function in the *proposed updates*.++// Similarly, if the code that is being preserved is at the end of a code structure in the *original file* and there's a *reference comment* like "// ... existing code ..." at the *end* of the code structure in the *proposed updates*, then the section is covered by that reference comment. Example:++// [ORIGINAL FILE]++// function update(name string, id string) {+// await doUpdate(name, id);++// await client.commit();+// await sendAnalyticsEvent('update-user', { name, id });+// }++// [/END ORIGINAL FILE]++// [PROPOSED UPDATES]++// function update(name string, id string) {+// await doUpdate(name, id);++// // ... existing code ...+// }++// [/END PROPOSED UPDATES]++// In the case above, all the code after 'await doUpdate(name, id);' is covered by the reference comment "// ... existing code ..." at the end of the 'update' function in the *proposed updates*.++// Similarly, if the code that is being preserved is in the middle of a code structure in the *original file* between two blocks of code that are being updated by the *proposed updates*, and there's a *reference comment* like "// ... existing code ..." *between* the two blocks of code in the *proposed updates*, then the section is covered by that reference comment. Example:++// [ORIGINAL FILE]++// function update(name string, id string) {+// const client = getClient();+// const logStatement = prepLogStatement('some-app');+// await sendLogStatement(logStatement);+// await doUpdate(name, id);+// await sendAnalyticsEvent('update-user', { name, id });+// await client.commit();+// }++// [/END ORIGINAL FILE]++// [PROPOSED UPDATES]++// function update(name string, id string) {+// const asyncClient = getAsyncClient();++// // ... existing code ...++// if (canUpdate(name, id)) {+// await doUpdate(name, id);+// }++// // ... existing code ...++// await asyncClient.commit();+// }++// [/END PROPOSED UPDATES]++// In the case above, the lines 'const logStatement = prepLogStatement('some-app');' and 'await sendLogStatement(logStatement);' that are being preserved are covered by the reference comment "// ... existing code ..." *between* the 'const asyncClient = getAsyncClient();' line and the 'if (canUpdate(name, id)) {' line in the *proposed updates*. The line 'await sendAnalyticsEvent('update-user', { name, id });' is covered by the reference comment "// ... existing code ..." *between* the '}' line (after the 'await doUpdate(name, id);' line) and the 'await asyncClient.commit();' line in the *proposed updates*.++// ---++// Section Reasoning:++// 1 - Import statements+// Reasoning: The import statements are not changing. They should be included in the final output as is.+// shouldChange: false+// shouldRemove: false+// shouldPreserve: true+// referenceCovers: false++// 2 - initialize() function+// Reasoning: New code for logging will be added at the beginning of the function. The rest of the function will remain the same and should be included in the final output as is.+// shouldChange: true+// changeDescription: New code for logging will be added at the beginning of the function. The rest of the function will remain the same.+// preservePart: true+// referenceCovers: The existing code in the initialize() function is already covered by the reference comment "// ... existing code ..." at the start of the initialize() function in the *proposed updates*.+// shouldRemove: false+// shouldPreserve: false++// 3 - main() function+// Reasoning: Between the last line of code that connects to the database (pdx-18) and the first of code that calls the 'update()' function (pdx-5), new code will be added for a permission check. The rest of the function will remain the same and should be included in the final output as is.+// shouldChange: true+// changeDescription: New code for a permission check will be added at the beginning of the function. The rest of the function will remain the same.+// preservePart: true+// referenceCovers: The existing code in the main() function is already covered by the reference comment "// ... existing update code ..." at the start of the main() function in the *proposed updates*.+// shouldRemove: false+// shouldPreserve: false++// ---++// *Implicit References*: Rewrites the *proposed updates* to add *reference comments* for any sections from the *original file* that should be *preserved* in the final output if there is not already a *reference comment* for that section in the *proposed updates*.++// ` + ExampleReferences + `++// In section 3, first list any sections or parts of sections from the *original file* that should be *preserved* in the final output but are not included in the *proposed updates* and do not already have a reference comment referencing them in the *proposed updates*.++// If there are no such sections, state that explicitly and stop there.++// Next, if there are any sections from the *original file* that should be *preserved* in the final output but do not already have a reference comment referencing them in the *proposed updates*, output a <ProposedUpdatesWithReferences> element++// The content of the <ProposedUpdatesWithReferences> element must be the *proposed updates* repeated *VERBATIM* with the addition of any *reference comments* for sections that should be *preserved* in the final output *but do not already have a reference comment referencing them* in the *proposed updates*.++// Inside the <ProposedUpdatesWithReferences> element, include nothing but the code for the *proposed updates* with the addition of any *reference* comments that you are adding. Don't include any other text. Don't include triple backticks or any other formatting.++// DO NOT add new reference comments if all the code from the *original file* that isn't changing is already present or already referenced by reference comments in the *proposed updates*. In that case, do not output a <ProposedUpdatesWithReferences> element.++// Every block of code from the *original file* that is *preserved* in the final output must either be reproduced in code in the *proposed updates* or referenced by a *single* *reference comment* in the *proposed updates*.++// You ABSOLUTELY MUST NOT add additional *reference comments* for code that is *already* covered by a reference comment in the *proposed updates*. There MUST NEVER be two or more consecutive reference comments without any actual code in between. If you add multiple consecutive reference comments like this:++// // ... existing code to start transaction ...++// // ... existing code ...++// Then you have failed at this step. Because if there is ALREADY a *reference comment* (like "// ... existing code to start transaction ..." in the *proposed updates*) for the code that is being preserved, you MUST NOT add another reference comment for it. The "// ... existing code ..." reference ALREADY covers that section of code that is being preserved, so no additional reference comment is needed. Again you MUST NOT output multiple consecutive reference comments without any actual code in between them.++// You MUST ALWAYS use a single-line comment and the exact text "... existing code ..." to reference code that is *already included* in the *proposed updates*. For example, if the programming language is JavaScript, you MUST use "// ... existing code ...". In python, you MUST use "# ... existing code ...". And so on for other languages. Do not add any other text to the reference comment. You MUST NOT under *any circumstances* use any other form of *reference comment*. ALWAYS use the exact text "... existing code ..." in a single-line comment that is appropriate for the programming language.++// You ABSOLUTELY MUST NOT add *reference comments* for code that is *already included* in the *proposed updates*.++// Example:++// ---++// Implicit References:++// The imports section is not changing and should be included in the final output as is. There is no reference comment mentioning the existing imports section in the *proposed updates*. Therefore, I will add a new reference comment for the existing imports section in the *proposed updates*.++// The other sections that aren't changing are already referenced by reference comments in the *proposed updates*.++// <ProposedUpdatesWithReferences>+// // ... existing imports ...+// import { createLogger } from './logger';++// function initialize() {+// const logger = createLogger('some-app');++// // ... existing code ...+// }++// function main() {+// // ... existing code ...++// if (canUpdate()) {+// // ... existing update code ...+// }++// // ... existing code to commit db transaction...+// }+// </ProposedUpdatesWithReferences>++// ---++// `diff --git a/app/server/types/model.go b/app/server/types/model.goindex f8d83779..28741ad1 100644--- a/app/server/types/model.go+++ b/app/server/types/model.go@@ -25,12 +25,13 @@ type UpdatedChangesWithLineNums struct {EntireFile bool `json:"entireFile"`Problems string `json:"problems"`OriginalSections []struct {- Description string `json:"description"`- Reasoning string `json:"reasoning"`- SectionStartLine string `json:"sectionStartLine"`- SectionEndLine string `json:"sectionEndLine"`- ShouldChange bool `json:"shouldChange"`- ShouldRemove bool `json:"shouldRemove"`+ Description string `json:"description"`+ Reasoning string `json:"reasoning"`+ SectionStartLine string `json:"sectionStartLine"`+ SectionEndLine string `json:"sectionEndLine"`+ ShouldChange bool `json:"shouldChange"`+ ShouldRemove bool `json:"shouldRemove"`+ Structure shared.Structure `json:"structure"`} `json:"originalSections"`Changes []*shared.StreamedChangeWithLineNumsUpdated `json:"changes"`}diff --git a/app/shared/streamed_change.go b/app/shared/streamed_change.goindex 99e43d91..f7e4907c 100644--- a/app/shared/streamed_change.go+++ b/app/shared/streamed_change.go@@ -32,8 +32,7 @@ type StreamedChangeWithLineNumsUpdated struct {Section string `json:"section"`NewReasoning string `json:"newReasoning"`OrderReasoning string `json:"orderReasoning"`- StructureReasoning string `json:"structureReasoning"`- ClosingSyntaxReasoning string `json:"closingSyntaxReasoning"`+ StructureReasoning StructureReasoning `json:"structureReasoning"`InsertBefore *InsertBefore `json:"insertBefore"`InsertAfter *InsertAfter `json:"insertAfter"`HasChange bool `json:"hasChange"`@@ -45,6 +44,17 @@ type StreamedChangeWithLineNumsUpdated struct {New StreamedChangeSection `json:"new"`}+type StructureReasoning struct {+ Old Structure `json:"old"`+ New Structure `json:"new"`+}++type Structure struct {+ Structure string `json:"structure"`+ StructureOpens string `json:"structureOpens"`+ StructureCloses string `json:"structureCloses"`+}+type InsertBefore struct {ShouldInsertBefore bool `json:"shouldInsertBefore"`Line string `json:"line"`