| 1 | package consult |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | "fmt" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "reflect" |
| 10 | "strings" |
| 11 | "testing" |
| 12 | "time" |
| 13 | |
| 14 | "the-valley/flow/internal/backend" |
| 15 | ) |
| 16 | |
| 17 | func TestThreadStore(t *testing.T) { |
| 18 | store := NewStore(t.TempDir()) |
| 19 | now := time.Now().UTC() |
| 20 | want := &Thread{Backend: backend.Codex, Model: "model", BackendSessionID: "id", Dir: "/repo", Role: "critic", CreatedAt: now, LastUsed: now, Turns: 2} |
| 21 | unlock, err := store.Lock("design") |
| 22 | if err != nil { |
| 23 | t.Fatal(err) |
| 24 | } |
| 25 | defer unlock() |
| 26 | if _, err := store.Lock("design"); err == nil { |
| 27 | t.Fatal("concurrent turn accepted") |
| 28 | } |
| 29 | if err := store.Save("design", want); err != nil { |
| 30 | t.Fatal(err) |
| 31 | } |
| 32 | got, err := store.Load("design") |
| 33 | if err != nil || !reflect.DeepEqual(got, want) { |
| 34 | t.Fatalf("round trip: %+v, %v", got, err) |
| 35 | } |
| 36 | turn, err := store.BeginTurn("design", want, "question", "abc123") |
| 37 | if err != nil { |
| 38 | t.Fatal(err) |
| 39 | } |
| 40 | pending, err := os.ReadFile(filepath.Join(store.Dir, "design.log")) |
| 41 | if err != nil { |
| 42 | t.Fatal(err) |
| 43 | } |
| 44 | var record Turn |
| 45 | if err := json.Unmarshal(pending, &record); err != nil { |
| 46 | t.Fatal(err) |
| 47 | } |
| 48 | if record.Status != "pending" || record.Prompt != "question" || record.Answer != "" || record.RepoRevision != "abc123" || record.ResumeID != "id" { |
| 49 | t.Fatalf("pending: %+v", record) |
| 50 | } |
| 51 | if err := store.FinishTurn("design", turn, Result{Answer: "answer", SessionID: "id", SessionIDSource: "stderr"}, nil); err != nil { |
| 52 | t.Fatal(err) |
| 53 | } |
| 54 | completed, _ := os.ReadFile(filepath.Join(store.Dir, "design.log")) |
| 55 | if err := json.Unmarshal(completed, &record); err != nil { |
| 56 | t.Fatal(err) |
| 57 | } |
| 58 | if record.Status != "ok" || record.SessionIDSource != "stderr" { |
| 59 | t.Fatalf("completed: %+v", record) |
| 60 | } |
| 61 | failed, err := store.BeginTurn("design", want, "failed question", "") |
| 62 | if err != nil { |
| 63 | t.Fatal(err) |
| 64 | } |
| 65 | if err := store.FinishTurn("design", failed, Result{Answer: "partial"}, fmt.Errorf("backend failed")); err != nil { |
| 66 | t.Fatal(err) |
| 67 | } |
| 68 | interrupted, err := store.BeginTurn("design", want, "interrupted question", "") |
| 69 | if err != nil { |
| 70 | t.Fatal(err) |
| 71 | } |
| 72 | next, err := store.BeginTurn("design", want, "next question", "") |
| 73 | if err != nil || next.Number != interrupted.Number+1 || interrupted.Number != failed.Number+1 { |
| 74 | t.Fatalf("attempt numbers: %+v, %v", next, err) |
| 75 | } |
| 76 | if err := store.FinishTurn("design", interrupted, Result{}, nil); err == nil { |
| 77 | t.Fatal("stale completion overwrote newer turn") |
| 78 | } |
| 79 | entries, err := store.List() |
| 80 | if err != nil || len(entries) != 1 { |
| 81 | t.Fatalf("list: %v, %v", entries, err) |
| 82 | } |
| 83 | data, err := os.ReadFile(filepath.Join(store.Dir, "design.log")) |
| 84 | if err != nil || !strings.Contains(string(data), "question") || !strings.Contains(string(data), "answer") { |
| 85 | t.Fatalf("log: %s, %v", data, err) |
| 86 | } |
| 87 | var statuses []string |
| 88 | for _, line := range bytes.Split(bytes.TrimSpace(data), []byte("\n")) { |
| 89 | var persisted Turn |
| 90 | if err := json.Unmarshal(line, &persisted); err != nil { |
| 91 | t.Fatal(err) |
| 92 | } |
| 93 | statuses = append(statuses, persisted.Status) |
| 94 | } |
| 95 | if !reflect.DeepEqual(statuses, []string{"ok", "error: backend failed", "pending", "pending"}) { |
| 96 | t.Fatalf("durable statuses: %v", statuses) |
| 97 | } |
| 98 | if err := store.Save("../escape", want); err == nil { |
| 99 | t.Fatal("accepted path traversal") |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | func TestInlineFiles(t *testing.T) { |
| 104 | dir := t.TempDir() |
| 105 | a, b := filepath.Join(dir, "plan"), filepath.Join(dir, "diff") |
| 106 | if err := os.WriteFile(a, []byte("plan contents\n"), 0600); err != nil { |
| 107 | t.Fatal(err) |
| 108 | } |
| 109 | if err := os.WriteFile(b, []byte("diff contents"), 0600); err != nil { |
| 110 | t.Fatal(err) |
| 111 | } |
| 112 | files, err := ReadFiles([]string{a, b}) |
| 113 | if err != nil { |
| 114 | t.Fatal(err) |
| 115 | } |
| 116 | for _, kind := range []backend.Kind{backend.Claude, backend.Codex} { |
| 117 | if got := InlineFiles(kind, "question", files); got != "question\n\n### "+a+"\nplan contents\n\n\n### "+b+"\ndiff contents" { |
| 118 | t.Fatalf("%s inline: %q", kind, got) |
| 119 | } |
| 120 | } |
| 121 | // agy is told each file is there whole, and its END line stands alone |
| 122 | // even after a file with no final newline. |
| 123 | got := InlineFiles(backend.Agy, "question", files) |
| 124 | for _, want := range []string{ |
| 125 | "question\n\n2 files are attached below, each in full", |
| 126 | "\n\n===== BEGIN ATTACHED FILE 1 of 2: " + a + " =====\nplan contents\n===== END ATTACHED FILE 1 of 2: " + a + " =====", |
| 127 | "\n\n===== BEGIN ATTACHED FILE 2 of 2: " + b + " =====\ndiff contents\n===== END ATTACHED FILE 2 of 2: " + b + " =====", |
| 128 | } { |
| 129 | if !strings.Contains(got, want) { |
| 130 | t.Fatalf("agy inline lacks %q:\n%s", want, got) |
| 131 | } |
| 132 | } |
| 133 | if got := InlineFiles(backend.Agy, "question", nil); got != "question" { |
| 134 | t.Fatalf("agy without files: %q", got) |
| 135 | } |
| 136 | if err := os.WriteFile(a, make([]byte, MaxFileBytes), 0600); err != nil { |
| 137 | t.Fatal(err) |
| 138 | } |
| 139 | if _, err := ReadFiles([]string{a}); err != nil { |
| 140 | t.Fatal(err) |
| 141 | } |
| 142 | if _, err := ReadFiles([]string{a, b}); err == nil || !strings.Contains(err.Error(), "200KB total: "+b) { |
| 143 | t.Fatalf("total cap: %v", err) |
| 144 | } |
| 145 | if _, err := ReadFiles([]string{filepath.Join(dir, "absent")}); err == nil { |
| 146 | t.Fatal("missing file accepted") |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | func TestInstalled(t *testing.T) { |
| 151 | old := LookupBinary |
| 152 | t.Cleanup(func() { LookupBinary = old }) |
| 153 | LookupBinary = func(name string) (string, error) { |
| 154 | if name == "agy" { |
| 155 | return "", os.ErrNotExist |
| 156 | } |
| 157 | return name, nil |
| 158 | } |
| 159 | got, err := Installed([]string{"agy", "claude", "codex", "claude"}, "codex") |
| 160 | if err != nil || !reflect.DeepEqual(got, []backend.Kind{backend.Claude}) { |
| 161 | t.Fatalf("selection: %v, %v", got, err) |
| 162 | } |
| 163 | if _, err := Installed([]string{"typo"}, ""); err == nil { |
| 164 | t.Fatal("invalid config accepted") |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | func TestSessionIDPaths(t *testing.T) { |
| 169 | for _, tt := range []struct { |
| 170 | name string |
| 171 | kind backend.Kind |
| 172 | stdout, stderr, diagnostic, source string |
| 173 | }{ |
| 174 | {"codex header", backend.Codex, "answer", "session id: abc123\n", "", "stderr"}, |
| 175 | {"stdout JSON", backend.Codex, `{"thread_id":"abc123"}`, "", "", "stdout-json"}, |
| 176 | {"text fallback", backend.Codex, "session id: abc123\n", "", "", "text"}, |
| 177 | {"agy diagnostic", backend.Agy, "answer", "", "Sending user message to conversation abc123 (items=1)", "diagnostic-log"}, |
| 178 | {"agy JSON fallback", backend.Agy, `{"conversation_id":"abc123"}`, "", "", "stdout-json"}, |
| 179 | } { |
| 180 | t.Run(tt.name, func(t *testing.T) { |
| 181 | id, source, err := extractSessionID(tt.kind, "", "", tt.stdout, tt.stderr, tt.diagnostic) |
| 182 | if err != nil || id != "abc123" || source != tt.source { |
| 183 | t.Fatalf("%q %q %v", id, source, err) |
| 184 | } |
| 185 | }) |
| 186 | } |
| 187 | for _, kind := range []backend.Kind{backend.Codex, backend.Agy} { |
| 188 | _, _, err := extractSessionID(kind, "", "", "answer", "diagnostics", "unrecognized") |
| 189 | if err == nil { |
| 190 | t.Fatal("missing ID accepted") |
| 191 | } |
| 192 | for _, path := range []string{string(kind), "stderr", "stdout-json", "text"} { |
| 193 | if !strings.Contains(err.Error(), path) { |
| 194 | t.Fatalf("missing path %s: %v", path, err) |
| 195 | } |
| 196 | } |
| 197 | if kind == backend.Agy && !strings.Contains(err.Error(), "diagnostic-log") { |
| 198 | t.Fatal(err) |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | func TestResumeIDRejectsAnswerText(t *testing.T) { |
| 204 | for _, output := range []string{`{"session_id":"unrelated"}`, "session id: unrelated\n"} { |
| 205 | id, source, err := extractSessionID(backend.Claude, "known", "", output, "", "") |
| 206 | if err != nil || id != "known" || source != "resume" { |
| 207 | t.Fatalf("resume: %s %s %v", id, source, err) |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | func TestLegacyTranscriptBoundary(t *testing.T) { |
| 213 | store := NewStore(t.TempDir()) |
| 214 | unlock, err := store.Lock("legacy") |
| 215 | if err != nil { |
| 216 | t.Fatal(err) |
| 217 | } |
| 218 | defer unlock() |
| 219 | path := filepath.Join(store.Dir, "legacy.log") |
| 220 | if err := os.WriteFile(path, []byte("legacy without newline"), 0600); err != nil { |
| 221 | t.Fatal(err) |
| 222 | } |
| 223 | thread := &Thread{Backend: backend.Codex} |
| 224 | turn, err := store.BeginTurn("legacy", thread, "question", "") |
| 225 | if err != nil { |
| 226 | t.Fatal(err) |
| 227 | } |
| 228 | if err := store.FinishTurn("legacy", turn, Result{}, fmt.Errorf("failed")); err != nil { |
| 229 | t.Fatal(err) |
| 230 | } |
| 231 | next, err := store.BeginTurn("legacy", thread, "retry", "") |
| 232 | if err != nil || next.Number != 2 { |
| 233 | t.Fatalf("next: %+v, %v", next, err) |
| 234 | } |
| 235 | data, err := os.ReadFile(path) |
| 236 | if err != nil { |
| 237 | t.Fatal(err) |
| 238 | } |
| 239 | lines := bytes.Split(bytes.TrimSpace(data), []byte("\n")) |
| 240 | if len(lines) != 3 || string(lines[0]) != "legacy without newline" { |
| 241 | t.Fatalf("legacy transcript: %s", data) |
| 242 | } |
| 243 | for _, line := range lines[1:] { |
| 244 | var saved Turn |
| 245 | if err := json.Unmarshal(line, &saved); err != nil { |
| 246 | t.Fatal(err) |
| 247 | } |
| 248 | } |
| 249 | } |