trusty-code 0.5.1

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
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
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
//! Unit tests for the in-process agent runner (issue #1029).
//!
//! Why: The runner is the runtime execution layer the PM delegates through;
//! every acceptance criterion — engineer runs its own loop on its own slug,
//! returns an `AgentOutput` to the PM, `tools.allowed` is enforced, and usage
//! rolls up — must be provable offline, without a live LLM. The scripted
//! `InferenceAdapter` mock from the agent-loop tests is the seam that makes this
//! deterministic.
//! What: Defines a `ScriptedLlm` that replays a queue of `ChatResponse`s and
//! records the system prompt + model of every request, a `RecordingTool` whose
//! execution is observable, and exercises the runner end-to-end: a stubbed PM
//! delegates to a `python-engineer` agent whose loop runs against its own slug.
//! Test: this module is itself the test surface.

use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

use async_trait::async_trait;
use serde_json::{Value, json};
use tempfile::TempDir;

use super::{InProcessAgentRunner, InProcessRunnerConfig};
use crate::agent_loop::ToolEventSink;
use crate::agents::AgentConfig;
use crate::llm::{ChatRequest, ChatResponse, InferenceAdapter, InferenceError};
use crate::tools::{
    AgentRunner, DelegateToAgentTool, RunContext, ToolExecutor, ToolRegistry, ToolResult,
};

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

/// A `InferenceAdapter` that replays a fixed script and records every request.
///
/// Why: Deterministic, offline substitute for the network client; recording the
/// requests lets tests assert what model and system prompt the runner resolved.
/// What: Holds scripted `ChatResponse`s, an atomic cursor, and a Mutex log of
/// `(model, system_prompt)` pairs captured from each `chat` call. Running past
/// the end yields a transport-style error so a runaway loop fails loudly.
/// Test: Used by every runner test below.
struct ScriptedLlm {
    responses: Vec<ChatResponse>,
    cursor: AtomicUsize,
    seen: Mutex<Vec<(String, String)>>,
    /// Every request's `max_tokens`, in call order — lets
    /// `engineer_llm_max_tokens_reaches_chat_request` assert the delegated
    /// engineer's `[llm].max_tokens` reached the wire request rather than
    /// being silently dropped in favour of the agent-loop default.
    max_tokens_seen: Mutex<Vec<Option<u32>>>,
}

impl ScriptedLlm {
    /// Build a scripted client from JSON response fixtures.
    ///
    /// Why: `ChatResponse` is `Deserialize`-only; tests author responses as JSON.
    /// What: Deserialises each fixture and seeds an empty request log.
    /// Test: Used by every runner test below.
    fn from_json(fixtures: &[Value]) -> Self {
        let responses = fixtures
            .iter()
            .map(|v| serde_json::from_value(v.clone()).expect("valid ChatResponse fixture"))
            .collect();
        Self {
            responses,
            cursor: AtomicUsize::new(0),
            seen: Mutex::new(Vec::new()),
            max_tokens_seen: Mutex::new(Vec::new()),
        }
    }

    /// Number of `chat` calls made so far.
    fn calls(&self) -> usize {
        self.cursor.load(Ordering::SeqCst)
    }

    /// The `(model, system_prompt)` of the first recorded request.
    fn first_request(&self) -> (String, String) {
        self.seen
            .lock()
            .expect("seen lock")
            .first()
            .cloned()
            .expect("at least one request recorded")
    }

    /// The `max_tokens` of the first recorded request.
    fn first_max_tokens(&self) -> Option<u32> {
        self.max_tokens_seen
            .lock()
            .expect("max_tokens_seen lock")
            .first()
            .copied()
            .expect("at least one request recorded")
    }
}

#[async_trait]
impl InferenceAdapter for ScriptedLlm {
    crate::llm::mock_adapter_identity!("mock-scripted");

    async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
        let system = req
            .messages
            .iter()
            .find(|m| m.role == "system")
            .and_then(|m| m.content.clone())
            .unwrap_or_default();
        self.seen
            .lock()
            .expect("seen lock")
            .push((req.model.clone(), system));
        self.max_tokens_seen
            .lock()
            .expect("max_tokens_seen lock")
            .push(req.max_tokens);

        let idx = self.cursor.fetch_add(1, Ordering::SeqCst);
        match self.responses.get(idx) {
            Some(resp) => Ok(resp.clone()),
            None => Err(InferenceError::MissingConfig(format!(
                "scripted LLM exhausted at call {idx}"
            ))),
        }
    }
}

/// An `InferenceAdapter` that sleeps before every `chat` call, then delegates.
///
/// Why: #2207's `with_timeout_secs` override must actually shorten the loop's
/// wall-clock budget; the only deterministic, offline way to prove that is a
/// mock whose response arrives later than a short configured deadline.
/// What: Wraps a `ScriptedLlm`; `chat` sleeps `delay` before returning
/// whatever the inner scripted client would have returned.
/// Test: `runner::tests::with_timeout_secs_shortens_the_deadline`.
struct SleepyLlm {
    inner: ScriptedLlm,
    delay: std::time::Duration,
}

#[async_trait]
impl InferenceAdapter for SleepyLlm {
    crate::llm::mock_adapter_identity!("mock-sleepy");

    async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
        tokio::time::sleep(self.delay).await;
        self.inner.chat(req).await
    }
}

/// A tool whose invocations are recorded, used to prove gating.
///
/// Why: To assert `tools.allowed` enforcement we need a tool that records
/// whether it was actually dispatched.
/// What: `execute` pushes its name onto a shared log and returns success.
/// Test: `tools_allowed_is_enforced`.
struct RecordingTool {
    name: &'static str,
    invoked: Arc<Mutex<Vec<String>>>,
}

#[async_trait]
impl ToolExecutor for RecordingTool {
    fn name(&self) -> &str {
        self.name
    }

    fn schema(&self) -> Value {
        json!({
            "type": "function",
            "function": {
                "name": self.name,
                "description": "recording tool",
                "parameters": { "type": "object", "properties": {} }
            }
        })
    }

    async fn execute(&self, _args: Value) -> ToolResult {
        self.invoked
            .lock()
            .expect("invoked lock")
            .push(self.name.to_string());
        ToolResult::ok(format!("{}: ran", self.name))
    }
}

// ── Fixture builders ─────────────────────────────────────────────────────────

/// A response in which the assistant calls a named tool with empty args.
fn tool_call_response(call_id: &str, tool: &str) -> Value {
    json!({
        "id": "gen-tool",
        "choices": [{
            "message": {
                "role": "assistant",
                "content": null,
                "tool_calls": [{
                    "id": call_id,
                    "type": "function",
                    "function": { "name": tool, "arguments": "{}" }
                }]
            },
            "finish_reason": "tool_calls"
        }],
        "usage": { "prompt_tokens": 30, "completion_tokens": 10, "total_tokens": 40 }
    })
}

/// A response in which the assistant emits final text and stops.
fn stop_response(text: &str) -> Value {
    json!({
        "id": "gen-stop",
        "choices": [{
            "message": { "role": "assistant", "content": text, "tool_calls": [] },
            "finish_reason": "stop"
        }],
        "usage": { "prompt_tokens": 15, "completion_tokens": 5, "total_tokens": 20 }
    })
}

// ── Fixtures: an agents config dir ───────────────────────────────────────────

/// Create a temp agents dir containing a `python-engineer.md`.
///
/// Why: The runner loads `<dir>/<agent>.md` (#2897 Slice D); tests need a
/// real file on disk.
/// What: Writes `python-engineer.md` with the given frontmatter+body and
/// returns the dir.
/// Test: Used by most runner tests.
fn agents_dir_with(body: &str, agent: &str) -> TempDir {
    let tmp = tempfile::tempdir().expect("tempdir");
    std::fs::write(tmp.path().join(format!("{agent}.md")), body).expect("write agent md");
    tmp
}

/// A registry factory closure that registers the given recording tools.
///
/// Why: Tests need a `RegistryFactory` that yields a known tool set so gating
/// and dispatch are observable.
/// What: Returns an `Arc<ToolRegistry>` with each `(name)` registered as a
/// `RecordingTool` sharing `invoked`.
fn recording_factory(
    tools: Vec<&'static str>,
    invoked: Arc<Mutex<Vec<String>>>,
) -> impl Fn(
    AgentConfig,
    RunContext,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = Arc<ToolRegistry>> + Send>> {
    move |_agent: AgentConfig, _ctx: RunContext| {
        let tools = tools.clone();
        let invoked = Arc::clone(&invoked);
        Box::pin(async move {
            let mut reg = ToolRegistry::new();
            for name in tools {
                reg.register(Arc::new(RecordingTool {
                    name,
                    invoked: Arc::clone(&invoked),
                }));
            }
            Arc::new(reg)
        })
    }
}

// ── Tests ────────────────────────────────────────────────────────────────────

/// Default config is sane.
///
/// Why: Defaults are the most-used construction path; guard them.
/// What: Assert positive turn cap and timeout.
/// Test: this test.
#[test]
fn config_default_is_sane() {
    let cfg = InProcessRunnerConfig::default();
    assert!(cfg.max_turns >= 1);
    assert!(cfg.timeout_secs >= 1);
}

/// The default turn budget is generous enough for a real multi-file task, not
/// the old 8-turn default that a package-sized delegation could exhaust
/// mid-work (bake-off L1 diagnosis).
///
/// Why: A regression here would silently reintroduce the destructive
/// re-delegation failure mode: a delegated engineer running out of turns
/// before finishing a multi-file package, forcing a `TurnCapExceeded` abort.
/// What: Asserts the default is comfortably above the old value of 8 and
/// still overridable (`with_config`/`RunContext.max_turns_override` are
/// covered by other tests in this module).
/// Test: this test.
#[test]
fn default_max_turns_is_generous() {
    let cfg = InProcessRunnerConfig::default();
    assert!(
        cfg.max_turns > 8,
        "default max_turns must be raised above the old 8-turn cap, got {}",
        cfg.max_turns
    );
    assert!(
        cfg.max_turns >= 30,
        "default max_turns should comfortably fit a multi-file package task, got {}",
        cfg.max_turns
    );
}

/// `agent_config_exists` detects present and absent configs.
///
/// Why: Callers pre-check agent names with the same path rule the runner uses.
/// What: Write one agent; assert present is true and a bogus name is false.
/// Test: this test.
#[test]
fn agent_config_exists_detects_present_and_absent() {
    let tmp = agents_dir_with("---\nname: python-engineer\n---\n", "python-engineer");
    assert!(super::agent_config_exists(tmp.path(), "python-engineer"));
    assert!(!super::agent_config_exists(tmp.path(), "ghost"));
}

/// `agent_config_exists` also recognises an embedded default roster name
/// with no disk config at all (#3046).
///
/// Why: `tools::delegate::DelegateToAgentTool::execute`'s pre-flight gate
/// calls this function directly; before #3046 it only ever consulted disk,
/// so a valid embedded roster name (e.g. `rust-engineer`) on a fresh
/// project with no `.claude/agents/` was rejected before the runner ever
/// got a chance to resolve it via the embedded fallback.
/// What: An empty/nonexistent agents dir; asserts `true` for a known
/// embedded roster name and `false` for a genuinely unknown one.
/// Test: this test.
#[test]
fn agent_config_exists_detects_embedded_default() {
    let tmp = tempfile::tempdir().expect("tempdir");
    assert!(super::agent_config_exists(tmp.path(), "rust-engineer"));
    assert!(!super::agent_config_exists(tmp.path(), "totally-bogus"));
}

/// `agent_config_exists` recognises a namespaced `<plugin>:<name>` plugin
/// agent, proving the `delegate_to_agent` pre-flight gate actually wires
/// plugin agents through to dispatch (code-critic PR #3547 review, HIGH 4 —
/// previously this always returned `false` for any namespaced name, so a
/// plugin agent was listed in `agents.list` but could never actually be
/// delegated to).
///
/// What: `dir` shaped `<root>/.claude/agents` (required so
/// `plugins::project_root_two_levels_up` can recover the root) plus a
/// plugin agent on disk under `<root>/.claude/plugins/my-plugin/agents/`.
/// Test: this test.
#[test]
fn agent_config_exists_detects_plugin_agent() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let agents_dir = tmp.path().join(".claude").join("agents");
    std::fs::create_dir_all(&agents_dir).expect("mkdir");
    let plugin_agents_dir = tmp
        .path()
        .join(".claude")
        .join("plugins")
        .join("my-plugin")
        .join("agents");
    std::fs::create_dir_all(&plugin_agents_dir).expect("mkdir");
    std::fs::write(
        plugin_agents_dir.join("reviewer.md"),
        "---\nname: reviewer\n---\n\nBody.\n",
    )
    .expect("write");

    assert!(super::agent_config_exists(
        &agents_dir,
        "my-plugin:reviewer"
    ));
    assert!(!super::agent_config_exists(&agents_dir, "my-plugin:ghost"));
    assert!(!super::agent_config_exists(
        &agents_dir,
        "no-such-plugin:reviewer"
    ));
}

/// A traversal payload in a namespaced name is rejected, never treated as
/// "exists" (code-critic PR #3547 review, HIGH 4's guard must hold even at
/// this pre-flight layer, not only inside `find_plugin_agent_config`).
///
/// Test: this test.
#[test]
fn agent_config_exists_rejects_plugin_traversal_name() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let agents_dir = tmp.path().join(".claude").join("agents");
    std::fs::create_dir_all(&agents_dir).expect("mkdir");

    assert!(!super::agent_config_exists(
        &agents_dir,
        "my-plugin:../../etc/passwd"
    ));
    assert!(!super::agent_config_exists(
        &agents_dir,
        "my-plugin:/etc/passwd"
    ));
}

/// A namespaced plugin agent whose `.md` FILE is a symlink escaping the
/// plugin's `agents/` directory must NOT count as "exists" — even though
/// the name is validly namespaced and the file literally exists on disk
/// (code-critic PR #3547 re-review, CRITICAL 5, CWE-59).
///
/// Why: `find_plugin_agent_config` returns `Some(Err(_))` for a symlinked
/// leaf file (found, but rejected) — before this fix, `agent_config_exists`
/// treated ANY `Some(_)` as "exists", letting a symlink-rejected name slip
/// past the `delegate_to_agent` pre-flight gate.
/// Test: this test.
#[test]
#[cfg(unix)]
fn agent_config_exists_rejects_symlinked_plugin_agent() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let agents_dir = tmp.path().join(".claude").join("agents");
    std::fs::create_dir_all(&agents_dir).expect("mkdir");
    let plugin_agents_dir = tmp
        .path()
        .join(".claude")
        .join("plugins")
        .join("my-plugin")
        .join("agents");
    std::fs::create_dir_all(&plugin_agents_dir).expect("mkdir");

    let secret_dir = tmp.path().join("outside");
    std::fs::create_dir_all(&secret_dir).expect("mkdir");
    let secret_path = secret_dir.join("id_rsa");
    std::fs::write(&secret_path, "SECRET_KEY_MATERIAL").expect("write secret");
    std::os::unix::fs::symlink(&secret_path, plugin_agents_dir.join("leak.md")).expect("symlink");

    assert!(!super::agent_config_exists(&agents_dir, "my-plugin:leak"));
}

/// Dispatching to an embedded, tools-restricted roster agent (`qa` — one of
/// the four Slice E3 restricted agents) with NO disk config at all still
/// enforces its `tools.allowed` — the embedded-fallback path in `load_agent`
/// (#3046) feeds `run_pipeline`'s `gate_registry` exactly like a disk-loaded
/// config does.
///
/// Why: Slice E3's own tests (`assets::tests::restricted_reviewer_agents_carry_read_only_tools`)
/// already prove the COMPOSED `AgentConfig` carries the restricted
/// allowlist; this proves the DISPATCH path — the thing #3046 actually
/// wires up — narrows the registry for a name that was NEVER on disk,
/// mirroring `tools_allowed_is_enforced`'s existing pattern but pointed at
/// an empty agents dir so `load_agent` must take the embedded branch.
/// What: An empty agents dir (no `qa.md`). Factory builds both an allowed
/// tool (`read_file`, in `qa`'s restricted allowlist) and a denied one
/// (`bash`, NOT in it). Script the model to call `bash`, then stop. Assert
/// the denied tool never ran.
/// Test: this test.
#[tokio::test]
async fn embedded_restricted_agent_dispatch_preserves_tools_allowed() {
    let tmp = tempfile::tempdir().expect("tempdir");

    let llm = Arc::new(ScriptedLlm::from_json(&[
        tool_call_response("c1", "bash"),
        stop_response("concluded"),
    ]));
    let invoked = Arc::new(Mutex::new(Vec::new()));
    let factory = Arc::new(recording_factory(
        vec!["read_file", "bash"],
        Arc::clone(&invoked),
    ));
    let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf());

    let out = runner
        .run("qa", "try the denied tool")
        .await
        .expect("loop completes (denied tool surfaces a recoverable error)");

    assert_eq!(out.content, "concluded");
    let ran = invoked.lock().expect("invoked");
    assert!(
        !ran.contains(&"bash".to_string()),
        "the embedded 'qa' agent's restricted allowlist must gate out 'bash' \
         even though it was never loaded from disk, ran: {ran:?}"
    );
}

/// Stubbed-PM: `delegate_to_agent(python-engineer)` runs the engineer's own loop
/// on its own slug and returns an `AgentOutput` to the PM.
///
/// Why: This is the core #1029 acceptance criterion — the PM's delegate tool
/// dispatches to the in-process runner, which drives the engineer's loop and
/// hands the result back. We assert the engineer's model slug was used and the
/// PM received the engineer's final text.
/// What: Engineer config pins `deepseek/deepseek-chat`. Script [tool_call,
/// stop("engineer done")]. Build the runner, wrap it in a `DelegateToAgentTool`
/// (the PM's tool), and `execute` a delegation. Assert success, the returned
/// content, that the engineer's slug drove the loop, and two chat calls.
/// Test: this test.
#[tokio::test]
async fn delegate_runs_engineer_loop() {
    let body = "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n\n\
                You are a Python engineer.\n";
    let tmp = agents_dir_with(body, "python-engineer");

    let llm = Arc::new(ScriptedLlm::from_json(&[
        tool_call_response("c1", "work_tool"),
        stop_response("engineer done"),
    ]));
    let invoked = Arc::new(Mutex::new(Vec::new()));
    let factory = Arc::new(recording_factory(vec!["work_tool"], Arc::clone(&invoked)));

    let runner = Arc::new(InProcessAgentRunner::new(
        llm.clone(),
        factory,
        tmp.path().to_path_buf(),
    ));

    // The PM dispatches through its delegate tool — the production call path.
    let delegate = DelegateToAgentTool::new(runner).with_config_dir(tmp.path().to_path_buf());
    let result = delegate
        .execute(json!({"agent_name": "python-engineer", "task": "write a function"}))
        .await;

    assert!(
        !result.is_error(),
        "delegation should succeed: {}",
        result.content()
    );
    assert_eq!(
        result.content(),
        "engineer done",
        "PM must receive the engineer's final AgentOutput content"
    );
    assert_eq!(llm.calls(), 2, "engineer loop made exactly two chat calls");
    let (model, _) = llm.first_request();
    assert_eq!(
        model, "deepseek/deepseek-chat",
        "engineer's own model slug must drive its loop"
    );
    assert_eq!(
        invoked.lock().expect("invoked").as_slice(),
        ["work_tool"],
        "the engineer's tool must have run inside its own loop"
    );
}

/// The delegated engineer's own `[llm].max_tokens` reaches its `ChatRequest`.
///
/// Why: This is the regression guard for the run_task bug where
/// `InProcessAgentRunner::run_pipeline` built the engineer's `AgentLoopConfig`
/// without ever consulting `agent.llm.max_tokens`, silently capping every
/// engineer turn at the agent-loop default (formerly a hard-coded 1024) and
/// truncating real file writes. `resolve_max_tokens` must now flow the
/// configured cap into the loop that actually drives the engineer.
/// What: Engineer config sets `[llm].max_tokens = 8192`. Script a single stop
/// turn; assert the `ScriptedLlm` observed `Some(8192)`.
/// Test: this test.
#[tokio::test]
async fn engineer_llm_max_tokens_reaches_chat_request() {
    let body = "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n\
                max_tokens: 8192\n---\n\nYou are a Python engineer.\n";
    let tmp = agents_dir_with(body, "python-engineer");

    let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("engineer done")]));
    let invoked = Arc::new(Mutex::new(Vec::new()));
    let factory = Arc::new(recording_factory(vec!["work_tool"], Arc::clone(&invoked)));

    let runner = Arc::new(InProcessAgentRunner::new(
        llm.clone(),
        factory,
        tmp.path().to_path_buf(),
    ));

    let delegate = DelegateToAgentTool::new(runner).with_config_dir(tmp.path().to_path_buf());
    let result = delegate
        .execute(json!({"agent_name": "python-engineer", "task": "write a function"}))
        .await;

    assert!(
        !result.is_error(),
        "delegation should succeed: {}",
        result.content()
    );
    assert_eq!(
        llm.first_max_tokens(),
        Some(8192),
        "the engineer's configured [llm].max_tokens must reach its ChatRequest"
    );
}

/// An unknown agent name yields a `RunnerError::UnknownAgent` (no loop runs).
///
/// Why: Delegating to a non-existent agent must fail cleanly, not panic or spin
/// the loop.
/// What: Empty agents dir; call `run("ghost", ...)`; assert an error whose
/// message names the agent, and that the LLM was never called.
/// Test: this test.
#[tokio::test]
async fn unknown_agent_errors() {
    let tmp = tempfile::tempdir().expect("tempdir");
    let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("never reached")]));
    let invoked = Arc::new(Mutex::new(Vec::new()));
    let factory = Arc::new(recording_factory(vec![], invoked));
    let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf());

    let err = runner
        .run("ghost", "do something")
        .await
        .expect_err("unknown agent must error");

    assert!(
        err.to_string().contains("ghost"),
        "error must name the unknown agent, got: {err}"
    );
    assert_eq!(llm.calls(), 0, "loop must not run for an unknown agent");
}

/// `tools.allowed` is enforced: a tool the model calls but the agent does not
/// allow is not dispatched (it is gated out of the registry).
///
/// Why: Per-agent tool gating is a hard #1029 criterion — an agent must not be
/// able to invoke a tool outside its allowlist.
/// What: Agent allows only `allowed_tool`. The factory builds BOTH `allowed_tool`
/// and `denied_tool`. Script the model to call `denied_tool`, then stop. Assert
/// the denied tool never ran (its name is absent from the invocation log) and the
/// allowed tool would have run had it been called.
/// Test: this test.
#[tokio::test]
async fn tools_allowed_is_enforced() {
    let body = "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n\
                tools: [allowed_tool]\n---\n";
    let tmp = agents_dir_with(body, "python-engineer");

    // Model tries to call the DENIED tool, then concludes.
    let llm = Arc::new(ScriptedLlm::from_json(&[
        tool_call_response("c1", "denied_tool"),
        stop_response("concluded"),
    ]));
    let invoked = Arc::new(Mutex::new(Vec::new()));
    let factory = Arc::new(recording_factory(
        vec!["allowed_tool", "denied_tool"],
        Arc::clone(&invoked),
    ));
    let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf());

    let out = runner
        .run("python-engineer", "try the denied tool")
        .await
        .expect("loop completes (denied tool surfaces a recoverable error)");

    assert_eq!(out.content, "concluded");
    let ran = invoked.lock().expect("invoked");
    assert!(
        !ran.contains(&"denied_tool".to_string()),
        "denied tool must never execute; gated out of the registry, ran: {ran:?}"
    );
}

/// With no `tools.allowed`, every tool the factory builds is permitted.
///
/// Why: An absent allowlist means "all tools"; gating must not strip them.
/// What: Agent has no `[tools]` table. Model calls `any_tool`, then stops.
/// Assert the tool actually ran.
/// Test: this test.
#[tokio::test]
async fn no_allowlist_permits_all() {
    let body = "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n";
    let tmp = agents_dir_with(body, "python-engineer");

    let llm = Arc::new(ScriptedLlm::from_json(&[
        tool_call_response("c1", "any_tool"),
        stop_response("ok"),
    ]));
    let invoked = Arc::new(Mutex::new(Vec::new()));
    let factory = Arc::new(recording_factory(vec!["any_tool"], Arc::clone(&invoked)));
    let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf());

    runner
        .run("python-engineer", "use a tool")
        .await
        .expect("completes");

    assert_eq!(
        invoked.lock().expect("invoked").as_slice(),
        ["any_tool"],
        "with no allowlist, the tool must run"
    );
}

/// The engineer's token usage rolls up into the returned `AgentOutput`.
///
/// Why: For #1030 the orchestrator sums the sub-agent's usage into the PM's
/// transcript; that requires the runner's `AgentOutput.usage` to carry the
/// engineer's accrued tokens across all of its turns.
/// What: Script [tool_call (30+10), stop (15+5)]; the returned usage must equal
/// the sum across both engineer turns.
/// Test: this test.
#[tokio::test]
async fn usage_rolls_up_to_output() {
    let body = "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n";
    let tmp = agents_dir_with(body, "python-engineer");

    let llm = Arc::new(ScriptedLlm::from_json(&[
        tool_call_response("c1", "any_tool"),
        stop_response("done"),
    ]));
    let invoked = Arc::new(Mutex::new(Vec::new()));
    let factory = Arc::new(recording_factory(vec!["any_tool"], invoked));
    let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf());

    let out = runner
        .run("python-engineer", "task")
        .await
        .expect("completes");

    assert_eq!(
        out.usage.prompt_tokens,
        30 + 15,
        "prompt tokens sum across turns"
    );
    assert_eq!(
        out.usage.completion_tokens,
        10 + 5,
        "completion tokens sum across turns"
    );
}

/// `RunContext.model` overrides the agent's configured model for one call.
///
/// Why: The orchestrator can pin a model per delegation; per-call override must
/// win over agent config (model-comparison harness varies the model per run).
/// What: Agent config pins one model; `RunContext.model` pins another. Assert the
/// RunContext slug drove the loop's request.
/// Test: this test.
#[tokio::test]
async fn run_context_overrides_model() {
    let body = "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n";
    let tmp = agents_dir_with(body, "python-engineer");

    let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("done")]));
    let invoked = Arc::new(Mutex::new(Vec::new()));
    let factory = Arc::new(recording_factory(vec![], invoked));
    let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf());

    let ctx = RunContext {
        model: Some("anthropic/claude-sonnet-4-6".to_string()),
        ..Default::default()
    };
    runner
        .run_with_context("python-engineer", "task", &ctx)
        .await
        .expect("completes");

    let (model, _) = llm.first_request();
    assert_eq!(
        model, "anthropic/claude-sonnet-4-6",
        "RunContext.model must override the agent's configured model"
    );
}

/// `RunContext.max_turns_override` caps the loop below the runner default.
///
/// Why: A per-call turn cap lets the orchestrator bound a single delegation; the
/// override must win over `InProcessRunnerConfig.max_turns`.
/// What: Runner default is 8 turns, but `max_turns_override = 1`. Script only
/// tool-call responses so the loop would run forever without a cap; assert it
/// aborts after exactly one chat call.
/// Test: this test.
#[tokio::test]
async fn run_context_overrides_max_turns() {
    let body = "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n";
    let tmp = agents_dir_with(body, "python-engineer");

    // Always-tool-call: the loop never converges, so only the cap stops it.
    let llm = Arc::new(ScriptedLlm::from_json(&[
        tool_call_response("c1", "any_tool"),
        tool_call_response("c2", "any_tool"),
        tool_call_response("c3", "any_tool"),
    ]));
    let invoked = Arc::new(Mutex::new(Vec::new()));
    let factory = Arc::new(recording_factory(vec!["any_tool"], invoked));
    let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf())
        .with_config(InProcessRunnerConfig {
            max_turns: 8,
            timeout_secs: 30,
        });

    let ctx = RunContext {
        max_turns_override: Some(1),
        ..Default::default()
    };
    let err = runner
        .run_with_context("python-engineer", "loop", &ctx)
        .await
        .expect_err("a 1-turn cap on a non-converging loop must abort");

    assert!(
        err.to_string().contains("turn cap of 1"),
        "error should report the overridden cap, got: {err}"
    );
    assert_eq!(
        llm.calls(),
        1,
        "loop must stop after the single allowed turn"
    );
}

/// `with_timeout_secs` actually shortens the loop's wall-clock deadline
/// (#2207).
///
/// Why: This is the direct regression guard for `run_task`/`task::executor`
/// threading a resolved run-wide deadline onto the delegated engineer's
/// runner — if `with_timeout_secs` were a no-op, a raised or lowered deadline
/// on the PM side would never actually reach the engineer's own loop.
/// What: A response that would otherwise arrive instantly is delayed 3s by
/// `SleepyLlm`; the runner's timeout is overridden down to 1s. Assert the run
/// errors with the `Timeout` variant's message (not `TurnCapExceeded` or a
/// transport error) and that it does so well before the full 3s delay would
/// have elapsed.
/// Test: this test.
#[tokio::test]
async fn with_timeout_secs_shortens_the_deadline() {
    let body = "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n";
    let tmp = agents_dir_with(body, "python-engineer");

    let llm = Arc::new(SleepyLlm {
        inner: ScriptedLlm::from_json(&[stop_response("done")]),
        delay: std::time::Duration::from_secs(3),
    });
    let invoked = Arc::new(Mutex::new(Vec::new()));
    let factory = Arc::new(recording_factory(vec![], invoked));
    let runner =
        InProcessAgentRunner::new(llm, factory, tmp.path().to_path_buf()).with_timeout_secs(1);

    let started = std::time::Instant::now();
    let err = runner
        .run("python-engineer", "task")
        .await
        .expect_err("a 1s deadline against a 3s-delayed response must time out");
    let elapsed = started.elapsed();

    assert!(
        err.to_string().contains("wall-clock timeout of 1s"),
        "error must be the Timeout variant, got: {err}"
    );
    assert!(
        elapsed < std::time::Duration::from_secs(3),
        "the 1s override must fire well before the mock's 3s delay, elapsed={elapsed:?}"
    );
}

/// `with_timeout_secs` changes ONLY the timeout, leaving a previously
/// configured `max_turns` untouched (#2207).
///
/// Why: `with_timeout_secs` is a targeted setter specifically so callers
/// don't have to reconstruct a whole `InProcessRunnerConfig` (risking a
/// silent `max_turns` reset to its default) just to change the deadline.
/// What: Configure `max_turns: 2` via `with_config`, then call
/// `with_timeout_secs` with a generous value; script tool calls that never
/// converge. Assert the run still aborts via `TurnCapExceeded` at exactly 2
/// calls, proving `max_turns` survived the later `with_timeout_secs` call.
/// Test: this test.
#[tokio::test]
async fn with_timeout_secs_preserves_configured_max_turns() {
    let body = "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n";
    let tmp = agents_dir_with(body, "python-engineer");

    let llm = Arc::new(ScriptedLlm::from_json(&[
        tool_call_response("c1", "any_tool"),
        tool_call_response("c2", "any_tool"),
        tool_call_response("c3", "any_tool"),
    ]));
    let invoked = Arc::new(Mutex::new(Vec::new()));
    let factory = Arc::new(recording_factory(vec!["any_tool"], invoked));
    let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf())
        .with_config(InProcessRunnerConfig {
            max_turns: 2,
            timeout_secs: 30,
        })
        .with_timeout_secs(300);

    let err = runner
        .run("python-engineer", "task")
        .await
        .expect_err("a 2-turn cap on a non-converging loop must abort");

    assert!(
        err.to_string().contains("turn cap of 2"),
        "max_turns=2 from with_config must survive the later with_timeout_secs call, got: {err}"
    );
    assert_eq!(
        llm.calls(),
        2,
        "loop must stop after the configured 2 turns"
    );
}

/// Project `CLAUDE.md` context is injected into the assembled system prompt.
///
/// Why: Sub-agents must see the same project rules as the PM (parity-spec); the
/// runner threads project context into `assemble_system_prompt`.
/// What: Attach a distinctive project-context marker; assert it appears in the
/// system prompt the scripted client received.
/// Test: this test.
#[tokio::test]
async fn project_context_reaches_prompt() {
    let body =
        "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n\nAGENT-PROMPT-MARKER\n";
    let tmp = agents_dir_with(body, "python-engineer");

    let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("done")]));
    let invoked = Arc::new(Mutex::new(Vec::new()));
    let factory = Arc::new(recording_factory(vec![], invoked));
    let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf())
        .with_project_context("PROJECT-CONTEXT-MARKER");

    runner
        .run("python-engineer", "task")
        .await
        .expect("completes");

    let (_, system) = llm.first_request();
    assert!(
        system.contains("AGENT-PROMPT-MARKER"),
        "assembled prompt must include the agent's own system prompt"
    );
    assert!(
        system.contains("PROJECT-CONTEXT-MARKER"),
        "assembled prompt must include the injected project context"
    );
}

/// The skill catalog (#2069) reaches the assembled prompt in
/// `HarnessMode::DailyDriver`.
///
/// Why: A delegated sub-agent must see the same cheap, metadata-only skill
/// catalog the delegating PM does.
/// What: Attach a distinctive catalog marker via `with_skills_catalog`,
/// default mode (`DailyDriver`); assert it appears in the assembled prompt.
/// Test: this test.
#[tokio::test]
async fn skills_catalog_reaches_daily_driver_prompt() {
    let body = "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n";
    let tmp = agents_dir_with(body, "python-engineer");

    let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("done")]));
    let invoked = Arc::new(Mutex::new(Vec::new()));
    let factory = Arc::new(recording_factory(vec![], invoked));
    let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf())
        .with_skills_catalog("SKILLS-CATALOG-MARKER");

    runner
        .run("python-engineer", "task")
        .await
        .expect("completes");

    let (_, system) = llm.first_request();
    assert!(
        system.contains("SKILLS-CATALOG-MARKER"),
        "assembled DailyDriver prompt must include the skill catalog"
    );
}

/// The skill catalog (#2069) is ignored entirely under `HarnessMode::Parity`.
///
/// Why: Parity's byte-identical-schema/prompt guarantee (parity-spec D2)
/// must never depend on a project's skill catalog.
/// What: Attach a catalog marker AND `with_mode(Parity)`; assert the marker
/// is absent from the assembled prompt.
/// Test: this test.
#[tokio::test]
async fn skills_catalog_ignored_in_parity() {
    let body = "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n";
    let tmp = agents_dir_with(body, "python-engineer");

    let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("done")]));
    let invoked = Arc::new(Mutex::new(Vec::new()));
    let factory = Arc::new(recording_factory(vec![], invoked));
    let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf())
        .with_skills_catalog("SKILLS-CATALOG-MARKER")
        .with_mode(crate::mode::HarnessMode::Parity);

    runner
        .run("python-engineer", "task")
        .await
        .expect("completes");

    let (_, system) = llm.first_request();
    assert!(
        !system.contains("SKILLS-CATALOG-MARKER"),
        "Parity prompt must never include the skill catalog"
    );
}

/// `with_mode` must be chainable and a delegated run must complete
/// successfully under EITHER `HarnessMode` (#2059) — both modes are
/// functionally identical in M1, so this pins "the builder wires through
/// without breaking the run", not a behavioural difference (there isn't
/// one yet — see `crate::mode`'s and `agent_loop::tests`'s own docs for
/// where the real branch point is exercised).
///
/// Why: `InProcessAgentRunner` is the seam that propagates the PM's
/// resolved mode to a delegated sub-agent's own `AgentLoop`; a broken
/// propagation would most likely surface as the delegated run failing to
/// construct/complete, which this test would catch.
/// What: runs the SAME scripted delegation twice, once per mode, asserting
/// both complete successfully.
/// Test: this test.
#[tokio::test]
async fn with_mode_completes_a_delegated_run_in_both_modes() {
    let body = "---\nname: python-engineer\nmodel: openai/gpt-4o-mini\n---\n";
    let tmp = agents_dir_with(body, "python-engineer");

    for mode in [
        crate::mode::HarnessMode::DailyDriver,
        crate::mode::HarnessMode::Parity,
    ] {
        let llm = Arc::new(ScriptedLlm::from_json(&[stop_response("done")]));
        let invoked = Arc::new(Mutex::new(Vec::new()));
        let factory = Arc::new(recording_factory(vec![], invoked));
        let runner =
            InProcessAgentRunner::new(llm, factory, tmp.path().to_path_buf()).with_mode(mode);

        runner
            .run("python-engineer", "task")
            .await
            .unwrap_or_else(|e| panic!("run must complete under mode {mode:?}: {e}"));
    }
}

// ── #2056: ToolEventSink / cancel-flag propagation into the delegated loop ──────

/// Minimal `ToolEventSink` recording call order (see
/// `agent_loop::tests::RecordingSink` for the same pattern exercising the loop
/// directly; this one proves the runner PROPAGATES a sink to its own
/// internally-built `AgentLoop`).
struct RecordingSink {
    calls: Mutex<Vec<String>>,
    /// (DOC-39 AC-13) `(agent, agent_id)` pairs seen by `tool_started`, in
    /// call order — kept separate from `calls` so every pre-existing test
    /// asserting `calls`'s string format is untouched; only
    /// `sequential_delegations_to_same_named_agent_get_distinct_ids` and
    /// `concurrently_delegated_same_named_agents_get_distinct_ids_under_tokio_join`
    /// read this.
    started_ids: Mutex<Vec<(String, String)>>,
}

#[async_trait]
impl ToolEventSink for RecordingSink {
    async fn tool_started(
        &self,
        agent: &str,
        agent_id: &str,
        call_id: &str,
        tool: &str,
        _args_preview: &str,
    ) {
        self.calls
            .lock()
            .expect("lock poisoned")
            .push(format!("started:{agent}:{tool}:{call_id}"));
        self.started_ids
            .lock()
            .expect("lock poisoned")
            .push((agent.to_string(), agent_id.to_string()));
    }

    async fn tool_finished(
        &self,
        agent: &str,
        _agent_id: &str,
        call_id: &str,
        tool: &str,
        success: bool,
        _result_preview: &str,
    ) {
        self.calls
            .lock()
            .expect("lock poisoned")
            .push(format!("finished:{agent}:{tool}:{call_id}:{success}"));
    }

    async fn tool_error(
        &self,
        agent: &str,
        _agent_id: &str,
        call_id: &str,
        tool: &str,
        _error: &str,
    ) {
        self.calls
            .lock()
            .expect("lock poisoned")
            .push(format!("error:{agent}:{tool}:{call_id}"));
    }
}

/// A sink attached via `with_tool_event_sink` must observe the DELEGATED
/// engineer's own tool dispatch, not just be silently dropped.
///
/// Why: #2056 needs a delegated sub-agent's tool activity to be observable to
/// the same sink the delegating (PM) loop uses; this is the propagation seam
/// that makes that possible.
/// What: Script [tool_call("mytool"), stop]; attach a `RecordingSink` to the
/// runner; assert it saw `started`/`finished` for `mytool`, ATTRIBUTED
/// (UI Phase 1) to `python-engineer` — the delegated agent — rather than to
/// the PM that shares this same sink instance.
/// Test: this test.
#[tokio::test]
async fn sink_reaches_delegated_loop() {
    let llm = Arc::new(ScriptedLlm::from_json(&[
        tool_call_response("call-1", "mytool"),
        stop_response("engineer done"),
    ]));
    let tmp = agents_dir_with(
        "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n",
        "python-engineer",
    );
    let invoked = Arc::new(Mutex::new(Vec::new()));
    let factory = Arc::new(recording_factory(vec!["mytool"], invoked));
    let sink = Arc::new(RecordingSink {
        calls: Mutex::new(Vec::new()),
        started_ids: Mutex::new(Vec::new()),
    });

    let runner = InProcessAgentRunner::new(llm, factory, tmp.path().to_path_buf())
        .with_tool_event_sink(sink.clone());

    runner
        .run("python-engineer", "task")
        .await
        .expect("completes");

    assert_eq!(
        sink.calls.lock().expect("lock poisoned").as_slice(),
        [
            "started:python-engineer:mytool:call-1",
            "finished:python-engineer:mytool:call-1:true"
        ],
        "the runner must attribute a delegated sub-agent's tool events to \
         that sub-agent — the sink is shared with the PM, so an unattributed \
         (or PM-attributed) event here would make the two indistinguishable"
    );
}

/// Two SEPARATE, SEQUENTIAL delegations to the SAME `agent_name` must mint
/// DISTINCT `agent_id`s, even though `agent` is identical on both (DOC-39
/// AC-13.1/13.2).
///
/// Why: this is the exact regression #2862 left open — `tools::delegate`
/// spawns a delegated agent purely by `agent_name`, so two delegations to
/// `python-engineer` were indistinguishable on the event stream. Each call to
/// `InProcessAgentRunner::run` re-enters `run_pipeline`, which now mints a
/// fresh UUID v4 per invocation — this test drives the SAME runner (and the
/// SAME shared sink, mirroring how one `Arc<dyn ToolEventSink>` is shared
/// across every delegation in production) twice and asserts the two
/// `agent_id`s differ while `agent` stays `"python-engineer"` both times.
/// NOTE (code-critic MEDIUM): this test awaits the FIRST `run()` call to
/// completion before starting the SECOND — it is SEQUENTIAL, not concurrent,
/// and the name says so deliberately. It still matters (it proves per-spawn
/// minting, not per-runner-instance caching), but the genuinely-concurrent
/// claim — two spawns racing under `tokio::join!` against one shared sink —
/// is a SEPARATE property, proven by
/// [`concurrently_delegated_same_named_agents_get_distinct_ids_under_tokio_join`]
/// below.
/// What: scripts `[tool_call, stop, tool_call, stop]` on one `ScriptedLlm` so
/// one runner + one llm serves both sequential `run()` calls; asserts both
/// recorded `(agent, agent_id)` pairs share `agent` but differ in `agent_id`,
/// and neither is empty/the unattributed sentinel.
/// Test: this test.
#[tokio::test]
async fn sequential_delegations_to_same_named_agent_get_distinct_ids() {
    let llm = Arc::new(ScriptedLlm::from_json(&[
        tool_call_response("call-1", "mytool"),
        stop_response("engineer done 1"),
        tool_call_response("call-2", "mytool"),
        stop_response("engineer done 2"),
    ]));
    let tmp = agents_dir_with(
        "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n",
        "python-engineer",
    );
    let invoked = Arc::new(Mutex::new(Vec::new()));
    let factory = Arc::new(recording_factory(vec!["mytool"], invoked));
    let sink = Arc::new(RecordingSink {
        calls: Mutex::new(Vec::new()),
        started_ids: Mutex::new(Vec::new()),
    });

    let runner = InProcessAgentRunner::new(llm, factory, tmp.path().to_path_buf())
        .with_tool_event_sink(sink.clone());

    runner
        .run("python-engineer", "task A")
        .await
        .expect("first delegation completes");
    runner
        .run("python-engineer", "task B")
        .await
        .expect("second delegation completes");

    let ids = sink.started_ids.lock().expect("lock poisoned").clone();
    assert_eq!(ids.len(), 2, "expected one tool_started per delegation");
    let (agent_a, id_a) = &ids[0];
    let (agent_b, id_b) = &ids[1];
    assert_eq!(agent_a, "python-engineer");
    assert_eq!(agent_b, "python-engineer");
    assert_ne!(
        id_a, id_b,
        "two delegations to the SAME agent_name must mint DISTINCT agent_ids \
         (DOC-39 AC-13) — otherwise same-named delegated agents stay \
         indistinguishable on the event stream"
    );
    assert!(!id_a.is_empty() && id_a != crate::events::UNATTRIBUTED_AGENT_ID);
    assert!(!id_b.is_empty() && id_b != crate::events::UNATTRIBUTED_AGENT_ID);
}

/// An `InferenceAdapter` whose response depends ONLY on the given request's
/// OWN transcript (whether its last message is a tool result) — NEVER a
/// shared cross-call cursor/counter.
///
/// Why: [`ScriptedLlm`] is a fixed-position cursor shared across every
/// `chat()` call; if two independent conversations issued `chat()` calls
/// that genuinely interleaved (as
/// [`concurrently_delegated_same_named_agents_get_distinct_ids_under_tokio_join`]
/// requires), a shared cursor would hand conversation A's turn-2 response to
/// conversation B's turn-1 call (or vice versa), corrupting both scripts
/// unpredictably. Keying the response off each REQUEST's own message history
/// instead makes the mock correct under ARBITRARY interleaving, because two
/// independent conversations never share transcript state — exactly how a
/// real LLM endpoint behaves (its response depends on what YOU sent it, not
/// on a global call counter).
/// What: returns a `bash`-tool-call fixture when the request's last message
/// is not yet a tool result, and a `stop` fixture once it is — i.e. "call
/// the tool once, then finish", regardless of how many OTHER conversations
/// are calling `chat()` concurrently against this SAME shared instance.
/// Calls `tokio::task::yield_now()` first so `tokio::join!`'s cooperative
/// scheduler actually interleaves the two conversations' polls instead of
/// silently running one to completion before ever polling the other (which
/// would degrade the concurrent test back into the sequential case it is
/// meant to rule out — see that test's own doc for why a synchronous mock
/// with no real `Pending` state cannot, by itself, prove interleaving-safety).
/// Test: `concurrently_delegated_same_named_agents_get_distinct_ids_under_tokio_join`.
struct ConversationAwareLlm;

#[async_trait]
impl InferenceAdapter for ConversationAwareLlm {
    crate::llm::mock_adapter_identity!("mock-conversation-aware");

    async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
        // Force a genuine yield point: without this, `tokio::join!` could
        // run one conversation's entire `AgentLoop::run` to completion (chat
        // -> dispatch -> chat -> stop, none of which are ever `Pending`
        // here) before the executor ever polls the other future, which
        // would make this test accidentally-sequential despite the
        // `tokio::join!` syntax.
        tokio::task::yield_now().await;

        let last_was_tool_result = req
            .messages
            .last()
            .map(|m| m.role == "tool")
            .unwrap_or(false);
        let fixture = if last_was_tool_result {
            stop_response("engineer done")
        } else {
            tool_call_response("call-1", "mytool")
        };
        serde_json::from_value(fixture).map_err(|e| {
            InferenceError::MissingConfig(format!("ConversationAwareLlm: invalid fixture: {e}"))
        })
    }
}

/// The GENUINELY CONCURRENT proof for DOC-39 AC-13 (code-critic MEDIUM
/// finding): two same-named delegations raced against ONE shared runner and
/// ONE shared sink via `tokio::join!` must still mint DISTINCT `agent_id`s.
///
/// Why: [`sequential_delegations_to_same_named_agent_get_distinct_ids`]
/// (above) only proves the property when the two delegations are strictly
/// ordered — it cannot rule out a race between two spawns whose execution
/// genuinely overlaps. `run_pipeline` mints its `agent_id` via a bare
/// `uuid::Uuid::new_v4()` call — no shared mutable counter, no `&mut self`
/// state on the runner — so no race is EXPECTED, but that safety claim was
/// previously asserted only by construction/inspection. This test drives
/// both delegations through `tokio::join!(runner.run(...), runner.run(...))`
/// against the SAME `runner` (hence the SAME shared `llm` and `sink` fields)
/// using [`ConversationAwareLlm`] — a stateless mock safe under arbitrary
/// interleaving — to empirically exercise the race rather than only assert
/// its absence by reading the code.
/// What: runs `runner.run("python-engineer", "task A")` concurrently with
/// `runner.run("python-engineer", "task B")`; asserts both `tool_started`
/// events recorded on the shared sink carry `agent == "python-engineer"`
/// with two DISTINCT, non-empty `agent_id`s.
/// Test: this test.
#[tokio::test]
async fn concurrently_delegated_same_named_agents_get_distinct_ids_under_tokio_join() {
    let llm = Arc::new(ConversationAwareLlm);
    let tmp = agents_dir_with(
        "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n",
        "python-engineer",
    );
    let invoked = Arc::new(Mutex::new(Vec::new()));
    let factory = Arc::new(recording_factory(vec!["mytool"], invoked));
    let sink = Arc::new(RecordingSink {
        calls: Mutex::new(Vec::new()),
        started_ids: Mutex::new(Vec::new()),
    });

    let runner = InProcessAgentRunner::new(llm, factory, tmp.path().to_path_buf())
        .with_tool_event_sink(sink.clone());

    let (result_a, result_b) = tokio::join!(
        runner.run("python-engineer", "task A"),
        runner.run("python-engineer", "task B"),
    );
    result_a.expect("delegation A completes");
    result_b.expect("delegation B completes");

    let ids = sink.started_ids.lock().expect("lock poisoned").clone();
    assert_eq!(
        ids.len(),
        2,
        "expected one tool_started per concurrently-run delegation: {ids:?}"
    );
    assert!(
        ids.iter().all(|(agent, _)| agent == "python-engineer"),
        "both concurrent delegations must attribute to the SAME agent name: {ids:?}"
    );
    let (_, id_a) = &ids[0];
    let (_, id_b) = &ids[1];
    assert_ne!(
        id_a, id_b,
        "two GENUINELY CONCURRENT delegations to the SAME agent_name must \
         still mint DISTINCT agent_ids (DOC-39 AC-13) — this empirically \
         exercises the per-spawn UUID mint under an actual race, not just a \
         by-construction argument"
    );
    assert!(!id_a.is_empty() && id_a != crate::events::UNATTRIBUTED_AGENT_ID);
    assert!(!id_b.is_empty() && id_b != crate::events::UNATTRIBUTED_AGENT_ID);
}

/// A cancel flag attached via `with_cancel_flag` must abort the DELEGATED
/// engineer's own loop before it makes any chat call, not just the PM's.
///
/// Why: `session.cancel` must stop a whole in-flight run, including any
/// sub-agent currently delegated to — otherwise cancelling a session would
/// leave an orphaned engineer loop running.
/// What: Pre-set the flag, attach it via `with_cancel_flag`, and assert the
/// run errors with zero chat calls made.
/// Test: this test.
#[tokio::test]
async fn cancel_flag_reaches_delegated_loop() {
    let llm = Arc::new(ScriptedLlm::from_json(&[stop_response(
        "should never be reached",
    )]));
    let tmp = agents_dir_with(
        "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n",
        "python-engineer",
    );
    let invoked = Arc::new(Mutex::new(Vec::new()));
    let factory = Arc::new(recording_factory(vec![], invoked));
    let cancel = Arc::new(AtomicBool::new(true));

    let runner = InProcessAgentRunner::new(llm.clone(), factory, tmp.path().to_path_buf())
        .with_cancel_flag(cancel);

    let result = runner.run("python-engineer", "task").await;
    assert!(result.is_err(), "a pre-cancelled run must error");
    assert_eq!(
        llm.calls(),
        0,
        "cancellation must be observed before any chat call"
    );
}