ag-protocol 0.16.4

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
use crate::model::{
    AgentResponse, AgentResponseParseError, ProtocolRequestProfile, ReviewCommentOutcome,
    ReviewCommentResolution,
};
use crate::parse::{
    format_protocol_parse_debug_details, parse_agent_response_strict,
    parse_protocol_response_strict,
};

#[test]
/// Strict parsing accepts a complete schema payload.
fn test_parse_agent_response_strict_structured_json_payload() {
    // Arrange
    let raw = r#"{"answer":"Here is my analysis.","questions":[]}"#;

    // Act
    let response = parse_agent_response_strict(raw);

    // Assert
    assert_eq!(
        response.expect("response should parse").answer,
        "Here is my analysis."
    );
}

#[test]
fn parse_protocol_response_strict_normalizes_direct_focused_review() {
    // Arrange
    let raw = concat!(
        r#"{"project_impact":["Improves reliability."],"suggestions":["#,
        r#"{"details":"Fix this.","severity":"high"},"#,
        r#"{"details":"Improve that.","severity":"medium"}]}"#,
    );

    // Act
    let response = parse_protocol_response_strict(raw, ProtocolRequestProfile::FocusedReview)
        .expect("focused review should parse");

    // Assert
    assert_eq!(response, AgentResponse::plain(raw));
}

#[test]
fn parse_protocol_response_strict_rejects_empty_focused_review() {
    // Arrange
    let raw = "  \n ";

    // Act
    let error = parse_protocol_response_strict(raw, ProtocolRequestProfile::FocusedReview)
        .expect_err("empty focused review should fail");

    // Assert
    assert_eq!(error, AgentResponseParseError::Empty);
}

#[test]
fn parse_protocol_response_strict_rejects_focused_review_trailing_text() {
    // Arrange
    let raw = r#"{"project_impact":[],"suggestions":[]} trailing text"#;

    // Act
    let error = parse_protocol_response_strict(raw, ProtocolRequestProfile::FocusedReview)
        .expect_err("trailing text should require protocol repair");

    // Assert
    assert!(error.to_string().contains("trailing characters"));
}

#[test]
fn parse_protocol_response_strict_rejects_unknown_focused_review_field() {
    // Arrange
    let raw = r#"{"project_impact":[],"suggestions":[],"summary":"extra"}"#;

    // Act
    let error = parse_protocol_response_strict(raw, ProtocolRequestProfile::FocusedReview)
        .expect_err("unknown focused-review field should require protocol repair");

    // Assert
    assert!(error.to_string().contains("unknown field `summary`"));
}

#[test]
fn parse_protocol_response_strict_rejects_unknown_suggestion_field() {
    // Arrange
    let raw = concat!(
        r#"{"project_impact":[],"suggestions":[{"#,
        r#""details":"Fix this.","severity":"medium","path":"src/lib.rs"}]}"#,
    );

    // Act
    let error = parse_protocol_response_strict(raw, ProtocolRequestProfile::FocusedReview)
        .expect_err("unknown suggestion field should require protocol repair");

    // Assert
    assert!(error.to_string().contains("unknown field `path`"));
}

#[test]
/// Strict parsing recovers a trailing protocol payload when a provider
/// prepends extra prose before the final JSON object.
fn test_parse_agent_response_strict_recovers_wrapped_text() {
    // Arrange
    let raw = concat!(
        "Some wrapper text\n",
        r#"{"answer":"Recovered payload","questions":[]}"#
    );

    // Act
    let response = parse_agent_response_strict(raw);

    // Assert
    assert_eq!(
        response.expect("response should parse"),
        AgentResponse::plain("Recovered payload")
    );
}

#[test]
/// Strict parsing rejects plain text that contains no protocol payload.
fn test_parse_agent_response_strict_rejects_plain_text() {
    // Arrange
    let raw = "plain text";

    // Act
    let response = parse_agent_response_strict(raw);

    // Assert
    assert!(response.is_err());
}

#[test]
/// Strict parsing rejects JSON objects with only unrecognized fields
/// because at least one protocol key must be present.
fn test_parse_agent_response_strict_rejects_unrecognized_only_fields() {
    // Arrange
    let raw = r#"{"message":"not the expected shape"}"#;

    // Act
    let response = parse_agent_response_strict(raw);

    // Assert
    assert!(response.is_err());
}

#[test]
/// Strict parsing rejects an empty JSON object because no recognized
/// protocol key is present.
fn test_parse_agent_response_strict_rejects_empty_json_object() {
    // Arrange
    let raw = "{}";

    // Act
    let response = parse_agent_response_strict(raw);

    // Assert
    assert!(response.is_err());
}

#[test]
/// Strict parsing rejects an empty code fence instead of treating it as a
/// structured response.
fn test_parse_agent_response_strict_rejects_empty_code_fence() {
    // Arrange
    let raw = "```json\n\n```";

    // Act
    let response = parse_agent_response_strict(raw);

    // Assert
    assert!(response.is_err());
}

#[test]
/// Strict parsing strips code fences and recovers the inner JSON payload.
fn test_parse_agent_response_strict_strips_code_fenced_payload() {
    // Arrange
    let raw = concat!(
        "```json\n",
        r#"{"answer":"Need details.","questions":[]}"#,
        "\n```"
    );

    // Act
    let response = parse_agent_response_strict(raw);

    // Assert
    assert_eq!(
        response.expect("response should parse").answer,
        "Need details."
    );
}

#[test]
/// Strict parsing strips code fences even when leading/trailing whitespace
/// surrounds the fenced block.
fn test_parse_agent_response_strict_strips_code_fenced_payload_with_whitespace() {
    // Arrange
    let raw = concat!(
        "\n\n```json\n",
        r#"{"answer":"Recovered.","questions":[]}"#,
        "\n```\n"
    );

    // Act
    let response = parse_agent_response_strict(raw);

    // Assert
    assert_eq!(
        response.expect("response should parse").answer,
        "Recovered."
    );
}

#[test]
/// Strict parsing strips plain code fences without a language tag.
fn test_parse_agent_response_strict_strips_plain_code_fenced_payload() {
    // Arrange
    let raw = concat!(
        "```\n",
        r#"{"answer":"Plain fence.","questions":[]}"#,
        "\n```"
    );

    // Act
    let response = parse_agent_response_strict(raw);

    // Assert
    assert_eq!(
        response.expect("response should parse").answer,
        "Plain fence."
    );
}

#[test]
/// Strict parsing tolerates extra top-level fields that providers may add
/// beyond the protocol schema.
fn test_parse_agent_response_strict_tolerates_extra_top_level_fields() {
    // Arrange
    let raw = r#"{"answer":"Hello.","questions":[],"reasoning":"internal thought"}"#;

    // Act
    let response = parse_agent_response_strict(raw);

    // Assert
    assert_eq!(response.expect("response should parse").answer, "Hello.");
}

#[test]
/// Strict parsing tolerates extra fields inside nested question objects.
fn test_parse_agent_response_strict_tolerates_extra_question_fields() {
    // Arrange
    let raw = r#"{"answer":"","questions":[{"text":"Which approach?","options":["A","B"],"priority":"high"}]}"#;

    // Act
    let response = parse_agent_response_strict(raw);

    // Assert
    let questions = response.expect("response should parse").question_items();
    assert_eq!(questions.len(), 1);
    assert_eq!(questions[0].text, "Which approach?");
}

#[test]
/// Parser accepts a payload with `questions` but no `answer` key,
/// exercising the documented asymmetry where the parser is lenient
/// (any recognized key suffices) while the prompt schema requires
/// `answer`.
fn test_parse_agent_response_strict_accepts_questions_without_answer() {
    // Arrange
    let raw = r#"{"questions":[{"text":"Which approach?"}]}"#;

    // Act
    let response = parse_agent_response_strict(raw);

    // Assert
    let response = response.expect("parser should accept questions-only payload");
    assert_eq!(response.answer, "");
    assert_eq!(response.question_items().len(), 1);
}

#[test]
/// Parser accepts a review-comment outcome without an `answer` key because
/// it is a recognized protocol field.
fn test_parse_agent_response_strict_accepts_review_outcome_without_answer() {
    // Arrange
    let raw = concat!(
        r#"{"review_comment_outcomes":[{"reply":"Fixed it.","resolution":"fixed","#,
        r#""thread_id":"thread-42"}]}"#
    );

    // Act
    let response = parse_agent_response_strict(raw);

    // Assert
    let response = response.expect("parser should accept review-outcome-only payload");
    assert_eq!(
        response.review_comment_outcomes,
        vec![ReviewCommentOutcome {
            reply: "Fixed it.".to_string(),
            resolution: ReviewCommentResolution::Fixed,
            thread_id: "thread-42".to_string(),
        }]
    );
}

#[test]
/// Recovery path skips non-protocol JSON objects embedded in prose when
/// they contain no recognized protocol keys.
fn test_parse_agent_response_strict_rejects_wrapped_non_protocol_json() {
    // Arrange
    let raw = concat!(
        "Some wrapper text\n",
        r#"{"reasoning":"internal thought","confidence":0.9}"#
    );

    // Act
    let response = parse_agent_response_strict(raw);

    // Assert
    assert!(response.is_err());
}

#[test]
/// Strict parsing still rejects trailing wrapper text after a recovered
/// schema object.
fn test_parse_agent_response_strict_rejects_trailing_wrapper_after_payload() {
    // Arrange
    let raw = concat!(
        "Some wrapper text\n",
        r#"{"answer":"Recovered payload","questions":[]}"#,
        "\ntrailing wrapper text"
    );

    // Act
    let response = parse_agent_response_strict(raw);

    // Assert
    assert!(response.is_err());
}

#[test]
/// Strict parsing recovers protocol JSON from an embedded code fence
/// preceded by prose text.
fn test_parse_agent_response_strict_recovers_embedded_code_fence_in_prose() {
    // Arrange
    let raw = concat!(
        "The commit message looks good. Let me refine it.\n\n",
        "```json\n",
        r#"{"answer":"Refined commit message","questions":[]}"#,
        "\n```"
    );

    // Act
    let response = parse_agent_response_strict(raw);

    // Assert
    assert_eq!(
        response.expect("response should parse").answer,
        "Refined commit message"
    );
}

#[test]
/// The debug report describes the payload without reproducing any of it,
/// so a turn error cannot print raw provider output into the transcript.
fn test_format_protocol_parse_debug_details_never_quotes_payload() {
    // Arrange
    let raw = format!("{} SECRETTAIL", "payload-filler ".repeat(40));

    // Act
    let details = format_protocol_parse_debug_details(&raw);

    // Assert
    assert!(!details.contains("payload-filler"));
    assert!(!details.contains("SECRETTAIL"));
    assert!(details.contains(&format!("response_len: {} chars", raw.chars().count())));
    assert!(details.contains("direct_json_error"));
}

#[test]
/// Debug formatting reports JSON parser location details for plain-text
/// responses that never produced protocol JSON.
fn test_format_protocol_parse_debug_details_reports_plain_text_json_error() {
    // Arrange
    let raw = "plain text";

    // Act
    let details = format_protocol_parse_debug_details(raw);

    // Assert
    assert!(details.contains("response_len: 10 chars"));
    assert!(details.contains("first_non_whitespace_char: 'p'"));
    assert!(details.contains("direct_json_error_category: syntax"));
    assert!(details.contains("direct_json_error_location: line 1, column 1"));
    assert!(details.contains("embedded_json_candidate: none"));
}

#[test]
/// Debug formatting reports visible top-level keys when the response is
/// valid JSON but does not include any protocol fields.
fn test_format_protocol_parse_debug_details_reports_unrecognized_json_keys() {
    // Arrange
    let raw = r#"{"message":"not the expected shape"}"#;

    // Act
    let details = format_protocol_parse_debug_details(raw);

    // Assert
    assert!(details.contains("direct_json_type: object"));
    assert!(details.contains("direct_json_keys: message"));
    assert!(details.contains("direct_json_recognized_protocol_keys: (none)"));
    assert!(details.contains(
        "direct_json_missing_protocol_keys: answer, questions, review_comment_outcomes, subtasks, \
         verification_verdicts"
    ));
}

#[test]
fn utility_profiles_validate_direct_wire_objects_before_normalizing() {
    // Arrange
    let metadata = serde_json::json!({"title":"Keep \"quotes\"", "description":"First line\nSecond line", "is_title_change_significant":false});
    let inputs = [
        (
            crate::ProtocolRequestProfile::UtilityPrompt,
            r#"{"answer":"First line\nSay \"hello\""}"#.to_string(),
        ),
        (
            crate::ProtocolRequestProfile::ReviewMetadata,
            metadata.to_string(),
        ),
    ];

    for (profile, wire) in inputs {
        // Act
        let response =
            crate::parse_protocol_response_strict(&wire, profile).expect("valid direct object");

        // Assert
        assert_eq!(response.questions.len(), 0);
        assert_eq!(response.subtasks.len(), 0);
        assert_ne!(response.answer, "");
        assert!(crate::parse_protocol_response_strict("", profile).is_err());
        assert!(crate::parse_protocol_response_strict("{}", profile).is_err());
        assert!(
            crate::parse_protocol_response_strict(r#"{"answer":"x","questions":[]}"#, profile)
                .is_err()
        );
    }
    let response = crate::parse_protocol_response_strict(
        &metadata.to_string(),
        crate::ProtocolRequestProfile::ReviewMetadata,
    )
    .expect("metadata");
    assert_eq!(
        serde_json::from_str::<serde_json::Value>(&response.answer).expect("json"),
        metadata
    );
}

#[test]
fn utility_wrapper_recovery_still_rejects_unexpected_fields() {
    // Arrange
    let payload = r#"{"answer":"Done"}"#;
    let wrappers = [
        payload.to_string(),
        format!("```json\n{payload}\n```"),
        format!("Commentary\n{payload}"),
        format!("Commentary\n```json\n{payload}\n```"),
    ];

    for raw in wrappers {
        // Act
        let response = crate::parse_protocol_response_strict(
            &raw,
            crate::ProtocolRequestProfile::UtilityPrompt,
        )
        .expect("recover valid utility");

        // Assert
        assert_eq!(response.answer, "Done");
    }
    assert!(
        crate::parse_protocol_response_strict(
            r#"{"answer":"Done","subtasks":[]}"#,
            crate::ProtocolRequestProfile::UtilityPrompt
        )
        .is_err()
    );
}