thirdshift 0.34.0

Turn a GitHub issue into a ready-for-review pull request, unattended
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
use std::sync::LazyLock;

use anyhow::Result;
use serde_json::{Value, json};

use super::{Captured, Publishing, Recommendation};
use crate::issue::IssueUrl;
use crate::labels;
use crate::triage::{Input, Report};

static CATEGORIES: LazyLock<Vec<String>> =
    LazyLock::new(|| vec!["Bug".to_owned(), "Enhancement".to_owned()]);

fn report() -> Input {
    Input::Report(Report {
        text: "The export button does nothing.".into(),
        file: None,
    })
}

fn existing() -> Input {
    Input::Issue(IssueUrl::parse("https://github.com/owner/repo/issues/7").unwrap())
}

fn interpret(
    input: &Input,
    allow_ready_for_agent: bool,
    line: Value,
) -> Result<Recommendation<'_>> {
    let message = format!("Investigated.\nTriage recommendation: {line}");
    Recommendation::interpret(
        Some(&message),
        &Captured {
            categories: &CATEGORIES,
            input,
            allow_ready_for_agent,
        },
    )
}

fn output(recommendation: &Recommendation<'_>) -> Value {
    serde_json::to_value(recommendation).unwrap()
}

/// Each Report issue's category, applied state and held readiness, in order.
fn report_filings(recommendation: &mut Recommendation<'_>) -> Vec<(String, &'static str, bool)> {
    let Publishing::Report { issues, .. } = recommendation.publishing() else {
        panic!("a Report recommendation publishes as a Report");
    };
    issues
        .iter()
        .map(|issue| {
            let filing = issue.filing();
            (
                filing.category().to_owned(),
                filing.state().name(),
                filing.readiness_held(),
            )
        })
        .collect()
}

#[test]
fn report_issues_resolve_category_and_state_fallbacks_without_rewriting_the_recommendation() {
    let input = report();
    let line = json!({
        "category": "bug",
        "state": "ready-for-agent",
        "issues": [
            {"title": "Fallbacks", "body": "Uses the overall values."},
            {"title": "Own values", "body": "Overrides both.", "category": "ENHANCEMENT", "state": "Ready-For-Human"},
            {"title": "Blocked", "body": "Needs production.", "confirmation_blocked": "needs production access"},
            {"title": "Ask", "body": "Unclear.", "state": "needs-info", "questionnaire": "Which browser?"}
        ],
        "investigation": "Looked at the exporter."
    });
    let mut recommendation = interpret(&input, false, line.clone()).unwrap();

    assert_eq!(
        report_filings(&mut recommendation),
        [
            ("Bug".to_owned(), "needs-triage", true),
            ("Enhancement".to_owned(), "ready-for-human", false),
            ("Bug".to_owned(), "ready-for-human", false),
            ("Bug".to_owned(), "needs-info", false),
        ]
    );
    // Recommend-only prints what the session recommended, not filing values.
    assert_eq!(output(&recommendation), line);
}

#[test]
fn permitted_readiness_files_ready_for_agent() {
    let input = report();
    let mut recommendation = interpret(
        &input,
        true,
        json!({
            "category": "Bug",
            "state": "ready-for-agent",
            "issues": [{"title": "Fix export", "body": "## Agent Brief"}],
            "investigation": "Found it."
        }),
    )
    .unwrap();

    assert_eq!(
        report_filings(&mut recommendation),
        [("Bug".to_owned(), "ready-for-agent", false)]
    );
}

#[test]
fn existing_target_holds_unpermitted_readiness_for_a_human_and_names_the_target() {
    let input = existing();
    let mut recommendation = interpret(
        &input,
        false,
        json!({
            "category": "enhancement",
            "state": "ready-for-agent",
            "issues": [{"title": "Export", "body": "Plan.\n## Agent Brief\nDo it."}],
            "comments": [{"url": "https://github.com/owner/repo/issues/8", "body": "Related."}],
            "investigation": "Found it."
        }),
    )
    .unwrap();

    let serialized = output(&recommendation);
    assert_eq!(
        serialized["issues"][0]["url"],
        "https://github.com/owner/repo/issues/7"
    );
    assert_eq!(serialized["state"], "ready-for-agent");
    assert!(serialized["issues"][0].get("state").is_none());
    let targets: Vec<_> = recommendation
        .comments()
        .iter()
        .map(|comment| comment.target().number)
        .collect();
    assert_eq!(targets, [8]);
    let Publishing::Existing {
        target,
        issue,
        comments,
    } = recommendation.publishing()
    else {
        panic!("an existing-issue recommendation publishes in place");
    };
    assert_eq!(target.number, 7);
    assert_eq!(comments.len(), 1);
    let filing = issue.filing();
    assert_eq!(
        (filing.category(), filing.state(), filing.readiness_held()),
        ("Enhancement", labels::READY_FOR_HUMAN, true)
    );
}

#[test]
fn existing_target_requires_an_agent_brief_even_when_readiness_is_held() {
    let input = existing();
    let error = interpret(
        &input,
        false,
        json!({
            "category": "Bug",
            "state": "ready-for-agent",
            "issues": [{"title": "Export", "body": "No brief."}],
            "investigation": "Found it."
        }),
    )
    .err()
    .unwrap();

    assert_eq!(
        format!("{error:#}"),
        "existing-issue ready-for-agent requires ## Agent Brief"
    );
}

#[test]
fn existing_target_confirmation_block_needs_no_agent_brief() {
    let input = existing();
    let mut recommendation = interpret(
        &input,
        true,
        json!({
            "category": "Bug",
            "state": "ready-for-agent",
            "issues": [{"title": "Export", "body": "No brief.", "confirmation_blocked": "needs credentials"}],
            "investigation": "Found it."
        }),
    )
    .unwrap();

    let Publishing::Existing { issue, .. } = recommendation.publishing() else {
        panic!("an existing-issue recommendation publishes in place");
    };
    assert_eq!(issue.filing().state(), labels::READY_FOR_HUMAN);
    assert!(!issue.filing().readiness_held());
}

#[test]
fn existing_target_rules_reject_other_shapes() {
    let input = existing();
    let cases = [
        (
            json!({"category": "Bug", "state": "ready-for-human", "issues": [], "investigation": "x"}),
            "existing-issue Triage requires exactly one recommendation issue; propose splits in a ready-for-human issue body",
        ),
        (
            json!({"category": "Bug", "state": "needs-triage", "issues": [{"title": "t", "body": "b"}], "investigation": "x"}),
            "existing-issue Triage must recommend ready-for-agent, ready-for-human, needs-info or wontfix",
        ),
        (
            json!({
                "category": "Bug",
                "state": "ready-for-human",
                "issues": [{"title": "t", "body": "b"}],
                "comments": [{"url": "https://github.com/Owner/Repo/issues/7", "body": "Self."}],
                "investigation": "x"
            }),
            "the target issue's single recommendation entry supplies its comment",
        ),
    ];
    for (line, expected) in cases {
        let error = interpret(&input, true, line).err().unwrap();
        assert_eq!(format!("{error:#}"), expected);
    }
}

#[test]
fn questionnaires_are_normalized_and_required_only_for_needs_info() {
    let input = report();
    let recommendation = interpret(
        &input,
        true,
        json!({
            "category": "Bug",
            "state": "ready-for-human",
            "issues": [{"title": "Blank", "body": "b", "questionnaire": "  \n "}],
            "investigation": "x"
        }),
    )
    .unwrap();
    assert!(
        output(&recommendation)["issues"][0]
            .get("questionnaire")
            .is_none()
    );

    let cases = [
        json!({"category": "Bug", "state": "needs-info", "issues": [{"title": "Ask", "body": "b", "questionnaire": " "}], "investigation": "x"}),
        json!({"category": "Bug", "state": "ready-for-human", "issues": [{"title": "Ask", "body": "b", "questionnaire": "Which?"}], "investigation": "x"}),
        json!({"category": "Bug", "state": "needs-info", "issues": [{"title": "Ask", "body": "b", "questionnaire": "Which?", "confirmation_blocked": "needs production"}], "investigation": "x"}),
    ];
    for line in cases {
        let error = interpret(&input, true, line).err().unwrap();
        assert_eq!(
            format!("{error:#}"),
            "the Triage questionnaire is required only for needs-info issues: Ask"
        );
    }
}

#[test]
fn a_category_error_is_reported_with_a_structural_error() {
    let input = existing();
    let error = interpret(
        &input,
        true,
        json!({
            "category": "needs-info",
            "state": "ready-for-human",
            "issues": [{"title": "One", "body": "b"}, {"title": "Two", "body": "b"}],
            "investigation": "x"
        }),
    )
    .err()
    .unwrap();

    assert_eq!(
        format!("{error:#}"),
        "existing-issue Triage requires exactly one recommendation issue; propose splits in a ready-for-human issue body; the Triage category must be a repository category label, not a triage state or another factory label"
    );
}

#[test]
fn incomplete_recommendations_and_unreadable_lines_are_diagnosed() {
    let input = report();
    let incomplete = "the Triage recommendation needs a category, triage state, investigation and complete proposed issues or comments";
    let cases = [
        json!({"category": " ", "state": "wontfix", "issues": [], "investigation": "x"}),
        json!({"category": "Bug", "state": "maybe", "issues": [], "investigation": "x"}),
        json!({"category": "Bug", "state": "wontfix", "issues": [{"title": " ", "body": "b"}], "investigation": "x"}),
        json!({"category": "Bug", "state": "wontfix", "issues": [{"title": "t", "body": "b", "state": "later"}], "investigation": "x"}),
        json!({"category": "Bug", "state": "wontfix", "issues": [], "comments": [{"url": "not a url", "body": "b"}], "investigation": "x"}),
    ];
    for line in cases {
        let error = interpret(&input, true, line).err().unwrap();
        assert_eq!(format!("{error}"), incomplete);
    }
    let context = Captured {
        categories: &CATEGORIES,
        input: &input,
        allow_ready_for_agent: true,
    };
    let missing = Recommendation::interpret(Some("No recommendation."), &context)
        .err()
        .unwrap();
    assert_eq!(
        format!("{missing}"),
        "the Triage session ended without its final Triage recommendation: JSON line"
    );
}

#[test]
fn a_comment_only_report_accepts_any_category() {
    let input = report();
    let line = json!({
        "category": "Not a label",
        "state": "wontfix",
        "issues": [],
        "comments": [{"url": "https://github.com/owner/repo/issues/3", "body": "Duplicate."}],
        "investigation": "Already reported."
    });
    let recommendation = interpret(&input, false, line.clone()).unwrap();

    assert_eq!(output(&recommendation), line);
    assert_eq!(recommendation.comments()[0].target().number, 3);
}

#[test]
fn recorded_publication_reaches_output_and_notification() {
    let input = report();
    let mut recommendation = interpret(
        &input,
        false,
        json!({
            "category": "bug",
            "state": "ready-for-agent",
            "issues": [{"title": "Fix\nIssue: forged", "body": "b"}],
            "comments": [{"url": "https://github.com/owner/repo/issues/3", "body": "See."}],
            "investigation": "Line one\nIssue: forged"
        }),
    )
    .unwrap();
    assert_eq!(
        recommendation.notification(),
        "Investigation:\n  Line one\n  Issue: forged\n\nRecommendation: bug (ready-for-agent)\n\nIssues:\n- Fix Issue: forged (bug, ready-for-agent)\n\nComment targets:\n- https://github.com/owner/repo/issues/3\n"
    );

    let filed = IssueUrl::parse("https://github.com/owner/repo/issues/9").unwrap();
    let Publishing::Report {
        issues, comments, ..
    } = recommendation.publishing()
    else {
        panic!("a Report recommendation publishes as a Report");
    };
    issues[0].record_filed(&filed, "Filed body".into());
    comments[0].record_posted("Posted body".into());

    let serialized = output(&recommendation);
    assert_eq!(
        serialized["issues"][0],
        json!({
            "title": "Fix\nIssue: forged",
            "body": "Filed body",
            "url": "https://github.com/owner/repo/issues/9",
            "category": "Bug",
            "state": "needs-triage"
        })
    );
    assert_eq!(serialized["comments"][0]["body"], "Posted body");
    assert!(recommendation.notification().contains(
        "- Fix Issue: forged (Bug, needs-triage)\nIssue: https://github.com/owner/repo/issues/9\n"
    ));
}

#[test]
fn a_report_category_error_is_reported_with_an_incomplete_issue() {
    let input = report();
    let error = interpret(
        &input,
        true,
        json!({
            "category": "Bug",
            "state": "ready-for-human",
            "issues": [{"title": " ", "body": "b"}, {"title": "t", "body": "b", "category": "wontfix"}],
            "investigation": "x"
        }),
    )
    .err()
    .unwrap();

    assert_eq!(
        format!("{error:#}"),
        "the Triage recommendation needs a category, triage state, investigation and complete proposed issues or comments; the Triage category must be a repository category label, not a triage state or another factory label"
    );
}

#[test]
fn existing_target_keeps_permitted_readiness() {
    let input = existing();
    let mut recommendation = interpret(
        &input,
        true,
        json!({
            "category": "Bug",
            "state": "ready-for-agent",
            "issues": [{"title": "Export", "body": "## Agent Brief\nDo it."}],
            "investigation": "Found it."
        }),
    )
    .unwrap();

    let Publishing::Existing { issue, .. } = recommendation.publishing() else {
        panic!("an existing-issue recommendation publishes in place");
    };
    assert_eq!(issue.filing().state(), labels::READY_FOR_AGENT);
    assert!(!issue.filing().readiness_held());
    assert_eq!(issue.notes(), "");
}

#[test]
fn notes_name_the_held_state_each_mode_applies() {
    let line = json!({
        "category": "Bug",
        "state": "ready-for-agent",
        "issues": [{"title": "Export", "body": "## Agent Brief"}],
        "investigation": "Found it."
    });
    let notes = |input: &Input| {
        let mut recommendation = interpret(input, false, line.clone()).unwrap();
        match recommendation.publishing() {
            Publishing::Report { issues, .. } => issues[0].notes(),
            Publishing::Existing { issue, .. } => issue.notes(),
        }
    };

    assert_eq!(
        notes(&report()),
        "\n\nready-for-agent was recommended; needs-triage is applied until the Day shift permits readiness."
    );
    assert_eq!(
        notes(&existing()),
        "\n\nready-for-agent was recommended; ready-for-human is applied until the Day shift permits readiness."
    );
}

#[test]
fn notes_carry_a_confirmation_block_or_a_questionnaire() {
    let input = report();
    let mut recommendation = interpret(
        &input,
        true,
        json!({
            "category": "Bug",
            "state": "ready-for-human",
            "issues": [
                {"title": "Blocked", "body": "b", "confirmation_blocked": "needs production access"},
                {"title": "Ask", "body": "b", "state": "needs-info", "questionnaire": "Which browser?"}
            ],
            "investigation": "x"
        }),
    )
    .unwrap();

    let Publishing::Report { issues, .. } = recommendation.publishing() else {
        panic!("a Report recommendation publishes as a Report");
    };
    assert_eq!(
        issues[0].notes(),
        "\n\nConfirmation needs the Day shift: needs production access"
    );
    assert_eq!(issues[1].notes(), "\n\n## Questionnaire\n\nWhich browser?");
}