trusty-review 0.4.1

LLM-backed code review service — reviews GitHub PRs and unified diffs via AWS Bedrock or OpenRouter
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
//! Tests for the intent/method-conformance back-gate context source (#1359).
//!
//! Why: extracted to a sibling file to keep `conformance.rs` under the 500-line
//! cap while covering the AC-8..AC-12 back-gate behaviours that live in the
//! source (the verdict-floor cap is tested in `grade_tests.rs`; the
//! finding-category parse in `parser_tests.rs`).
//! What: drives `gather` against MOCK ISR seams (`TicketFetcher` / `SpecLookup`)
//! so no network or GitHub auth is touched — a ticket-method contradiction
//! renders a section; an unresolved/gap intent fails open to an empty section;
//! semantic mode errors; a disabled source skips.
//! Test: this file is the test module included from `conformance.rs`.

use super::*;
use trusty_common::intent_source::{
    Method, MethodKind, Precedence, ResolvedIntent, TicketData, TicketRef,
};

// ─── Mock ISR seams (no network) ──────────────────────────────────────────────

/// A `TicketFetcher` that returns a fixed body (or a failure) for any id.
struct MockFetcher {
    body: String,
    fail: bool,
}

#[async_trait]
impl TicketFetcher for MockFetcher {
    async fn fetch(
        &self,
        _owner: &str,
        _repo: &str,
        ticket_id: &str,
    ) -> Result<TicketData, IsrError> {
        if self.fail {
            return Err(IsrError::TicketFetch("mock fetch failure".to_string()));
        }
        Ok(TicketData {
            id: ticket_id.to_string(),
            title: "Mock ticket".to_string(),
            body: self.body.clone(),
            url: Some("https://example/issues/1325".to_string()),
            backend: "github".to_string(),
        })
    }
}

/// A `SpecLookup` that never resolves a spec (spec axis is a gap in these tests).
struct NoSpecLookup;
impl SpecLookup for NoSpecLookup {
    fn load(&self, _spec_file: &str) -> Option<String> {
        None
    }
}

/// PR number used by the test subject; lets `query_carries_pr_number` assert the
/// real number is threaded into the ISR query rather than the old hard-coded `0`.
const TEST_PR_NUMBER: u64 = 1359;

/// Build a subject whose PR body links a ticket via `Closes #N`.
fn subject_with_body(body: &str) -> ReviewSubject {
    ReviewSubject {
        owner: "bobmatnyc".to_string(),
        repo: "trusty-tools".to_string(),
        title: "Add pagination".to_string(),
        body: body.to_string(),
        changed_files: vec!["src/page.rs".to_string()],
        identifiers: vec![],
        pr_number: TEST_PR_NUMBER,
    }
}

fn source_with_fetcher(fetcher: MockFetcher) -> ConformanceSource {
    ConformanceSource::new(
        true,
        RetrievalMode::Live,
        Box::new(fetcher),
        Box::new(NoSpecLookup),
    )
}

// ─── gather: happy path (ticket method rendered) ──────────────────────────────

/// A ticket whose body prescribes a method renders a non-empty section naming
/// the prescribed method (the thing to check conformance against).
///
/// Why: the back gate must surface the resolved ticket method to the reviewer
/// LLM so it can flag a contradicting diff (M1).  AC-8's finding emission is the
/// LLM's job; the source's job is to render the intent.
/// What: a `Closes #1325` body + a ticket body prescribing "use cursor-based
/// pagination" → a section with a snippet whose body carries the method text.
/// Test: this test; no network.
#[tokio::test]
async fn gather_renders_ticket_method() {
    let fetcher = MockFetcher {
        body: "Implement listing. Method: use cursor-based pagination, not offset.".to_string(),
        fail: false,
    };
    let src = source_with_fetcher(fetcher);
    let subject = subject_with_body("Closes #1325 — add the listing endpoint.");
    let section = src.gather(&subject).await.expect("gather must not error");
    assert_eq!(section.heading, "Intended method (ticket/spec)");
    assert!(
        !section.snippets.is_empty(),
        "a ticket with a prescribed method must render a non-empty section"
    );
    let rendered = section
        .snippets
        .iter()
        .filter_map(|s| s.body.clone())
        .collect::<Vec<_>>()
        .join(" ");
    assert!(
        rendered.to_lowercase().contains("cursor"),
        "the prescribed method text must be surfaced: {rendered}"
    );
}

// ─── gather: fail-open (AC-11) ────────────────────────────────────────────────

/// A ticket-fetch failure (ISR unresolved) yields an EMPTY section and NO
/// conformance content (AC-11 fail-open).
///
/// Why: a missing/unfetchable intent source must never manufacture a finding;
/// the source returns an empty section the orchestrator drops.
/// What: a failing `MockFetcher` → empty section, gather returns Ok.
/// Test: this test; no network.
#[tokio::test]
async fn gather_fail_open_on_unresolved() {
    let src = source_with_fetcher(MockFetcher {
        body: String::new(),
        fail: true,
    });
    let subject = subject_with_body("Closes #1325");
    let section = src.gather(&subject).await.expect("fail-open: Ok, not Err");
    assert!(
        section.snippets.is_empty(),
        "an unresolved ISR must render an EMPTY section (AC-11 fail-open)"
    );
}

/// A PR with NO ticket linkage resolves to no intent → empty section (AC-11).
///
/// Why: non-ticketed work has no intent to conform to; the gate no-ops.
/// What: a body with no `Closes #N` → ISR `none()` → empty section.
/// Test: this test; no network.
#[tokio::test]
async fn gather_no_linkage_renders_empty() {
    let src = source_with_fetcher(MockFetcher {
        body: "use cursor pagination".to_string(),
        fail: false,
    });
    let subject = subject_with_body("A PR with no ticket reference at all.");
    let section = src.gather(&subject).await.expect("Ok");
    assert!(
        section.snippets.is_empty(),
        "no ticket linkage → empty section (no intent to conform to)"
    );
}

/// A ticket with NO prescribed method (a gap, M3) renders an empty section.
///
/// Why: a gap is advisory/none — never a blocking finding (AC-9 / M3); the
/// source surfaces nothing to flag against.
/// What: a fetched ticket whose body prescribes no method → empty section.
/// Test: this test; no network.
#[tokio::test]
async fn gather_gap_renders_empty() {
    let src = source_with_fetcher(MockFetcher {
        body: "Please add a feature flag. Thanks!".to_string(),
        fail: false,
    });
    let subject = subject_with_body("Closes #1325");
    let section = src.gather(&subject).await.expect("Ok");
    assert!(
        section.snippets.is_empty(),
        "a ticket with no prescribed method is a gap (M3) → empty section (AC-9)"
    );
}

// ─── render_section: stale-spec advisory (M4) ─────────────────────────────────

/// A stale-spec conflict (M4) renders the ticket method PLUS an advisory snippet
/// for the conflicting spec — never as the thing to fail against.
///
/// Why: under precedence the ticket wins; the conflicting spec is downgraded to
/// advisory context (spec §5.2 precedence wiring, M4 → ADVISORY).
/// What: a `ResolvedIntent` with ticket+spec methods, `stale_spec = true`, and
/// `precedence_winner = Ticket` → two snippets, one flagged advisory/stale.
/// Test: this test; constructs the intent directly (renderer is pure).
#[test]
fn render_stale_spec_advisory() {
    let intent = ResolvedIntent {
        ticket: Some(TicketRef {
            id: "#1325".to_string(),
            title: "t".to_string(),
            url: None,
            backend: "github".to_string(),
        }),
        ticket_method: Some(Method {
            text: "add dependency X".to_string(),
            kind: MethodKind::Approach,
            source_excerpt: "add dependency X".to_string(),
        }),
        spec_section: None,
        spec_method: Some(Method {
            text: "no new dependencies".to_string(),
            kind: MethodKind::Constraint,
            source_excerpt: "no new dependencies".to_string(),
        }),
        precedence_winner: Precedence::Ticket,
        conflict: true,
        stale_spec: true,
        unresolved: None,
    };
    let section = ConformanceSource::render_section(&intent);
    assert_eq!(
        section.snippets.len(),
        2,
        "ticket method + stale-spec advisory"
    );
    let advisory = section
        .snippets
        .iter()
        .any(|s| s.title.to_lowercase().contains("stale"));
    assert!(
        advisory,
        "the conflicting spec must be rendered as a stale advisory (M4)"
    );
}

/// An `unresolved` intent renders an empty section (renderer-level AC-11).
///
/// Why: pin the renderer's fail-open behaviour independently of `gather`.
/// What: `ResolvedIntent::unresolved(..)` → empty section.
/// Test: this test; pure.
#[test]
fn render_unresolved_is_empty() {
    let intent = ResolvedIntent::unresolved("ticket fetch failed");
    let section = ConformanceSource::render_section(&intent);
    assert!(section.snippets.is_empty());
}

// ─── would_flag predicate (cross-gate AC-18 contribution) ─────────────────────

/// A resolved intent whose TICKET prescribes `m` (precedence: Ticket) — the M5
/// shape (a prescribed method the diff could contradict).
fn ticket_intent(m: &str) -> ResolvedIntent {
    ResolvedIntent {
        ticket: Some(TicketRef {
            id: "#1362".to_string(),
            title: "t".to_string(),
            url: None,
            backend: "github".to_string(),
        }),
        ticket_method: Some(Method {
            text: m.to_string(),
            kind: MethodKind::Approach,
            source_excerpt: m.to_string(),
        }),
        spec_section: None,
        spec_method: None,
        precedence_winner: Precedence::Ticket,
        conflict: false,
        stale_spec: false,
        unresolved: None,
    }
}

/// `would_flag` is TRUE when a prescribed method exists (M1/M2/M5) — the back
/// gate surfaces a method to check the diff against.
///
/// Why: AC-18 asserts FRONT `Escalate` ⇔ BACK would-flag for M5 inputs; this
/// pins the BACK half of that equivalence at the renderer level (spec §5.2).
/// What: a ticket-prescribed-method intent → `would_flag == true`.
/// Test: this test; pure, no network.
#[test]
fn would_flag_true_for_prescribed_method() {
    let intent = ticket_intent("use cursor-based pagination");
    assert!(
        ConformanceSource::would_flag(&intent),
        "a prescribed method must be surfaced (M5 would-flag)"
    );
}

/// `would_flag` is FALSE for a gap (M3) — nothing to flag against.
///
/// Why: AC-18 asserts FRONT `AutoAccept` ⇔ BACK no-finding for M3 inputs; this
/// pins the BACK half (spec §4.1 M3, §4.2).
/// What: `ResolvedIntent::none()` → `would_flag == false`.
/// Test: this test; pure.
#[test]
fn would_flag_false_for_gap() {
    assert!(
        !ConformanceSource::would_flag(&ResolvedIntent::none()),
        "a gap (M3) surfaces no method → no finding possible"
    );
}

/// `would_flag` is FALSE for an `unresolved` (fail-open) intent (AC-11).
///
/// Why: a missing/unfetchable intent source must never manufacture a finding.
/// What: `ResolvedIntent::unresolved(..)` → `would_flag == false`.
/// Test: this test; pure.
#[test]
fn would_flag_false_for_unresolved() {
    assert!(
        !ConformanceSource::would_flag(&ResolvedIntent::unresolved("fetch failed")),
        "an unresolved intent is fail-open → no finding (AC-11)"
    );
}

// ─── gather: mode + enabled ───────────────────────────────────────────────────

/// Semantic mode is not implemented (PR-B parity) → error (logged, fail-open by
/// the orchestrator).
///
/// Why: like every live source, conformance only supports `Live` retrieval in
/// C2; a `Semantic` config surfaces a clear not-implemented error.
/// What: a `Semantic`-mode source → `SemanticNotImplemented`.
/// Test: this test; no network.
#[tokio::test]
async fn semantic_mode_errors() {
    let src = ConformanceSource::new(
        true,
        RetrievalMode::Semantic,
        Box::new(MockFetcher {
            body: String::new(),
            fail: false,
        }),
        Box::new(NoSpecLookup),
    );
    let subject = subject_with_body("Closes #1325");
    let err = src.gather(&subject).await.unwrap_err();
    assert!(matches!(
        err,
        ContextSourceError::SemanticNotImplemented { .. }
    ));
}

/// A subject with no owner/repo (local-diff mode) renders an empty section.
///
/// Why: no repo scope → nothing to resolve; skip with an empty section, not an
/// error.
/// What: an empty-owner subject → empty section.
/// Test: this test; no network.
#[tokio::test]
async fn gather_local_diff_renders_empty() {
    let src = source_with_fetcher(MockFetcher {
        body: "use cursor pagination".to_string(),
        fail: false,
    });
    let subject = ReviewSubject::default(); // empty owner/repo
    let section = src.gather(&subject).await.expect("Ok");
    assert!(section.snippets.is_empty());
}

/// `from_config` honours an explicit `enabled = false` (default-disabled source).
///
/// Why: the conformance source is opt-in (it needs GitHub auth); an explicit
/// disable must keep it off, and the default (no creds auto-enable) is off.
/// What: a `SourceConfig { enabled: Some(false), .. }` → `is_enabled() == false`;
/// a default `SourceConfig` → also `false` (no auto-enable on cred presence).
/// Test: this test; no network.
#[test]
fn from_config_respects_explicit_disable() {
    let cfg_off = crate::integrations::context::SourceConfig {
        enabled: Some(false),
        mode: RetrievalMode::Live,
    };
    let src = ConformanceSource::from_config(&cfg_off, RunMode::Cli, ReviewConfig::load(None));
    assert!(
        !src.is_enabled(),
        "explicit disable must keep the source off"
    );

    let cfg_default = crate::integrations::context::SourceConfig::default();
    let src2 = ConformanceSource::from_config(&cfg_default, RunMode::Cli, ReviewConfig::load(None));
    assert!(
        !src2.is_enabled(),
        "default conformance source is DISABLED (no auto-enable)"
    );
}

/// `from_config` honours an explicit `enabled = true`.
///
/// Why: an operator opting in must turn the source on.
/// What: `SourceConfig { enabled: Some(true), .. }` → `is_enabled() == true`.
/// Test: this test; no network.
#[test]
fn from_config_respects_explicit_enable() {
    let cfg_on = crate::integrations::context::SourceConfig {
        enabled: Some(true),
        mode: RetrievalMode::Live,
    };
    let src = ConformanceSource::from_config(&cfg_on, RunMode::Cli, ReviewConfig::load(None));
    assert!(src.is_enabled(), "explicit enable must turn the source on");
    assert_eq!(src.name(), "conformance");
}

// ─── build_query: PR-number threading (#1359) ─────────────────────────────────

/// `build_query` threads the real PR number into the ISR query (no hard-coded 0).
///
/// Why: the ISR's `IntentQuery::Pr` keys ticket linkage off the PR (body +
/// number); the source previously hard-coded `pr_number: 0`, losing the real
/// number.  This pins the threading so a regression to `0` is caught.
/// What: builds a query from a subject carrying `TEST_PR_NUMBER` and asserts the
/// resulting `IntentQuery::Pr.pr_number` matches.
/// Test: this test; no network.
#[test]
fn query_carries_pr_number() {
    let subject = subject_with_body("Closes #1325");
    let query = ConformanceSource::build_query(&subject).expect("owner/repo present → Some");
    match query {
        IntentQuery::Pr { pr_number, .. } => {
            assert_eq!(
                pr_number, TEST_PR_NUMBER,
                "the real PR number must be threaded, not hard-coded 0"
            );
        }
        other => panic!("build_query must produce IntentQuery::Pr, got {other:?}"),
    }
}

/// `build_query` returns `None` when there is no owner/repo (local-diff mode).
///
/// Why: a local diff has no PR to resolve intent against; `gather` must skip with
/// an empty section rather than issue a meaningless ISR query.
/// What: a subject with empty owner/repo → `build_query` returns `None`.
/// Test: this test; no network.
#[test]
fn query_none_without_owner_repo() {
    let subject = ReviewSubject {
        owner: String::new(),
        repo: String::new(),
        ..subject_with_body("Closes #1325")
    };
    assert!(
        ConformanceSource::build_query(&subject).is_none(),
        "no owner/repo (local-diff) must yield None"
    );
}