| 1 |
package clnkr |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"encoding/json" |
| 6 |
"errors" |
| 7 |
"fmt" |
| 8 |
"path/filepath" |
| 9 |
"strings" |
| 10 |
"testing" |
| 11 |
|
| 12 |
"github.com/clnkr-ai/clnkr/internal/core/transcript" |
| 13 |
) |
| 14 |
|
| 15 |
func TestStepRecordsModelTurnsAndProtocolFailures(t *testing.T) { |
| 16 |
t.Run( |
| 17 |
"successful turn is sent state, stored canonically, and not executed", |
| 18 |
func(t *testing.T) { |
| 19 |
replayJSON := json.RawMessage(`["x"]`) |
| 20 |
model := &fakeModel{responses: []Response{ |
| 21 |
{ |
| 22 |
Turn: &ActTurn{ |
| 23 |
Bash: BashBatch{Commands: []BashAction{{ID: "call_1", Command: "pwd"}}}, |
| 24 |
}, |
| 25 |
Raw: `{"turn":{"type":"act"}}`, |
| 26 |
Usage: Usage{InputTokens: 9, OutputTokens: 4}, |
| 27 |
BashToolCalls: []BashToolCall{{ID: "call_1", Command: "pwd"}}, |
| 28 |
ProviderReplay: []ProviderReplayItem{ |
| 29 |
{ |
| 30 |
Provider: "openai", |
| 31 |
ProviderAPI: "openai-responses", |
| 32 |
Type: "reasoning", |
| 33 |
JSON: replayJSON, |
| 34 |
}, |
| 35 |
}, |
| 36 |
}, |
| 37 |
}} |
| 38 |
executor := &fakeExecutor{results: []CommandResult{{Stdout: "/tmp\n", ExitCode: 0}}} |
| 39 |
notify, events := collectEvents() |
| 40 |
agent := NewAgent(model, executor, "/repo") |
| 41 |
agent.Notify = notify |
| 42 |
agent.AppendUserMessage("where am I") |
| 43 |
|
| 44 |
result, err := agent.Step(context.Background()) |
| 45 |
if err != nil { |
| 46 |
t.Fatalf("Step: %v", err) |
| 47 |
} |
| 48 |
if _, ok := result.Turn.(*ActTurn); !ok { |
| 49 |
t.Fatalf("turn = %T, want *ActTurn", result.Turn) |
| 50 |
} |
| 51 |
if len(executor.gotCmds) != 0 { |
| 52 |
t.Fatalf("Step executed %d commands", len(executor.gotCmds)) |
| 53 |
} |
| 54 |
if !hasMessage(model.got[0], "user", transcript.FormatStateMessage("/repo")) { |
| 55 |
t.Fatalf("model query missing cwd state: %#v", model.got[0]) |
| 56 |
} |
| 57 |
assistant := agent.Messages()[len(agent.Messages())-1] |
| 58 |
if assistant.Role != "assistant" || len(assistant.BashToolCalls) != 1 || |
| 59 |
assistant.BashToolCalls[0].ID != "call_1" || |
| 60 |
len(assistant.ProviderReplay) != 1 || |
| 61 |
string(assistant.ProviderReplay[0].JSON) != string(replayJSON) { |
| 62 |
t.Fatalf("assistant transcript = %#v", assistant) |
| 63 |
} |
| 64 |
if !strings.Contains(assistant.Content, `"type":"act"`) || |
| 65 |
strings.Contains(assistant.Content, `"turn"`) { |
| 66 |
t.Fatalf("assistant content = %q, want canonical act turn", assistant.Content) |
| 67 |
} |
| 68 |
ev, ok := firstEvent[EventResponse](*events) |
| 69 |
if !ok || ev.Raw != `{"turn":{"type":"act"}}` || ev.Usage.InputTokens != 9 { |
| 70 |
t.Fatalf("response event = %#v", ev) |
| 71 |
} |
| 72 |
}, |
| 73 |
) |
| 74 |
|
| 75 |
t.Run( |
| 76 |
"protocol failure stores raw assistant response and emits failure event", |
| 77 |
func(t *testing.T) { |
| 78 |
model := &fakeModel{ |
| 79 |
responses: []Response{{Raw: "no json", ProtocolErr: ErrInvalidJSON}}, |
| 80 |
} |
| 81 |
notify, events := collectEvents() |
| 82 |
agent := NewAgent(model, &fakeExecutor{}, "/repo") |
| 83 |
agent.Notify = notify |
| 84 |
agent.AppendUserMessage("do it") |
| 85 |
|
| 86 |
result, err := agent.Step(context.Background()) |
| 87 |
if err != nil { |
| 88 |
t.Fatalf("Step: %v", err) |
| 89 |
} |
| 90 |
msgs := agent.Messages() |
| 91 |
if !errors.Is(result.ParseErr, ErrInvalidJSON) || result.Turn != nil || |
| 92 |
msgs[len(msgs)-2].Content != "no json" || |
| 93 |
!strings.Contains(msgs[len(msgs)-1].Content, "[protocol_error]") { |
| 94 |
t.Fatalf("result=%#v messages=%#v", result, msgs) |
| 95 |
} |
| 96 |
if !hasEvent[EventProtocolFailure](*events) || hasEvent[EventResponse](*events) { |
| 97 |
t.Fatalf("events = %#v", *events) |
| 98 |
} |
| 99 |
}, |
| 100 |
) |
| 101 |
|
| 102 |
t.Run("model query cannot mutate stored transcript metadata", func(t *testing.T) { |
| 103 |
agent := NewAgent(mutatingModel{}, &fakeExecutor{}, "/tmp") |
| 104 |
agent.messages = []Message{ |
| 105 |
{ |
| 106 |
Role: "assistant", |
| 107 |
Content: `{"type":"act","bash":{"commands":[{"command":"pwd","workdir":null}]}}`, |
| 108 |
BashToolCalls: []BashToolCall{{ID: "call_1", Command: "pwd"}}, |
| 109 |
ProviderReplay: []ProviderReplayItem{{JSON: json.RawMessage(`["x"]`)}}, |
| 110 |
}, |
| 111 |
} |
| 112 |
if _, err := agent.Step(context.Background()); err != nil { |
| 113 |
t.Fatalf("Step: %v", err) |
| 114 |
} |
| 115 |
if got := agent.Messages()[0]; got.BashToolCalls[0].Command != "pwd" || |
| 116 |
string(got.ProviderReplay[0].JSON) != `["x"]` { |
| 117 |
t.Fatalf("stored transcript was mutated: %#v", got) |
| 118 |
} |
| 119 |
}) |
| 120 |
} |
| 121 |
|
| 122 |
func TestExecuteTurnCoordinatesCommandBatch(t *testing.T) { |
| 123 |
t.Run( |
| 124 |
"forwards cwd and env across commands and appends observable results", |
| 125 |
func(t *testing.T) { |
| 126 |
root := t.TempDir() |
| 127 |
next := filepath.Join(root, "sub") |
| 128 |
executor := &fakeExecutor{results: []CommandResult{ |
| 129 |
{ |
| 130 |
Stdout: "moved\n", |
| 131 |
ExitCode: 0, |
| 132 |
PostCwd: next, |
| 133 |
PostEnv: map[string]string{"CLNKR_TEST": "ok"}, |
| 134 |
}, |
| 135 |
{Stdout: "ok\n", ExitCode: 0}, |
| 136 |
}} |
| 137 |
notify, events := collectEvents() |
| 138 |
agent := NewAgent(&fakeModel{}, executor, root) |
| 139 |
agent.Notify = notify |
| 140 |
|
| 141 |
result, err := agent.ExecuteTurn( |
| 142 |
context.Background(), |
| 143 |
&ActTurn{Bash: BashBatch{Commands: []BashAction{ |
| 144 |
{Command: "cd sub"}, |
| 145 |
{ID: "call_2", Command: "printf %s $CLNKR_TEST", Workdir: "nested"}, |
| 146 |
}}}, |
| 147 |
) |
| 148 |
if err != nil { |
| 149 |
t.Fatalf("ExecuteTurn: %v", err) |
| 150 |
} |
| 151 |
if result.ExecCount != 2 || result.ExecErr != nil { |
| 152 |
t.Fatalf("result = %#v", result) |
| 153 |
} |
| 154 |
if executor.gotDirs[0] != root || executor.gotDirs[1] != filepath.Join(next, "nested") { |
| 155 |
t.Fatalf("executor dirs = %#v", executor.gotDirs) |
| 156 |
} |
| 157 |
if got := executor.gotEnv[1]["CLNKR_TEST"]; got != "ok" { |
| 158 |
t.Fatalf("second command env = %#v", executor.gotEnv[1]) |
| 159 |
} |
| 160 |
msgs := agent.Messages() |
| 161 |
if !hasMessage(msgs, "user", transcript.FormatStateMessage(next)) { |
| 162 |
t.Fatalf("messages missing updated cwd state: %#v", msgs) |
| 163 |
} |
| 164 |
results := collectToolResults(msgs) |
| 165 |
if len(results) != 1 || results[0].ID != "call_2" || results[0].IsError { |
| 166 |
t.Fatalf("tool results = %#v", results) |
| 167 |
} |
| 168 |
if !hasEvent[EventCommandStart](*events) || !hasEvent[EventCommandDone](*events) { |
| 169 |
t.Fatalf("command events = %#v", *events) |
| 170 |
} |
| 171 |
}, |
| 172 |
) |
| 173 |
|
| 174 |
t.Run( |
| 175 |
"stops after a command error and completes later provider tool calls as skipped", |
| 176 |
func(t *testing.T) { |
| 177 |
execErr := errors.New("run command: exit status 2") |
| 178 |
executor := &fakeExecutor{ |
| 179 |
results: []CommandResult{{Stderr: "nope\n", ExitCode: 2}}, |
| 180 |
errs: []error{execErr}, |
| 181 |
} |
| 182 |
agent := NewAgent(&fakeModel{}, executor, "/repo") |
| 183 |
|
| 184 |
result, err := agent.ExecuteTurn( |
| 185 |
context.Background(), |
| 186 |
&ActTurn{Bash: BashBatch{Commands: []BashAction{ |
| 187 |
{ID: "call_1", Command: "false"}, |
| 188 |
{ID: "call_2", Command: "echo later"}, |
| 189 |
}}}, |
| 190 |
) |
| 191 |
if err != nil { |
| 192 |
t.Fatalf("ExecuteTurn API error: %v", err) |
| 193 |
} |
| 194 |
if !errors.Is(result.ExecErr, execErr) || result.ExecCount != 1 || |
| 195 |
len(executor.gotCmds) != 1 { |
| 196 |
t.Fatalf("result = %#v executor calls=%d", result, len(executor.gotCmds)) |
| 197 |
} |
| 198 |
results := collectToolResults(agent.Messages()) |
| 199 |
if len(results) != 2 || !results[0].IsError || results[1].ID != "call_2" || |
| 200 |
!results[1].IsError { |
| 201 |
t.Fatalf("tool results = %#v", results) |
| 202 |
} |
| 203 |
if payloadOutcome(t, results[1].Content) != CommandOutcomeSkipped { |
| 204 |
t.Fatalf("skipped content = %s", results[1].Content) |
| 205 |
} |
| 206 |
}, |
| 207 |
) |
| 208 |
|
| 209 |
t.Run("appends timeout guidance as structured command JSON", func(t *testing.T) { |
| 210 |
execErr := errors.New("run command: timeout") |
| 211 |
executor := &fakeExecutor{ |
| 212 |
results: []CommandResult{{ |
| 213 |
Stderr: "timed out\n", |
| 214 |
Outcome: CommandOutcome{Type: CommandOutcomeTimeout}, |
| 215 |
}}, |
| 216 |
errs: []error{execErr}, |
| 217 |
} |
| 218 |
agent := NewAgent(&fakeModel{}, executor, "/repo") |
| 219 |
|
| 220 |
result, err := agent.ExecuteTurn( |
| 221 |
context.Background(), |
| 222 |
&ActTurn{Bash: BashBatch{Commands: []BashAction{{Command: "sleep 60"}}}}, |
| 223 |
) |
| 224 |
if err != nil { |
| 225 |
t.Fatalf("ExecuteTurn API error: %v", err) |
| 226 |
} |
| 227 |
if !errors.Is(result.ExecErr, execErr) { |
| 228 |
t.Fatalf("ExecuteTurn ExecErr = %v, want timeout command error", result.ExecErr) |
| 229 |
} |
| 230 |
|
| 231 |
got := messagesText(agent.Messages()) |
| 232 |
for _, want := range []string{ |
| 233 |
`"type":"timeout"`, |
| 234 |
timeoutGuidance, |
| 235 |
} { |
| 236 |
if !strings.Contains(got, want) { |
| 237 |
t.Fatalf("messages missing %q:\n%s", want, got) |
| 238 |
} |
| 239 |
} |
| 240 |
var payload struct { |
| 241 |
Guidance string `json:"guidance"` |
| 242 |
} |
| 243 |
if err := json.Unmarshal([]byte(agent.Messages()[0].Content), &payload); err != nil { |
| 244 |
t.Fatalf( |
| 245 |
"timeout command message is not JSON: %v\n%s", |
| 246 |
err, |
| 247 |
agent.Messages()[0].Content, |
| 248 |
) |
| 249 |
} |
| 250 |
if payload.Guidance != timeoutGuidance { |
| 251 |
t.Fatalf("timeout guidance = %q, want %q", payload.Guidance, timeoutGuidance) |
| 252 |
} |
| 253 |
}) |
| 254 |
} |
| 255 |
|
| 256 |
func TestRunWithPolicyCoordinatesTheFacadeLoop(t *testing.T) { |
| 257 |
t.Run( |
| 258 |
"full-send executes act, sends command result and resource state, then stops on done", |
| 259 |
func(t *testing.T) { |
| 260 |
model := &fakeModel{responses: []Response{ |
| 261 |
{Turn: &ActTurn{Bash: BashBatch{Commands: []BashAction{{Command: "echo hi"}}}}}, |
| 262 |
{Turn: verifiedDone("finished")}, |
| 263 |
}} |
| 264 |
executor := &fakeExecutor{results: []CommandResult{{Stdout: "hi\n", ExitCode: 0}}} |
| 265 |
agent := NewAgent(model, executor, "/tmp") |
| 266 |
|
| 267 |
if err := agent.Run(context.Background(), "say hi"); err != nil { |
| 268 |
t.Fatalf("Run: %v", err) |
| 269 |
} |
| 270 |
if strings.Join(executor.gotCmds, ",") != "echo hi" { |
| 271 |
t.Fatalf("commands = %#v", executor.gotCmds) |
| 272 |
} |
| 273 |
secondQuery := messagesText(model.got[1]) |
| 274 |
for _, want := range []string{`"stdout":"hi\n"`, `"type":"resource_state"`, `"commands_used":1`, `"model_turns_used":1`} { |
| 275 |
if !strings.Contains(secondQuery, want) { |
| 276 |
t.Fatalf("second query missing %q:\n%s", want, secondQuery) |
| 277 |
} |
| 278 |
} |
| 279 |
}, |
| 280 |
) |
| 281 |
|
| 282 |
t.Run("clarification and rejection are policy-mediated user turns", func(t *testing.T) { |
| 283 |
model := &fakeModel{responses: []Response{ |
| 284 |
{Turn: &ClarifyTurn{Question: "Which repo?"}}, |
| 285 |
{ |
| 286 |
Turn: &ActTurn{ |
| 287 |
Bash: BashBatch{Commands: []BashAction{{Command: "rm important.txt"}}}, |
| 288 |
}, |
| 289 |
}, |
| 290 |
{Turn: verifiedDone("finished")}, |
| 291 |
}} |
| 292 |
policy := &scriptedPolicy{ |
| 293 |
clarifies: []string{"/tmp/repo"}, |
| 294 |
decisions: []ActDecision{{Kind: ActDecisionReject, Guidance: "list files instead"}}, |
| 295 |
} |
| 296 |
executor := &fakeExecutor{} |
| 297 |
agent := NewAgent(model, executor, "/tmp") |
| 298 |
|
| 299 |
if err := agent.RunWithPolicy(context.Background(), "inspect", policy); err != nil { |
| 300 |
t.Fatalf("RunWithPolicy: %v", err) |
| 301 |
} |
| 302 |
if len(executor.gotCmds) != 0 { |
| 303 |
t.Fatalf("executor calls = %d, want 0", len(executor.gotCmds)) |
| 304 |
} |
| 305 |
if len(policy.questions) != 1 || policy.questions[0] != "Which repo?" { |
| 306 |
t.Fatalf("questions = %#v", policy.questions) |
| 307 |
} |
| 308 |
if !hasMessage(model.got[1], "user", "/tmp/repo") || |
| 309 |
!hasMessage(model.got[2], "user", "list files instead") { |
| 310 |
t.Fatalf("model queries missing policy replies: %#v", model.got) |
| 311 |
} |
| 312 |
}) |
| 313 |
|
| 314 |
t.Run( |
| 315 |
"protocol failures retry with correction and stop after three consecutive failures", |
| 316 |
func(t *testing.T) { |
| 317 |
model := &fakeModel{responses: []Response{ |
| 318 |
{Raw: "bad 1", ProtocolErr: ErrInvalidJSON}, |
| 319 |
{Raw: "bad 2", ProtocolErr: ErrInvalidJSON}, |
| 320 |
{Raw: "bad 3", ProtocolErr: ErrInvalidJSON}, |
| 321 |
}} |
| 322 |
agent := NewAgent(model, &fakeExecutor{}, "/tmp") |
| 323 |
|
| 324 |
err := agent.Run(context.Background(), "do it") |
| 325 |
if err == nil || !strings.Contains(err.Error(), "consecutive protocol failures") { |
| 326 |
t.Fatalf("Run error = %v", err) |
| 327 |
} |
| 328 |
if model.calls != 3 { |
| 329 |
t.Fatalf("model calls = %d, want 3", model.calls) |
| 330 |
} |
| 331 |
correction := messagesText(model.got[1]) |
| 332 |
if !strings.Contains(correction, "[protocol_error]") || |
| 333 |
!strings.Contains( |
| 334 |
correction, |
| 335 |
"Your previous response was ignored and no command ran", |
| 336 |
) || |
| 337 |
!strings.Contains(correction, "invalid_json") { |
| 338 |
t.Fatalf("second query missing correction: %#v", model.got[1]) |
| 339 |
} |
| 340 |
}, |
| 341 |
) |
| 342 |
|
| 343 |
t.Run("resource pressure guidance appears only on pressure transitions", func(t *testing.T) { |
| 344 |
firstBatch := make([]BashAction, 7) |
| 345 |
secondBatch := make([]BashAction, 2) |
| 346 |
results := make([]CommandResult, 9) |
| 347 |
for i := range firstBatch { |
| 348 |
firstBatch[i] = BashAction{Command: fmt.Sprintf("echo first-%d", i)} |
| 349 |
results[i] = CommandResult{Stdout: "ok\n", ExitCode: 0} |
| 350 |
} |
| 351 |
for i := range secondBatch { |
| 352 |
secondBatch[i] = BashAction{Command: fmt.Sprintf("echo second-%d", i)} |
| 353 |
results[len(firstBatch)+i] = CommandResult{Stdout: "ok\n", ExitCode: 0} |
| 354 |
} |
| 355 |
model := &fakeModel{responses: []Response{ |
| 356 |
{Turn: &ActTurn{Bash: BashBatch{Commands: firstBatch}}}, |
| 357 |
{Turn: &ActTurn{Bash: BashBatch{Commands: secondBatch}}}, |
| 358 |
{Turn: verifiedDone("finished")}, |
| 359 |
}} |
| 360 |
agent := NewAgent(model, &fakeExecutor{results: results}, "/tmp") |
| 361 |
agent.MaxSteps = 10 |
| 362 |
|
| 363 |
if err := agent.Run(context.Background(), "use budget"); err != nil { |
| 364 |
t.Fatalf("Run: %v", err) |
| 365 |
} |
| 366 |
|
| 367 |
got := messagesText(agent.Messages()) |
| 368 |
lowGuidance := resourcePressureGuidance(resourcePressureLow) |
| 369 |
criticalGuidance := resourcePressureGuidance(resourcePressureCritical) |
| 370 |
for _, want := range []string{ |
| 371 |
`"pressure":"normal"`, |
| 372 |
`"pressure":"low","guidance":"` + lowGuidance + `"`, |
| 373 |
`"pressure":"critical","guidance":"` + criticalGuidance + `"`, |
| 374 |
} { |
| 375 |
if !strings.Contains(got, want) { |
| 376 |
t.Fatalf("transcript missing %q:\n%s", want, got) |
| 377 |
} |
| 378 |
} |
| 379 |
if strings.Count(got, lowGuidance) != 1 || strings.Count(got, criticalGuidance) != 1 { |
| 380 |
t.Fatalf("guidance should be transition-only:\n%s", got) |
| 381 |
} |
| 382 |
}) |
| 383 |
} |
| 384 |
|
| 385 |
func TestRunWithPolicyCompletesDeniedToolResults(t *testing.T) { |
| 386 |
model := &fakeModel{responses: []Response{ |
| 387 |
{Turn: &ActTurn{Bash: BashBatch{Commands: []BashAction{ |
| 388 |
{ID: "call_1", Command: "rm important.txt"}, |
| 389 |
{ID: "call_2", Command: "git status"}, |
| 390 |
}}}}, |
| 391 |
{Turn: verifiedDone("finished")}, |
| 392 |
}} |
| 393 |
policy := &scriptedPolicy{ |
| 394 |
decisions: []ActDecision{{Kind: ActDecisionReject, Guidance: "list files instead"}}, |
| 395 |
} |
| 396 |
agent := NewAgent(model, &fakeExecutor{}, "/tmp") |
| 397 |
|
| 398 |
if err := agent.RunWithPolicy(context.Background(), "do it", policy); err != nil { |
| 399 |
t.Fatalf("RunWithPolicy: %v", err) |
| 400 |
} |
| 401 |
results := collectToolResults(agent.Messages()) |
| 402 |
if len(results) != 2 || results[0].ID != "call_1" || results[1].ID != "call_2" { |
| 403 |
t.Fatalf("tool results = %#v", results) |
| 404 |
} |
| 405 |
for _, result := range results { |
| 406 |
if !result.IsError || payloadOutcome(t, result.Content) != CommandOutcomeDenied { |
| 407 |
t.Fatalf("denied result = %#v", result) |
| 408 |
} |
| 409 |
} |
| 410 |
} |
| 411 |
|
| 412 |
func TestRunWithPolicyStopsCleanlyOnPolicyErrors(t *testing.T) { |
| 413 |
errApprovalPending := errors.New("approval pending") |
| 414 |
model := &fakeModel{ |
| 415 |
responses: []Response{ |
| 416 |
{ |
| 417 |
Turn: &ActTurn{ |
| 418 |
Bash: BashBatch{Commands: []BashAction{{Command: "rm important.txt"}}}, |
| 419 |
}, |
| 420 |
}, |
| 421 |
}, |
| 422 |
} |
| 423 |
executor := &fakeExecutor{} |
| 424 |
policy := &scriptedPolicy{decideErr: errApprovalPending} |
| 425 |
agent := NewAgent(model, executor, "/tmp") |
| 426 |
|
| 427 |
err := agent.RunWithPolicy(context.Background(), "do it", policy) |
| 428 |
if !errors.Is(err, errApprovalPending) { |
| 429 |
t.Fatalf("RunWithPolicy error = %v", err) |
| 430 |
} |
| 431 |
if len(executor.gotCmds) != 0 || hasMessage(agent.Messages(), "user", "") { |
| 432 |
t.Fatalf("executor calls=%d messages=%#v", len(executor.gotCmds), agent.Messages()) |
| 433 |
} |
| 434 |
} |
| 435 |
|
| 436 |
func TestRunWithPolicyOptionsBackstopsContextLengthOnce(t *testing.T) { |
| 437 |
contextErr := fmt.Errorf("%w: provider said context too long", ErrContextLengthExceeded) |
| 438 |
model := &fakeModel{ |
| 439 |
errs: []error{contextErr, nil}, |
| 440 |
responses: []Response{ |
| 441 |
{Turn: verifiedDone("done")}, |
| 442 |
}, |
| 443 |
} |
| 444 |
agent := NewAgent(model, &fakeExecutor{}, "/tmp") |
| 445 |
backstopCalls := 0 |
| 446 |
|
| 447 |
err := agent.RunWithPolicyOptions( |
| 448 |
context.Background(), |
| 449 |
"inspect", |
| 450 |
FullSendPolicy{}, |
| 451 |
RunOptions{ |
| 452 |
ContextLengthBackstop: func(context.Context, error) error { |
| 453 |
backstopCalls++ |
| 454 |
agent.AppendUserMessage("compacted marker") |
| 455 |
return nil |
| 456 |
}, |
| 457 |
}, |
| 458 |
) |
| 459 |
if err != nil { |
| 460 |
t.Fatalf("RunWithPolicyOptions: %v", err) |
| 461 |
} |
| 462 |
if backstopCalls != 1 { |
| 463 |
t.Fatalf("backstop calls = %d, want 1", backstopCalls) |
| 464 |
} |
| 465 |
if model.calls != 2 { |
| 466 |
t.Fatalf("model calls = %d, want 2", model.calls) |
| 467 |
} |
| 468 |
if countUserMessages(agent.Messages(), "inspect") != 1 { |
| 469 |
t.Fatalf("prompt was appended more than once: %#v", agent.Messages()) |
| 470 |
} |
| 471 |
if countUserMessages(agent.Messages(), "compacted marker") != 1 { |
| 472 |
t.Fatalf("backstop marker not appended once: %#v", agent.Messages()) |
| 473 |
} |
| 474 |
} |
| 475 |
|
| 476 |
func TestRunWithPolicyOptionsBackstopsStepLimitSummaryContextLength(t *testing.T) { |
| 477 |
contextErr := fmt.Errorf("%w: final summary context too long", ErrContextLengthExceeded) |
| 478 |
model := &fakeModel{ |
| 479 |
responses: []Response{ |
| 480 |
{Turn: &ActTurn{Bash: BashBatch{Commands: []BashAction{{Command: "pwd"}}}}}, |
| 481 |
{Turn: verifiedDone("step limit summary")}, |
| 482 |
}, |
| 483 |
errs: []error{nil, contextErr}, |
| 484 |
} |
| 485 |
executor := &fakeExecutor{results: []CommandResult{{Stdout: "/tmp\n", ExitCode: 0}}} |
| 486 |
policy := &scriptedPolicy{decisions: []ActDecision{{Kind: ActDecisionApprove}}} |
| 487 |
agent := NewAgent(model, executor, "/tmp") |
| 488 |
agent.MaxSteps = 1 |
| 489 |
backstopCalls := 0 |
| 490 |
|
| 491 |
err := agent.RunWithPolicyOptions( |
| 492 |
context.Background(), |
| 493 |
"inspect", |
| 494 |
policy, |
| 495 |
RunOptions{ |
| 496 |
ContextLengthBackstop: func(context.Context, error) error { |
| 497 |
backstopCalls++ |
| 498 |
agent.AppendUserMessage("compacted marker") |
| 499 |
return nil |
| 500 |
}, |
| 501 |
}, |
| 502 |
) |
| 503 |
if err != nil { |
| 504 |
t.Fatalf("RunWithPolicyOptions: %v", err) |
| 505 |
} |
| 506 |
if backstopCalls != 1 { |
| 507 |
t.Fatalf("backstop calls = %d, want 1", backstopCalls) |
| 508 |
} |
| 509 |
if model.calls != 3 { |
| 510 |
t.Fatalf("model calls = %d, want 3", model.calls) |
| 511 |
} |
| 512 |
if countUserMessages(agent.Messages(), "compacted marker") != 1 { |
| 513 |
t.Fatalf("backstop marker not appended once: %#v", agent.Messages()) |
| 514 |
} |
| 515 |
if countUserMessages( |
| 516 |
agent.Messages(), |
| 517 |
"Step limit reached. Respond with "+protocolDoneExample+" summarizing your progress.", |
| 518 |
) != 1 { |
| 519 |
t.Fatalf("step-limit summary prompt count changed: %#v", agent.Messages()) |
| 520 |
} |
| 521 |
} |
| 522 |
|
| 523 |
func TestRunWithPolicyOptionsReportsStepLimitSummaryCompactionFailure(t *testing.T) { |
| 524 |
contextErr := fmt.Errorf("%w: final summary context too long", ErrContextLengthExceeded) |
| 525 |
compactionErr := errors.New("compact boom") |
| 526 |
model := &fakeModel{ |
| 527 |
responses: []Response{ |
| 528 |
{Turn: &ActTurn{Bash: BashBatch{Commands: []BashAction{{Command: "pwd"}}}}}, |
| 529 |
}, |
| 530 |
errs: []error{nil, contextErr}, |
| 531 |
} |
| 532 |
executor := &fakeExecutor{results: []CommandResult{{Stdout: "/tmp\n", ExitCode: 0}}} |
| 533 |
policy := &scriptedPolicy{decisions: []ActDecision{{Kind: ActDecisionApprove}}} |
| 534 |
agent := NewAgent(model, executor, "/tmp") |
| 535 |
agent.MaxSteps = 1 |
| 536 |
|
| 537 |
err := agent.RunWithPolicyOptions( |
| 538 |
context.Background(), |
| 539 |
"inspect", |
| 540 |
policy, |
| 541 |
RunOptions{ |
| 542 |
ContextLengthBackstop: func(context.Context, error) error { |
| 543 |
return compactionErr |
| 544 |
}, |
| 545 |
}, |
| 546 |
) |
| 547 |
if err == nil { |
| 548 |
t.Fatal("RunWithPolicyOptions error = nil, want failure") |
| 549 |
} |
| 550 |
if !errors.Is(err, ErrContextLengthExceeded) { |
| 551 |
t.Fatalf("error = %v, want ErrContextLengthExceeded", err) |
| 552 |
} |
| 553 |
if !errors.Is(err, compactionErr) { |
| 554 |
t.Fatalf("error = %v, want compaction failure", err) |
| 555 |
} |
| 556 |
if !strings.Contains(err.Error(), "context_length_backstop") || |
| 557 |
!strings.Contains(err.Error(), "compaction failed") { |
| 558 |
t.Fatalf("error = %q, want backstop compaction context", err.Error()) |
| 559 |
} |
| 560 |
} |
| 561 |
|
| 562 |
func TestRunWithPolicyOptionsReportsStepLimitSummaryRetryFailure(t *testing.T) { |
| 563 |
contextErr := fmt.Errorf("%w: final summary context too long", ErrContextLengthExceeded) |
| 564 |
retryErr := errors.New("network down") |
| 565 |
model := &fakeModel{ |
| 566 |
responses: []Response{ |
| 567 |
{Turn: &ActTurn{Bash: BashBatch{Commands: []BashAction{{Command: "pwd"}}}}}, |
| 568 |
}, |
| 569 |
errs: []error{nil, contextErr, retryErr}, |
| 570 |
} |
| 571 |
executor := &fakeExecutor{results: []CommandResult{{Stdout: "/tmp\n", ExitCode: 0}}} |
| 572 |
policy := &scriptedPolicy{decisions: []ActDecision{{Kind: ActDecisionApprove}}} |
| 573 |
agent := NewAgent(model, executor, "/tmp") |
| 574 |
agent.MaxSteps = 1 |
| 575 |
|
| 576 |
err := agent.RunWithPolicyOptions( |
| 577 |
context.Background(), |
| 578 |
"inspect", |
| 579 |
policy, |
| 580 |
RunOptions{ |
| 581 |
ContextLengthBackstop: func(context.Context, error) error { |
| 582 |
return nil |
| 583 |
}, |
| 584 |
}, |
| 585 |
) |
| 586 |
if err == nil { |
| 587 |
t.Fatal("RunWithPolicyOptions error = nil, want failure") |
| 588 |
} |
| 589 |
if !errors.Is(err, ErrContextLengthExceeded) { |
| 590 |
t.Fatalf("error = %v, want original context failure", err) |
| 591 |
} |
| 592 |
if !errors.Is(err, retryErr) { |
| 593 |
t.Fatalf("error = %v, want retry failure", err) |
| 594 |
} |
| 595 |
if !strings.Contains(err.Error(), "retry failed") { |
| 596 |
t.Fatalf("error = %q, want retry failure context", err.Error()) |
| 597 |
} |
| 598 |
} |
| 599 |
|
| 600 |
func TestRunWithPolicyOptionsDoesNotBackstopStepLimitSummaryTwice(t *testing.T) { |
| 601 |
contextErr := fmt.Errorf("%w: final summary context too long", ErrContextLengthExceeded) |
| 602 |
model := &fakeModel{ |
| 603 |
responses: []Response{ |
| 604 |
{Turn: &ActTurn{Bash: BashBatch{Commands: []BashAction{{Command: "pwd"}}}}}, |
| 605 |
}, |
| 606 |
errs: []error{nil, contextErr, contextErr}, |
| 607 |
} |
| 608 |
executor := &fakeExecutor{results: []CommandResult{{Stdout: "/tmp\n", ExitCode: 0}}} |
| 609 |
policy := &scriptedPolicy{decisions: []ActDecision{{Kind: ActDecisionApprove}}} |
| 610 |
agent := NewAgent(model, executor, "/tmp") |
| 611 |
agent.MaxSteps = 1 |
| 612 |
backstopCalls := 0 |
| 613 |
|
| 614 |
err := agent.RunWithPolicyOptions( |
| 615 |
context.Background(), |
| 616 |
"inspect", |
| 617 |
policy, |
| 618 |
RunOptions{ |
| 619 |
ContextLengthBackstop: func(context.Context, error) error { |
| 620 |
backstopCalls++ |
| 621 |
return nil |
| 622 |
}, |
| 623 |
}, |
| 624 |
) |
| 625 |
if err == nil { |
| 626 |
t.Fatal("RunWithPolicyOptions error = nil, want failure") |
| 627 |
} |
| 628 |
if backstopCalls != 1 { |
| 629 |
t.Fatalf("backstop calls = %d, want 1", backstopCalls) |
| 630 |
} |
| 631 |
if !errors.Is(err, ErrContextLengthExceeded) { |
| 632 |
t.Fatalf("error = %v, want ErrContextLengthExceeded", err) |
| 633 |
} |
| 634 |
if !strings.Contains(err.Error(), "retry failed") { |
| 635 |
t.Fatalf("error = %q, want retry failure context", err.Error()) |
| 636 |
} |
| 637 |
} |
| 638 |
|
| 639 |
func TestRunWithPolicyOptionsReportsCompactionFailureWithOriginalContextFailure(t *testing.T) { |
| 640 |
contextErr := fmt.Errorf("%w: provider said context too long", ErrContextLengthExceeded) |
| 641 |
compactionErr := errors.New("compact boom") |
| 642 |
model := &fakeModel{errs: []error{contextErr}} |
| 643 |
agent := NewAgent(model, &fakeExecutor{}, "/tmp") |
| 644 |
|
| 645 |
err := agent.RunWithPolicyOptions( |
| 646 |
context.Background(), |
| 647 |
"inspect", |
| 648 |
FullSendPolicy{}, |
| 649 |
RunOptions{ |
| 650 |
ContextLengthBackstop: func(context.Context, error) error { |
| 651 |
return compactionErr |
| 652 |
}, |
| 653 |
}, |
| 654 |
) |
| 655 |
if err == nil { |
| 656 |
t.Fatal("RunWithPolicyOptions error = nil, want failure") |
| 657 |
} |
| 658 |
if !errors.Is(err, ErrContextLengthExceeded) { |
| 659 |
t.Fatalf("error = %v, want ErrContextLengthExceeded", err) |
| 660 |
} |
| 661 |
if !errors.Is(err, compactionErr) { |
| 662 |
t.Fatalf("error = %v, want compaction failure", err) |
| 663 |
} |
| 664 |
if !strings.Contains(err.Error(), "context_length_backstop") || |
| 665 |
!strings.Contains(err.Error(), "compaction failed") { |
| 666 |
t.Fatalf("error = %q, want backstop compaction context", err.Error()) |
| 667 |
} |
| 668 |
} |
| 669 |
|
| 670 |
func TestRunWithPolicyOptionsReportsRetryFailureWithOriginalContextFailure(t *testing.T) { |
| 671 |
contextErr := fmt.Errorf("%w: provider said context too long", ErrContextLengthExceeded) |
| 672 |
retryErr := errors.New("network down") |
| 673 |
model := &fakeModel{errs: []error{contextErr, retryErr}} |
| 674 |
agent := NewAgent(model, &fakeExecutor{}, "/tmp") |
| 675 |
|
| 676 |
err := agent.RunWithPolicyOptions( |
| 677 |
context.Background(), |
| 678 |
"inspect", |
| 679 |
FullSendPolicy{}, |
| 680 |
RunOptions{ |
| 681 |
ContextLengthBackstop: func(context.Context, error) error { |
| 682 |
return nil |
| 683 |
}, |
| 684 |
}, |
| 685 |
) |
| 686 |
if err == nil { |
| 687 |
t.Fatal("RunWithPolicyOptions error = nil, want failure") |
| 688 |
} |
| 689 |
if !errors.Is(err, ErrContextLengthExceeded) { |
| 690 |
t.Fatalf("error = %v, want original context failure", err) |
| 691 |
} |
| 692 |
if !errors.Is(err, retryErr) { |
| 693 |
t.Fatalf("error = %v, want retry failure", err) |
| 694 |
} |
| 695 |
if !strings.Contains(err.Error(), "retry failed") { |
| 696 |
t.Fatalf("error = %q, want retry failure context", err.Error()) |
| 697 |
} |
| 698 |
} |
| 699 |
|
| 700 |
func TestRunWithPolicyOptionsDoesNotBackstopTwice(t *testing.T) { |
| 701 |
contextErr := fmt.Errorf("%w: provider said context too long", ErrContextLengthExceeded) |
| 702 |
model := &fakeModel{errs: []error{contextErr, contextErr}} |
| 703 |
agent := NewAgent(model, &fakeExecutor{}, "/tmp") |
| 704 |
backstopCalls := 0 |
| 705 |
|
| 706 |
err := agent.RunWithPolicyOptions( |
| 707 |
context.Background(), |
| 708 |
"inspect", |
| 709 |
FullSendPolicy{}, |
| 710 |
RunOptions{ |
| 711 |
ContextLengthBackstop: func(context.Context, error) error { |
| 712 |
backstopCalls++ |
| 713 |
return nil |
| 714 |
}, |
| 715 |
}, |
| 716 |
) |
| 717 |
if err == nil { |
| 718 |
t.Fatal("RunWithPolicyOptions error = nil, want failure") |
| 719 |
} |
| 720 |
if backstopCalls != 1 { |
| 721 |
t.Fatalf("backstop calls = %d, want 1", backstopCalls) |
| 722 |
} |
| 723 |
if model.calls != 2 { |
| 724 |
t.Fatalf("model calls = %d, want 2", model.calls) |
| 725 |
} |
| 726 |
} |
| 727 |
|
| 728 |
func TestRunCommandBudgetIsLocalToEachRun(t *testing.T) { |
| 729 |
model := &fakeModel{responses: []Response{ |
| 730 |
{Turn: &ActTurn{Bash: BashBatch{Commands: []BashAction{{Command: "echo one"}}}}}, |
| 731 |
{Turn: verifiedDone("first")}, |
| 732 |
{Turn: &ActTurn{Bash: BashBatch{Commands: []BashAction{{Command: "echo two"}}}}}, |
| 733 |
{Turn: verifiedDone("second")}, |
| 734 |
}} |
| 735 |
executor := &fakeExecutor{ |
| 736 |
results: []CommandResult{{Stdout: "one\n", ExitCode: 0}, {Stdout: "two\n", ExitCode: 0}}, |
| 737 |
} |
| 738 |
agent := NewAgent(model, executor, "/tmp") |
| 739 |
agent.MaxSteps = 1 |
| 740 |
|
| 741 |
if err := agent.Run(context.Background(), "first"); err != nil { |
| 742 |
t.Fatalf("first Run: %v", err) |
| 743 |
} |
| 744 |
if err := agent.Run(context.Background(), "second"); err != nil { |
| 745 |
t.Fatalf("second Run: %v", err) |
| 746 |
} |
| 747 |
if got := strings.Join(executor.gotCmds, ","); got != "echo one,echo two" { |
| 748 |
t.Fatalf("commands = %q", got) |
| 749 |
} |
| 750 |
} |
| 751 |
|
| 752 |
func TestRunBoundsCommandObservationButKeepsRawCommandEvent(t *testing.T) { |
| 753 |
hugeStdout := "stdout-head-" + strings.Repeat("o", 128*1024) + "-stdout-tail" |
| 754 |
hugeStderr := "stderr-head-" + strings.Repeat("e", 128*1024) + "-stderr-tail" |
| 755 |
model := &fakeModel{responses: []Response{ |
| 756 |
{Turn: &ActTurn{Bash: BashBatch{Commands: []BashAction{{Command: "generate-noise"}}}}}, |
| 757 |
{Turn: verifiedDone("finished")}, |
| 758 |
}} |
| 759 |
executor := &fakeExecutor{ |
| 760 |
results: []CommandResult{{Stdout: hugeStdout, Stderr: hugeStderr, ExitCode: 0}}, |
| 761 |
} |
| 762 |
notify, events := collectEvents() |
| 763 |
agent := NewAgent(model, executor, "/tmp") |
| 764 |
agent.Notify = notify |
| 765 |
|
| 766 |
if err := agent.Run(context.Background(), "handle noisy command"); err != nil { |
| 767 |
t.Fatalf("Run: %v", err) |
| 768 |
} |
| 769 |
payload := messagesText(model.got[1]) |
| 770 |
if strings.Contains(payload, hugeStdout) || strings.Contains(payload, hugeStderr) || |
| 771 |
!strings.Contains(payload, "compressed") { |
| 772 |
t.Fatalf("model query received unbounded command output") |
| 773 |
} |
| 774 |
done, ok := firstEvent[EventCommandDone](*events) |
| 775 |
if !ok || done.Stdout != hugeStdout || done.Stderr != hugeStderr { |
| 776 |
t.Fatalf("command done event = %#v", done) |
| 777 |
} |
| 778 |
} |
| 779 |
|
| 780 |
func TestRunWithPolicyEnforcesBudgetsAndCompletionGate(t *testing.T) { |
| 781 |
t.Run( |
| 782 |
"truncates approval proposal and asks for one final summary at the step limit", |
| 783 |
func(t *testing.T) { |
| 784 |
model := &fakeModel{responses: []Response{ |
| 785 |
{Turn: &ActTurn{Bash: BashBatch{Commands: []BashAction{ |
| 786 |
{ID: "call_1", Command: "pwd"}, |
| 787 |
{ID: "call_2", Command: "go test ./...", Workdir: "subdir"}, |
| 788 |
{ID: "call_3", Command: "git status"}, |
| 789 |
}}, Reasoning: "need status"}}, |
| 790 |
{Turn: verifiedDone("step limit summary")}, |
| 791 |
}} |
| 792 |
executor := &fakeExecutor{ |
| 793 |
results: []CommandResult{ |
| 794 |
{Stdout: "/tmp\n", ExitCode: 0}, |
| 795 |
{Stdout: "ok\n", ExitCode: 0}, |
| 796 |
}, |
| 797 |
} |
| 798 |
policy := &scriptedPolicy{decisions: []ActDecision{{Kind: ActDecisionApprove}}} |
| 799 |
agent := NewAgent(model, executor, "/tmp") |
| 800 |
agent.MaxSteps = 2 |
| 801 |
|
| 802 |
if err := agent.RunWithPolicy(context.Background(), "do it", policy); err != nil { |
| 803 |
t.Fatalf("RunWithPolicy: %v", err) |
| 804 |
} |
| 805 |
if got, want := policy.proposals[0].Prompt, "1. pwd\n2. go test ./... in subdir"; got != want { |
| 806 |
t.Fatalf("proposal = %q, want %q", got, want) |
| 807 |
} |
| 808 |
if len(policy.proposals[0].Skipped) != 1 || |
| 809 |
strings.Join(executor.gotCmds, ",") != "pwd,go test ./..." { |
| 810 |
t.Fatalf("proposal=%#v commands=%#v", policy.proposals[0], executor.gotCmds) |
| 811 |
} |
| 812 |
if results := collectToolResults( |
| 813 |
agent.Messages(), |
| 814 |
); len(results) != 3 || |
| 815 |
payloadOutcome(t, results[2].Content) != CommandOutcomeSkipped { |
| 816 |
t.Fatalf("tool results = %#v", results) |
| 817 |
} |
| 818 |
if strings.Count(messagesText(agent.Messages()), "Step limit reached.") != 1 { |
| 819 |
t.Fatalf("messages = %#v", agent.Messages()) |
| 820 |
} |
| 821 |
}, |
| 822 |
) |
| 823 |
|
| 824 |
} |
| 825 |
|
| 826 |
func TestRunWithPolicyCompletionGateEvents(t *testing.T) { |
| 827 |
weakDone := &DoneTurn{ |
| 828 |
Summary: "Protocol correction: need to continue.", |
| 829 |
Verification: CompletionVerification{ |
| 830 |
Status: VerificationVerified, |
| 831 |
Checks: []VerificationCheck{{ |
| 832 |
Command: "true", Outcome: "passed", Evidence: "true exited zero", |
| 833 |
}}, |
| 834 |
}, |
| 835 |
KnownRisks: []string{}, |
| 836 |
} |
| 837 |
challenge := &DoneTurn{ |
| 838 |
Summary: "Created result.txt.", |
| 839 |
Verification: CompletionVerification{ |
| 840 |
Status: VerificationVerified, |
| 841 |
Checks: []VerificationCheck{{ |
| 842 |
Command: "true", Outcome: "passed", Evidence: "ok", |
| 843 |
}}, |
| 844 |
}, |
| 845 |
KnownRisks: []string{}, |
| 846 |
} |
| 847 |
for _, tc := range []struct { |
| 848 |
name string |
| 849 |
turn *DoneTurn |
| 850 |
wantText []string |
| 851 |
wantEvent string |
| 852 |
}{ |
| 853 |
{"reject", weakDone, []string{"Completion rejected", "incomplete_summary"}, "reject,accept"}, |
| 854 |
{"challenge", challenge, []string{"Completion challenged", "verification evidence"}, "challenge,accept"}, |
| 855 |
} { |
| 856 |
t.Run(tc.name, func(t *testing.T) { |
| 857 |
model := &fakeModel{ |
| 858 |
responses: []Response{{Turn: tc.turn}, {Turn: verifiedDone("Finished.")}}, |
| 859 |
} |
| 860 |
agent := NewAgent(model, &fakeExecutor{}, "/tmp") |
| 861 |
notify, events := collectEvents() |
| 862 |
agent.Notify = notify |
| 863 |
if err := agent.Run(context.Background(), "finish"); err != nil { |
| 864 |
t.Fatalf("Run: %v", err) |
| 865 |
} |
| 866 |
guidance := messagesText(model.got[1]) |
| 867 |
if model.calls != 2 || !strings.Contains(guidance, tc.wantText[0]) || |
| 868 |
!strings.Contains(guidance, tc.wantText[1]) { |
| 869 |
t.Fatalf("queries = %#v", model.got) |
| 870 |
} |
| 871 |
if got := strings.Join(eventDecisions(*events), ","); got != tc.wantEvent { |
| 872 |
t.Fatalf("completion gate decisions = %q", got) |
| 873 |
} |
| 874 |
}) |
| 875 |
} |
| 876 |
|
| 877 |
approval := &fakeModel{responses: []Response{{Turn: weakDone}}} |
| 878 |
approvalAgent := NewAgent(approval, &fakeExecutor{}, "/tmp") |
| 879 |
notify, events := collectEvents() |
| 880 |
approvalAgent.Notify = notify |
| 881 |
if err := approvalAgent.RunWithPolicy( |
| 882 |
context.Background(), |
| 883 |
"finish", |
| 884 |
&scriptedPolicy{}, |
| 885 |
); err != nil { |
| 886 |
t.Fatalf("RunWithPolicy: %v", err) |
| 887 |
} |
| 888 |
if approval.calls != 1 || len(eventDecisions(*events)) != 0 { |
| 889 |
t.Fatalf("approval calls=%d events=%#v", approval.calls, *events) |
| 890 |
} |
| 891 |
} |
| 892 |
|
| 893 |
func TestAgentPublicAPIGuards(t *testing.T) { |
| 894 |
t.Run("default max steps", func(t *testing.T) { |
| 895 |
if got := NewAgent(&fakeModel{}, &fakeExecutor{}, "/tmp").MaxSteps; got != DefaultMaxSteps { |
| 896 |
t.Fatalf("MaxSteps = %d, want %d", got, DefaultMaxSteps) |
| 897 |
} |
| 898 |
}) |
| 899 |
|
| 900 |
t.Run("full-send clarify returns clarification needed", func(t *testing.T) { |
| 901 |
agent := NewAgent( |
| 902 |
&fakeModel{responses: []Response{{Turn: &ClarifyTurn{Question: "Which repo?"}}}}, |
| 903 |
&fakeExecutor{}, |
| 904 |
"/tmp", |
| 905 |
) |
| 906 |
if err := agent.Run( |
| 907 |
context.Background(), |
| 908 |
"inspect", |
| 909 |
); !errors.Is( |
| 910 |
err, |
| 911 |
ErrClarificationNeeded, |
| 912 |
) { |
| 913 |
t.Fatalf("Run error = %v, want ErrClarificationNeeded", err) |
| 914 |
} |
| 915 |
}) |
| 916 |
|
| 917 |
t.Run("value turns from model are accepted", func(t *testing.T) { |
| 918 |
model := &fakeModel{responses: []Response{ |
| 919 |
{Turn: ActTurn{Bash: BashBatch{Commands: []BashAction{{Command: "pwd"}}}}}, |
| 920 |
{Turn: *verifiedDone("done")}, |
| 921 |
}} |
| 922 |
executor := &fakeExecutor{results: []CommandResult{{Stdout: "/tmp\n", ExitCode: 0}}} |
| 923 |
if err := NewAgent(model, executor, "/tmp").Run(context.Background(), "pwd"); err != nil { |
| 924 |
t.Fatalf("Run: %v", err) |
| 925 |
} |
| 926 |
if len(executor.gotCmds) != 1 { |
| 927 |
t.Fatalf("executor calls = %d, want 1", len(executor.gotCmds)) |
| 928 |
} |
| 929 |
}) |
| 930 |
|
| 931 |
t.Run("cancelled context stops run", func(t *testing.T) { |
| 932 |
ctx, cancel := context.WithCancel(context.Background()) |
| 933 |
cancel() |
| 934 |
model := &fakeModel{} |
| 935 |
err := NewAgent(model, &fakeExecutor{}, "/tmp").Run(ctx, "do it") |
| 936 |
if !errors.Is(err, context.Canceled) || model.calls != 0 { |
| 937 |
t.Fatalf("Run error=%v model calls=%d", err, model.calls) |
| 938 |
} |
| 939 |
}) |
| 940 |
|
| 941 |
t.Run("AddMessages seeds caller-owned history before start", func(t *testing.T) { |
| 942 |
agent := NewAgent(&fakeModel{}, &fakeExecutor{}, "/wrong") |
| 943 |
agent.messages = []Message{{Role: "user", Content: "existing"}} |
| 944 |
caller := []Message{ |
| 945 |
{Role: "user", Content: "seed"}, |
| 946 |
{Role: "user", Content: transcript.FormatStateMessage("/restored")}, |
| 947 |
} |
| 948 |
if err := agent.AddMessages(caller); err != nil { |
| 949 |
t.Fatalf("AddMessages: %v", err) |
| 950 |
} |
| 951 |
caller[0].Content = "mutated" |
| 952 |
msgs := agent.Messages() |
| 953 |
if msgs[0].Content != "seed" || msgs[2].Content != "existing" || |
| 954 |
agent.Cwd() != "/restored" { |
| 955 |
t.Fatalf("messages=%#v cwd=%q", msgs, agent.Cwd()) |
| 956 |
} |
| 957 |
agent.AppendUserMessage("started") |
| 958 |
if err := agent.AddMessages([]Message{{Role: "user", Content: "late"}}); err == nil { |
| 959 |
t.Fatal("AddMessages after start succeeded") |
| 960 |
} |
| 961 |
}) |
| 962 |
|
| 963 |
t.Run("ExecuteTurn rejects nil act turns", func(t *testing.T) { |
| 964 |
_, err := NewAgent( |
| 965 |
&fakeModel{}, |
| 966 |
&fakeExecutor{}, |
| 967 |
"/tmp", |
| 968 |
).ExecuteTurn(context.Background(), nil) |
| 969 |
if !errors.Is(err, ErrMissingCommand) { |
| 970 |
t.Fatalf("ExecuteTurn nil error = %v", err) |
| 971 |
} |
| 972 |
}) |
| 973 |
|
| 974 |
t.Run( |
| 975 |
"step-limit final summary uses final query path and canonical transcript", |
| 976 |
func(t *testing.T) { |
| 977 |
model := &fakeFinalModel{fakeModel: fakeModel{responses: []Response{{ |
| 978 |
Raw: `{"turn":{"type":"done","summary":"wrapped"}}`, |
| 979 |
Turn: verifiedDone("wrapped"), |
| 980 |
}}}, mutateFinal: true} |
| 981 |
agent := NewAgent(model, &fakeExecutor{}, "/tmp") |
| 982 |
agent.messages = []Message{ |
| 983 |
{ |
| 984 |
Role: "assistant", |
| 985 |
Content: "previous", |
| 986 |
BashToolCalls: []BashToolCall{{ID: "call_1", Command: "pwd"}}, |
| 987 |
}, |
| 988 |
} |
| 989 |
if err := agent.RequestStepLimitSummary(context.Background()); err != nil { |
| 990 |
t.Fatalf("RequestStepLimitSummary: %v", err) |
| 991 |
} |
| 992 |
got := agent.Messages()[len(agent.Messages())-1].Content |
| 993 |
if !model.finalCalled || agent.Messages()[0].BashToolCalls[0].Command != "pwd" || |
| 994 |
strings.Contains(got, `"turn"`) || |
| 995 |
!strings.Contains(got, `"summary":"wrapped"`) { |
| 996 |
t.Fatalf( |
| 997 |
"finalCalled=%v messages=%#v final=%q", |
| 998 |
model.finalCalled, |
| 999 |
agent.Messages(), |
| 1000 |
got, |
| 1001 |
) |
| 1002 |
} |
| 1003 |
bad := NewAgent( |
| 1004 |
&fakeModel{ |
| 1005 |
responses: []Response{ |
| 1006 |
{Turn: &ActTurn{Bash: BashBatch{Commands: []BashAction{{Command: "pwd"}}}}}, |
| 1007 |
}, |
| 1008 |
}, |
| 1009 |
&fakeExecutor{}, |
| 1010 |
"/tmp", |
| 1011 |
) |
| 1012 |
if err := bad.RequestStepLimitSummary( |
| 1013 |
context.Background(), |
| 1014 |
); err == nil || |
| 1015 |
!strings.Contains(err.Error(), "expected done turn") { |
| 1016 |
t.Fatalf("bad final error = %v", err) |
| 1017 |
} |
| 1018 |
}, |
| 1019 |
) |
| 1020 |
|
| 1021 |
t.Run("Messages returns caller-owned copy", func(t *testing.T) { |
| 1022 |
agent := NewAgent(&fakeModel{}, &fakeExecutor{}, "/tmp") |
| 1023 |
agent.messages = []Message{{ |
| 1024 |
Role: "user", |
| 1025 |
Content: "original", |
| 1026 |
BashToolCalls: []BashToolCall{{ID: "call_1", Command: "pwd"}}, |
| 1027 |
BashToolResult: &BashToolResult{ID: "call_1", Content: "payload"}, |
| 1028 |
ProviderReplay: []ProviderReplayItem{{JSON: json.RawMessage(`["x"]`)}}, |
| 1029 |
}} |
| 1030 |
|
| 1031 |
msgs := agent.Messages() |
| 1032 |
msgs[0].Content = "mutated" |
| 1033 |
msgs[0].BashToolCalls[0].Command = "mutated" |
| 1034 |
msgs[0].BashToolResult.Content = "mutated" |
| 1035 |
msgs[0].ProviderReplay[0].JSON[0] = '{' |
| 1036 |
|
| 1037 |
got := agent.Messages()[0] |
| 1038 |
if got.Content != "original" || got.BashToolCalls[0].Command != "pwd" || |
| 1039 |
got.BashToolResult.Content != "payload" || |
| 1040 |
string(got.ProviderReplay[0].JSON) != `["x"]` { |
| 1041 |
t.Fatalf("stored message was mutated: %#v", got) |
| 1042 |
} |
| 1043 |
}) |
| 1044 |
} |
| 1045 |
|
| 1046 |
func TestCommandBudgetPressure(t *testing.T) { |
| 1047 |
tests := []struct { |
| 1048 |
name string |
| 1049 |
commandsUsed int |
| 1050 |
maxCommands int |
| 1051 |
wantPressure resourcePressure |
| 1052 |
wantGuidance string |
| 1053 |
}{ |
| 1054 |
{name: "disabled", commandsUsed: 4, maxCommands: 0, wantPressure: resourcePressureNormal}, |
| 1055 |
{name: "normal", commandsUsed: 5, maxCommands: 10, wantPressure: resourcePressureNormal}, |
| 1056 |
{ |
| 1057 |
name: "low at rounded quarter", |
| 1058 |
commandsUsed: 7, |
| 1059 |
maxCommands: 10, |
| 1060 |
wantPressure: resourcePressureLow, |
| 1061 |
wantGuidance: "Command budget pressure is low. Prefer targeted checks and edits over broad exploration.", |
| 1062 |
}, |
| 1063 |
{ |
| 1064 |
name: "critical at one remaining", |
| 1065 |
commandsUsed: 9, |
| 1066 |
maxCommands: 10, |
| 1067 |
wantPressure: resourcePressureCritical, |
| 1068 |
wantGuidance: "Command budget pressure is critical. Stop broad exploration, produce the smallest viable result, run one cheap check, then finish.", |
| 1069 |
}, |
| 1070 |
{ |
| 1071 |
name: "critical when exhausted", |
| 1072 |
commandsUsed: 10, |
| 1073 |
maxCommands: 10, |
| 1074 |
wantPressure: resourcePressureCritical, |
| 1075 |
wantGuidance: "Command budget pressure is critical. Stop broad exploration, produce the smallest viable result, run one cheap check, then finish.", |
| 1076 |
}, |
| 1077 |
} |
| 1078 |
|
| 1079 |
for _, tc := range tests { |
| 1080 |
t.Run(tc.name, func(t *testing.T) { |
| 1081 |
got := commandBudgetPressure(tc.commandsUsed, tc.maxCommands) |
| 1082 |
if got != tc.wantPressure { |
| 1083 |
t.Fatalf( |
| 1084 |
"commandBudgetPressure(%d, %d) = %q, want %q", |
| 1085 |
tc.commandsUsed, |
| 1086 |
tc.maxCommands, |
| 1087 |
got, |
| 1088 |
tc.wantPressure, |
| 1089 |
) |
| 1090 |
} |
| 1091 |
if gotGuidance := resourcePressureGuidance(got); gotGuidance != tc.wantGuidance { |
| 1092 |
t.Fatalf( |
| 1093 |
"resourcePressureGuidance(%q) = %q, want %q", |
| 1094 |
got, |
| 1095 |
gotGuidance, |
| 1096 |
tc.wantGuidance, |
| 1097 |
) |
| 1098 |
} |
| 1099 |
}) |
| 1100 |
} |
| 1101 |
} |
| 1102 |
|
| 1103 |
func TestAppendResourceStateMessageIncludesPressure(t *testing.T) { |
| 1104 |
t.Run("budgeted state includes pressure without guidance", func(t *testing.T) { |
| 1105 |
agent := NewAgent(&fakeModel{}, &fakeExecutor{}, "/tmp") |
| 1106 |
agent.MaxSteps = 10 |
| 1107 |
|
| 1108 |
agent.appendResourceStateMessage(8, 6, false) |
| 1109 |
|
| 1110 |
got := agent.Messages()[0].Content |
| 1111 |
for _, want := range []string{ |
| 1112 |
`"type":"resource_state"`, |
| 1113 |
`"commands_used":8`, |
| 1114 |
`"commands_remaining":2`, |
| 1115 |
`"max_commands":10`, |
| 1116 |
`"model_turns_used":6`, |
| 1117 |
`"pressure":"low"`, |
| 1118 |
} { |
| 1119 |
if !strings.Contains(got, want) { |
| 1120 |
t.Fatalf("resource state missing %q: %s", want, got) |
| 1121 |
} |
| 1122 |
} |
| 1123 |
if strings.Contains(got, `"guidance"`) { |
| 1124 |
t.Fatalf("resource state included guidance unexpectedly: %s", got) |
| 1125 |
} |
| 1126 |
}) |
| 1127 |
|
| 1128 |
t.Run("budgeted state includes transition guidance", func(t *testing.T) { |
| 1129 |
agent := NewAgent(&fakeModel{}, &fakeExecutor{}, "/tmp") |
| 1130 |
agent.MaxSteps = 10 |
| 1131 |
|
| 1132 |
agent.appendResourceStateMessage(9, 6, true) |
| 1133 |
|
| 1134 |
got := agent.Messages()[0].Content |
| 1135 |
for _, want := range []string{ |
| 1136 |
`"pressure":"critical"`, |
| 1137 |
`"guidance":"Command budget pressure is critical. Stop broad exploration, produce the smallest viable result, run one cheap check, then finish."`, |
| 1138 |
} { |
| 1139 |
if !strings.Contains(got, want) { |
| 1140 |
t.Fatalf("resource state missing %q: %s", want, got) |
| 1141 |
} |
| 1142 |
} |
| 1143 |
}) |
| 1144 |
|
| 1145 |
t.Run("unbudgeted state keeps existing fields only", func(t *testing.T) { |
| 1146 |
agent := NewAgent(&fakeModel{}, &fakeExecutor{}, "/tmp") |
| 1147 |
agent.MaxSteps = 0 |
| 1148 |
|
| 1149 |
agent.appendResourceStateMessage(8, 6, true) |
| 1150 |
|
| 1151 |
got := agent.Messages()[0].Content |
| 1152 |
for _, notWant := range []string{`"commands_remaining"`, `"max_commands"`, `"pressure"`, `"guidance"`} { |
| 1153 |
if strings.Contains(got, notWant) { |
| 1154 |
t.Fatalf("unbudgeted resource state included %q: %s", notWant, got) |
| 1155 |
} |
| 1156 |
} |
| 1157 |
}) |
| 1158 |
} |
| 1159 |
|
| 1160 |
func TestAgentCompactFacade(t *testing.T) { |
| 1161 |
seed := []Message{ |
| 1162 |
{Role: "user", Content: "first"}, |
| 1163 |
{Role: "assistant", Content: `{"type":"done","summary":"first"}`}, |
| 1164 |
{Role: "user", Content: transcript.FormatStateMessage("/restored")}, |
| 1165 |
{Role: "user", Content: "second"}, |
| 1166 |
{Role: "assistant", Content: `{"type":"done","summary":"second"}`}, |
| 1167 |
{Role: "user", Content: "third"}, |
| 1168 |
} |
| 1169 |
agent := NewAgent(&fakeModel{}, &fakeExecutor{}, "/wrong") |
| 1170 |
if err := agent.AddMessages(seed); err != nil { |
| 1171 |
t.Fatalf("AddMessages: %v", err) |
| 1172 |
} |
| 1173 |
stats, err := agent.Compact( |
| 1174 |
context.Background(), |
| 1175 |
&fakeCompactor{summary: " older work "}, |
| 1176 |
CompactOptions{KeepRecentTurns: 2}, |
| 1177 |
) |
| 1178 |
if err != nil { |
| 1179 |
t.Fatalf("Compact: %v", err) |
| 1180 |
} |
| 1181 |
if stats.CompactedMessages != 3 || agent.Cwd() != "/restored" || |
| 1182 |
!strings.Contains(agent.Messages()[0].Content, "older work") { |
| 1183 |
t.Fatalf("stats=%#v cwd=%q messages=%#v", stats, agent.Cwd(), agent.Messages()) |
| 1184 |
} |
| 1185 |
|
| 1186 |
before := agent.Messages() |
| 1187 |
compactor := &fakeCompactor{summary: "summary"} |
| 1188 |
if _, err := agent.Compact( |
| 1189 |
context.Background(), |
| 1190 |
compactor, |
| 1191 |
CompactOptions{KeepRecentTurns: -1}, |
| 1192 |
); err == nil || |
| 1193 |
len(compactor.got) != 0 { |
| 1194 |
t.Fatalf("negative keep recent: err=%v calls=%d", err, len(compactor.got)) |
| 1195 |
} |
| 1196 |
if _, err := agent.Compact( |
| 1197 |
context.Background(), |
| 1198 |
&fakeCompactor{summary: " \n"}, |
| 1199 |
CompactOptions{KeepRecentTurns: 2}, |
| 1200 |
); err == nil || |
| 1201 |
messagesText(agent.Messages()) != messagesText(before) { |
| 1202 |
t.Fatalf("empty summary err=%v messages=%#v", err, agent.Messages()) |
| 1203 |
} |
| 1204 |
} |
| 1205 |
|
| 1206 |
type fakeModel struct { |
| 1207 |
responses []Response |
| 1208 |
errs []error |
| 1209 |
calls int |
| 1210 |
responseCalls int |
| 1211 |
got [][]Message |
| 1212 |
} |
| 1213 |
|
| 1214 |
func (m *fakeModel) Query(_ context.Context, messages []Message) (Response, error) { |
| 1215 |
m.got = append(m.got, transcript.CloneMessages(messages)) |
| 1216 |
call := m.calls |
| 1217 |
m.calls++ |
| 1218 |
if call < len(m.errs) && m.errs[call] != nil { |
| 1219 |
return Response{}, m.errs[call] |
| 1220 |
} |
| 1221 |
if m.responseCalls >= len(m.responses) { |
| 1222 |
return Response{}, fmt.Errorf("no more responses") |
| 1223 |
} |
| 1224 |
resp := m.responses[m.responseCalls] |
| 1225 |
m.responseCalls++ |
| 1226 |
return resp, nil |
| 1227 |
} |
| 1228 |
|
| 1229 |
type mutatingModel struct{} |
| 1230 |
|
| 1231 |
func (mutatingModel) Query(_ context.Context, messages []Message) (Response, error) { |
| 1232 |
messages[0].BashToolCalls[0].Command, messages[0].ProviderReplay[0].JSON[0] = "mutated", '{' |
| 1233 |
return Response{Turn: verifiedDone("done")}, nil |
| 1234 |
} |
| 1235 |
|
| 1236 |
type fakeFinalModel struct { |
| 1237 |
fakeModel |
| 1238 |
finalCalled bool |
| 1239 |
mutateFinal bool |
| 1240 |
} |
| 1241 |
|
| 1242 |
func (m *fakeFinalModel) QueryFinal(ctx context.Context, messages []Message) (Response, error) { |
| 1243 |
m.finalCalled = true |
| 1244 |
if m.mutateFinal { |
| 1245 |
messages[0].BashToolCalls[0].Command = "mutated" |
| 1246 |
} |
| 1247 |
return m.Query(ctx, messages) |
| 1248 |
} |
| 1249 |
|
| 1250 |
type fakeCompactor struct { |
| 1251 |
summary string |
| 1252 |
err error |
| 1253 |
got [][]Message |
| 1254 |
} |
| 1255 |
|
| 1256 |
func (c *fakeCompactor) Summarize(_ context.Context, messages []Message) (string, error) { |
| 1257 |
c.got = append(c.got, transcript.CloneMessages(messages)) |
| 1258 |
if c.err != nil { |
| 1259 |
return "", c.err |
| 1260 |
} |
| 1261 |
return c.summary, nil |
| 1262 |
} |
| 1263 |
|
| 1264 |
func countUserMessages(messages []Message, content string) int { |
| 1265 |
count := 0 |
| 1266 |
for _, msg := range messages { |
| 1267 |
if msg.Role == "user" && msg.Content == content { |
| 1268 |
count++ |
| 1269 |
} |
| 1270 |
} |
| 1271 |
return count |
| 1272 |
} |
| 1273 |
|
| 1274 |
type fakeExecutor struct { |
| 1275 |
results []CommandResult |
| 1276 |
errs []error |
| 1277 |
gotCmds []string |
| 1278 |
gotDirs []string |
| 1279 |
gotEnv []map[string]string |
| 1280 |
} |
| 1281 |
|
| 1282 |
func (e *fakeExecutor) Execute(_ context.Context, command, dir string) (CommandResult, error) { |
| 1283 |
e.gotCmds = append(e.gotCmds, command) |
| 1284 |
e.gotDirs = append(e.gotDirs, dir) |
| 1285 |
idx := len(e.gotCmds) - 1 |
| 1286 |
if idx >= len(e.results) { |
| 1287 |
return CommandResult{}, fmt.Errorf("no more results") |
| 1288 |
} |
| 1289 |
result := e.results[idx] |
| 1290 |
if result.Command == "" { |
| 1291 |
result.Command = command |
| 1292 |
} |
| 1293 |
var err error |
| 1294 |
if idx < len(e.errs) { |
| 1295 |
err = e.errs[idx] |
| 1296 |
} |
| 1297 |
return result, err |
| 1298 |
} |
| 1299 |
|
| 1300 |
func (e *fakeExecutor) SetEnv(env map[string]string) { |
| 1301 |
cp := make(map[string]string, len(env)) |
| 1302 |
for k, v := range env { |
| 1303 |
cp[k] = v |
| 1304 |
} |
| 1305 |
e.gotEnv = append(e.gotEnv, cp) |
| 1306 |
} |
| 1307 |
|
| 1308 |
type scriptedPolicy struct { |
| 1309 |
decisions []ActDecision |
| 1310 |
clarifies []string |
| 1311 |
proposals []ActProposal |
| 1312 |
questions []string |
| 1313 |
decideErr error |
| 1314 |
} |
| 1315 |
|
| 1316 |
func (p *scriptedPolicy) DecideAct(_ context.Context, proposal ActProposal) (ActDecision, error) { |
| 1317 |
p.proposals = append(p.proposals, proposal) |
| 1318 |
if p.decideErr != nil { |
| 1319 |
return ActDecision{}, p.decideErr |
| 1320 |
} |
| 1321 |
if len(p.decisions) == 0 { |
| 1322 |
return ActDecision{Kind: ActDecisionApprove}, nil |
| 1323 |
} |
| 1324 |
decision := p.decisions[0] |
| 1325 |
p.decisions = p.decisions[1:] |
| 1326 |
return decision, nil |
| 1327 |
} |
| 1328 |
|
| 1329 |
func (p *scriptedPolicy) Clarify(_ context.Context, question string) (string, error) { |
| 1330 |
p.questions = append(p.questions, question) |
| 1331 |
if len(p.clarifies) == 0 { |
| 1332 |
return "", ErrClarificationNeeded |
| 1333 |
} |
| 1334 |
reply := p.clarifies[0] |
| 1335 |
p.clarifies = p.clarifies[1:] |
| 1336 |
return reply, nil |
| 1337 |
} |
| 1338 |
|
| 1339 |
func verifiedDone(summary string) *DoneTurn { |
| 1340 |
return &DoneTurn{ |
| 1341 |
Summary: summary, |
| 1342 |
Verification: CompletionVerification{ |
| 1343 |
Status: VerificationVerified, |
| 1344 |
Checks: []VerificationCheck{ |
| 1345 |
{ |
| 1346 |
Command: "go test ./...", |
| 1347 |
Outcome: "passed", |
| 1348 |
Evidence: "tests passed and expected files exist", |
| 1349 |
}, |
| 1350 |
}, |
| 1351 |
}, |
| 1352 |
KnownRisks: []string{}, |
| 1353 |
} |
| 1354 |
} |
| 1355 |
|
| 1356 |
func collectEvents() (func(Event), *[]Event) { |
| 1357 |
var events []Event |
| 1358 |
return func(e Event) { events = append(events, e) }, &events |
| 1359 |
} |
| 1360 |
|
| 1361 |
func hasEvent[T Event](events []Event) bool { |
| 1362 |
_, ok := firstEvent[T](events) |
| 1363 |
return ok |
| 1364 |
} |
| 1365 |
|
| 1366 |
func firstEvent[T Event](events []Event) (T, bool) { |
| 1367 |
for _, event := range events { |
| 1368 |
if ev, ok := event.(T); ok { |
| 1369 |
return ev, true |
| 1370 |
} |
| 1371 |
} |
| 1372 |
var zero T |
| 1373 |
return zero, false |
| 1374 |
} |
| 1375 |
|
| 1376 |
func eventDecisions(events []Event) []string { |
| 1377 |
var decisions []string |
| 1378 |
for _, event := range events { |
| 1379 |
if ev, ok := event.(EventCompletionGate); ok { |
| 1380 |
decisions = append(decisions, ev.Decision) |
| 1381 |
} |
| 1382 |
} |
| 1383 |
return decisions |
| 1384 |
} |
| 1385 |
|
| 1386 |
func hasMessage(messages []Message, role, content string) bool { |
| 1387 |
for _, msg := range messages { |
| 1388 |
if msg.Role == role && msg.Content == content { |
| 1389 |
return true |
| 1390 |
} |
| 1391 |
} |
| 1392 |
return false |
| 1393 |
} |
| 1394 |
|
| 1395 |
func messagesText(messages []Message) string { |
| 1396 |
var b strings.Builder |
| 1397 |
for _, msg := range messages { |
| 1398 |
b.WriteString(msg.Content) |
| 1399 |
b.WriteByte('\n') |
| 1400 |
} |
| 1401 |
return b.String() |
| 1402 |
} |
| 1403 |
|
| 1404 |
func collectToolResults(messages []Message) []BashToolResult { |
| 1405 |
var results []BashToolResult |
| 1406 |
for _, msg := range messages { |
| 1407 |
if msg.BashToolResult != nil { |
| 1408 |
results = append(results, *msg.BashToolResult) |
| 1409 |
} |
| 1410 |
} |
| 1411 |
return results |
| 1412 |
} |
| 1413 |
|
| 1414 |
func payloadOutcome(t *testing.T, raw string) CommandOutcomeType { |
| 1415 |
t.Helper() |
| 1416 |
var payload struct { |
| 1417 |
Outcome CommandOutcome `json:"outcome"` |
| 1418 |
} |
| 1419 |
if err := json.Unmarshal([]byte(raw), &payload); err != nil { |
| 1420 |
t.Fatalf("payload is not JSON: %v\n%s", err, raw) |
| 1421 |
} |
| 1422 |
return payload.Outcome.Type |
| 1423 |
} |