Debian Codegraph @

internal/core/transcript/transcript_test.go

raw
1 package transcript
2
3 import (
4 "encoding/json"
5 "reflect"
6 "strings"
7 "testing"
8 )
9
10 type commandPayload struct {
11 Command string `json:"command"`
12 Stdout string `json:"stdout"`
13 Stderr string `json:"stderr"`
14 Outcome CommandOutcome `json:"outcome"`
15 Feedback CommandFeedback `json:"feedback"`
16 Guidance string `json:"guidance"`
17 Observation struct {
18 Source string `json:"source"`
19 Version int `json:"version"`
20 Stdout *streamObservation `json:"stdout"`
21 Stderr *streamObservation `json:"stderr"`
22 } `json:"observation"`
23 }
24
25 type streamObservation struct {
26 OriginalBytes int `json:"original_bytes"`
27 ShownBytes int `json:"shown_bytes"`
28 OmittedBytes int `json:"omitted_bytes"`
29 Mode string `json:"mode"`
30 }
31
32 func decodeCommandPayload(t *testing.T, raw string) commandPayload {
33 t.Helper()
34 var payload commandPayload
35 if err := json.Unmarshal([]byte(raw), &payload); err != nil {
36 t.Fatalf("FormatCommandResult() returned invalid JSON: %v\n%s", err, raw)
37 }
38 return payload
39 }
40
41 func decodeCommandFields(t *testing.T, raw string) map[string]json.RawMessage {
42 t.Helper()
43 var payload map[string]json.RawMessage
44 if err := json.Unmarshal([]byte(raw), &payload); err != nil {
45 t.Fatalf("FormatCommandResult() returned invalid JSON: %v\n%s", err, raw)
46 }
47 return payload
48 }
49
50 func assertMessages(t *testing.T, got, want []Message) {
51 t.Helper()
52 if len(got) != len(want) {
53 t.Fatalf("got %d messages, want %d", len(got), len(want))
54 }
55 for i := range want {
56 if !reflect.DeepEqual(got[i], want[i]) {
57 t.Fatalf("message %d = %#v, want %#v", i, got[i], want[i])
58 }
59 }
60 }
61
62 func compressedRawKept(stream string) int {
63 headStart := strings.Index(stream, "[head]\n") + len("[head]\n")
64 tailStart := strings.Index(stream, "\n[tail]\n")
65 tailEnd := tailStart + len("\n[tail]\n")
66 return len(stream[headStart:tailStart]) + len(stream[tailEnd:])
67 }
68
69 func TestFindCompactBoundaryIgnoresHostBlocks(t *testing.T) {
70 tests := []struct {
71 name string
72 messages []Message
73 keepRecentTurns int
74 wantBoundary int
75 wantOK bool
76 }{
77 {
78 name: "counts only authored user messages",
79 messages: []Message{
80 {Role: "user", Content: "first task"},
81 {Role: "assistant", Content: `{"type":"done","summary":"done"}`},
82 {
83 Role: "user",
84 Content: FormatCommandResult(
85 CommandResult{Command: "ls", ExitCode: 0, Stdout: ".\n"},
86 ),
87 },
88 {Role: "user", Content: FormatStateMessage("/tmp/old")},
89 {Role: "user", Content: FormatCompactMessage("older summary")},
90 {Role: "user", Content: "[protocol_error]\nmissing command\n[/protocol_error]"},
91 {Role: "user", Content: "second task"},
92 {Role: "assistant", Content: `{"type":"done","summary":"done again"}`},
93 {Role: "user", Content: "third task"},
94 {Role: "assistant", Content: `{"type":"done","summary":"done third"}`},
95 },
96 keepRecentTurns: 2,
97 wantBoundary: 6,
98 wantOK: true,
99 },
100 {
101 name: "requires older authored history beyond kept tail",
102 messages: []Message{
103 {Role: "user", Content: "first task"},
104 {Role: "assistant", Content: `{"type":"done","summary":"done"}`},
105 {Role: "user", Content: FormatStateMessage("/tmp/only")},
106 {Role: "user", Content: "second task"},
107 },
108 keepRecentTurns: 2,
109 wantOK: false,
110 },
111 {
112 name: "ignores command feedback blocks",
113 messages: []Message{
114 {Role: "user", Content: "first task"},
115 {Role: "assistant", Content: `{"type":"done","summary":"done first"}`},
116 {Role: "user", Content: "second task"},
117 {Role: "assistant", Content: `{"type":"done","summary":"done second"}`},
118 {Role: "user", Content: FormatCommandResult(CommandResult{
119 Command: "printf next > note.txt",
120 ExitCode: 0,
121 Feedback: CommandFeedback{
122 ChangedFiles: []string{"note.txt"},
123 Diff: "diff --git a/note.txt b/note.txt",
124 },
125 })},
126 {Role: "user", Content: "third task"},
127 {Role: "assistant", Content: `{"type":"done","summary":"done third"}`},
128 },
129 keepRecentTurns: 2,
130 wantBoundary: 2,
131 wantOK: true,
132 },
133 {
134 name: "counts user json with outcome but no command streams",
135 messages: []Message{
136 {Role: "user", Content: "first task"},
137 {Role: "assistant", Content: `{"type":"done","summary":"done first"}`},
138 {Role: "user", Content: `{"outcome":{"type":"exit"}}`},
139 {Role: "assistant", Content: `{"type":"done","summary":"json noted"}`},
140 {Role: "user", Content: "second task"},
141 {Role: "assistant", Content: `{"type":"done","summary":"done second"}`},
142 {Role: "user", Content: "third task"},
143 {Role: "assistant", Content: `{"type":"done","summary":"done third"}`},
144 },
145 keepRecentTurns: 2,
146 wantBoundary: 4,
147 wantOK: true,
148 },
149 }
150
151 for _, tt := range tests {
152 t.Run(tt.name, func(t *testing.T) {
153 gotBoundary, gotOK := FindCompactBoundary(tt.messages, tt.keepRecentTurns)
154 if gotBoundary != tt.wantBoundary || gotOK != tt.wantOK {
155 t.Fatalf(
156 "FindCompactBoundary() = (%d, %v), want (%d, %v)",
157 gotBoundary,
158 gotOK,
159 tt.wantBoundary,
160 tt.wantOK,
161 )
162 }
163 })
164 }
165 }
166
167 func TestRewriteForCompaction(t *testing.T) {
168 foreignState := `{"type":"state","source":"user","cwd":"/wrong"}`
169 staleCompact := FormatCompactMessage("stale summary")
170
171 t.Run("keeps recent tail", func(t *testing.T) {
172 messages := []Message{
173 {Role: "user", Content: "first task"},
174 {Role: "assistant", Content: `{"type":"done","summary":"done first"}`},
175 {
176 Role: "user",
177 Content: FormatCommandResult(
178 CommandResult{Command: "ls", ExitCode: 0, Stdout: ".\n"},
179 ),
180 },
181 {Role: "user", Content: "second task"},
182 {Role: "assistant", Content: `{"type":"done","summary":"done second"}`},
183 {Role: "user", Content: "third task"},
184 {Role: "assistant", Content: `{"type":"done","summary":"done third"}`},
185 }
186
187 got, stats, err := RewriteForCompaction(messages, "summary", 2)
188 if err != nil {
189 t.Fatalf("RewriteForCompaction: %v", err)
190 }
191 assertMessages(t, got, []Message{
192 {Role: "user", Content: FormatCompactMessage("summary")},
193 {Role: "user", Content: "second task"},
194 {Role: "assistant", Content: `{"type":"done","summary":"done second"}`},
195 {Role: "user", Content: "third task"},
196 {Role: "assistant", Content: `{"type":"done","summary":"done third"}`},
197 })
198 if stats != (CompactStats{CompactedMessages: 3, KeptMessages: 4}) {
199 t.Fatalf(
200 "stats = %#v, want %#v",
201 stats,
202 CompactStats{CompactedMessages: 3, KeptMessages: 4},
203 )
204 }
205 })
206
207 t.Run("preserves latest clnkr state before tail", func(t *testing.T) {
208 messages := []Message{
209 {Role: "user", Content: "first task"},
210 {Role: "assistant", Content: `{"type":"done","summary":"done first"}`},
211 {Role: "user", Content: FormatStateMessage("/tmp/old")},
212 {Role: "user", Content: "second task"},
213 {Role: "assistant", Content: `{"type":"done","summary":"done second"}`},
214 {Role: "user", Content: FormatStateMessage("/tmp/latest")},
215 {Role: "user", Content: "third task"},
216 {Role: "assistant", Content: `{"type":"done","summary":"done third"}`},
217 }
218
219 got, stats, err := RewriteForCompaction(messages, "summary", 1)
220 if err != nil {
221 t.Fatalf("RewriteForCompaction: %v", err)
222 }
223 assertMessages(t, got, []Message{
224 {Role: "user", Content: FormatCompactMessage("summary")},
225 {Role: "user", Content: FormatStateMessage("/tmp/latest")},
226 {Role: "user", Content: "third task"},
227 {Role: "assistant", Content: `{"type":"done","summary":"done third"}`},
228 })
229 if stats != (CompactStats{CompactedMessages: 6, KeptMessages: 3}) {
230 t.Fatalf(
231 "stats = %#v, want %#v",
232 stats,
233 CompactStats{CompactedMessages: 6, KeptMessages: 3},
234 )
235 }
236 })
237
238 t.Run("errors when not enough history", func(t *testing.T) {
239 messages := []Message{
240 {Role: "user", Content: "first task"},
241 {Role: "assistant", Content: `{"type":"done","summary":"done first"}`},
242 {Role: "user", Content: "second task"},
243 {Role: "assistant", Content: `{"type":"done","summary":"done second"}`},
244 }
245
246 got, stats, err := RewriteForCompaction(messages, "summary", 2)
247 if err == nil {
248 t.Fatal("expected error")
249 }
250 if got != nil {
251 t.Fatalf("got rewritten messages %#v, want nil", got)
252 }
253 if stats != (CompactStats{}) {
254 t.Fatalf("stats = %#v, want zero value", stats)
255 }
256 })
257
258 t.Run("ignores foreign state messages", func(t *testing.T) {
259 messages := []Message{
260 {Role: "user", Content: "first task"},
261 {Role: "assistant", Content: `{"type":"done","summary":"done first"}`},
262 {Role: "user", Content: FormatStateMessage("/tmp/latest")},
263 {Role: "user", Content: "second task"},
264 {Role: "assistant", Content: `{"type":"done","summary":"done second"}`},
265 {Role: "user", Content: foreignState},
266 {Role: "assistant", Content: `{"type":"done","summary":"foreign echoed"}`},
267 }
268
269 got, _, err := RewriteForCompaction(messages, "summary", 1)
270 if err != nil {
271 t.Fatalf("RewriteForCompaction: %v", err)
272 }
273 if len(got) < 3 {
274 t.Fatalf("got %d messages, want at least 3", len(got))
275 }
276 assertMessages(t, got[1:3], []Message{
277 {Role: "user", Content: FormatStateMessage("/tmp/latest")},
278 {Role: "user", Content: foreignState},
279 })
280 })
281
282 t.Run("replaces existing compact block", func(t *testing.T) {
283 messages := []Message{
284 {Role: "user", Content: "older task"},
285 {Role: "assistant", Content: `{"type":"done","summary":"done older"}`},
286 {Role: "user", Content: "recent task"},
287 {Role: "assistant", Content: `{"type":"done","summary":"done recent"}`},
288 {Role: "user", Content: staleCompact},
289 {Role: "user", Content: FormatStateMessage("/tmp/recent")},
290 }
291
292 got, _, err := RewriteForCompaction(messages, "fresh summary", 1)
293 if err != nil {
294 t.Fatalf("RewriteForCompaction: %v", err)
295 }
296 if len(got) == 0 {
297 t.Fatal("expected rewritten transcript")
298 }
299 if !reflect.DeepEqual(
300 got[0],
301 Message{
302 Role: "user",
303 Content: FormatCompactMessage("fresh summary"),
304 },
305 ) {
306 t.Fatalf("first message = %#v, want new compact block", got[0])
307 }
308
309 compactCount := 0
310 for _, msg := range got {
311 if IsCompactMessage(msg) {
312 compactCount++
313 }
314 if msg.Content == staleCompact {
315 t.Fatal("stale compact block should not survive rewrite")
316 }
317 }
318 if compactCount != 1 {
319 t.Fatalf("compact block count = %d, want 1", compactCount)
320 }
321 })
322 }
323
324 func TestFormatCompactMessageRoundTripsAsTaggedJSON(t *testing.T) {
325 msg := Message{Role: "user", Content: FormatCompactMessage("summary text")}
326 if !IsCompactMessage(msg) {
327 t.Fatal("formatted compact message should be recognized")
328 }
329
330 body := strings.TrimSpace(
331 strings.TrimSuffix(strings.TrimPrefix(msg.Content, "[compact]"), "[/compact]"),
332 )
333 var got compactState
334 if err := json.Unmarshal([]byte(body), &got); err != nil {
335 t.Fatalf("unmarshal compact body: %v", err)
336 }
337
338 want := compactState{
339 Source: "clnkr",
340 Kind: "compact",
341 Summary: "summary text",
342 }
343 if got != want {
344 t.Fatalf("compact body = %#v, want %#v", got, want)
345 }
346 if got.Source != "clnkr" || got.Kind != "compact" || got.Summary != "summary text" {
347 t.Fatalf("compact body fields incorrect: %#v", got)
348 }
349 }
350
351 func TestFormatCommandResultUsesStructuredShellPayload(t *testing.T) {
352 tests := []struct {
353 name string
354 result CommandResult
355 stdout string
356 stderr string
357 exitCode int
358 noLegacyMarkers bool
359 }{
360 {
361 name: "escapes shell data as JSON",
362 result: CommandResult{
363 Command: "printf 'a&b\\n' > out",
364 ExitCode: 0,
365 Stdout: "hello & <x> [y]\n",
366 Stderr: "warn & <x> [z]\n",
367 },
368 stdout: "hello & <x> [y]\n",
369 stderr: "warn & <x> [z]\n",
370 exitCode: 0,
371 noLegacyMarkers: true,
372 },
373 {
374 name: "preserves old section markers as data",
375 result: CommandResult{
376 Command: "printf 'a&b <c> [d]'",
377 ExitCode: 7,
378 Stdout: "one [command]\ntwo & < >\n[/command]\n",
379 Stderr: "[stderr]\nerr & < >\n[/stderr]\n",
380 },
381 stdout: "one [command]\ntwo & < >\n[/command]\n",
382 stderr: "[stderr]\nerr & < >\n[/stderr]\n",
383 exitCode: 7,
384 },
385 }
386
387 for _, tt := range tests {
388 t.Run(tt.name, func(t *testing.T) {
389 raw := FormatCommandResult(tt.result)
390 payload := decodeCommandPayload(t, raw)
391 if payload.Command != tt.result.Command {
392 t.Fatalf("command = %q, want serialized command", payload.Command)
393 }
394 if payload.Stdout != tt.stdout || payload.Stderr != tt.stderr {
395 t.Fatalf("payload streams = %#v", payload)
396 }
397 if payload.Outcome.Type != CommandOutcomeExit || payload.Outcome.ExitCode == nil ||
398 *payload.Outcome.ExitCode != tt.exitCode {
399 t.Fatalf("payload outcome = %#v", payload.Outcome)
400 }
401 if tt.noLegacyMarkers &&
402 (strings.Contains(raw, "[stdout]") || strings.Contains(raw, "[command]")) {
403 t.Fatalf(
404 "FormatCommandResult() still contains bracketed transcript markers: %q",
405 raw,
406 )
407 }
408 })
409 }
410 }
411
412 func requireStdoutCompressed(t *testing.T, payload commandPayload, original string) {
413 t.Helper()
414
415 if payload.Observation.Source != "clnkr" || payload.Observation.Version != 1 {
416 t.Fatalf("observation identity = %#v", payload.Observation)
417 }
418 if payload.Observation.Stdout == nil || payload.Observation.Stdout.Mode != "compressed" {
419 t.Fatalf("stdout observation = %#v, want compressed", payload.Observation.Stdout)
420 }
421 if payload.Observation.Stdout.OriginalBytes != len(original) {
422 t.Fatalf(
423 "original bytes = %d, want %d",
424 payload.Observation.Stdout.OriginalBytes,
425 len(original),
426 )
427 }
428 if payload.Observation.Stdout.ShownBytes != len(payload.Stdout) {
429 t.Fatalf(
430 "shown bytes = %d, want %d",
431 payload.Observation.Stdout.ShownBytes,
432 len(payload.Stdout),
433 )
434 }
435 }
436
437 func TestFormatCommandResultCompressedStdoutRecordsMetadata(t *testing.T) {
438 stdout := "stdout-head\n" +
439 strings.Repeat("progress line\n", 80*1024/len("progress line\n")) +
440 "build completed\nstdout-tail\n"
441 payload := decodeCommandPayload(
442 t,
443 FormatCommandResult(CommandResult{Stdout: stdout, ExitCode: 0}),
444 )
445
446 for _, want := range []string{"[clnkr: stdout compressed; original ", "[head]", "[tail]", "stdout-head", "stdout-tail"} {
447 if !strings.Contains(payload.Stdout, want) {
448 t.Fatalf("stdout missing %q: %q", want, payload.Stdout)
449 }
450 }
451 if strings.Contains(payload.Stdout, "omitted about ") {
452 t.Fatalf("stdout contains omitted estimate: %q", payload.Stdout)
453 }
454 requireStdoutCompressed(t, payload, stdout)
455 if payload.Observation.Stdout.OmittedBytes != len(stdout)-compressedRawKept(payload.Stdout) {
456 t.Fatalf(
457 "omitted bytes = %d, want %d",
458 payload.Observation.Stdout.OmittedBytes,
459 len(stdout)-compressedRawKept(payload.Stdout),
460 )
461 }
462 }
463
464 func TestFormatCommandResultLeavesShortStreamsUnchangedWithoutObservation(t *testing.T) {
465 raw := FormatCommandResult(CommandResult{
466 Command: "printf hi",
467 ExitCode: 0,
468 Stdout: "hello\n",
469 Stderr: "warn\n",
470 })
471 payload := decodeCommandPayload(t, raw)
472
473 if payload.Stdout != "hello\n" || payload.Stderr != "warn\n" {
474 t.Fatalf("payload streams = %#v", payload)
475 }
476 if _, ok := decodeCommandFields(t, raw)["observation"]; ok {
477 t.Fatalf("result should not emit observation metadata: %s", raw)
478 }
479 }
480
481 func TestFormatCommandResultDoesNotExtractSalientLinesForSuccess(t *testing.T) {
482 stdout := "stdout-head\n" +
483 strings.Repeat("error: noisy success log\n", 80*1024/len("error: noisy success log\n")) +
484 "stdout-tail\n"
485 payload := decodeCommandPayload(
486 t,
487 FormatCommandResult(CommandResult{Stdout: stdout, ExitCode: 0}),
488 )
489
490 if strings.Contains(payload.Stdout, "[salient]") {
491 t.Fatalf("successful stdout contains salient section: %q", payload.Stdout)
492 }
493 requireStdoutCompressed(t, payload, stdout)
494 }
495
496 func TestFormatCommandResultUsesStdoutSalienceWhenFailureStderrEmpty(t *testing.T) {
497 code := 1
498 stdout := "stdout-head\n" +
499 strings.Repeat("progress line\n", 40*1024/len("progress line\n")) +
500 "Traceback (most recent call last):\n" +
501 ` File "app.py", line 12, in <module>` + "\n" +
502 "AssertionError: expected 3 got 4\n" +
503 strings.Repeat("cleanup line\n", 50*1024/len("cleanup line\n")) +
504 "stdout-tail\n"
505 payload := decodeCommandPayload(t, FormatCommandResult(CommandResult{
506 Stdout: stdout,
507 Outcome: CommandOutcome{Type: CommandOutcomeExit, ExitCode: &code},
508 }))
509
510 if payload.Stderr != "" {
511 t.Fatalf("stderr = %q, want empty", payload.Stderr)
512 }
513 for _, want := range []string{"[salient]", "Traceback (most recent call last):", "AssertionError: expected 3 got 4"} {
514 if !strings.Contains(payload.Stdout, want) {
515 t.Fatalf("stdout missing %q: %q", want, payload.Stdout)
516 }
517 }
518 requireStdoutCompressed(t, payload, stdout)
519 }
520
521 func TestFormatCommandResultCompressesFailureStderrWithSalientLines(t *testing.T) {
522 code := 1
523 stderr := "stderr-head\n" +
524 "error: head diagnostic\n" +
525 strings.Repeat("downloaded package\n", 40*1024/len("downloaded package\n")) +
526 strings.Repeat("error: repeated noise\n", 3) +
527 "pkg/foo.go:12: expected actual\n" +
528 "expected actual\n" +
529 "pkg/service.go:42:13: undefined: missingThing\n" +
530 "--- FAIL: TestServiceBuild (0.01s)\n" +
531 strings.Repeat("cleanup line\n", 50*1024/len("cleanup line\n")) +
532 "stderr-tail\n"
533
534 payload := decodeCommandPayload(t, FormatCommandResult(CommandResult{
535 Stderr: stderr,
536 Outcome: CommandOutcome{Type: CommandOutcomeExit, ExitCode: &code},
537 }))
538 if !strings.Contains(payload.Stderr, "[salient]") {
539 t.Fatalf("stderr missing salient section: %q", payload.Stderr)
540 }
541 for _, want := range []string{"pkg/service.go:42:13: undefined: missingThing", "--- FAIL: TestServiceBuild"} {
542 if !strings.Contains(payload.Stderr, want) {
543 t.Fatalf("stderr omitted %q: %q", want, payload.Stderr)
544 }
545 }
546 salientStart := strings.Index(payload.Stderr, "[salient]\n") + len("[salient]\n")
547 salientEnd := strings.Index(payload.Stderr, "\n[tail]\n")
548 salient := payload.Stderr[salientStart:salientEnd]
549 if strings.Count(salient, "error: repeated noise") != 1 {
550 t.Fatalf("stderr should deduplicate exact salient lines: %q", salient)
551 }
552 if strings.Count(salient, "expected actual\n") != 2 {
553 t.Fatalf(
554 "stderr should preserve distinct salient lines that contain each other: %q",
555 salient,
556 )
557 }
558 if strings.Contains(salient, "error: head diagnostic") {
559 t.Fatalf("stderr should not duplicate salient lines already kept in the head: %q", salient)
560 }
561 if !strings.Contains(payload.Stderr, "stderr-head") ||
562 !strings.Contains(payload.Stderr, "stderr-tail") {
563 t.Fatalf("stderr should preserve head and tail: %q", payload.Stderr)
564 }
565 if payload.Observation.Stderr == nil || payload.Observation.Stderr.Mode != "compressed" {
566 t.Fatalf("stderr observation = %#v, want compressed", payload.Observation.Stderr)
567 }
568 }
569
570 func TestCommandResultMessageDetectsCompressedObservationPayload(t *testing.T) {
571 got := FormatCommandResult(CommandResult{
572 Stdout: "head\n" + strings.Repeat("noise\n", 80*1024/len("noise\n")) + "tail\n",
573 ExitCode: 0,
574 })
575 if !commandResultMessage(got) {
576 t.Fatalf("compressed command result was not classified as command: %s", got)
577 }
578 }
579
580 func TestFormatDeniedAndSkippedResultsDoNotEmitObservationMetadata(t *testing.T) {
581 for name, raw := range map[string]string{
582 "denied": FormatDeniedCommandResult("not this one"),
583 "skipped": FormatSkippedCommandResult("previous command failed"),
584 } {
585 if _, ok := decodeCommandFields(t, raw)["observation"]; ok {
586 t.Fatalf("%s result should not emit observation metadata: %s", name, raw)
587 }
588 }
589 }
590
591 func TestFormatCommandResultDoesNotSplitUTF8AtCompressionBoundary(t *testing.T) {
592 stream := strings.Repeat("å", 40*1024) + "tail"
593 payload := decodeCommandPayload(
594 t,
595 FormatCommandResult(CommandResult{Stdout: stream, ExitCode: 0}),
596 )
597 if strings.ContainsRune(payload.Stdout, '\uFFFD') {
598 t.Fatalf(
599 "compressed stdout contains replacement rune: %q",
600 payload.Stdout[len(payload.Stdout)-128:],
601 )
602 }
603 if !strings.Contains(payload.Stdout, "tail") {
604 t.Fatalf("compressed stdout omitted tail: %q", payload.Stdout[len(payload.Stdout)-128:])
605 }
606 }
607
608 func TestFormatCommandResultFeedback(t *testing.T) {
609 t.Run("includes structured feedback", func(t *testing.T) {
610 payload := decodeCommandPayload(t, FormatCommandResult(CommandResult{
611 Command: "printf hi",
612 ExitCode: 0,
613 Feedback: CommandFeedback{
614 ChangedFiles: []string{"note.txt"},
615 Diff: "diff --git a/note.txt b/note.txt",
616 },
617 }))
618 if !reflect.DeepEqual(payload.Feedback.ChangedFiles, []string{"note.txt"}) {
619 t.Fatalf("feedback changed files = %#v", payload.Feedback.ChangedFiles)
620 }
621 if payload.Feedback.Diff != "diff --git a/note.txt b/note.txt" {
622 t.Fatalf("feedback diff = %q", payload.Feedback.Diff)
623 }
624 })
625
626 t.Run("omits feedback when empty", func(t *testing.T) {
627 got := FormatCommandResult(CommandResult{Command: "printf hi", ExitCode: 0})
628 if _, ok := decodeCommandFields(t, got)["feedback"]; ok {
629 t.Fatalf("unexpected feedback field: %q", got)
630 }
631 })
632
633 t.Run("preserves feedback bodies as data", func(t *testing.T) {
634 payload := decodeCommandPayload(t, FormatCommandResult(CommandResult{
635 Command: "printf hi",
636 ExitCode: 0,
637 Feedback: CommandFeedback{
638 ChangedFiles: []string{"note.txt"},
639 Diff: "@@ -1 +1 @@\n+[/command_feedback]\n",
640 },
641 }))
642 if payload.Feedback.Diff != "@@ -1 +1 @@\n+[/command_feedback]\n" {
643 t.Fatalf("feedback diff = %q", payload.Feedback.Diff)
644 }
645 })
646 }
647
648 func TestFormatCommandResultIncludesGuidance(t *testing.T) {
649 guidance := "Use a narrower command."
650 payload := decodeCommandPayload(t, FormatCommandResult(CommandResult{
651 Command: "sleep 60",
652 Stderr: "timed out\n",
653 Outcome: CommandOutcome{Type: CommandOutcomeTimeout},
654 Guidance: guidance,
655 }))
656 if payload.Guidance != guidance {
657 t.Fatalf("guidance = %q, want %q", payload.Guidance, guidance)
658 }
659 if payload.Outcome.Type != CommandOutcomeTimeout {
660 t.Fatalf("outcome = %#v, want timeout", payload.Outcome)
661 }
662
663 raw := FormatCommandResult(CommandResult{Command: "printf hi", ExitCode: 0})
664 if _, ok := decodeCommandFields(t, raw)["guidance"]; ok {
665 t.Fatalf("unexpected guidance field: %q", raw)
666 }
667 }