mahbot 0.7.3

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
//! Shared test utilities for initializing global stores and building test
//! tickets.
//!
//! Provides a single temporary directory shared across all test initializations,
//! instead of the previous per-module pattern that leaked a separate temp dir
//! per store.
//!
//! The shared test root is created once per process; on unix it is removed at
//! process exit via an exit hook (pass, failure, and per-test panics all exit
//! the process normally), and on other platforms it is left for the OS temp
//! sweep. Since global [`OnceCell`]s can only be set once, each store is
//! initialized at most once per test run.
//!
//! Also provides [`TicketBuilder`], a builder for creating test tickets that was
//! historically defined in the `board` module and imported from there by sibling
//! modules, and [`TicketFixture`], the in-memory `Ticket` value the GUI and
//! channel tests share. Moved here so all test infrastructure lives in one place.
//!
//! Also provides [`JobRowBuilder`], a builder for inserting test `jobs` rows
//! (the durability/resume substrate in the consolidated domain database) that
//! mirrors the production INSERT in [`crate::jobs::spawn_job`].
//!
//! Also provides [`create_test_workspace`] (inserting a workspace into the test DB)
//! and [`init_management_test_stores`] (initializing all stores plus the manager
//! queue), relocated from `management.rs` tests so they are discoverable alongside
//! the rest of the shared test infrastructure.
//!
//! Also provides [`seed_session_row`], a session-seeding helper shared by the
//! analyze/implement tool tests (it exists because the session store's
//! `batch_append` is `session`-module private); [`ProbeFile`], a self-removing
//! probe file for the tests that author a tool into a shared catalogue folder;
//! and [`rs_files_under`] with [`rel_source_path`], the file list and the
//! relative-path spelling the source-scanning tripwires walk.

#![cfg(test)]

use crate::db;
use crate::pipeline::board::{BoardStore, Ticket, TicketComment, TicketParams, TicketPhase};
use crate::util::UnwrapPoison;
use crate::workspace::test_ws_named;
use std::path::{Path, PathBuf};
use std::sync::{Arc, OnceLock};

/// Shared test root directory, created once per process.
///
/// Removed at process exit on unix via [`register_test_root_cleanup`]; on
/// other platforms it is left for the OS temp sweep. This is the process-level
/// shared root only — per-test temp dirs (`open_test_store!`,
/// `init_temp_repo`, per-test `TempDir`s) keep their own create/drop
/// lifecycle.
static TEST_ROOT: OnceLock<PathBuf> = OnceLock::new();

/// PID of the process that created [`TEST_ROOT`].
///
/// Guards the exit-time cleanup: `atexit` handlers registered before `fork()`
/// run in the child too, and a fork child must never remove its parent's
/// live root.
#[cfg(unix)]
static TEST_ROOT_CREATOR_PID: OnceLock<libc::pid_t> = OnceLock::new();

/// Mutex serializing env-var-modifying tests to prevent thread-safety
/// issues with `std::env::set_var` (which is `unsafe` in Rust 2024).
///
/// All test modules that modify environment variables should use this
/// shared lock to prevent data races between concurrent tests.
pub fn env_lock() -> &'static std::sync::Mutex<()> {
    static ENV_LOCK: OnceLock<std::sync::Mutex<()>> = OnceLock::new();
    ENV_LOCK.get_or_init(|| std::sync::Mutex::new(()))
}

/// A probe file that removes itself on drop.
pub(crate) struct ProbeFile(pub PathBuf);

impl Drop for ProbeFile {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.0);
    }
}

// ── Test-global exclusion via serial_test keys ─────────────

// Test-global exclusion is via [`serial_test`] keys: `provider` guards the
// process-global fake-provider + retry-policy globals, `drain` guards the
// shutdown drain flag. A test needs a key whenever it MUTATES the guarded
// global or its assertions depend on the global's value — a drain-flag reader
// asserting non-drain behavior needs `drain` just as much as a mutator does.
// A test awaiting a routed manager envelope is such a reader: manager-envelope
// routing skips the live route while the flag is set, so its wait would never
// resolve.
// Multi-key attributes may list keys in any order: serial_test's derive macro
// sorts them alphabetically at expansion ("avoids dining philosopher issues"),
// so the library itself guarantees a consistent global acquisition order.
// Tests that touch no guarded global carry no key and must not share
// process-global state of their own (unique workspace/job ids against the
// shared test store), e.g. the jobs boot-recovery and research-cancel tests.

// ── Retry-policy guard for scoped-retry tests ──────────────

/// RAII guard restoring the previous test retry-policy override on drop.
///
/// Returned by [`install_test_retry_policy`] — holding it (typically
/// `let _policy_guard`) restores the pre-test override (or unset state) when
/// the test finishes, including on panic, so a tiny test policy never leaks
/// into other tests. Mirrors [`FakeProviderGuard`].
#[must_use]
pub(crate) struct RetryPolicyGuard {
    previous: Option<crate::retry::RetryPolicy>,
}

impl Drop for RetryPolicyGuard {
    fn drop(&mut self) {
        crate::retry::restore_test_retry_policy(self.previous.take());
    }
}

/// Install a test retry-policy override for the duration of the returned
/// guard.
///
/// The caller must be annotated `#[serial_test::serial(provider)]` (the
/// serial key guards the process-global retry-policy override) and keep the
/// returned guard alive — dropping it restores the previous override.
pub(crate) fn install_test_retry_policy(policy: crate::retry::RetryPolicy) -> RetryPolicyGuard {
    let previous = crate::retry::swap_test_retry_policy(policy);
    RetryPolicyGuard { previous }
}

// ── Fake provider for scoped-retry tests ──────────────────

/// Scripted [`crate::Provider`] test double for the scoped retry loops.
///
/// Each [`chat_scoped`](crate::Provider::chat_scoped) call pops the next
/// scripted outcome: either `Ok(ChatResponse)` or an error carrying an
/// explicit [`FailureClass`] (so classification is exercised without HTTP).
/// Every request's `Debug` fingerprint is recorded so tests can assert
/// byte-identical retries vs. parse-failure re-prompts.
pub(crate) struct FakeProvider {
    script: std::sync::Mutex<
        std::collections::VecDeque<Result<crate::ChatResponse, crate::providers::ScopedCallError>>,
    >,
    /// `Debug` fingerprint of every request received (byte-identity checks).
    pub request_fingerprints: std::sync::Mutex<Vec<String>>,
    /// `Debug` fingerprint of just each request's message list — the
    /// byte-stable-prefix property (append-only growth of the continuation
    /// tail) is asserted on this. Per-message `Debug` joined with NUL (which
    /// cannot appear in `Debug` output — control chars are escaped), so a
    /// plain `starts_with` prefix check holds for appended-only growth.
    pub request_messages: std::sync::Mutex<Vec<String>>,
}

impl FakeProvider {
    #[must_use]
    pub(crate) fn new() -> Self {
        Self {
            script: std::sync::Mutex::new(std::collections::VecDeque::new()),
            request_fingerprints: std::sync::Mutex::new(Vec::new()),
            request_messages: std::sync::Mutex::new(Vec::new()),
        }
    }

    /// Push a scripted successful response with the given text.
    #[must_use]
    pub(crate) fn ok(self, text: &str) -> Self {
        self.ok_with_finish(text, None)
    }

    /// Push a scripted successful response with an explicit finish_reason
    /// (e.g. "length" to simulate provider truncation).
    #[must_use]
    pub(crate) fn ok_with_finish(self, text: &str, finish_reason: Option<&str>) -> Self {
        self.script
            .lock()
            .unwrap()
            .push_back(Ok(crate::ChatResponse {
                text: Some(text.to_string()),
                finish_reason: finish_reason.map(str::to_string),
                ..crate::ChatResponse::default()
            }));
        self
    }

    /// Push a scripted reasoning-only response (empty content, no tool calls,
    /// reasoning fields set) — the reasoning-only-stop class. `reasoning` is
    /// mirrored into both `reasoning` and `reasoning_content` (the DeepSeek
    /// wire shape).
    #[must_use]
    pub(crate) fn ok_reasoning_only(self, reasoning: &str, finish_reason: Option<&str>) -> Self {
        self.script
            .lock()
            .unwrap()
            .push_back(Ok(crate::ChatResponse {
                text: None,
                reasoning: Some(crate::Reasoning {
                    reasoning: Some(reasoning.to_string()),
                    reasoning_content: Some(reasoning.to_string()),
                    reasoning_details: None,
                }),
                finish_reason: finish_reason.map(str::to_string),
                ..crate::ChatResponse::default()
            }));
        self
    }

    /// Like [`Self::ok_reasoning_only`] but with real provider usage on the
    /// envelope — a real reasoning-only response always carries usage, and the
    /// session-length recording tests need usage-bearing fakes.
    #[must_use]
    pub(crate) fn ok_reasoning_only_with_usage(
        self,
        reasoning: &str,
        finish_reason: Option<&str>,
        input_tokens: u64,
        output_tokens: u64,
    ) -> Self {
        self.script
            .lock()
            .unwrap()
            .push_back(Ok(crate::ChatResponse {
                text: None,
                reasoning: Some(crate::Reasoning {
                    reasoning: Some(reasoning.to_string()),
                    reasoning_content: Some(reasoning.to_string()),
                    reasoning_details: None,
                }),
                finish_reason: finish_reason.map(str::to_string),
                usage: Some(crate::ProviderUsage {
                    input_tokens: Some(input_tokens),
                    output_tokens: Some(output_tokens),
                    ..crate::ProviderUsage::default()
                }),
                ..crate::ChatResponse::default()
            }));
        self
    }

    /// Push a scripted successful response with the given text and real
    /// provider usage (input/output tokens).
    #[must_use]
    pub(crate) fn ok_with_usage(self, text: &str, input_tokens: u64, output_tokens: u64) -> Self {
        self.script
            .lock()
            .unwrap()
            .push_back(Ok(crate::ChatResponse {
                text: Some(text.to_string()),
                usage: Some(crate::ProviderUsage {
                    input_tokens: Some(input_tokens),
                    output_tokens: Some(output_tokens),
                    ..crate::ProviderUsage::default()
                }),
                ..crate::ChatResponse::default()
            }));
        self
    }

    /// Push a scripted tool-call response (empty text, one tool call) — the
    /// valid empty-text tool-call turn.
    #[must_use]
    pub(crate) fn ok_tool_call(self, name: &str) -> Self {
        self.script
            .lock()
            .unwrap()
            .push_back(Ok(crate::ChatResponse {
                text: None,
                tool_calls: vec![crate::ToolCall {
                    id: "call_test".to_string(),
                    name: name.to_string(),
                    arguments: serde_json::json!({}),
                }],
                finish_reason: Some("tool_calls".to_string()),
                ..crate::ChatResponse::default()
            }));
        self
    }

    /// Push a scripted response with accompanying text AND one or more tool
    /// calls (ids `call_test_0`, `call_test_1`, ... in order) — the
    /// sleep-delivery-guard violation shapes.
    #[must_use]
    pub(crate) fn ok_text_and_tool_calls(
        self,
        text: &str,
        calls: &[(&str, serde_json::Value)],
    ) -> Self {
        let tool_calls = calls
            .iter()
            .enumerate()
            .map(|(i, (name, args))| crate::ToolCall {
                id: format!("call_test_{i}"),
                name: name.to_string(),
                arguments: args.clone(),
            })
            .collect();
        let text = Some(text.to_string());
        self.script
            .lock()
            .unwrap()
            .push_back(Ok(crate::ChatResponse {
                text,
                tool_calls,
                finish_reason: Some("tool_calls".to_string()),
                ..crate::ChatResponse::default()
            }));
        self
    }

    /// Push a scripted failure with the given granular class.
    #[must_use]
    pub(crate) fn err(self, class: crate::retry::FailureClass, msg: &str) -> Self {
        let inner = anyhow::anyhow!("{msg}");
        let record = crate::retry::RetryFailureRecord::new_simple(class, &inner, None);
        self.script
            .lock()
            .unwrap()
            .push_back(Err(crate::providers::ScopedCallError::new(
                inner, record, class,
            )));
        self
    }

    /// Push a scripted non-retryable HTTP failure with a raw provider body,
    /// formatted exactly like the production `HttpError` display
    /// (`"{context} API error ({status}): {body}"`), so detection logic that
    /// scans the error-trail text (e.g. the input-image-rejection strip) sees
    /// the same shape as a real provider rejection.
    #[must_use]
    pub(crate) fn err_http(self, status: u16, body: &str) -> Self {
        let msg = format!("OpenRouter API error ({status}): {body}");
        self.err(crate::retry::FailureClass::NonRetryable, &msg)
    }
}

#[async_trait::async_trait]
impl crate::Provider for FakeProvider {
    // `ScopedCallError` is deliberately large (full diagnostics payload); the
    // scripted-Result shape is the point of this test double.
    async fn chat_scoped(
        &self,
        request: crate::ChatRequest,
    ) -> Result<crate::ChatResponse, crate::providers::ScopedCallError> {
        self.request_fingerprints
            .lock()
            .unwrap()
            .push(format!("{request:?}"));
        self.request_messages.lock().unwrap().push(
            request
                .messages
                .iter()
                .map(|m| format!("{m:?}"))
                .collect::<Vec<_>>()
                .join("\u{0}"),
        );
        self.script.lock().unwrap().pop_front().unwrap_or_else(|| {
            Ok(crate::ChatResponse {
                text: Some("unscripted default".to_string()),
                ..crate::ChatResponse::default()
            })
        })
    }

    async fn warmup(&self) -> anyhow::Result<()> {
        Ok(())
    }
}

/// RAII guard restoring the previous global provider on drop.
///
/// Returned by [`install_fake_provider`] — holding it (typically `let _guard`)
/// restores the pre-test provider (or unset state) when the test finishes,
/// including on panic, so the fake never leaks into other tests. The restore is
/// conditional on the provider not having been replaced by a concurrent test
/// (see [`restore_provider_for_test_if`]), so a guard never clobbers a newer
/// fake installed by another test.
#[must_use]
pub(crate) struct FakeProviderGuard {
    previous: Option<Arc<dyn crate::Provider>>,
    installed: Arc<dyn crate::Provider>,
}

impl Drop for FakeProviderGuard {
    fn drop(&mut self) {
        crate::providers::restore_provider_for_test_if(&self.installed, self.previous.take());
    }
}

/// Install a [`FakeProvider`] as the global provider for tests.
///
/// The caller must be annotated `#[serial_test::serial(provider)]` (the
/// serial key guards the process-global fake provider) and keep the returned
/// guard alive — dropping it (on test end or panic) restores the previous
/// provider without clobbering a newer fake installed concurrently.
pub(crate) fn install_fake_provider(provider: Arc<dyn crate::Provider>) -> FakeProviderGuard {
    let previous = crate::providers::swap_provider_for_test(provider.clone());
    FakeProviderGuard {
        previous,
        installed: provider,
    }
}

// ── Combined retry+provider test seam ────────────────────

/// RAII guard for [`install_retry_seam`]: holds the tiny retry-policy
/// override and the fake provider until dropped, so both restore at scope
/// exit (including on panic). Fields are ordered so the drop restores
/// provider → policy (reverse of install).
///
/// The caller must be annotated `#[serial_test::serial(provider)]` (the
/// serial key guards the process-global fake provider + retry-policy
/// override).
#[must_use]
pub(crate) struct RetrySeam {
    _fake: FakeProviderGuard,
    _retry: RetryPolicyGuard,
}

/// Scoped install of the full retry-provider test seam: installs
/// [`crate::retry::tiny_test_policy`] and `provider` as the global provider.
/// Everything restores when the returned [`RetrySeam`] drops.
///
/// The caller must be annotated `#[serial_test::serial(provider)]`.
pub(crate) fn install_retry_seam(provider: impl crate::Provider + 'static) -> RetrySeam {
    install_retry_seam_dyn(Arc::new(provider))
}

/// [`install_retry_seam`] for an already-arc'd provider.
pub(crate) fn install_retry_seam_dyn(provider: Arc<dyn crate::Provider>) -> RetrySeam {
    let retry = install_test_retry_policy(crate::retry::tiny_test_policy());
    let fake = install_fake_provider(provider);
    RetrySeam {
        _fake: fake,
        _retry: retry,
    }
}

/// Recording [`crate::Channel`] test double: every sent message is pushed
/// into a shared buffer, `listen` is a no-op.
///
/// `name` is required because the registry keys channels by name and
/// silently drops duplicate registrations — call sites pass distinct names
/// to avoid cross-test collisions.
pub(crate) struct SpyChannel {
    name: &'static str,
    sent: Arc<std::sync::Mutex<Vec<crate::SendMessage>>>,
}

impl SpyChannel {
    /// Returns the spy and its shared sent-messages buffer.
    #[must_use]
    pub(crate) fn new(
        name: &'static str,
    ) -> (Self, Arc<std::sync::Mutex<Vec<crate::SendMessage>>>) {
        let sent = Arc::new(std::sync::Mutex::new(Vec::new()));
        (
            Self {
                name,
                sent: Arc::clone(&sent),
            },
            sent,
        )
    }
}

#[async_trait::async_trait]
impl crate::Channel for SpyChannel {
    async fn send(&self, message: &crate::SendMessage) -> anyhow::Result<()> {
        self.sent.lock().unwrap_poison().push(message.clone());
        Ok(())
    }

    async fn listen(
        &self,
        _tx: tokio::sync::mpsc::Sender<crate::ChannelMessage>,
    ) -> anyhow::Result<()> {
        Ok(())
    }

    fn name(&self) -> &'static str {
        self.name
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

/// Install a caller-owned logs store for `record_llm_*` stat writes for the
/// duration of the returned guard (mirrors [`install_fake_provider`]).
///
/// The boot `LOG_STORE` is a process-global `OnceCell` set by `init_tracing`,
/// which tests never run — so stat recording is normally a silent no-op.
/// This seam redirects it to a test store so end-to-end tests can assert on
/// the recorded rows.
///
/// While the guard is alive the redirect is PROCESS-GLOBAL: every
/// `record_llm_*` write in any concurrently-running test lands in this store.
/// Callers must hold the serial_test keys covering every global their test
/// touches for the guard's lifetime — the redirect is PROCESS-GLOBAL, so any
/// concurrently-running LLM-writing test's rows land in this store (the
/// current sole caller holds `provider`) — and filter queries by a
/// test-unique `agent_id`.
pub(crate) fn install_test_log_store(store: crate::logs::LogStore) -> TestLogStoreGuard {
    let previous = crate::stats::swap_test_log_store(Some(store));
    TestLogStoreGuard { previous }
}

/// RAII guard restoring the previous test log-store override on drop
/// (including during a panic), so it never leaks into other tests.
#[must_use]
pub(crate) struct TestLogStoreGuard {
    previous: Option<crate::logs::LogStore>,
}

impl Drop for TestLogStoreGuard {
    fn drop(&mut self) {
        crate::stats::swap_test_log_store(self.previous.take());
    }
}

/// RAII guard that restores an environment variable to its original value
/// on drop, including during a panic (unwind safety).
///
/// Created by [`set_env_var`]. Holds the shared [`env_lock()`] for the
/// entire duration to serialize concurrent env access across tests.
///
/// # Panic safety
///
/// The `Drop` implementation restores the original value even if the
/// enclosing scope panics, preventing test-isolation leaks. This is the
/// key advantage over a closure-based `with_env_var` helper.
pub struct EnvVarGuard {
    /// Serializes concurrent env access — held for the guard's entire lifetime.
    _lock: std::sync::MutexGuard<'static, ()>,
    key: String,
    /// Original value captured before mutation. Stored as [`OsString`] to
    /// preserve arbitrary (non-UTF-8) env var values on restore.
    original: Option<std::ffi::OsString>,
}

impl Drop for EnvVarGuard {
    fn drop(&mut self) {
        // SAFETY: We hold the env_lock, prohibiting concurrent env writes
        // from other test threads while we restore the original value.
        unsafe {
            match &self.original {
                Some(val) => std::env::set_var(&self.key, val),
                None => std::env::remove_var(&self.key),
            }
        }
    }
}

/// Set an environment variable for the duration of the returned guard.
///
/// The environment variable `key` is immediately set to `value` (or
/// removed if `value` is `None`). When the returned [`EnvVarGuard`] is
/// dropped — including on panic — the original value is restored.
///
/// Acquires the shared [`env_lock()`] to prevent data races with other
/// tests that manipulate environment variables.
///
/// # Example
///
/// ```ignore
/// let _guard = set_env_var("SOME_TEST_VAR", Some("value"));
/// // _guard drops here, restoring the variable to its original value
/// ```
#[must_use]
pub fn set_env_var(key: &str, value: Option<&str>) -> EnvVarGuard {
    let guard = env_lock().lock().unwrap_poison();
    let original = std::env::var_os(key);
    // SAFETY: Protected by the env_lock acquired above — no concurrent
    // env writes can happen from other test threads.
    unsafe {
        match value {
            Some(val) => std::env::set_var(key, val),
            None => std::env::remove_var(key),
        }
    }
    EnvVarGuard {
        _lock: guard,
        key: key.to_owned(),
        original,
    }
}

/// Make a file executable (0o755). Unix only, like the tests that need it:
/// every one of them drives a `sh` stub, and the file's mode is the only way to
/// make one runnable there.
#[cfg(unix)]
pub fn make_executable(path: &Path) {
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(path, PermissionsExt::from_mode(0o755)).unwrap();
}

/// 1×1 red PNG as a native data-URI — a payload that survives the media
/// gate's base64 + bounded raster decode; used wherever tests need a marker
/// the provider promotes to a vision part.
pub(crate) fn tiny_png_data_uri() -> String {
    use base64::Engine as _;
    use base64::engine::general_purpose::STANDARD;
    let img = image::RgbaImage::from_pixel(1, 1, image::Rgba([255, 0, 0, 255]));
    let mut buf = Vec::new();
    img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
        .expect("test PNG must encode");
    format!("data:image/png;base64,{}", STANDARD.encode(&buf))
}

/// The single process-level test temp root.
///
/// All test-owned process-global state that needs a temp directory — the
/// CONFIG storage root (stores, user workspaces, models) and the embedder
/// test config — resolves under this one root, so the whole process owns
/// exactly one test temp directory that self-cleans on normal exit (unix).
pub(crate) fn test_root() -> &'static PathBuf {
    TEST_ROOT.get_or_init(|| {
        let tmp = tempfile::TempDir::new().expect("failed to create test temp dir");
        let path = tmp.path().to_path_buf();
        // Deliberately leak the TempDir guard: keeping it around would race
        // with the exit-time removal below (both would try to delete the same
        // directory). The directory is instead removed by the atexit handler
        // (unix) or reclaimed by the OS temp sweep otherwise.
        std::mem::forget(tmp);
        #[cfg(unix)]
        register_test_root_cleanup();
        path
    })
}

/// Register exit-time removal of the shared test root (unix).
///
/// Runs on normal process exit — pass, failure, and per-test panics alike
/// (the test harness catches panics and the process still exits via
/// `exit()`, which runs atexit handlers under the default `panic = "unwind"`
/// profile). Killed processes (abort, signals) skip atexit handlers entirely
/// — leftovers from killed test processes are intentionally out of scope
/// (the OS reclaims them).
///
/// Race safety: each test process creates its own unique root (one per
/// process via [`TEST_ROOT`]) and removes only that one. The handler is
/// panic-free and guarded by the creator PID, so a `fork()` child spawned by
/// a test never removes its parent's root (exec'd children replace the
/// process image and lose the atexit list anyway).
#[cfg(unix)]
fn register_test_root_cleanup() {
    // Runs exactly once per process (called only from the TEST_ROOT
    // get_or_init closure), so no double-registration guard is needed.
    TEST_ROOT_CREATOR_PID.get_or_init(|| unsafe { libc::getpid() });
    // Registration failure is non-fatal: the directory simply leaks to the
    // OS temp sweep (the pre-change behavior).
    unsafe {
        libc::atexit(cleanup_test_root);
    }
}

/// Panic-free atexit handler removing the shared test root.
#[cfg(unix)]
extern "C" fn cleanup_test_root() {
    // SAFETY: getpid is safe to call from an atexit handler.
    let current_pid = unsafe { libc::getpid() };
    if TEST_ROOT_CREATOR_PID.get().copied() != Some(current_pid) {
        return;
    }
    if let Some(path) = TEST_ROOT.get() {
        // Panic-free by construction: remove_dir_all returns a Result, and
        // errors (e.g. ENOENT, leftovers) are ignored — the OS temp sweep
        // reclaims anything remaining.
        let _ = std::fs::remove_dir_all(path);
    }
}

/// Open a temporary store for testing.
///
/// Creates a temporary directory and opens the given store inside it.
/// Returns `(store, TempDir)`.  The `TempDir` MUST be held for the store's
/// lifetime (typically bound to `_tmp` / `_dir` in the calling test).
///
/// `store_name` is used in the panic message if opening the store fails,
/// so it should be a human-readable identifier (e.g. `"workspace"`, `"board"`).
///
/// This is a macro (not a generic function) because Rust's type system cannot
/// express the lifetime relationship between a closure argument and the future
/// returned by `async fn open(path: &Path) -> Result<T>` — the future captures
/// a borrow of the argument, which would require higher-ranked lifetime bounds
/// that `FnOnce` / `AsyncFnOnce` cannot express in the current edition without
/// boxing.
///
/// # Panics
///
/// Panics if the temporary directory cannot be created, or if opening the
/// store fails.
#[macro_export]
macro_rules! open_test_store {
    ($store:ty, $store_name:expr) => {{
        let tmp = ::tempfile::TempDir::new().expect("temp dir for test store");
        let store = <$store>::open(tmp.path()).await.unwrap_or_else(|e| {
            ::std::panic!(
                "failed to open test {store_name} store: {e:?}",
                store_name = $store_name
            )
        });
        (store, tmp)
    }};
}

/// Convenience helper to create a test ticket with just a title and phase.
///
/// Reduces the common boilerplate:
/// ```ignore
/// let id = TicketBuilder::new(&store, &ws)
///     .title("My Ticket")
///     .phase(TicketPhase::Backlog)
///     .create()
///     .await
///     .expect("create my ticket");
/// ```
/// to:
/// ```ignore
/// let id = make_ticket(&store, &ws, "My Ticket", TicketPhase::Backlog).await;
/// ```
///
/// For tickets that need `.desc()` or `.prereqs()`, use [`TicketBuilder`]
/// directly.
///
/// # Panics
///
/// Panics if the ticket cannot be created. The panic message includes the title
/// and phase for debugging.
pub(crate) async fn make_ticket(
    store: &BoardStore,
    ws: &crate::Workspace,
    title: &str,
    phase: TicketPhase,
) -> String {
    TicketBuilder::new(store, ws)
        .title(title)
        .phase(phase)
        .create()
        .await
        .unwrap_or_else(|e| panic!("make_ticket({title}, {phase}) failed: {e}"))
}

/// Fetch a ticket by ID, panicking if the DB query fails or the ticket
/// does not exist.
///
/// Replaces the common test boilerplate:
/// ```ignore
/// let ticket = store.get_ticket(&id).await.expect("get").expect("exists");
/// ```
/// with the more concise:
/// ```ignore
/// let ticket = expect_ticket(&store, &id).await;
/// ```
///
/// # Panics
///
/// Panics if the DB query fails or the ticket is not found (returns `None`).
/// The panic originates from within this helper function.
pub async fn expect_ticket(store: &BoardStore, id: &str) -> Ticket {
    store
        .get_ticket(id)
        .await
        .expect("BoardStore::get_ticket query failed")
        .expect("expected ticket to exist")
}

/// Fetch a ticket's phase by ID, panicking if the DB query fails or the
/// ticket does not exist.
///
/// Replaces the common test boilerplate:
/// ```ignore
/// let phase = store.get_ticket_phase(&id).await.expect("query").expect("exists");
/// ```
/// with the more concise:
/// ```ignore
/// let phase = expect_ticket_phase(&store, &id).await;
/// ```
///
/// # Panics
///
/// Panics if the DB query fails or the ticket is not found (returns `None`).
/// The panic originates from within this helper function.
pub async fn expect_ticket_phase(store: &BoardStore, id: &str) -> TicketPhase {
    store
        .get_ticket_phase(id)
        .await
        .expect("BoardStore::get_ticket_phase query failed")
        .expect("expected ticket phase to exist")
}

/// Builder for creating test tickets with common defaults.
///
/// Defaults: `desc="desc"`, `phase=Backlog`, `prerequisites=[]`, `reporter="test"`,
/// `embedding=None`. Title is required (no default) via `.title()`.
///
/// # Examples
/// ```ignore
/// // Simple ticket with defaults
/// TicketBuilder::new(&store, &ws).title("A").create().await?;
///
/// // Custom phase and prerequisites
/// TicketBuilder::new(&store, &ws)
///     .title("B")
///     .phase(TicketPhase::InDevelopment)
///     .prereqs(&[a_id, b_id])
///     .create().await?;
/// ```
pub(crate) struct TicketBuilder<'a> {
    store: &'a BoardStore,
    ws: crate::Workspace,
    title: String,
    desc: String,
    phase: TicketPhase,
    prereqs: Vec<String>,
    reporter: String,
    embedding: Option<Vec<u8>>,
    priority: i64,
}

impl<'a> TicketBuilder<'a> {
    /// Start building a test ticket for `store` in workspace `ws`.
    pub(crate) fn new(store: &'a BoardStore, ws: &crate::Workspace) -> Self {
        Self {
            store,
            ws: ws.clone(),
            title: String::new(),
            desc: "desc".into(),
            phase: TicketPhase::Backlog,
            prereqs: Vec::new(),
            reporter: "test".into(),
            embedding: None,
            priority: 1,
        }
    }

    /// Set the ticket title (required).
    pub(crate) fn title(mut self, title: impl Into<String>) -> Self {
        self.title = title.into();
        self
    }

    /// Set the description (default: `"desc"`).
    pub(crate) fn desc(mut self, desc: impl Into<String>) -> Self {
        self.desc = desc.into();
        self
    }

    /// Set the phase (default: [`TicketPhase::Backlog`]).
    pub(crate) fn phase(mut self, phase: TicketPhase) -> Self {
        self.phase = phase;
        self
    }

    /// Set prerequisites (default: empty).
    pub(crate) fn prereqs(mut self, prereqs: &[String]) -> Self {
        self.prereqs = prereqs.to_vec();
        self
    }

    /// Set the priority (default: 1).
    pub(crate) fn priority(mut self, priority: i64) -> Self {
        self.priority = priority;
        self
    }

    /// Set the reporter (default: `"test"`).
    pub(crate) fn reporter(mut self, reporter: impl Into<String>) -> Self {
        self.reporter = reporter.into();
        self
    }

    /// Create the ticket with the accumulated parameters.
    pub(crate) async fn create(self) -> anyhow::Result<String> {
        let (store, params) = self.into_parts();
        store.create_ticket(&params).await
    }

    fn into_parts(self) -> (&'a BoardStore, TicketParams) {
        (
            self.store,
            TicketParams {
                title: self.title,
                description: self.desc,
                workspace_name: self.ws.name,
                phase: self.phase,
                prerequisites: self.prereqs,
                reporter: self.reporter,
                embedding: self.embedding,
                priority: self.priority,
            },
        )
    }
}

/// In-memory [`Ticket`] fixture, for tests that need a `Ticket` value without a
/// store — distinct from the DB-insert [`TicketBuilder`].
pub(crate) struct TicketFixture(Ticket);

impl TicketFixture {
    pub(crate) fn new(id: &str, phase: TicketPhase) -> Self {
        Self(Ticket {
            id: id.into(),
            title: "Test ticket".into(),
            description: String::new(),
            phase,
            workspace_name: "test_ws".into(),
            created_at: "2026-01-01T00:00:00Z".into(),
            updated_at: "2026-01-01T00:00:00Z".into(),
            comments: Vec::new(),
            prerequisites: Vec::new(),
            supersedes: None,
            superseded_by: None,
            commit_hash: None,
            lines_added: None,
            lines_removed: None,
            reporter: "test".into(),
            is_archived: false,
            priority: 0,
            reviewed_head: None,
            reviewed_tree: None,
            done_at: None,
            bounce_count: 0,
        })
    }

    pub(crate) fn title(mut self, title: &str) -> Self {
        self.0.title = title.into();
        self
    }

    pub(crate) fn workspace(mut self, workspace: &str) -> Self {
        self.0.workspace_name = workspace.into();
        self
    }

    pub(crate) fn archived(mut self, archived: bool) -> Self {
        self.0.is_archived = archived;
        self
    }

    pub(crate) fn created_at(mut self, created_at: &str) -> Self {
        self.0.created_at = created_at.into();
        self
    }

    pub(crate) fn done_at(mut self, done_at: Option<&str>) -> Self {
        self.0.done_at = done_at.map(str::to_string);
        self
    }

    pub(crate) fn comment(mut self, role: &str, content: &str, created_at: &str) -> Self {
        self.0.comments.push(TicketComment {
            role: role.into(),
            content: content.into(),
            created_at: created_at.into(),
        });
        self
    }

    pub(crate) fn build(self) -> Ticket {
        self.0
    }
}

/// Builder for inserting a test `jobs` row (the durability/resume substrate
/// in the consolidated domain database).
///
/// Mirrors the production INSERT in [`crate::jobs::spawn_job`] — when the
/// `jobs` schema changes, update both this builder and the production insert.
///
/// Required schema columns live in the constructor (`id`, `kind`, `role`,
/// `workspace_name`); the columns the fixtures vary between (user identity,
/// channel, retry count) are opt-in setters, and `task`
/// defaults to `''`. Timestamps are required via [`Self::timestamps`] and
/// transcribed verbatim — the helper never generates timestamps internally
/// (tests assert exact equality on them).
///
/// # Panics
///
/// [`Self::insert`] panics if [`Self::timestamps`] was not called.
pub(crate) struct JobRowBuilder<'a> {
    conn: &'a crate::db::Connection,
    id: String,
    kind: String,
    role: String,
    workspace_name: String,
    task: String,
    user_name: Option<String>,
    channel: Option<String>,
    retry_count: Option<i64>,
    timestamps: Option<String>,
}

impl<'a> JobRowBuilder<'a> {
    /// Start a builder for a `jobs` row with the schema-required columns.
    pub(crate) fn new(
        conn: &'a crate::db::Connection,
        id: impl Into<String>,
        kind: impl Into<String>,
        role: impl Into<String>,
        workspace_name: impl Into<String>,
    ) -> Self {
        Self {
            conn,
            id: id.into(),
            kind: kind.into(),
            role: role.into(),
            workspace_name: workspace_name.into(),
            task: String::new(),
            user_name: None,
            channel: None,
            retry_count: None,
            timestamps: None,
        }
    }

    /// Set `task` (default: `''`).
    pub(crate) fn task(mut self, task: impl Into<String>) -> Self {
        self.task = task.into();
        self
    }

    /// Set `user_name` explicitly (default: column omitted → schema default
    /// `''`). Pass an empty string to force the explicit `''` value.
    pub(crate) fn user_name(mut self, user_name: impl Into<String>) -> Self {
        self.user_name = Some(user_name.into());
        self
    }

    /// Set `channel` explicitly (default: column omitted → schema default
    /// `''`). Pass an empty string to force the explicit `''` value.
    pub(crate) fn channel(mut self, channel: impl Into<String>) -> Self {
        self.channel = Some(channel.into());
        self
    }

    /// Set `created_at` AND `updated_at` (both required, transcribed
    /// verbatim — the helper never generates timestamps internally).
    pub(crate) fn timestamps(mut self, timestamps: impl Into<String>) -> Self {
        self.timestamps = Some(timestamps.into());
        self
    }

    /// Insert the row.
    pub(crate) async fn insert(self) -> anyhow::Result<()> {
        let Self {
            conn,
            id,
            kind,
            role,
            workspace_name,
            task,
            user_name,
            channel,
            retry_count,
            timestamps,
        } = self;
        let mut columns = vec!["id", "kind", "task", "workspace_name", "role"];
        let mut values: Vec<crate::db::Value> = vec![
            crate::db::Value::Text(id),
            crate::db::Value::Text(kind),
            crate::db::Value::Text(task),
            crate::db::Value::Text(workspace_name),
            crate::db::Value::Text(role),
        ];
        if let Some(user_name) = user_name {
            columns.push("user_name");
            values.push(crate::db::Value::Text(user_name));
        }
        if let Some(channel) = channel {
            columns.push("channel");
            values.push(crate::db::Value::Text(channel));
        }
        if let Some(retry_count) = retry_count {
            columns.push("retry_count");
            values.push(crate::db::Value::Integer(retry_count));
        }
        let timestamps = timestamps.expect(
            "JobRowBuilder::insert: `.timestamps()` is required — the helper never generates timestamps internally",
        );
        columns.push("created_at");
        columns.push("updated_at");
        values.push(crate::db::Value::Text(timestamps.clone()));
        values.push(crate::db::Value::Text(timestamps));
        let placeholders = vec!["?"; values.len()].join(", ");
        let table = "jobs";
        let sql = format!(
            "INSERT INTO {table} ({}) VALUES ({placeholders})",
            columns.join(", ")
        );
        conn.execute(&sql, values).await?;
        Ok(())
    }
}

/// Initialize all global test stores (session, board, workspace, users,
/// config, stats, chat_history) with a shared temp directory by delegating
/// to [`db::init_all_stores`].
///
/// Also initializes the search engine registry (required by workspace store)
/// and sets the CONFIG storage root.
///
/// Idempotent — subsequent calls are no-ops.
pub async fn init_test_stores() {
    static INIT: tokio::sync::OnceCell<()> = tokio::sync::OnceCell::const_new();
    INIT.get_or_init(|| async {
        // Set CONFIG storage root (no-op if already set by another test)
        let _ = crate::config::CONFIG.try_set_storage_root(test_root().clone());

        // search_engine is sync — must be initialized before workspace
        crate::search_engine::init_global();

        // chronicle is sync — lightweight allocation, no DB I/O.
        crate::pipeline::chronicle::init_global();

        crate::db::init_all_stores()
            .await
            .expect("failed to initialize test stores (see chained error for per-store details)");

        // Start the CDC-driven chronicle subscriber so the timeline is
        // materialized from ticket change events in tests too.
        crate::pipeline::chronicle::start_subscriber();
    })
    .await;
}

/// Initialize all stores needed by management tests that interact with
/// the chronicle timeline.
///
/// Calls [`init_test_stores`] (all test DBs) then initializes the global
/// message_router. The router is required by callers that
/// exercise the pipeline `notify_ticket` path, which
/// enqueues notifications via [`crate::agent::message_router::route`].
///
/// # Panics
///
/// Panics if [`init_test_stores`] has not been called first (the route
/// depends on stores being available), or if initialization of the
/// router fails.
///
/// # Idempotency note
///
/// [`init_test_stores`] is idempotent (uses a [`tokio::sync::OnceCell`]).
/// [`crate::agent::message_router::init_global`] initialises the router's internal
/// [`HashMap`](std::collections::HashMap) (via [`std::sync::OnceLock`]).
/// No consumer loops are spawned until the first [`route`](crate::agent::message_router::route)
/// to each agent ID.
pub async fn init_management_test_stores() {
    init_test_stores().await;

    let _ = crate::agent::message_router::init_global();
}

/// Create a test workspace by inserting it into the test DB and returning
/// a [`Workspace`](crate::Workspace) struct with the given `path` and `name`.
///
/// Parameters are `(path, name)` to match the convention of
/// [`test_ws_named`](crate::workspace::test_ws_named).
///
/// # Precondition
///
/// [`init_test_stores`] must be called before this function — the
/// workspace store's [`OnceCell`](tokio::sync::OnceCell) panics if
/// accessed before initialization.
///
/// # Panics
///
/// Panics if the workspace store is not initialized, or if the INSERT
/// SQL query fails.
pub async fn create_test_workspace(path: &str, name: &str) -> crate::Workspace {
    let now = crate::db::now();
    crate::workspace::store()
        .conn
        .execute(
            "INSERT INTO workspaces (name, path, created_at, updated_at, paused) \
             VALUES (?1, ?2, ?3, ?4, ?5)",
            db::params![name, path, now.clone(), now, 0],
        )
        .await
        .expect("insert test workspace");
    test_ws_named(path, name)
}

/// Seed one session row directly via SQL (the store's `batch_append` is
/// `session`-module private).
pub(crate) async fn seed_session_row(
    conn: &crate::db::Connection,
    agent_id: &str,
    role: &str,
    content: &str,
) {
    conn.execute(
        "INSERT INTO sessions (agent_id, role, content, created_at) VALUES (?1, ?2, ?3, ?4)",
        db::params![agent_id, role, content, crate::db::now()],
    )
    .await
    .unwrap();
}

/// Create a temporary directory initialized as a git repository with a
/// committed file named `test.txt` (containing `"line1\nline2\nline3\n"`)
/// and a single commit titled `"Initial commit"`.
///
/// The returned [`TempDir`](tempfile::TempDir) MUST be kept alive (bound to
/// `_dir` or similar) for the returned [`PathBuf`] to remain valid.
///
/// # Panics
///
/// Panics if `git` is not available, or if any git command fails.
pub(crate) fn init_temp_repo() -> (tempfile::TempDir, std::path::PathBuf) {
    let dir = tempfile::tempdir().expect("create temp dir");
    let repo_path = dir.path().to_path_buf();

    // git init
    let status = std::process::Command::new("git")
        .args(["init"])
        .current_dir(&repo_path)
        .status()
        .expect("git init");
    assert!(status.success());

    // Set user config (required for commit)
    for (key, value) in [("user.name", "Test"), ("user.email", "test@test.com")] {
        let status = std::process::Command::new("git")
            .args(["config", key, value])
            .current_dir(&repo_path)
            .status()
            .expect("git config");
        assert!(status.success());
    }

    // Create a file and make initial commit
    std::fs::write(repo_path.join("test.txt"), b"line1\nline2\nline3\n").expect("write test file");
    let status = std::process::Command::new("git")
        .args(["add", "-A"])
        .current_dir(&repo_path)
        .status()
        .expect("git add");
    assert!(status.success());
    let status = std::process::Command::new("git")
        .args(["commit", "-m", "Initial commit"])
        .current_dir(&repo_path)
        .status()
        .expect("git commit");
    assert!(status.success());

    (dir, repo_path)
}

/// Every `.rs` file under `dir`, recursively, in directory-walk order — the file
/// list the source-scanning tripwires walk (`db`'s raw-builder guard and
/// `tools::shell::tree`'s window guarantee).
///
/// # Panics
///
/// Panics if `dir` cannot be read.
pub(crate) fn rs_files_under(dir: &Path) -> Vec<PathBuf> {
    fn walk(dir: &Path, out: &mut Vec<PathBuf>) {
        for entry in std::fs::read_dir(dir).expect("read source directory") {
            let path = entry.expect("read directory entry").path();
            if path.is_dir() {
                walk(&path, out);
            } else if path.extension().is_some_and(|e| e == "rs") {
                out.push(path);
            }
        }
    }

    let mut files = Vec::new();
    walk(dir, &mut files);
    files
}

/// Where a source file sits relative to `manifest_dir`, spelled with `/`
/// separators — how the tripwires compare a walked file against their literal
/// lists, so the comparison does not depend on the host's separators.
///
/// # Panics
///
/// Panics if `file` is not under `manifest_dir`.
pub(crate) fn rel_source_path(manifest_dir: &Path, file: &Path) -> String {
    file.strip_prefix(manifest_dir)
        .expect("source files live under the manifest dir")
        .components()
        .map(|c| c.as_os_str().to_string_lossy())
        .collect::<Vec<_>>()
        .join("/")
}

// ── EnvVarGuard tests ─────────────────────────────────────────────────
//
// These tests use `unsafe { std::env::set_var/remove_var }` directly for
// setup and cleanup rather than going through the guard — ironic given the
// helper's purpose. This is an accepted trade-off: we're testing the
// wrapper's correctness, and the env_lock is independently exercised by
// every non-helper caller. Unique-per-test variable names prevent
// collisions within this module, but per std::env docs even writes to
// *different* variables are a data race without the lock.

#[cfg(test)]
mod env_var_guard_tests {
    use super::*;

    #[test]
    fn sets_and_restores_to_absent() {
        let guard = set_env_var("MAHBOT_TEST_SET_RESTORE", Some("hello"));
        assert_eq!(std::env::var("MAHBOT_TEST_SET_RESTORE"), Ok("hello".into()));
        drop(guard);

        // Variable was absent before the guard (unique name, first use).
        // The guard should restore to that state.
        assert!(
            std::env::var_os("MAHBOT_TEST_SET_RESTORE").is_none(),
            "guard should restore env var to absent on drop"
        );
    }

    #[test]
    fn removes_env_var() {
        // SAFETY: This bypasses env_lock (unique var name mitigates but
        // doesn't eliminate the race — see mod-level doc above). We need
        // pre-existing state to test the removal+restore path.
        unsafe {
            std::env::set_var("MAHBOT_TEST_REMOVE", "present");
        }

        let guard = set_env_var("MAHBOT_TEST_REMOVE", None);
        assert!(
            std::env::var_os("MAHBOT_TEST_REMOVE").is_none(),
            "set_env_var(key, None) should remove the variable"
        );
        drop(guard);

        // Original should be restored.
        assert_eq!(
            std::env::var("MAHBOT_TEST_REMOVE"),
            Ok("present".into()),
            "guard should restore the original value on drop"
        );

        // SAFETY: Bypasses env_lock (same trade-off as above).
        unsafe {
            std::env::remove_var("MAHBOT_TEST_REMOVE");
        }
    }

    #[test]
    fn captures_and_restores_original_value() {
        // SAFETY: Bypasses env_lock (unique var name — see mod-level doc).
        unsafe {
            std::env::set_var("MAHBOT_TEST_CAPTURE", "original");
        }

        let guard = set_env_var("MAHBOT_TEST_CAPTURE", Some("override"));
        assert_eq!(std::env::var("MAHBOT_TEST_CAPTURE"), Ok("override".into()));
        drop(guard);

        assert_eq!(
            std::env::var("MAHBOT_TEST_CAPTURE"),
            Ok("original".into()),
            "guard should restore the original value on drop"
        );

        // SAFETY: Bypasses env_lock (same trade-off).
        unsafe {
            std::env::remove_var("MAHBOT_TEST_CAPTURE");
        }
    }

    #[test]
    fn restores_on_panic() {
        // SAFETY: Bypasses env_lock (unique var name — see mod-level doc).
        unsafe {
            std::env::remove_var("MAHBOT_TEST_PANIC_ABSENT");
        }

        let result = std::panic::catch_unwind(|| {
            let _guard = set_env_var("MAHBOT_TEST_PANIC_ABSENT", Some("panic-value"));
            panic!("intentional panic");
        });
        assert!(result.is_err());

        assert!(
            std::env::var_os("MAHBOT_TEST_PANIC_ABSENT").is_none(),
            "MAHBOT_TEST_PANIC_ABSENT should be absent after panic-restore"
        );
    }

    #[test]
    fn restores_original_on_panic() {
        // SAFETY: Bypasses env_lock (unique var name — see mod-level doc).
        unsafe {
            std::env::set_var("MAHBOT_TEST_PANIC_ORIGINAL", "original");
        }

        let result = std::panic::catch_unwind(|| {
            let _guard = set_env_var("MAHBOT_TEST_PANIC_ORIGINAL", Some("panic-value"));
            panic!("intentional panic");
        });
        assert!(result.is_err());

        assert_eq!(
            std::env::var("MAHBOT_TEST_PANIC_ORIGINAL"),
            Ok("original".into()),
            "should restore original value after panic"
        );

        // SAFETY: Bypasses env_lock (same trade-off).
        unsafe {
            std::env::remove_var("MAHBOT_TEST_PANIC_ORIGINAL");
        }
    }
}

#[cfg(test)]
mod retry_policy_guard_tests {
    use super::*;

    /// The tiny test policy's `max_attempts` (3) — distinguishes it from the
    /// production default (13) when asserting restore semantics.
    const TINY_MAX_ATTEMPTS: u32 = 3;

    #[test]
    #[serial_test::serial(provider)] // serializes the process-global fake provider (providers::PROVIDER)
    fn installs_and_restores_on_drop() {
        assert_eq!(
            crate::retry::RetryPolicy::current().max_attempts,
            crate::retry::DEFAULT_RETRY_MAX_ATTEMPTS
        );
        let guard = install_test_retry_policy(crate::retry::tiny_test_policy());
        assert_eq!(
            crate::retry::RetryPolicy::current().max_attempts,
            TINY_MAX_ATTEMPTS
        );
        drop(guard);
        assert_eq!(
            crate::retry::RetryPolicy::current().max_attempts,
            crate::retry::DEFAULT_RETRY_MAX_ATTEMPTS,
            "guard must restore the pre-test override on drop"
        );
    }

    #[test]
    #[serial_test::serial(provider)] // serializes the process-global fake provider (providers::PROVIDER)
    fn restores_on_panic() {
        let result = std::panic::catch_unwind(|| {
            let _guard = install_test_retry_policy(crate::retry::tiny_test_policy());
            assert_eq!(
                crate::retry::RetryPolicy::current().max_attempts,
                TINY_MAX_ATTEMPTS
            );
            panic!("intentional panic while holding the policy guard");
        });
        assert!(result.is_err());
        assert_eq!(
            crate::retry::RetryPolicy::current().max_attempts,
            crate::retry::DEFAULT_RETRY_MAX_ATTEMPTS,
            "a panicking test must not leak the tiny policy into later tests"
        );
    }
}

/// Deterministic per-pixel noise that defeats image compression (used by the
/// reference-image loader and body-budget tests to build reliably large files),
/// in the format the caller hands a writer.
fn noisy_image(width: u32, height: u32, format: image::ImageFormat) -> Vec<u8> {
    use image::{ImageBuffer, Rgb};
    let img: ImageBuffer<Rgb<u8>, Vec<u8>> = ImageBuffer::from_fn(width, height, |x, y| {
        let mut v = x.wrapping_mul(0x9E37_79B9) ^ y.wrapping_mul(0x85EB_CA6B);
        v ^= v >> 13;
        v ^= v << 17;
        v ^= v >> 5;
        Rgb([
            (v & 0xFF) as u8,
            ((v >> 8) & 0xFF) as u8,
            ((v >> 16) & 0xFF) as u8,
        ])
    });
    let mut out = Vec::new();
    image::DynamicImage::ImageRgb8(img)
        .write_to(&mut std::io::Cursor::new(&mut out), format)
        .unwrap();
    out
}

/// The PNG form of [`noisy_image`].
pub fn noisy_png(width: u32, height: u32) -> Vec<u8> {
    noisy_image(width, height, image::ImageFormat::Png)
}

/// The JPEG form of [`noisy_image`], for the writers that embed either kind.
pub fn noisy_jpeg(width: u32, height: u32) -> Vec<u8> {
    noisy_image(width, height, image::ImageFormat::Jpeg)
}

/// The canonical path as the resolvers hand it on: the platform's
/// [`std::fs::canonicalize`] with the Windows verbatim prefix stripped.
pub fn canonical_without_verbatim_prefix(path: &Path) -> PathBuf {
    crate::util::strip_verbatim_prefix(&std::fs::canonicalize(path).expect("canonicalize"))
}