trusty-common 0.19.0

Shared utilities and provider-agnostic streaming chat (ChatProvider, OllamaProvider, OpenRouter, tool-use) for trusty-* projects
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
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
//! Unit tests for the intent-source resolver (ISR), covering AC-1..AC-7.
//!
//! Why: the ISR is the shared contract both conformance gates depend on; its
//! precedence rule, linkage, spec-resolution, and fail-open behaviour must be
//! pinned by tests that run with **no network** (spec §8 acceptance criteria).
//! What: a mock `TicketFetcher`, an in-memory `SpecLookup`, and tests for every
//! acceptance criterion AC-1..AC-7 plus the supporting linkage / extraction /
//! precedence helpers.
//! Test: this file is itself the test surface; `cargo test -p trusty-common
//! --features intent-source` runs it.

use async_trait::async_trait;

use super::backend_fetcher::FsSpecLookup;
use super::extract::{HeuristicMethodExtractor, MethodExtractor, heuristic_method};
use super::linkage::{extract_branch_ticket, extract_pr_ticket, extract_ticket_id, is_ticketed};
use super::resolve::{
    EnvTokenResolver, IntentTokenResolver, SpecLookup, TicketData, TicketFetcher, resolve,
    resolve_default,
};
use super::spec_resolve::{
    extract_spec_method, parse_spec_refs, resolve_spec_section, revision_of,
};
use super::types::{ChangedFile, IntentQuery, IsrError, MethodKind, Precedence, ResolvedIntent};

// ───────────────────────── Test doubles ──────────────────────────────────────

/// A mock `TicketFetcher` returning a canned body (or a canned error).
///
/// Why: the resolver must be testable offline; this lets a test inject any
/// ticket body (or simulate a fetch failure) without a GitHub client.
/// What: holds an optional `TicketData` (Ok) or an error string (Err).
/// Test: used by every `resolve`-driven test below.
struct MockFetcher {
    result: Result<TicketData, String>,
}

impl MockFetcher {
    fn ok(body: &str) -> Self {
        Self {
            result: Ok(TicketData {
                id: "#1358".to_string(),
                title: "ISR".to_string(),
                body: body.to_string(),
                url: Some("https://github.com/x/y/issues/1358".to_string()),
                backend: "github".to_string(),
            }),
        }
    }
    fn err(msg: &str) -> Self {
        Self {
            result: Err(msg.to_string()),
        }
    }
}

#[async_trait]
impl TicketFetcher for MockFetcher {
    async fn fetch(
        &self,
        _owner: &str,
        _repo: &str,
        _ticket_id: &str,
    ) -> Result<TicketData, IsrError> {
        self.result.clone().map_err(IsrError::TicketFetch)
    }
}

/// An in-memory `SpecLookup` mapping spec-file paths to markdown text.
///
/// Why: spec-resolution must run without reading the real `docs/specs/` tree.
/// What: a `Vec<(path, markdown)>`; `load` returns the first matching text.
/// Test: used by the spec-resolution `resolve` tests below.
struct MapSpecLookup {
    entries: Vec<(String, String)>,
}

impl MapSpecLookup {
    fn empty() -> Self {
        Self {
            entries: Vec::new(),
        }
    }
    fn with(path: &str, markdown: &str) -> Self {
        Self {
            entries: vec![(path.to_string(), markdown.to_string())],
        }
    }
}

impl SpecLookup for MapSpecLookup {
    fn load(&self, spec_file: &str) -> Option<String> {
        self.entries
            .iter()
            .find(|(p, _)| p == spec_file)
            .map(|(_, md)| md.clone())
    }
}

// Helper: a ticket-only query with the given changed files.
fn ticket_query(changed: Vec<ChangedFile>) -> IntentQuery {
    IntentQuery::Ticket {
        ticket_id: "#1358".to_string(),
        owner: "x".to_string(),
        repo: "y".to_string(),
        changed_files: changed,
    }
}

// Helper: a spec markdown document whose anchor section prescribes a method.
fn spec_md(anchor: &str, method_line: &str) -> String {
    format!(
        "# Doc\n\n## Section {{#{anchor}}}\n\n**Behavior Contract (WHAT):**\n\n- {method_line}\n\n## Next\n\nunrelated\n"
    )
}

// A changed file declaring an SLD ref to the given spec id/anchor.
fn sld_file(path: &str, spec_id: &str, spec_file: &str, anchor: &str) -> ChangedFile {
    ChangedFile {
        path: path.to_string(),
        content: format!(
            "//! # Spec References\n//!\n//! - [`{spec_id}`]({spec_file}#{anchor})\n\npub fn f() {{}}\n"
        ),
    }
}

// ───────────────────────── AC-1: ticket method ──────────────────────────────

/// AC-1: a ticket whose body prescribes a method →
/// `ticket_method = Some`, `precedence_winner = Ticket`.
#[tokio::test]
async fn ac1_ticket_method_present() {
    let fetcher = MockFetcher::ok("We must use cursor-based pagination for the list endpoint.");
    let lookup = MapSpecLookup::empty();
    let intent = resolve_default(ticket_query(vec![]), &fetcher, &lookup).await;

    assert!(
        intent.ticket_method.is_some(),
        "ticket method should resolve"
    );
    assert_eq!(intent.precedence_winner, Precedence::Ticket);
    assert!(intent.ticket.is_some());
    assert!(!intent.conflict);
    assert!(!intent.stale_spec);
    assert!(intent.unresolved.is_none());
    let m = intent.ticket_method.unwrap();
    assert_eq!(m.kind, MethodKind::Approach);
    assert!(m.source_excerpt.contains("cursor-based pagination"));
}

// ───────────────────────── AC-2: agree ──────────────────────────────────────

/// AC-2: a ticket and a spec section that AGREE →
/// `conflict = false`, `stale_spec = false`.
#[tokio::test]
async fn ac2_ticket_and_spec_agree() {
    let method = "use cursor-based pagination";
    let fetcher = MockFetcher::ok(method);
    let spec_file = "docs/specs/search.md";
    let anchor = "SPEC-SEARCH-04~draft";
    let lookup = MapSpecLookup::with(spec_file, &spec_md(anchor, method));
    let changed = vec![sld_file(
        "crates/x/src/lib.rs",
        "SPEC-SEARCH-04~draft",
        spec_file,
        anchor,
    )];

    let intent = resolve_default(ticket_query(changed), &fetcher, &lookup).await;

    assert!(intent.ticket_method.is_some());
    assert!(intent.spec_method.is_some(), "spec method should resolve");
    assert_eq!(intent.precedence_winner, Precedence::Ticket);
    assert!(!intent.conflict, "agreeing methods must not conflict");
    assert!(!intent.stale_spec);
    assert!(intent.spec_section.is_some());
}

// ───────────────────────── AC-3: disagree → ticket wins ─────────────────────

/// AC-3: a ticket and a spec that DISAGREE →
/// `precedence_winner = Ticket`, `conflict = true`, `stale_spec = true`.
#[tokio::test]
async fn ac3_ticket_and_spec_conflict_ticket_wins() {
    let fetcher = MockFetcher::ok("use cursor-based pagination");
    let spec_file = "docs/specs/search.md";
    let anchor = "SPEC-SEARCH-04~draft";
    // Spec prescribes a *different* method.
    let lookup = MapSpecLookup::with(spec_file, &spec_md(anchor, "use offset-based pagination"));
    let changed = vec![sld_file(
        "crates/x/src/lib.rs",
        "SPEC-SEARCH-04~draft",
        spec_file,
        anchor,
    )];

    let intent = resolve_default(ticket_query(changed), &fetcher, &lookup).await;

    assert_eq!(
        intent.precedence_winner,
        Precedence::Ticket,
        "ticket > spec"
    );
    assert!(intent.conflict, "disagreeing methods must conflict");
    assert!(intent.stale_spec, "conflicting spec is stale/advisory");
    assert!(intent.ticket_method.is_some());
    assert!(intent.spec_method.is_some());
}

// ───────────────────────── AC-4: gap ────────────────────────────────────────

/// AC-4: neither a ticket method nor a spec method →
/// all method fields `None`, `precedence_winner = None`.
#[tokio::test]
async fn ac4_gap_no_methods() {
    // Body with no imperative-method cue.
    let fetcher = MockFetcher::ok("Add a new field to the response payload. See discussion.");
    let lookup = MapSpecLookup::empty();
    let intent = resolve_default(ticket_query(vec![]), &fetcher, &lookup).await;

    assert!(intent.ticket_method.is_none());
    assert!(intent.spec_method.is_none());
    assert_eq!(intent.precedence_winner, Precedence::None);
    assert!(intent.is_gap());
    assert!(!intent.conflict);
    assert!(!intent.stale_spec);
}

// ───────────────────────── AC-5: PR → ticket linkage ────────────────────────

/// AC-5: PR body `Closes #1325`, a commit trailer, and a branch `fix/1325-x`
/// each resolve to ticket `#1325`; a PR with no linkage resolves to `None`.
#[test]
fn ac5_pr_body_closes() {
    assert_eq!(
        extract_pr_ticket("Implements the thing.\n\nCloses #1325", &[], None),
        Some("#1325".to_string())
    );
}

#[test]
fn ac5_commit_trailer() {
    let commits = vec!["wip".to_string(), "done, fixes #1325".to_string()];
    assert_eq!(
        extract_pr_ticket("no linkage here", &commits, None),
        Some("#1325".to_string())
    );
}

#[test]
fn ac5_branch_name() {
    assert_eq!(
        extract_pr_ticket("no linkage", &[], Some("fix/1325-intent-source")),
        Some("#1325".to_string())
    );
}

/// Review MEDIUM #3 (tga #445): a bare `#N` mentioned only in passing in the
/// free-text PR body must NOT resolve, but a qualifying `Closes #N` must.
#[test]
fn ac5_pr_body_bare_ref_does_not_link() {
    // Bare `#42` in prose — NOT a qualifying ref — must not resolve from body.
    assert_eq!(
        extract_pr_ticket("See discussion in #42 for background", &[], None),
        None,
        "a bare #N mentioned in passing must not link (tga #445)"
    );
    // Action-keyword ref qualifies and resolves.
    assert_eq!(
        extract_pr_ticket("Closes #42", &[], None),
        Some("#42".to_string()),
        "a qualifying `Closes #N` must resolve"
    );
}

/// The bare-`#N` last resort is retained for commit messages (terse trailers),
/// even though the PR body rejects it.
#[test]
fn ac5_commit_bare_ref_still_links() {
    let commits = vec!["address #42".to_string()];
    assert_eq!(
        extract_pr_ticket("See discussion in #42", &commits, None),
        Some("#42".to_string()),
        "commit messages keep the bare-#N fallback"
    );
}

#[test]
fn ac5_no_linkage_is_none() {
    assert_eq!(
        extract_pr_ticket(
            "just a description",
            &["misc cleanup".to_string()],
            Some("main")
        ),
        None
    );
}

/// AC-5 (end-to-end): a `Pr` query with no linkage → `ResolvedIntent::none()`.
#[tokio::test]
async fn ac5_pr_without_linkage_resolves_none() {
    let query = IntentQuery::Pr {
        owner: "x".to_string(),
        repo: "y".to_string(),
        pr_number: 7,
        body: "no ticket here".to_string(),
        branch: Some("main".to_string()),
        commit_messages: vec!["misc".to_string()],
        changed_files: vec![],
    };
    // Fetcher would error if called — proves we short-circuit on no linkage.
    let fetcher = MockFetcher::err("should not be called");
    let lookup = MapSpecLookup::empty();
    let intent = resolve_default(query, &fetcher, &lookup).await;

    assert_eq!(intent.precedence_winner, Precedence::None);
    assert!(intent.ticket.is_none());
    assert!(
        intent.unresolved.is_none(),
        "non-ticketed is a clean gap, not a failure"
    );
}

/// AC-5 (end-to-end): a `Pr` body `Closes #1325` drives a successful resolve.
#[tokio::test]
async fn ac5_pr_with_linkage_resolves_ticket() {
    let query = IntentQuery::Pr {
        owner: "x".to_string(),
        repo: "y".to_string(),
        pr_number: 1358,
        body: "Implements ISR.\n\nCloses #1358".to_string(),
        branch: None,
        commit_messages: vec![],
        changed_files: vec![],
    };
    let fetcher = MockFetcher::ok("Reuse the existing ContextSource trait.");
    let lookup = MapSpecLookup::empty();
    let intent = resolve_default(query, &fetcher, &lookup).await;

    assert!(intent.ticket.is_some());
    assert_eq!(intent.precedence_winner, Precedence::Ticket);
    assert_eq!(intent.ticket_method.unwrap().kind, MethodKind::Reuse);
}

// ───────────────────────── AC-6: spec resolution ────────────────────────────

/// AC-6: a changed file with a `# Spec References` rustdoc block pointing at
/// `SPEC-X-01` resolves `spec_section = Some(SPEC-X-01)`.
#[tokio::test]
async fn ac6_spec_ref_resolves_section() {
    let spec_file = "docs/specs/x.md";
    let anchor = "SPEC-X-01~draft";
    let lookup = MapSpecLookup::with(spec_file, &spec_md(anchor, "use the existing trait T"));
    let changed = vec![sld_file(
        "crates/x/src/lib.rs",
        "SPEC-X-01~draft",
        spec_file,
        anchor,
    )];

    // Ticket silent so the spec axis is the only method.
    let fetcher = MockFetcher::ok("Add the thing.");
    let intent = resolve_default(ticket_query(changed), &fetcher, &lookup).await;

    let sref = intent.spec_section.expect("spec section should resolve");
    assert_eq!(sref.spec_id, "SPEC-X-01~draft");
    assert_eq!(sref.file, spec_file);
    assert!(intent.spec_method.is_some());
    assert_eq!(
        intent.precedence_winner,
        Precedence::Spec,
        "spec-only → Spec"
    );
}

/// AC-6: a changed file with NO SLD ref resolves `spec_section = None` (gap).
#[tokio::test]
async fn ac6_no_sld_ref_is_gap() {
    let changed = vec![ChangedFile {
        path: "crates/x/src/lib.rs".to_string(),
        content: "// plain file, no spec references\npub fn f() {}\n".to_string(),
    }];
    let fetcher = MockFetcher::ok("Add the thing."); // ticket also silent on method
    let lookup = MapSpecLookup::empty();
    let intent = resolve_default(ticket_query(changed), &fetcher, &lookup).await;

    assert!(
        intent.spec_section.is_none(),
        "no SLD ref → no spec section"
    );
    assert!(intent.spec_method.is_none());
    assert_eq!(intent.precedence_winner, Precedence::None);
}

// ───────────────────────── AC-7: fail-open ──────────────────────────────────

/// AC-7: ticket fetch error → `unresolved = Some(reason)`, all methods `None`.
#[tokio::test]
async fn ac7_fetch_error_is_fail_open() {
    let fetcher = MockFetcher::err("HTTP 503 from GitHub");
    let lookup = MapSpecLookup::empty();
    let intent = resolve_default(ticket_query(vec![]), &fetcher, &lookup).await;

    let reason = intent.unresolved.expect("fetch error must set unresolved");
    assert!(reason.contains("503") || reason.contains("ticket fetch"));
    assert!(intent.ticket_method.is_none());
    assert!(intent.spec_method.is_none());
    assert_eq!(intent.precedence_winner, Precedence::None);
}

// ───────────────────────── linkage helper coverage ──────────────────────────

#[test]
fn linkage_is_ticketed() {
    assert!(is_ticketed("closes #42"));
    assert!(is_ticketed("ENG-7 add feature"));
    assert!(is_ticketed("AB#10 work item"));
    assert!(!is_ticketed("just a note about #42"));
    assert!(!is_ticketed("misc cleanup"));
}

#[test]
fn linkage_extract_priority() {
    assert_eq!(
        extract_ticket_id("AB#10 fixes PROJ-99"),
        Some("AB#10".to_string())
    );
    assert_eq!(
        extract_ticket_id("ENG-7 closes #10"),
        Some("ENG-7".to_string())
    );
    assert_eq!(extract_ticket_id("fixes #99"), Some("#99".to_string()));
    assert_eq!(extract_ticket_id("misc cleanup"), None);
}

#[test]
fn linkage_branch_variants() {
    assert_eq!(
        extract_branch_ticket("fix/1325-x"),
        Some("#1325".to_string())
    );
    assert_eq!(extract_branch_ticket("feat/42"), Some("#42".to_string()));
    assert_eq!(
        extract_branch_ticket("1325-bare"),
        Some("#1325".to_string())
    );
    assert_eq!(extract_branch_ticket("main"), None);
    // No leading numeric work-item segment after the `/`, so no linkage.
    assert_eq!(extract_branch_ticket("release/v1.2.3"), None);
}

// ───────────────────────── method extraction coverage ───────────────────────

#[test]
fn extract_heuristic_constraint() {
    let m = heuristic_method("- No new dependency may be added.").unwrap();
    assert_eq!(m.kind, MethodKind::Constraint);
}

#[test]
fn extract_heuristic_reuse() {
    let m = heuristic_method("Reuse the existing ContextSource trait.").unwrap();
    assert_eq!(m.kind, MethodKind::Reuse);
}

#[test]
fn extract_heuristic_approach_feature_flag() {
    let m = heuristic_method("Please gate this behind a feature flag.").unwrap();
    assert_eq!(m.kind, MethodKind::Approach);
}

#[test]
fn extract_heuristic_ambiguous_is_none() {
    assert!(heuristic_method("Make it work and ship it.").is_none());
    assert!(heuristic_method("").is_none());
    assert!(heuristic_method("Add a flag to the CLI.").is_none());
}

/// A Rust `use` import must NOT be misclassified as an approach method
/// (review MEDIUM #1: the old `cue.starts_with("use ")` guard was too broad).
#[test]
fn extract_heuristic_use_import_not_approach() {
    assert!(
        heuristic_method("use std::collections::HashMap;").is_none(),
        "a Rust import must not classify as an Approach method"
    );
    assert!(
        heuristic_method("    use crate::foo::Bar;").is_none(),
        "an indented Rust import must not classify either"
    );
    assert!(
        heuristic_method("use caution when deploying").is_none(),
        "casual `use X` phrasing must not classify as Approach"
    );
}

/// A narrow `use …` directive that IS a prescribed approach still classifies —
/// proves the tightened guard did not over-reject genuine cues.
#[test]
fn extract_heuristic_use_directive_is_approach() {
    let m = heuristic_method("Use the existing pagination helper.").unwrap();
    assert_eq!(m.kind, MethodKind::Reuse);
    let m = heuristic_method("- use offset-based windows").unwrap();
    assert_eq!(m.kind, MethodKind::Approach);
}

#[test]
fn extract_trait_default_matches_fn() {
    let extractor = HeuristicMethodExtractor;
    let body = "use cursor-based pagination";
    assert_eq!(extractor.extract(body), heuristic_method(body));
}

// ───────────────────────── spec_resolve helper coverage ─────────────────────

#[test]
fn spec_resolve_parse_dedup() {
    let src = "//! # Spec References\n\
        //! - [`SPEC-CONFORMANCE-03~draft`](docs/specs/intent-conformance.md#SPEC-CONFORMANCE-03~draft)\n\
        /// also [`SPEC-CONFORMANCE-03~draft`](docs/specs/intent-conformance.md#SPEC-CONFORMANCE-03~draft)\n";
    let refs = parse_spec_refs(src);
    assert_eq!(refs.len(), 1, "duplicate refs collapse to one");
    assert_eq!(refs[0].spec_id, "SPEC-CONFORMANCE-03~draft");
    assert_eq!(refs[0].file, "docs/specs/intent-conformance.md");
    assert_eq!(refs[0].anchor, "SPEC-CONFORMANCE-03~draft");
}

#[test]
fn spec_resolve_parse_none() {
    assert!(parse_spec_refs("// plain comment, no spec ref\n").is_empty());
}

#[test]
fn spec_resolve_method_from_section() {
    let md = spec_md("SPEC-X-01~draft", "use the existing trait T for dispatch");
    let m = extract_spec_method(&md, "SPEC-X-01~draft").unwrap();
    assert_eq!(m.kind, MethodKind::Reuse);
    assert!(m.text.contains("existing trait T"));
}

#[test]
fn spec_resolve_method_missing_anchor() {
    let md = spec_md("SPEC-X-01~draft", "use cursor pagination");
    assert!(extract_spec_method(&md, "SPEC-OTHER-99~draft").is_none());
}

#[test]
fn spec_resolve_method_section_scoped() {
    // The method cue lives in the NEXT section, not the anchored one — it must
    // NOT be attributed to this anchor.
    let md = "# Doc\n\n## A {#SPEC-X-01~draft}\n\njust prose, no method.\n\n## B\n\n- use cursor pagination\n";
    assert!(extract_spec_method(md, "SPEC-X-01~draft").is_none());
}

/// Review LOW #4: a top-level `# ` heading must terminate the section too, so a
/// following top-level section's method does not bleed into this anchor.
#[test]
fn spec_resolve_method_section_scoped_top_level_heading() {
    let md = "## A {#SPEC-X-01~draft}\n\njust prose, no method.\n\n# Next Top Level\n\n- use cursor pagination\n";
    assert!(
        extract_spec_method(md, "SPEC-X-01~draft").is_none(),
        "a `# ` top-level heading must terminate the anchored section"
    );
}

/// C4 (review C4, Finding 3): `anchor_in_heading` only treats a `{#…}` marker
/// as a candidate when it is a SPEC id. A heading carrying an ordinary markdown
/// slug (`{#overview}`) must NOT be matched as a spec section — so resolving a
/// SPEC anchor against a doc whose only `{#…}` marker is a non-SPEC slug yields
/// no section (the method block under that slug is never attributed).
#[test]
fn spec_resolve_anchor_in_heading_rejects_non_spec() {
    let md = "## Overview {#overview}\n\n- use cursor pagination\n";
    assert!(
        resolve_spec_section(md, "SPEC-X-01~draft").is_none(),
        "a non-SPEC `{{#slug}}` anchor must not match a SPEC section"
    );
}

// ───────────────────────── FsSpecLookup path-traversal guard ────────────────

/// Review MEDIUM #2 (path traversal): `FsSpecLookup::load` must refuse a
/// `..`-laden spec_file that escapes the repo root, even though such a file may
/// physically exist on disk. The in-root file loads; the traversal returns
/// `None`.
#[test]
fn fs_spec_lookup_rejects_traversal() {
    use std::fs;

    let root = tempfile::tempdir().expect("tempdir");
    let root_path = root.path();

    // A legitimate spec under docs/specs/ loads fine.
    let specs_dir = root_path.join("docs/specs");
    fs::create_dir_all(&specs_dir).expect("create docs/specs");
    fs::write(specs_dir.join("real.md"), "# real spec\n").expect("write spec");

    // A "secret" file OUTSIDE the repo root that a traversal would try to read.
    let secret_dir = tempfile::tempdir().expect("secret tempdir");
    let secret = secret_dir.path().join("passwd");
    fs::write(&secret, "root:x:0:0:root\n").expect("write secret");

    let lookup = FsSpecLookup::new(root_path);

    // In-root path resolves.
    assert_eq!(
        lookup.load("docs/specs/real.md").as_deref(),
        Some("# real spec\n"),
        "an in-root spec must load"
    );

    // Build a traversal that points at the secret file relative to the root.
    // e.g. docs/specs/../../<secret-dir-basename>/passwd, then enough `..` to
    // climb out — we construct it relative to root so canonicalize would land on
    // the secret were the guard absent.
    let secret_canon = secret.canonicalize().expect("canonicalize secret");
    let root_canon = root_path.canonicalize().expect("canonicalize root");
    let traversal = pathdiff_relative(&root_canon, &secret_canon);
    assert!(
        lookup.load(&traversal).is_none(),
        "a `..` traversal escaping repo_root must return None (got Some for {traversal})"
    );

    // A blatantly bad literal also returns None (the file does not exist under
    // root, so canonicalize fails → None).
    assert!(
        lookup.load("docs/specs/../../etc/passwd").is_none(),
        "a docs/specs/../../etc/passwd traversal must return None"
    );
}

/// Compute a `from`→`to` relative path as a `/`-joined string (test helper).
///
/// Why: the traversal test needs a relative path (with `..` segments) from the
/// repo root to an out-of-tree secret so the guard is exercised against a path
/// that *would* canonicalize successfully without the containment check.
/// What: walks up from `from` to the common ancestor, then down to `to`.
/// Test: used by `fs_spec_lookup_rejects_traversal`.
fn pathdiff_relative(from: &std::path::Path, to: &std::path::Path) -> String {
    let from_c: Vec<_> = from.components().collect();
    let to_c: Vec<_> = to.components().collect();
    let common = from_c
        .iter()
        .zip(to_c.iter())
        .take_while(|(a, b)| a == b)
        .count();
    let ups = from_c.len() - common;
    let mut parts: Vec<String> = std::iter::repeat_n("..".to_string(), ups).collect();
    for c in &to_c[common..] {
        parts.push(c.as_os_str().to_string_lossy().into_owned());
    }
    parts.join("/")
}

// ───────────────────────── constructors / error display ─────────────────────

#[test]
fn none_is_gap() {
    let n = ResolvedIntent::none();
    assert!(n.is_gap());
    assert_eq!(n.precedence_winner, Precedence::None);
    assert!(n.unresolved.is_none());
}

#[test]
fn unresolved_carries_reason() {
    let u = ResolvedIntent::unresolved("boom");
    assert_eq!(u.unresolved.as_deref(), Some("boom"));
    assert!(u.is_gap());
    assert!(u.ticket_method.is_none());
}

#[test]
fn error_display_variants() {
    assert_eq!(
        IsrError::NoTicketLinkage.to_string(),
        "no ticket linkage found in PR"
    );
    assert!(
        IsrError::TicketFetch("x".into())
            .to_string()
            .contains("ticket fetch failed")
    );
    assert!(
        IsrError::NoToken("y".into())
            .to_string()
            .contains("no auth token")
    );
}

// ───────────────────────── token resolver seam ──────────────────────────────

/// A custom token resolver demonstrates the §7.4 pluggable seam (App/JWT mode).
struct StaticTokenResolver;

#[async_trait]
impl IntentTokenResolver for StaticTokenResolver {
    async fn token(&self, _owner: &str, _repo: &str) -> Result<String, IsrError> {
        Ok("app-jwt-token".to_string())
    }
}

#[tokio::test]
async fn token_resolver_pluggable() {
    let r = StaticTokenResolver;
    assert_eq!(r.token("x", "y").await.unwrap(), "app-jwt-token");
}

#[tokio::test]
async fn token_resolver_env_missing_errors() {
    // Do not mutate the global env (parallel tests); just assert the error type
    // path is reachable by constructing the resolver and checking a name.
    let r = EnvTokenResolver;
    // If GITHUB_TOKEN happens to be set in CI we accept Ok; otherwise NoToken.
    match r.token("x", "y").await {
        Ok(t) => assert!(!t.is_empty()),
        Err(e) => assert!(matches!(e, IsrError::NoToken(_))),
    }
}

// ───────────────────────── explicit-extractor resolve path ──────────────────

/// `resolve` (non-default) accepts a custom extractor — proves the OQ-1 seam
/// is wired end-to-end, not just on the default path.
#[tokio::test]
async fn resolve_with_explicit_extractor() {
    struct AlwaysSome;
    impl MethodExtractor for AlwaysSome {
        fn extract(&self, _body: &str) -> Option<super::types::Method> {
            Some(super::types::Method {
                text: "forced".to_string(),
                kind: MethodKind::Constraint,
                source_excerpt: "forced".to_string(),
            })
        }
    }
    let fetcher = MockFetcher::ok("ambiguous prose the heuristic would skip");
    let lookup = MapSpecLookup::empty();
    let intent = resolve(ticket_query(vec![]), &fetcher, &AlwaysSome, &lookup).await;
    assert_eq!(intent.precedence_winner, Precedence::Ticket);
    assert_eq!(intent.ticket_method.unwrap().text, "forced");
}

// ═════════════════════ C4 (#1361): SLD spec-resolver hardening ═══════════════
//
// AC-6 hardening + AC-18 contribution. Each test pins one normative §6.4 rule:
// SLD-block scoping (module + fn level), Behavior-Contract/Rationale-scoped
// extraction, revision-drift (v1 ref → v2 section resolves + flags), and the
// no-linkage gap.

/// C4: a ref declared in a MODULE-level `//! # Spec References` block parses.
#[test]
fn spec_resolve_parse_module_level_block() {
    let src = "//! Some crate doc.\n\
        //!\n\
        //! # Spec References\n\
        //!\n\
        //! - [`SPEC-X-01~v1`](docs/specs/x.md#SPEC-X-01~v1)\n\
        \n\
        pub fn f() {}\n";
    let refs = parse_spec_refs(src);
    assert_eq!(refs.len(), 1, "module-level block ref must parse");
    assert_eq!(refs[0].spec_id, "SPEC-X-01~v1");
    assert_eq!(refs[0].anchor, "SPEC-X-01~v1");
}

/// C4: a ref declared in a FUNCTION-level `/// # Spec References` block parses.
#[test]
fn spec_resolve_parse_fn_level_block() {
    let src = "/// Does a thing.\n\
        ///\n\
        /// # Spec References\n\
        ///\n\
        /// - [`SPEC-Y-02~draft`](docs/specs/y.md#SPEC-Y-02~draft)\n\
        pub fn g() {}\n";
    let refs = parse_spec_refs(src);
    assert_eq!(refs.len(), 1, "fn-level block ref must parse");
    assert_eq!(refs[0].spec_id, "SPEC-Y-02~draft");
    assert_eq!(refs[0].file, "docs/specs/y.md");
}

/// C4 NORMATIVE (§6.4 "the ISR does not invent linkage"): a `SPEC-…` link that
/// is NOT inside a `# Spec References` block must NOT be treated as linkage.
#[test]
fn spec_resolve_parse_ignores_non_block_ref() {
    // The link sits in a plain code comment and in ordinary rustdoc prose — but
    // never under a `# Spec References` heading.
    let src = "// see [`SPEC-Z-09~v1`](docs/specs/z.md#SPEC-Z-09~v1) for context\n\
        /// This fn relates to [`SPEC-Z-09~v1`](docs/specs/z.md#SPEC-Z-09~v1).\n\
        pub fn h() {}\n";
    assert!(
        parse_spec_refs(src).is_empty(),
        "a SPEC link outside a `# Spec References` block must not link"
    );
}

/// C4: a different rustdoc heading after the block terminates it — a ref placed
/// under the *following* heading is not attributed to `# Spec References`.
#[test]
fn spec_resolve_parse_block_terminated_by_next_heading() {
    let src = "//! # Spec References\n\
        //!\n\
        //! - [`SPEC-A-01~v1`](docs/specs/a.md#SPEC-A-01~v1)\n\
        //!\n\
        //! # Examples\n\
        //!\n\
        //! - [`SPEC-B-02~v1`](docs/specs/b.md#SPEC-B-02~v1)\n";
    let refs = parse_spec_refs(src);
    assert_eq!(refs.len(), 1, "only the in-block ref counts");
    assert_eq!(refs[0].spec_id, "SPEC-A-01~v1");
}

/// C4 (review C4, Finding 1): a `## Sub-section` heading (double-hash) after an
/// opened `# Spec References` block MUST terminate it — a ref under the
/// sub-section is not attributed to the spec-references block. Regression for
/// the bug where termination only fired on single-`#` headings.
#[test]
fn spec_resolve_parse_block_terminated_by_subsection_heading() {
    let src = "//! # Spec References\n\
        //!\n\
        //! - [`SPEC-A-01~v1`](docs/specs/a.md#SPEC-A-01~v1)\n\
        //!\n\
        //! ## Implementation Notes\n\
        //!\n\
        //! - [`SPEC-B-02~v1`](docs/specs/b.md#SPEC-B-02~v1)\n";
    let refs = parse_spec_refs(src);
    assert_eq!(
        refs.len(),
        1,
        "a `## Sub-section` heading must terminate the spec-references block"
    );
    assert_eq!(refs[0].spec_id, "SPEC-A-01~v1");
    assert!(
        !refs.iter().any(|r| r.spec_id == "SPEC-B-02~v1"),
        "a ref after a `## Sub-section` heading must NOT be attributed to the block"
    );
}

/// C4: `revision_of` splits the `~rev` suffix off a spec id/anchor.
#[test]
fn spec_resolve_revision_of() {
    assert_eq!(revision_of("SPEC-X-01~v2").as_deref(), Some("v2"));
    assert_eq!(revision_of("SPEC-X-01~draft").as_deref(), Some("draft"));
    assert_eq!(revision_of("SPEC-X-01"), None);
}

/// C4 (§6.4 Behavior Contract + Rationale): the method is lifted from the BC and
/// Rationale sub-blocks, NOT from an unrelated sub-block (e.g. an Inputs list).
#[test]
fn spec_resolve_contract_scoped() {
    let md = "## Gate {#SPEC-X-01~draft}\n\
        \n\
        **Inputs:**\n\
        \n\
        - reuse the existing FooBar trait (this is NOT the method block)\n\
        \n\
        **Behavior Contract (WHAT):**\n\
        \n\
        - use cursor-based pagination\n\
        \n\
        **Rationale (WHY):** keeps it stable.\n\
        \n\
        ## Next\n";
    let r = resolve_spec_section(md, "SPEC-X-01~draft").expect("section resolves");
    let m = r.method.expect("BC block prescribes a method");
    assert_eq!(m.kind, MethodKind::Approach);
    assert!(
        m.source_excerpt.contains("cursor-based pagination"),
        "method must come from the Behavior Contract block, not Inputs"
    );
}

/// C4: a section with NO formal BC/Rationale labels falls back to the whole
/// section body so an inline method still resolves (conservative for loose specs).
#[test]
fn spec_resolve_contract_fallback() {
    let md = "## Gate {#SPEC-X-01~draft}\n\nuse cursor-based pagination\n\n## Next\n";
    let r = resolve_spec_section(md, "SPEC-X-01~draft").expect("section resolves");
    assert!(
        r.method.is_some(),
        "an inline method in an unlabelled section must still resolve"
    );
}

/// C4 (§6.4 revision awareness, OQ-6): a `~v1` ref pointing at a `~v2` section
/// STILL resolves the method (from the current section) AND flags
/// `revision_drift = true` — stale-adjacent metadata, never an error.
#[test]
fn spec_resolve_drift_v1_ref_v2_section_resolves_and_flags() {
    let md = "## Gate {#SPEC-X-01~v2}\n\
        \n\
        **Behavior Contract (WHAT):**\n\
        \n\
        - use cursor-based pagination\n\
        \n\
        ## Next\n";
    // Reference the v1 anchor; the section is v2.
    let r = resolve_spec_section(md, "SPEC-X-01~v1").expect("v1 ref still resolves v2 section");
    assert!(
        r.method.is_some(),
        "method resolves from the current section"
    );
    assert_eq!(r.section_revision.as_deref(), Some("v2"));
    assert!(r.revision_drift, "v1 ref → v2 section must flag drift");
}

/// C4: a ref whose revision MATCHES the section does not flag drift.
#[test]
fn spec_resolve_drift_matching_revision_no_flag() {
    let md = "## Gate {#SPEC-X-01~v2}\n\n**Rationale (WHY):** use cursor pagination.\n\n## Next\n";
    let r = resolve_spec_section(md, "SPEC-X-01~v2").expect("section resolves");
    assert!(!r.revision_drift, "matching revision must not flag drift");
}

/// C4 end-to-end (§6.4): a drifted SLD ref resolves the spec method AND raises
/// `stale_spec` on the `ResolvedIntent` WITHOUT setting `conflict` — non-blocking
/// (OUTDATED enforcement is a non-goal).
#[tokio::test]
async fn spec_resolve_drift_sets_stale_spec_without_conflict() {
    let spec_file = "docs/specs/x.md";
    // Section heading is v2; the changed file references v1.
    let md = "## Gate {#SPEC-X-01~v2}\n\
        \n\
        **Behavior Contract (WHAT):**\n\
        \n\
        - use cursor-based pagination\n\
        \n\
        ## Next\n";
    let lookup = MapSpecLookup::with(spec_file, md);
    let changed = vec![sld_file(
        "crates/x/src/lib.rs",
        "SPEC-X-01~v1",
        spec_file,
        "SPEC-X-01~v1",
    )];
    // Ticket silent so the spec axis is the sole method (spec-only → Spec).
    let fetcher = MockFetcher::ok("Add the thing.");
    let intent = resolve_default(ticket_query(changed), &fetcher, &lookup).await;

    assert!(
        intent.spec_method.is_some(),
        "drifted spec still resolves a method"
    );
    assert_eq!(intent.precedence_winner, Precedence::Spec);
    assert!(
        intent.stale_spec,
        "revision drift flags stale_spec-adjacent metadata"
    );
    assert!(
        !intent.conflict,
        "drift is advisory, not a method conflict (non-blocking)"
    );
    assert!(intent.unresolved.is_none(), "drift never fails the resolve");
}

/// C4 NORMATIVE end-to-end (§6.4): a changed file with NO SLD ref returns
/// `spec_section = None` (a gap) — the ISR does not fabricate linkage.
#[tokio::test]
async fn spec_resolve_no_block_ref_is_gap_end_to_end() {
    // A SPEC link in a plain comment (NOT a `# Spec References` block) must not
    // produce a spec section.
    let changed = vec![ChangedFile {
        path: "crates/x/src/lib.rs".to_string(),
        content: "// related: [`SPEC-X-01~v1`](docs/specs/x.md#SPEC-X-01~v1)\npub fn f() {}\n"
            .to_string(),
    }];
    let fetcher = MockFetcher::ok("Add the thing.");
    let lookup = MapSpecLookup::with(
        "docs/specs/x.md",
        &spec_md("SPEC-X-01~v1", "use cursor pagination"),
    );
    let intent = resolve_default(ticket_query(changed), &fetcher, &lookup).await;

    assert!(
        intent.spec_section.is_none(),
        "a non-block SPEC link must not invent linkage"
    );
    assert!(intent.spec_method.is_none());
    assert!(!intent.stale_spec);
}

/// C4: `extract_spec_method` back-compat wrapper still returns the section
/// method (so the C1 calling convention is unchanged).
#[test]
fn spec_resolve_extract_method_wrapper_unchanged() {
    let md = spec_md("SPEC-X-01~draft", "use cursor-based pagination");
    let m = extract_spec_method(&md, "SPEC-X-01~draft").expect("wrapper resolves method");
    assert_eq!(m.kind, MethodKind::Approach);
}