ag-agent 0.16.7

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
use std::collections::HashSet;
use std::future;
use std::time::{Duration, SystemTime};

use ag_session::AgentKind;
use ag_telemetry::{CaptureToolContent, Context, FutureExt as _, Outcome, Span};
use opentelemetry::{KeyValue, global};
use opentelemetry_sdk::trace::{InMemorySpanExporter, SdkTracerProvider, SpanData};
use serde_json::{Value, json};
use tokio::sync::oneshot;

use crate::agent::trace::{MAX_OPERATIONS, OperationTrace};
use crate::telemetry::TRACER_PROVIDER_LOCK;

#[tokio::test]
async fn provider_tool_metadata_and_content_follow_the_host_policy() {
    // Arrange
    let fixtures = [
        (
            AgentKind::Codex,
            vec![
                json!({"method": "item/started", "params": {"item": {"id": "call-1", "type": "commandExecution", "command": "cargo test"}}}),
                json!({"method": "item/completed", "params": {"item": {"id": "call-1", "type": "commandExecution", "aggregatedOutput": "test failed", "exitCode": 1}}}),
            ],
            None,
        ),
        (
            AgentKind::Claude,
            vec![
                json!({"type": "message", "content": [{"type": "tool_use", "id": "call-1", "name": "Bash", "input": {"command": "cargo test"}}]}),
                json!({"type": "message", "content": [{"type": "tool_result", "tool_use_id": "call-1", "content": "test failed", "is_error": true}]}),
            ],
            Some("Bash"),
        ),
        (
            AgentKind::Gemini,
            vec![
                gemini(
                    &json!({"sessionUpdate": "tool_call", "toolCallId": "call-1", "kind": "execute", "name": "run_shell_command", "rawInput": {"command": "cargo test"}, "title": "Private tool title"}),
                ),
                gemini(
                    &json!({"sessionUpdate": "tool_call_update", "toolCallId": "call-1", "status": "failed", "rawOutput": "test failed"}),
                ),
            ],
            Some("run_shell_command"),
        ),
    ];

    // Act / Assert
    for (kind, events, name) in fixtures {
        for capture in [false, true] {
            let spans = capture_with_policy(kind, events.clone(), capture).await;
            assert_children(&spans, 1);
            let tool = spans
                .iter()
                .find(|span| span.name == "agent.tool")
                .expect("tool");
            for attribute in [
                KeyValue::new("gen_ai.tool.call.id", "call-1"),
                KeyValue::new("process.executable.name", "cargo"),
                KeyValue::new("agentty.tool.output.bytes", 11_i64),
                KeyValue::new("agentty.outcome", "failed"),
            ] {
                assert!(
                    tool.attributes.contains(&attribute),
                    "{kind:?}: {attribute:?}"
                );
            }
            if let Some(name) = name {
                assert!(
                    tool.attributes
                        .contains(&KeyValue::new("gen_ai.tool.name", name))
                );
            } else {
                assert!(
                    !tool
                        .attributes
                        .iter()
                        .any(|attribute| attribute.key.as_str() == "gen_ai.tool.name")
                );
            }
            assert_eq!(
                tool.attributes
                    .contains(&KeyValue::new("agentty.tool.command", "cargo test")),
                capture
            );
            assert_eq!(
                tool.attributes
                    .contains(&KeyValue::new("gen_ai.tool.call.result", "test failed")),
                capture
            );
            if kind != AgentKind::Codex {
                assert_eq!(
                    tool.attributes.contains(&KeyValue::new(
                        "gen_ai.tool.call.arguments",
                        r#"{"command":"cargo test"}"#
                    )),
                    capture
                );
            }
            assert!(!format!("{spans:?}").contains("Private tool title"));
        }
    }
}

#[tokio::test]
async fn codex_dynamic_results_and_mcp_errors_use_the_wire_fields() {
    // Arrange
    let dynamic_output = json!([{"type": "inputText", "text": "ok"}]);
    let mcp_error = json!({"message": "Tool disconnected"});
    let events = vec![
        json!({"method": "item/completed", "params": {"item": {"id": "dynamic", "type": "dynamicToolCall", "tool": "lookup", "arguments": {"query": "example"}, "contentItems": dynamic_output, "success": true}}}),
        json!({"method": "item/completed", "params": {"item": {"id": "mcp-error", "type": "mcpToolCall", "tool": "lookup", "arguments": {}, "result": null, "error": mcp_error, "status": "failed"}}}),
    ];

    // Act / Assert
    for capture in [false, true] {
        let spans = capture_with_policy(AgentKind::Codex, events.clone(), capture).await;
        for (id, output) in [("dynamic", &dynamic_output), ("mcp-error", &mcp_error)] {
            let tool = spans
                .iter()
                .find(|span| {
                    span.attributes
                        .contains(&KeyValue::new("gen_ai.tool.call.id", id))
                })
                .expect("tool");
            assert!(tool.attributes.contains(&KeyValue::new(
                "agentty.tool.output.bytes",
                i64::try_from(output.to_string().len()).expect("fixture size")
            )));
            assert_eq!(
                tool.attributes.contains(&KeyValue::new(
                    "gen_ai.tool.call.result",
                    output.to_string()
                )),
                capture
            );
            assert!(tool.attributes.contains(&KeyValue::new(
                "agentty.outcome",
                if id == "dynamic" {
                    "completed"
                } else {
                    "failed"
                }
            )));
        }
    }
}

#[tokio::test]
async fn gemini_content_fallback_and_separate_streams_keep_partial_update_metadata() {
    // Arrange
    let events = vec![
        gemini(
            &json!({"sessionUpdate": "tool_call", "toolCallId": "streams", "kind": "execute", "rawInput": {"command": "cargo test"}}),
        ),
        gemini(
            &json!({"sessionUpdate": "tool_call_update", "toolCallId": "streams", "status": "failed", "rawOutput": {"stdout": "building", "stderr": "compilation failed"}}),
        ),
        gemini(
            &json!({"sessionUpdate": "tool_call_update", "toolCallId": "fallback", "status": "completed", "rawOutput": null, "content": [{"type": "content", "content": {"type": "text", "text": "ok"}}]}),
        ),
    ];

    // Act / Assert
    for capture in [false, true] {
        let spans = capture_with_policy(AgentKind::Gemini, events.clone(), capture).await;
        let tool = spans
            .iter()
            .find(|span| {
                span.attributes
                    .contains(&KeyValue::new("gen_ai.tool.call.id", "streams"))
            })
            .expect("streams");
        assert!(
            tool.attributes
                .contains(&KeyValue::new("agentty.provider.operation.type", "command"))
        );
        assert!(
            tool.attributes
                .contains(&KeyValue::new("agentty.tool.stderr.bytes", 18_i64))
        );
        assert_eq!(
            tool.attributes
                .contains(&KeyValue::new("agentty.tool.stderr", "compilation failed")),
            capture
        );
        assert_eq!(
            tool.attributes
                .contains(&KeyValue::new("agentty.tool.stdout", "building")),
            capture
        );
        let fallback = spans
            .iter()
            .find(|span| {
                span.attributes
                    .contains(&KeyValue::new("gen_ai.tool.call.id", "fallback"))
            })
            .expect("fallback");
        assert_eq!(
            fallback
                .attributes
                .iter()
                .any(|attribute| attribute.key.as_str() == "gen_ai.tool.call.result"),
            capture
        );
    }
}

#[tokio::test]
async fn content_capture_never_exports_response_reasoning_or_subagent_prompts() {
    // Arrange
    let codex = vec![
        json!({"method": "item/completed", "params": {"item": {"id": "reasoning", "type": "reasoning", "text": "Private thought", "arguments": "Private thought"}}}),
        json!({"method": "item/completed", "params": {"item": {"id": "response", "type": "agentMessage", "text": "Private response"}}}),
        json!({"method": "item/completed", "params": {"item": {"id": "mcp", "type": "mcpToolCall", "tool": "lookup", "arguments": {"token": "Private credential"}, "result": {"content": ["ok"]}}}}),
        json!({"method": "item/completed", "params": {"item": {"id": "dynamic", "type": "dynamicToolCall", "tool": "lookup", "arguments": {"query": "example"}, "contentItems": [{"type": "inputText", "text": "ok"}]}}}),
    ];
    let claude = vec![json!({"type": "message", "content": [
        {"type": "tool_use", "id": "agent", "name": "Agent", "input": {"prompt": "Private prompt"}},
        {"type": "tool_use", "id": "structured", "name": "StructuredOutput", "input": {"answer": "Private response"}},
    ]})];
    let antigravity_events = vec![antigravity(
        &json!({"step_index": 1, "step_type": "tool", "state": "DONE", "tool_name": "shell", "tool_info": {"command": "Private command", "output": "Private output"}}),
    )];

    // Act / Assert
    for (kind, events) in [
        (AgentKind::Codex, codex),
        (AgentKind::Claude, claude),
        (AgentKind::Antigravity, antigravity_events),
    ] {
        let spans = capture_with_policy(kind, events, true).await;
        assert!(!format!("{spans:?}").contains("Private"));
        if kind == AgentKind::Codex {
            assert!(spans.iter().any(|span| {
                span.attributes.contains(&KeyValue::new(
                    "gen_ai.tool.call.arguments",
                    r#""[REDACTED]""#,
                ))
            }));
            assert!(spans.iter().any(|span| {
                span.attributes
                    .contains(&KeyValue::new("gen_ai.tool.name", "lookup"))
            }));
        }
    }
}

#[tokio::test]
async fn codex_operations_keep_attempt_parentage_outcomes_and_numeric_metadata() {
    // Arrange
    let types = [
        "commandExecution",
        "command_execution",
        "fileChange",
        "file_change",
        "mcpToolCall",
        "mcp_tool_call",
        "dynamicToolCall",
        "dynamic_tool_call",
        "webSearch",
        "web_search",
        "reasoning",
        "agentMessage",
        "agent_message",
        "contextCompaction",
        "context_compaction",
        "collabAgentToolCall",
        "collab_agent_tool_call",
        "imageGeneration",
        "image_generation",
    ];
    let mut events = Vec::new();
    for (index, item_type) in types.into_iter().enumerate() {
        let item = json!({"id": index.to_string(), "type": item_type, "command": "cargo test private command", "arguments": "private arguments", "text": "private text"});
        let started = json!({"method": "item/started", "params": {"item": item}});
        events.push(started.clone());
        events.push(started);
        let completed = json!({"method": "item/completed", "params": {"item": {
            "id": index.to_string(), "type": item_type, "exitCode": 0, "durationMs": 25,
            "aggregatedOutput": "private output", "error": null,
        }}});
        events.push(completed.clone());
        events.push(completed);
    }
    for (index, extra) in [
        json!({"status": "failed"}),
        json!({"status": "declined"}),
        json!({"status": "denied"}),
        json!({"success": false}),
        json!({"error": {"message": "private error"}}),
        json!({"exitCode": 7}),
        json!({"status": "canceled"}),
        json!({"status": "cancelled"}),
        json!({"status": "interrupted"}),
    ]
    .into_iter()
    .enumerate()
    {
        let mut item = json!({"id": format!("terminal-{index}"), "type": "mcpToolCall"});
        item.as_object_mut()
            .expect("item")
            .extend(extra.as_object().expect("extra").clone());
        events.push(json!({"method": "item/completed", "params": {"item": item}}));
    }

    // Act
    let spans = capture(AgentKind::Codex, events).await;

    // Assert
    assert_children(&spans, types.len() + 9);
    assert_eq!(
        spans
            .iter()
            .filter(|span| span
                .attributes
                .contains(&KeyValue::new("agentty.timing.source", "lifecycle")))
            .count(),
        types.len()
    );
    for name in [
        "agent.tool",
        "agent.response",
        "agent.reasoning",
        "agent.compaction",
        "agent.subagent",
    ] {
        assert!(spans.iter().any(|span| span.name == name));
    }
    let outcomes = outcomes(&spans);
    assert_eq!(
        outcomes.iter().filter(|value| **value == "failed").count(),
        6
    );
    assert_eq!(
        outcomes
            .iter()
            .filter(|value| **value == "canceled")
            .count(),
        3
    );
    assert!(spans.iter().any(|span| {
        span.attributes
            .contains(&KeyValue::new("agentty.provider.duration_ms", 25.0))
    }));
    assert!(!format!("{spans:?}").contains("private"));
}

#[tokio::test]
async fn gemini_updates_retain_original_category_and_finish_partial_payloads() {
    // Arrange
    let mut events = Vec::new();
    for (index, kind) in [
        "read",
        "edit",
        "execute",
        "search",
        "fetch",
        "private custom kind",
    ]
    .into_iter()
    .enumerate()
    {
        events.push(gemini(&json!({"sessionUpdate": "tool_call", "toolCallId": index.to_string(), "kind": kind, "status": "pending", "title": "private title", "rawInput": "private input"})));
        events.push(gemini(&json!({"sessionUpdate": "tool_call_update", "toolCallId": index.to_string(), "status": "in_progress"})));
        events.push(gemini(&json!({"sessionUpdate": "tool_call_update", "toolCallId": index.to_string(), "status": "completed", "content": "private output"})));
    }
    for status in ["failed", "canceled", "cancelled"] {
        events.push(gemini(
            &json!({"sessionUpdate": "tool_call_update", "toolCallId": status, "status": status}),
        ));
    }

    // Act
    let spans = capture(AgentKind::Gemini, events).await;

    // Assert
    assert_children(&spans, 9);
    for category in ["read", "file_change", "command", "search", "fetch", "tool"] {
        assert!(spans.iter().any(|span| {
            span.attributes
                .contains(&KeyValue::new("agentty.provider.operation.type", category))
        }));
    }
    assert!(!format!("{spans:?}").contains("private"));
}

#[tokio::test]
async fn antigravity_steps_preserve_reported_durations_and_usage_without_content() {
    // Arrange
    let mut events = Vec::new();
    for (index, kind) in [
        "tool",
        "agent_response",
        "reasoning",
        "thought",
        "context_compaction",
        "context-compaction",
        "context_compression",
        "checkpoint",
    ]
    .into_iter()
    .enumerate()
    {
        events.push(antigravity(&json!({"step_index": index, "step_type": kind, "state": "ACTIVE", "tool_name": "private tool"})));
        events.push(antigravity(&json!({"step_index": index, "step_type": kind, "state": "DONE", "duration_seconds": 0.25,
            "usage": {"input_tokens": 20, "output_tokens": 3, "cache_read_tokens": 4, "thinking_tokens": 2},
            "tool_info": {"output": "private output", "parameters": "private parameters"}, "text_delta": "private text"
        })));
    }
    events.push(antigravity(&json!({"step_index": 10, "step_type": "tool", "state": "done", "tool_info": {"error": {"message": "private error"}}})));
    events.push(antigravity(&json!({"step_index": 11, "step_type": "agent_response", "state": "done", "duration_seconds": 0.1})));
    events.push(antigravity(&json!({"step_index": 12, "step_type": "tool", "state": "done", "subagent_info": {"prompt": "private prompt"}, "usage": {"input_tokens": -1, "output_tokens": u64::MAX, "cache_read_tokens": "private tokens"}})));

    // Act
    let spans = capture(AgentKind::Antigravity, events).await;

    // Assert
    assert_children(&spans, 11);
    assert!(spans.iter().any(|span| span.name == "agent.checkpoint"));
    let subagent = spans
        .iter()
        .find(|span| span.name == "agent.subagent")
        .expect("subagent");
    assert!(
        !subagent
            .attributes
            .iter()
            .any(|attribute| attribute.key.as_str().starts_with("gen_ai.usage"))
    );
    assert!(spans.iter().any(|span| {
        span.attributes
            .contains(&KeyValue::new("agentty.provider.duration_ms", 250.0))
    }));
    for (key, count) in [
        ("gen_ai.usage.input_tokens", 20),
        ("gen_ai.usage.output_tokens", 3),
        ("gen_ai.usage.cache_read.input_tokens", 4),
        ("gen_ai.usage.reasoning.output_tokens", 2),
    ] {
        assert!(
            spans
                .iter()
                .any(|span| span.attributes.contains(&KeyValue::new(key, count)))
        );
    }
    assert!(!format!("{spans:?}").contains("private"));
}

#[tokio::test]
async fn claude_tool_messages_pair_calls_with_results_without_content() {
    // Arrange
    let mut events = Vec::new();
    for (index, name) in [
        "Bash",
        "Read",
        "Edit",
        "Write",
        "MultiEdit",
        "Grep",
        "Glob",
        "WebFetch",
        "WebSearch",
        "Agent",
        "Task",
        "private custom tool",
    ]
    .into_iter()
    .enumerate()
    {
        events.push(json!({"type": "assistant", "message": {"content": [{"type": "tool_use", "id": index.to_string(), "name": name, "input": "private input"}]}}));
        events.push(json!({"type": "user", "message": {"content": [{"type": "tool_result", "tool_use_id": index.to_string(), "is_error": index == 0, "content": "private output"}]}}));
    }

    // Act
    let spans = capture(AgentKind::Claude, events).await;

    // Assert
    assert_children(&spans, 12);
    assert!(outcomes(&spans).contains(&"failed"));
    assert!(!format!("{spans:?}").contains("private"));
}

#[tokio::test]
async fn claude_direct_and_wrapped_tool_messages_pair_across_formats() {
    // Arrange
    let mut events = Vec::new();
    for (index, (direct_call, direct_result)) in
        [(true, true), (true, false), (false, true), (false, false)]
            .into_iter()
            .enumerate()
    {
        let call = json!({"type": "message", "role": "assistant", "content": [
            {"type": "text", "text": "private explanation"},
            {"type": "tool_use", "id": index.to_string(), "name": "Bash", "input": {"command": "cargo test private command"}},
        ]});
        let result = json!({"type": "message", "role": "user", "content": [
            {"type": "tool_result", "tool_use_id": index.to_string(), "is_error": index == 0, "content": "private output"},
        ]});
        events.push(if direct_call {
            call
        } else {
            json!({"type": "assistant", "message": call})
        });
        let completed = if direct_result {
            result
        } else {
            json!({"type": "user", "message": result})
        };
        events.push(completed.clone());
        events.push(completed);
    }

    // Act
    let spans = capture(AgentKind::Claude, events).await;

    // Assert
    assert_children(&spans, 4);
    assert!(!format!("{spans:?}").contains("private"));
    let tools = spans
        .into_iter()
        .filter(|span| span.name == "agent.tool")
        .collect::<Vec<_>>();
    assert_eq!(tools.len(), 4);
    for span in &tools {
        assert!(
            span.attributes
                .contains(&KeyValue::new("agentty.provider.operation.type", "command"))
        );
        assert!(
            span.attributes
                .contains(&KeyValue::new("agentty.timing.source", "lifecycle"))
        );
    }
    let outcomes = outcomes(&tools);
    assert_eq!(
        outcomes
            .iter()
            .filter(|outcome| **outcome == "completed")
            .count(),
        3
    );
    assert_eq!(
        outcomes
            .iter()
            .filter(|outcome| **outcome == "failed")
            .count(),
        1
    );
}

#[tokio::test]
async fn malformed_unknown_and_unrelated_provider_events_are_ignored() {
    // Arrange
    let fixtures = [
        (
            AgentKind::Codex,
            vec![
                json!({}),
                json!({"method": "other"}),
                json!({"method": "item/started"}),
                json!({"method": "item/started", "params": {"item": {}}}),
                json!({"method": "item/started", "params": {"item": {"id": "one", "type": "unknown"}}}),
            ],
        ),
        (
            AgentKind::Gemini,
            vec![
                json!({}),
                json!({"method": "session/update"}),
                gemini(&json!({"sessionUpdate": "agent_message_chunk"})),
                gemini(&json!({"sessionUpdate": "tool_call"})),
            ],
        ),
        (
            AgentKind::Antigravity,
            vec![
                json!({}),
                json!({"event": "step_update"}),
                antigravity(&json!({})),
                antigravity(&json!({"step_index": 0, "step_type": "user_input"})),
                antigravity(&json!({"step_index": 0, "step_type": "tool", "state": "unknown"})),
            ],
        ),
        (
            AgentKind::Claude,
            vec![
                json!({}),
                json!({"message": {}}),
                json!({"type": "message", "content": "private non-array content"}),
                json!({"type": "message", "content": [{"type": "text"}, {"type": "tool_use"}, {"type": "tool_result"}]}),
                json!({"type": "result", "content": [{"type": "tool_use", "id": "unrelated", "name": "Bash"}]}),
                json!({"message": {"content": [{"type": "text"}, {"type": "tool_use"}, {"type": "tool_result"}]}}),
            ],
        ),
    ];

    // Act / Assert
    for (kind, events) in fixtures {
        assert_children(&capture(kind, events).await, 0);
    }
}

#[tokio::test]
async fn pending_operations_close_when_the_attempt_future_is_canceled() {
    // Arrange
    let _guard = TRACER_PROVIDER_LOCK.lock().await;
    let exporter = install_provider();
    let (ready_tx, ready_rx) = oneshot::channel();
    let root = Span::root("agent.attempt", Vec::new());

    // Act
    let task = tokio::spawn(root.scope(async move {
        let mut trace = OperationTrace::new();
        trace.observe(AgentKind::Gemini, &gemini(&json!({"sessionUpdate": "tool_call", "toolCallId": "unfinished", "kind": "execute"})));
        let _ = ready_tx.send(());
        future::pending::<()>().await;
    }));
    ready_rx.await.expect("operation started");
    task.abort();
    let _ = task.await;

    // Assert
    let spans = exporter.get_finished_spans().expect("spans");
    assert_children(&spans, 1);
    assert!(
        outcomes(&spans)
            .iter()
            .all(|outcome| *outcome == "canceled")
    );
}

#[tokio::test]
async fn reconstructed_and_observed_intervals_are_distinguished_and_bounded() {
    // Arrange
    let _guard = TRACER_PROVIDER_LOCK.lock().await;
    let exporter = install_provider();
    let started_at = SystemTime::now() - Duration::from_secs(1);
    let root = Span::child_at("agent.attempt", started_at);

    // Act
    root.scope(async {
        let mut trace = OperationTrace::new();
        trace.started_at = started_at;
        trace.record(
            "reported",
            "command",
            Some(Outcome::Completed),
            Some(125.0),
            Vec::new(),
        );
        trace.record(
            "clamped",
            "tool",
            Some(Outcome::Completed),
            Some(2000.0),
            Vec::new(),
        );
        trace.record(
            "negative",
            "tool",
            Some(Outcome::Completed),
            Some(-1.0),
            Vec::new(),
        );
        trace.record(
            "nan",
            "tool",
            Some(Outcome::Completed),
            Some(f64::NAN),
            Vec::new(),
        );
        trace.record(
            "overflow",
            "tool",
            Some(Outcome::Completed),
            Some(f64::MAX),
            Vec::new(),
        );
        trace.record("", "tool", None, None, Vec::new());
        trace.record(&"x".repeat(257), "tool", None, None, Vec::new());
        trace.observe_line(AgentKind::Claude, b"invalid json");
    })
    .await;

    // Assert
    let spans = exporter.get_finished_spans().expect("spans");
    assert_children(&spans, 5);
    let reported = spans
        .iter()
        .find(|span| {
            span.attributes
                .contains(&KeyValue::new("agentty.provider.duration_ms", 125.0))
        })
        .expect("reconstructed interval");
    assert!(
        reported
            .attributes
            .contains(&KeyValue::new("agentty.timing.source", "provider"))
    );
    assert!(
        reported
            .end_time
            .duration_since(reported.start_time)
            .expect("ordered times")
            >= Duration::from_millis(125)
    );
    let clamped = spans
        .iter()
        .find(|span| {
            span.attributes
                .contains(&KeyValue::new("agentty.provider.duration_ms", 2000.0))
        })
        .expect("clamped interval");
    assert_eq!(clamped.start_time, started_at);
    for span in &spans {
        assert!(span.start_time >= started_at);
    }
    assert_eq!(
        spans
            .iter()
            .filter(|span| span
                .attributes
                .contains(&KeyValue::new("agentty.timing.source", "completion")))
            .count(),
        3
    );
}

#[tokio::test]
async fn capacity_limits_new_operations_but_allows_existing_operations_to_finish() {
    // Arrange
    let _guard = TRACER_PROVIDER_LOCK.lock().await;
    let exporter = install_provider();
    let root = Span::root("agent.attempt", Vec::new());

    // Act
    root.scope(async {
        let mut trace = OperationTrace::new();
        trace.record("active", "tool", None, None, Vec::new());
        trace.completed = (0..MAX_OPERATIONS - 1)
            .map(|index| index.to_string())
            .collect::<HashSet<_>>();
        trace.record("rejected", "tool", None, None, Vec::new());
        trace.record("active", "tool", Some(Outcome::Completed), None, Vec::new());
        assert_eq!(trace.completed.len(), MAX_OPERATIONS);
        assert!(trace.operations.is_empty());
    })
    .await;

    // Assert
    assert_children(&exporter.get_finished_spans().expect("spans"), 1);
}

#[test]
fn disabled_tracing_ignores_provider_payloads() {
    // Arrange
    let _guard = Context::new().attach();
    let mut trace = OperationTrace::new();

    // Act
    trace.observe(AgentKind::Codex, &json!({"method": "item/started", "params": {"item": {"id": "one", "type": "commandExecution"}}}));
    trace.observe_line(AgentKind::Claude, b"{}");
    trace.observe_codex_completed_turn(
        &json!({"params": {"turn": {"items": [{"id": "one", "type": "commandExecution"}]}}}),
    );

    // Assert
    assert!(trace.operations.is_empty());
}

async fn capture(kind: AgentKind, events: Vec<Value>) -> Vec<SpanData> {
    capture_with_policy(kind, events, false).await
}

async fn capture_with_policy(kind: AgentKind, events: Vec<Value>, capture: bool) -> Vec<SpanData> {
    let _guard = TRACER_PROVIDER_LOCK.lock().await;
    let exporter = install_provider();
    async {
        Span::root("agent.attempt", Vec::new())
            .scope(async {
                let mut trace = OperationTrace::new();
                for event in events {
                    trace.observe_line(kind, &serde_json::to_vec(&event).expect("event"));
                }
            })
            .await;
    }
    .with_context(Context::new().with_value(CaptureToolContent(capture)))
    .await;

    exporter.get_finished_spans().expect("spans")
}

fn install_provider() -> InMemorySpanExporter {
    let exporter = InMemorySpanExporter::default();
    global::set_tracer_provider(
        SdkTracerProvider::builder()
            .with_simple_exporter(exporter.clone())
            .build(),
    );

    exporter
}

fn assert_children(spans: &[SpanData], count: usize) {
    let root = spans
        .iter()
        .find(|span| span.name == "agent.attempt")
        .expect("attempt");
    assert_eq!(spans.len(), count + 1);
    for child in spans.iter().filter(|span| span.name != "agent.attempt") {
        assert_eq!(child.parent_span_id, root.span_context.span_id());
        assert_eq!(child.span_context.trace_id(), root.span_context.trace_id());
    }
}

fn outcomes(spans: &[SpanData]) -> Vec<&str> {
    spans
        .iter()
        .filter_map(|span| {
            span.attributes
                .iter()
                .find(|attribute| attribute.key.as_str() == "agentty.outcome")
        })
        .filter_map(|attribute| match &attribute.value {
            opentelemetry::Value::String(value) => Some(value.as_str()),
            _ => None,
        })
        .collect()
}

fn gemini(update: &Value) -> Value {
    json!({"method": "session/update", "params": {"sessionId": "session", "update": update}})
}

fn antigravity(step: &Value) -> Value {
    json!({"event": "step_update", "step_update": step})
}