trusty-code 0.4.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
//! Tests for #2056's background task-execution orchestration. Split out of
//! `executor.rs` per the crate's `_tests.rs` sibling-file convention (see
//! `intent::classifier_tests` for precedent) to keep the production file
//! under the 500-SLOC cap.

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

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

use super::*;
use crate::agent_loop::telemetry;
use crate::agent_loop::with_cadence_env;
use crate::llm::{ChatRequest, ChatResponse, InferenceAdapter, InferenceError};
use crate::session::{SessionRegistry, SessionStatus};
use crate::task::mock_llm::EchoLlmClient;

/// Agents dir fixture with `pm.md` + `python-engineer.md` (mirrors
/// `run_task::tests::agents_dir`).
fn agents_dir() -> TempDir {
    let tmp = tempfile::tempdir().expect("agents tempdir");
    std::fs::write(
        tmp.path().join("pm.md"),
        "---\nname: pm\nmodel: openai/gpt-4o-mini\n---\n\nYou are the PM.\n",
    )
    .expect("write pm.md");
    std::fs::write(
        tmp.path().join("python-engineer.md"),
        "---\nname: python-engineer\nmodel: deepseek/deepseek-chat\n---\n\nYou are a Python engineer.\n",
    )
    .expect("write python-engineer.md");
    tmp
}

fn params(agents: &TempDir, project: &TempDir, session_id: &str) -> TaskRunParams {
    TaskRunParams {
        session_id: session_id.to_string(),
        task: "do something".to_string(),
        agent_name: "pm".to_string(),
        binding: crate::binding::ProjectBinding::resolve(Some(project.path().to_path_buf()))
            .expect("tempdir must bind"),
        agents_dir: agents.path().to_path_buf(),
        model_override: None,
        mode: crate::mode::HarnessMode::default(),
        deadline_secs: None,
        // #3902: this daemon path (`run_and_record`) always sets `cadence:
        // Some(_)` on the PM loop, so any test built from this shared
        // helper that runs enough turns to trip a real cadence/threshold
        // fire needs an isolated telemetry dir — `AgentLoop::telemetry_data_dir`'s
        // `#[cfg(test)]` guard panics on the first un-injected fire rather
        // than risk the race. Isolating every call unconditionally (rather
        // than only the specific tests known to fire today) means a FUTURE
        // test built on this same helper can never reintroduce the
        // omission either.
        telemetry_data_dir: Some(telemetry::test_temp_dir("task-executor")),
    }
}

/// A second `spawn_task_run` against the SAME session before the first
/// finishes must be rejected — the core "no overlapping runs" guarantee.
#[tokio::test]
async fn spawn_task_run_rejects_second_overlapping_run() {
    let registry = Arc::new(SessionRegistry::new());
    let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");
    let llm: Arc<dyn InferenceAdapter> = Arc::new(EchoLlmClient::new());

    let p = params(&agents, &project, &session.id);

    spawn_task_run(Arc::clone(&registry), Arc::clone(&llm), p.clone())
        .expect("first run must start");
    let err = spawn_task_run(Arc::clone(&registry), llm, p)
        .expect_err("second overlapping run must be rejected");
    assert_eq!(err.code, -32003);

    // Let the background task actually finish so this test doesn't leak a
    // dangling tokio task past its own scope.
    registry
        .shutdown_executions(std::time::Duration::from_secs(5))
        .await;
}

/// `spawn_task_run` against an unknown session must error rather than
/// spawning anything.
#[tokio::test]
async fn spawn_task_run_unknown_session_errors() {
    let registry = Arc::new(SessionRegistry::new());
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");
    let llm: Arc<dyn InferenceAdapter> = Arc::new(EchoLlmClient::new());

    let p = params(&agents, &project, "does-not-exist");
    let err = spawn_task_run(registry, llm, p).unwrap_err();
    assert_eq!(err.code, -32007);
}

// `aggregate_usage_per_role` itself is now `run_task::aggregate_usage_per_role`
// (#2061, #1475 bug 1) — its per-role pricing behaviour is tested once, at
// its actual definition site, in `run_task::report::tests`
// (`aggregate_usage_per_role_prices_each_role_separately`). This module only
// tests THIS daemon path's own wrapper (`resolve_engineer_model`, below).

/// `resolve_engineer_model` resolves via the embedded default roster
/// (#3046) — never panics, and no longer degrades to the literal
/// `"unknown"` — when the on-disk engineer config is missing, because
/// `ENGINEER_AGENT_NAME` (`"python-engineer"`) is one of the 31 embedded
/// roster names.
///
/// Why: before #3046, `resolve_agent_model_slug` read
/// `<agents_dir>/python-engineer.md` directly with no embedded fallback, so
/// a fresh project with no `.claude/agents/` priced every engineer turn
/// under the degraded `"unknown"` slug even though the run itself (once
/// #3046's other fixes land) now actually dispatches a real embedded
/// `python-engineer` config. This pins the corrected behaviour: pricing and
/// dispatch now agree.
/// What: empty agents dir, no `python-engineer.md`; asserts the resolved
/// slug is neither empty nor the literal `"unknown"` fallback string.
/// Test: this test.
#[test]
fn resolve_engineer_model_falls_back_to_embedded_when_disk_config_missing() {
    let empty_agents = tempfile::tempdir().expect("empty agents tempdir");
    let p = TaskRunParams {
        session_id: "s".to_string(),
        task: "do something".to_string(),
        agent_name: "pm".to_string(),
        binding: crate::binding::ProjectBinding::resolve(Some(empty_agents.path().to_path_buf()))
            .expect("tempdir must bind"),
        agents_dir: empty_agents.path().to_path_buf(),
        model_override: None,
        mode: crate::mode::HarnessMode::default(),
        deadline_secs: None,
        // Never reaches an `AgentLoop` run in this test (only
        // `resolve_engineer_model` is called below) — irrelevant here.
        telemetry_data_dir: None,
    };
    let model = resolve_engineer_model(&p);
    assert_ne!(
        model, "unknown",
        "python-engineer is embedded (#3046); a missing disk config must resolve \
         via the embedded fallback, not degrade to unknown"
    );
    assert!(!model.is_empty());
}

/// `daily_driver_skills_catalog` returns `None` under `HarnessMode::Parity`,
/// even when the project has a real `.claude/skills/` catalog (#2069's
/// scope note: "Parity mode should NOT progressively disclose").
#[test]
fn daily_driver_skills_catalog_none_in_parity() {
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");
    let skills_dir = project.path().join(".claude").join("skills").join("demo");
    std::fs::create_dir_all(&skills_dir).expect("mkdir skill dir");
    std::fs::write(
        skills_dir.join("SKILL.md"),
        "---\nname: demo\ndescription: Demo skill\n---\nbody\n",
    )
    .expect("write SKILL.md");

    let mut p = params(&agents, &project, "s");
    p.mode = crate::mode::HarnessMode::Parity;

    assert!(
        daily_driver_skills_catalog(&p, p.binding.root().expect("bound in this test")).is_none()
    );
}

/// `daily_driver_skills_catalog` falls back to the embedded default skill
/// catalog (#2895) when the project has no `.claude/skills/` directory at
/// all, in `HarnessMode::DailyDriver`.
///
/// Why: `skills::discover_skill_metadata`'s embedded-fallback (#2895) means
/// a project with no disk skills is no longer catalog-empty — it now
/// resolves to `crate::assets::DEFAULT_SKILLS`. This test previously asserted
/// `None` here; that assumption is exactly what #2895 changes, so the
/// assertion now pins the new (intended) behavior instead.
/// Test: this test.
#[test]
fn daily_driver_skills_catalog_falls_back_to_embedded_when_no_skills_dir() {
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");

    let mut p = params(&agents, &project, "s");
    p.mode = crate::mode::HarnessMode::DailyDriver;

    let (catalog, resolver) =
        daily_driver_skills_catalog(&p, p.binding.root().expect("bound in this test"))
            .expect("embedded catalog present");
    assert!(catalog.contains("systematic-debugging"));
    assert!(resolver.resolve("systematic-debugging").is_some());
}

/// A project's `.claude/settings.json` `code_harness.cadence_turns` override
/// reaches `resolve_cadence_config` exactly the way `run_and_record` calls it
/// (#2346) — the same `params.project` path a real `spawn_task_run` would use.
///
/// Why: #2346's acceptance criteria explicitly call for an integration-style
/// proof that the settings.json precedence chain changes `cadence_turns`, not
/// just a unit test isolated to `agent_loop::cadence`'s own module (see
/// `cadence::tests::resolve_cadence_config_settings_json_override` for that
/// unit-level coverage) — this test exercises the SAME `TaskRunParams.project`
/// shape `run_and_record`'s `cadence: Some(resolve_cadence_config(&params.project))`
/// wiring consumes.
/// What: Build a project `TempDir` (via the same `params` helper every other
/// executor test uses) with a `.claude/settings.json` overriding
/// `cadence_turns` to `3`; assert `crate::agent_loop::resolve_cadence_config`
/// against `p.project` returns `3`, not the built-in default of `8`.
/// Test: this test.
///
/// Hermeticity: `resolve_cadence_config` reads the process-global
/// `TCODE_CADENCE_TURNS` env var, which the sibling
/// `crate::agent_loop::cadence::tests::resolve_cadence_config_env_wins_over_settings_json`
/// test sets to `"5"` while it runs. This test therefore resolves under
/// `with_cadence_env(None, None, …)` — holding `CADENCE_ENV_LOCK` and forcing
/// the env var unset — so a concurrent env-setting test cannot bleed its
/// `TCODE_CADENCE_TURNS=5` into this resolver and make the `== 3` assertion
/// observe `5` (fixing the pre-existing flake this test guards against).
#[tokio::test]
async fn settings_json_cadence_turns_override_reaches_resolver() {
    with_cadence_env(None, None, || {
        let agents = agents_dir();
        let project = tempfile::tempdir().expect("project tempdir");
        std::fs::create_dir_all(project.path().join(".claude")).expect("mkdir .claude");
        std::fs::write(
            project.path().join(".claude").join("settings.json"),
            r#"{"code_harness": {"cadence_turns": 3}}"#,
        )
        .expect("write settings.json");

        let p = params(&agents, &project, "s");
        let cfg = crate::agent_loop::resolve_cadence_config(
            p.binding.root().expect("bound in this test"),
        );
        assert_eq!(cfg.cadence_turns, 3);
        assert_ne!(
            cfg.cadence_turns,
            crate::agent_loop::CadenceConfig::default().cadence_turns
        );
    })
    .await;
}

/// `daily_driver_skills_catalog` returns the rendered catalog + a working
/// resolver under `HarnessMode::DailyDriver` when skills exist.
#[test]
fn daily_driver_skills_catalog_some_when_skills_exist() {
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");
    let skills_dir = project.path().join(".claude").join("skills").join("demo");
    std::fs::create_dir_all(&skills_dir).expect("mkdir skill dir");
    std::fs::write(
        skills_dir.join("SKILL.md"),
        "---\nname: demo\ndescription: Demo skill\n---\nfull body\n",
    )
    .expect("write SKILL.md");

    let mut p = params(&agents, &project, "s");
    p.mode = crate::mode::HarnessMode::DailyDriver;

    let (catalog, resolver) =
        daily_driver_skills_catalog(&p, p.binding.root().expect("bound in this test"))
            .expect("catalog present");
    assert!(catalog.contains("demo: Demo skill"));
    assert_eq!(resolver.resolve("demo").as_deref(), Some("full body"));
}

/// `ProjectToolFactory::build` threads the run's resolved `HarnessMode` onto
/// the engineer's `EditTool` (#2073) — under `HarnessMode::Parity`, the
/// dispatched `edit` call must prefer a supplied unified-diff payload even
/// when the calling model slug would prefer SEARCH/REPLACE under the plain
/// per-model matrix, proving the daemon path actually wires `with_mode`
/// through, not just that `EditTool` supports it in isolation
/// (`tools::fs::edit::tests::edit_under_parity_mode_prefers_unified_diff_even_for_flagship_model_slug`
/// covers the tool itself).
#[tokio::test]
async fn project_tool_factory_threads_parity_mode_into_edit_tool() {
    let project = tempfile::tempdir().expect("project tempdir");
    std::fs::write(project.path().join("f.py"), "line1\nline2\n").expect("seed file");

    let factory = ProjectToolFactory {
        project: project.path().to_path_buf(),
        mode: crate::mode::HarnessMode::Parity,
        skill_resolver: None,
    };
    let agent = crate::agents::AgentConfig::default();
    let ctx = crate::tools::RunContext {
        model: Some("anthropic/claude-opus-4-5".to_string()),
        ..Default::default()
    };
    let registry = factory.build(&agent, &ctx).await;

    let result = registry
        .dispatch_gated(
            "edit",
            serde_json::json!({
                "path": "f.py",
                "old_string": "not-present",
                "new_string": "x",
                "diff": "@@ -2,1 +2,1 @@\n-line2\n+line2-diffed\n"
            }),
            None,
        )
        .await;

    assert!(!result.is_error(), "unexpected error: {}", result.content());
    assert!(result.content().contains("unified_diff"));
    let updated = std::fs::read_to_string(project.path().join("f.py")).expect("read");
    assert_eq!(updated, "line1\nline2-diffed\n");
}

/// #2152: `ProjectToolFactory::build` registers `use_skill` when a skill
/// resolver was threaded in — the gap PR #2942 fixed on the legacy
/// `run_task/mod.rs` path but left open on this daemon path (`task::executor`),
/// where the engineer's prompt (`with_skills_catalog`) advertised `use_skill`
/// while its registry omitted the tool, so a following call errored with
/// "no tool registered".
///
/// Why: the positive case (`Some(resolver)` registers the tool) and the
/// negative case (`None` must NOT register it) are both asserted directly
/// against `ProjectToolFactory::build`'s resulting `ToolRegistry`, mirroring
/// `run_task::tests::use_skill_absent_from_engineer_when_no_skills`'s direct
/// (non-end-to-end) style — the embedded-default-skill-catalog fallback
/// (#2895) makes `skill_resolver` virtually always `Some` on any real project
/// directory, so exercising the `None` branch end-to-end would be impractical.
/// What: builds one `ProjectToolFactory` with a resolver present and one with
/// `skill_resolver: None`, calls `.build()` on each, and asserts
/// `registry.contains("use_skill")` accordingly.
/// Test: this test.
#[tokio::test]
async fn engineer_registry_includes_use_skill_when_catalog_present() {
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");
    let skills_dir = project.path().join(".claude").join("skills").join("demo");
    std::fs::create_dir_all(&skills_dir).expect("mkdir skill dir");
    std::fs::write(
        skills_dir.join("SKILL.md"),
        "---\nname: demo\ndescription: Demo skill\n---\nfull body\n",
    )
    .expect("write SKILL.md");

    let mut p = params(&agents, &project, "s");
    p.mode = crate::mode::HarnessMode::DailyDriver;
    let (_, resolver) =
        daily_driver_skills_catalog(&p, p.binding.root().expect("bound")).expect("catalog present");

    let with_resolver = ProjectToolFactory {
        project: project.path().to_path_buf(),
        mode: crate::mode::HarnessMode::DailyDriver,
        skill_resolver: Some(resolver),
    };
    let registry = with_resolver
        .build(
            &crate::agents::AgentConfig::default(),
            &RunContext::default(),
        )
        .await;
    assert!(
        registry.contains("use_skill"),
        "engineer registry must advertise use_skill when skill_resolver is Some"
    );

    let without_resolver = ProjectToolFactory {
        project: project.path().to_path_buf(),
        mode: crate::mode::HarnessMode::DailyDriver,
        skill_resolver: None,
    };
    let registry = without_resolver
        .build(
            &crate::agents::AgentConfig::default(),
            &RunContext::default(),
        )
        .await;
    assert!(
        !registry.contains("use_skill"),
        "engineer registry must NOT advertise use_skill when skill_resolver is None"
    );
    assert!(
        registry.contains("finish_task"),
        "sanity check: registry should still contain other always-present tools"
    );
}

// ── #2207/#2206: daemon-path deadline wiring + distinct status + telemetry ─────

/// A response in which the assistant calls `finish_task` with a required
/// field (`summary`) missing — recoverable per #2072's schema-validation
/// path, NOT terminal (mirrors `run_task::tests::malformed_finish_task_response`).
fn malformed_finish_task_response() -> Value {
    json!({
        "id": "gen-finish-malformed",
        "choices": [{
            "message": {
                "role": "assistant",
                "content": null,
                "tool_calls": [{
                    "id": "call-missing",
                    "type": "function",
                    "function": {
                        "name": "finish_task",
                        "arguments": json!({"status": "completed"}).to_string()
                    }
                }]
            },
            "finish_reason": "tool_calls"
        }],
        "usage": {"prompt_tokens": 40, "completion_tokens": 10, "total_tokens": 50}
    })
}

/// 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 }
    })
}

/// An `InferenceAdapter` that sleeps before its Nth `chat` call, then replays a
/// scripted response (mirrors `run_task::tests::DeadlineTriggerLlm`).
///
/// Why: deterministically drives the PM's own wall-clock deadline past its
/// configured budget, entirely within the PM's own loop (no delegation), so
/// the daemon path's `run_and_record` observes a genuine
/// `AgentLoopError::Timeout` rather than racing against the delegated
/// engineer's own independently-resolved deadline.
struct DeadlineTriggerLlm {
    responses: Vec<ChatResponse>,
    cursor: AtomicUsize,
    stall_at_call: usize,
    stall_for: std::time::Duration,
}

impl DeadlineTriggerLlm {
    fn new(fixtures: &[Value], stall_at_call: usize, stall_for: std::time::Duration) -> Self {
        let responses = fixtures
            .iter()
            .map(|v| serde_json::from_value(v.clone()).expect("valid ChatResponse fixture"))
            .collect();
        Self {
            responses,
            cursor: AtomicUsize::new(0),
            stall_at_call,
            stall_for,
        }
    }
}

#[async_trait]
impl InferenceAdapter for DeadlineTriggerLlm {
    crate::llm::mock_adapter_identity!("mock-deadline-trigger");

    async fn chat(&self, _req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
        let idx = self.cursor.fetch_add(1, Ordering::SeqCst);
        if idx == self.stall_at_call {
            tokio::time::sleep(self.stall_for).await;
        }
        match self.responses.get(idx) {
            Some(resp) => Ok(resp.clone()),
            None => Err(InferenceError::MissingConfig(format!(
                "scripted LLM exhausted at call {idx}"
            ))),
        }
    }
}

/// A tiny `deadline_secs` override on the daemon path yields
/// `SessionStatus::DeadlineExceeded` (distinct from `Failed`), and the
/// persisted transcript/usage still reflect the turn that completed before
/// the deadline fired (#2207 + #2206's daemon-path equivalent of
/// `run_task::tests::exit_code_reflects_deadline_exceeded_distinct_from_run_failure`).
///
/// Why: `task::executor::run_and_record` calls `registry.set_run_outcome`
/// unconditionally before branching on the loop's `result` (#2206 was
/// already correct here — this test pins that #2207's new
/// `SessionStatus::DeadlineExceeded` arm doesn't regress it), and the
/// deadline must actually reach the PM's `AgentLoopConfig` via
/// `resolve_deadline_secs(params.deadline_secs)`.
/// What: `deadline_secs: Some(1)`; turn 0 is a malformed `finish_task` call
/// (instant, recoverable, recorded with real usage), turn 1 sleeps 3s. Assert
/// the session ends `DeadlineExceeded` (not `Failed`) and its stored usage is
/// non-zero.
/// Test: this test.
#[tokio::test]
async fn spawn_task_run_deadline_exceeded_is_distinct_and_preserves_usage() {
    let registry = Arc::new(SessionRegistry::new());
    let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");

    let llm: Arc<dyn InferenceAdapter> = Arc::new(DeadlineTriggerLlm::new(
        &[
            malformed_finish_task_response(),
            stop_response("recovered (never reached in time)"),
        ],
        1,
        std::time::Duration::from_secs(3),
    ));

    let mut p = params(&agents, &project, &session.id);
    p.deadline_secs = Some(1);

    spawn_task_run(Arc::clone(&registry), llm, p).expect("run must start");

    // Poll for the run to reach a terminal state naturally (via its own 1s
    // deadline), WITHOUT `shutdown_executions` — that flips every tracked
    // execution's cancel flag immediately, which would race the deadline and
    // spuriously report `Cancelled` instead of `DeadlineExceeded`.
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
    loop {
        let status = registry.status(&session.id).expect("session must exist");
        if status.status.is_terminal() {
            break;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "run did not reach a terminal state within 5s"
        );
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
    }

    let status = registry.status(&session.id).expect("session must exist");
    assert_eq!(
        status.status,
        SessionStatus::DeadlineExceeded,
        "a deadline hit must map to DeadlineExceeded, not Failed"
    );

    let transcript = registry
        .get_transcript(&session.id)
        .expect("transcript must exist");
    assert!(
        transcript.usage.prompt_tokens > 0,
        "the completed first turn must still contribute real usage, got {:?}",
        transcript.usage
    );
    assert!(
        transcript.cost_usd.is_some(),
        "cost must be populated (not None) on the deadline-exceeded path"
    );
}

/// A response in which the assistant calls `set_goal` and never stops —
/// used to drive a scripted LLM through `max_turns` consecutive tool-call
/// turns without ever reaching a natural `stop`/`finish_task` terminal state
/// (#3888's `TurnCapExceeded` regression test below).
fn set_goal_tool_call_response(call_id: &str) -> Value {
    json!({
        "id": format!("gen-{call_id}"),
        "choices": [{
            "message": {
                "role": "assistant",
                "content": null,
                "tool_calls": [{
                    "id": call_id,
                    "type": "function",
                    "function": {
                        "name": crate::tools::goals::SET_GOAL_TOOL_NAME,
                        "arguments": json!({"slot": 1, "text": "keep going"}).to_string()
                    }
                }]
            },
            "finish_reason": "tool_calls"
        }],
        "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}
    })
}

/// An `InferenceAdapter` that replays a fixed script, erroring past the end —
/// mirrors `agent_loop::tests::ScriptedLlm` but scoped to this module so the
/// daemon-path executor tests don't need to reach into `agent_loop`'s
/// `#[cfg(test)]`-private fixtures.
struct ScriptedLlm {
    responses: Vec<ChatResponse>,
    cursor: AtomicUsize,
}

impl ScriptedLlm {
    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),
        }
    }
}

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

    async fn chat(&self, _req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
        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}"
            ))),
        }
    }
}

/// (#3888) Exhausting the PM's per-call `max_turns` budget must map to
/// `SessionStatus::TurnCapExceeded`, NOT `SessionStatus::Failed` — and the
/// session must remain resumable via a SECOND `spawn_task_run` against the
/// same `session_id`, exactly like a naturally `Finished` session (#2344).
///
/// Why: this is the exact regression reported in #3888 — before this fix,
/// `task::executor::run_and_record`'s terminal-status match had no
/// `TurnCapExceeded` arm, so `AgentLoopError::TurnCapExceeded` fell through
/// the catch-all into `SessionStatus::Failed`, which
/// `SessionRegistry::begin_execution` permanently rejects — directly
/// regressing epic #2343's infinite-sessions goal (a session must never die
/// just because one call used its whole per-call turn allowance).
/// What: scripts `AgentLoopConfig::default().max_turns` (8) consecutive
/// `set_goal` tool-call turns — the PM never calls `finish_task` or emits a
/// bare `stop`, so the loop can only terminate via the turn cap. Asserts the
/// session lands in `TurnCapExceeded` (not `Failed`), then issues a SECOND
/// `spawn_task_run` against the SAME session and asserts it is accepted (not
/// the `-32003` terminal-session rejection) and reaches a fresh terminal
/// state.
/// Test: this test.
#[tokio::test]
async fn spawn_task_run_turn_cap_exceeded_is_resumable() {
    let registry = Arc::new(SessionRegistry::new());
    let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");

    // 8 responses = `AgentLoopConfig::default().max_turns`; none stop or
    // call `finish_task`, so the PM loop can only end via `TurnCapExceeded`.
    let scripts: Vec<Value> = (0..8)
        .map(|i| set_goal_tool_call_response(&format!("call_{i}")))
        .collect();
    let llm: Arc<dyn InferenceAdapter> = Arc::new(ScriptedLlm::from_json(&scripts));

    let p1 = params(&agents, &project, &session.id);
    spawn_task_run(Arc::clone(&registry), llm, p1).expect("run 1 must start");
    wait_for_terminal(&registry, &session.id).await;

    assert_eq!(
        registry.status(&session.id).unwrap().status,
        SessionStatus::TurnCapExceeded,
        "exhausting max_turns must map to TurnCapExceeded, not Failed (#3888)"
    );

    // The regression: a second `task.run` on this session must be ACCEPTED,
    // not rejected with "session ... is already terminal" (-32003).
    let llm2: Arc<dyn InferenceAdapter> = Arc::new(EchoLlmClient::new());
    let p2 = params(&agents, &project, &session.id);
    spawn_task_run(Arc::clone(&registry), llm2, p2).expect(
        "a TurnCapExceeded session must accept a resuming task.run, \
         not be permanently unresumable (#3888)",
    );
    wait_for_terminal(&registry, &session.id).await;

    // `EchoLlmClient`'s script deterministically ends in a natural stop
    // (`task::mock_llm::EchoLlmClient`'s own docs), so a correctly-resumed
    // run must reach `Finished` exactly — not merely "not Failed", which
    // would also pass if resumption silently regressed to e.g. another
    // `TurnCapExceeded`/`DeadlineExceeded`/`Cancelled`.
    let final_status = registry.status(&session.id).unwrap().status;
    assert_eq!(
        final_status,
        SessionStatus::Finished,
        "the resumed run must reach its own natural Finished terminal state"
    );
}

// ── #2344: persistent session-scoped transcript across task.run calls ──────────

/// Poll `registry.status(id)` until it reaches a terminal state, bounded by
/// a 5s deadline (mirrors the inline poll loop in
/// `spawn_task_run_deadline_exceeded_is_distinct_and_preserves_usage`).
async fn wait_for_terminal(registry: &SessionRegistry, id: &str) {
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
    loop {
        let status = registry.status(id).expect("session must exist");
        if status.status.is_terminal() {
            return;
        }
        assert!(
            std::time::Instant::now() < deadline,
            "run did not reach a terminal state within 5s"
        );
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
    }
}

/// A SECOND `spawn_task_run` on the SAME session, issued AFTER the first run
/// has already `Finished`, must be ACCEPTED (not rejected as terminal, #2344)
/// and must APPEND onto the first run's turns/usage rather than overwrite
/// them — this is #2344's headline acceptance criterion exercised through
/// the real daemon wiring (`spawn_task_run` -> `run_and_record` ->
/// `SessionRegistry::begin_pm_transcript`/`begin_execution` resumption /
/// `set_run_outcome` accumulation), not just the unit-level registry/loop
/// tests.
///
/// Why: unit tests already cover each collaborator (`begin_pm_transcript`,
/// `begin_execution`'s `Finished`-resumption, `set_run_outcome`
/// accumulation, `AgentLoop::run_with_transcript`'s no-reseed/output-scoping
/// behaviour) in isolation; this test is the integration proof that
/// `task::executor` actually wires them together correctly end to end.
/// What: run 1 completes via the `EchoLlmClient` script; poll to terminal;
/// snapshot `get_transcript`. Run 2 (a FRESH `EchoLlmClient`, its own script
/// from call 0 — the daemon builds a new LLM client per `task.run`
/// regardless of session) targets the SAME `session_id`; assert
/// `spawn_task_run` accepts it (not `-32003` terminal-session rejection);
/// poll to terminal again; assert the session's cumulative turn count grew,
/// run 1's turns are still present unchanged at the front, and usage
/// accumulated (run 2's usage > 0 on top of run 1's).
/// Test: this test.
#[tokio::test]
async fn spawn_task_run_second_call_after_finish_appends_to_cumulative_transcript() {
    let registry = Arc::new(SessionRegistry::new());
    let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");

    // Run 1: completes the full delegate -> bash -> stop -> stop script.
    let llm1: Arc<dyn InferenceAdapter> = Arc::new(EchoLlmClient::new());
    let p1 = params(&agents, &project, &session.id);
    spawn_task_run(Arc::clone(&registry), llm1, p1).expect("run 1 must start");
    wait_for_terminal(&registry, &session.id).await;
    assert_eq!(
        registry.status(&session.id).unwrap().status,
        SessionStatus::Finished
    );

    let after_run_one = registry
        .get_transcript(&session.id)
        .expect("transcript must exist after run 1");
    assert!(
        !after_run_one.turns.is_empty(),
        "run 1 must have recorded turns"
    );

    // Run 2 against the SAME session_id, issued only AFTER run 1 fully
    // finished — must be ACCEPTED, not rejected as an already-terminal
    // session.
    let llm2: Arc<dyn InferenceAdapter> = Arc::new(EchoLlmClient::new());
    let mut p2 = params(&agents, &project, &session.id);
    p2.task = "do something else".to_string();
    spawn_task_run(Arc::clone(&registry), llm2, p2)
        .expect("a Finished session must accept a follow-up task.run (#2344)");
    wait_for_terminal(&registry, &session.id).await;
    assert_eq!(
        registry.status(&session.id).unwrap().status,
        SessionStatus::Finished,
        "run 2 must also finish successfully"
    );

    let after_run_two = registry
        .get_transcript(&session.id)
        .expect("transcript must exist after run 2");
    assert!(
        after_run_two.turns.len() > after_run_one.turns.len(),
        "run 2 must APPEND more turns onto run 1's, not replace them: {} vs {}",
        after_run_two.turns.len(),
        after_run_one.turns.len()
    );
    assert_eq!(
        after_run_two.turns[..after_run_one.turns.len()],
        after_run_one.turns[..],
        "run 1's turns must still be present, unchanged, at the front of the cumulative list"
    );
    assert!(
        after_run_two.usage.prompt_tokens > after_run_one.usage.prompt_tokens,
        "usage must accumulate across runs, not reset: run1={:?} run2={:?}",
        after_run_one.usage,
        after_run_two.usage
    );
}

/// A scripted `InferenceAdapter` that records the tool-schema names of every
/// request it receives, then immediately stops (no tool calls) — the D3
/// no-tool-call convention `finish_task`'s own docs describe, so a run
/// completes in a single PM turn with no delegation needed.
///
/// Why: #2348's `recall_session` registration is a daemon-session-path-only
/// concern (`task::executor::run_and_record`'s `pm_registry`, never
/// `run_task::execute_run_task`'s). Asserting on the ACTUAL tool schemas the
/// PM's `AgentLoop` sends the LLM (rather than re-deriving the registration
/// logic in the test) proves the real wiring, not a duplicate of it.
struct SchemaCapturingLlm {
    tool_names: Mutex<Vec<String>>,
}

impl SchemaCapturingLlm {
    fn new() -> Self {
        Self {
            tool_names: Mutex::new(Vec::new()),
        }
    }
}

#[async_trait]
impl InferenceAdapter for SchemaCapturingLlm {
    crate::llm::mock_adapter_identity!("mock-schema-capturing");

    async fn chat(&self, req: &ChatRequest) -> Result<ChatResponse, InferenceError> {
        let names = req
            .tools
            .as_ref()
            .map(|tools| tools.iter().map(|t| t.function.name.clone()).collect())
            .unwrap_or_default();
        *self.tool_names.lock().expect("tool_names lock") = names;
        let fixture = json!({
            "id": "mock-stop",
            "choices": [{
                "message": {"role": "assistant", "content": "done", "tool_calls": []},
                "finish_reason": "stop"
            }],
            "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}
        });
        serde_json::from_value(fixture).map_err(|e| InferenceError::MissingConfig(e.to_string()))
    }
}

/// The daemon-session path's `pm_registry` (`task::executor::run_and_record`)
/// must register `recall_session` (#2348) alongside `delegate_to_agent` and
/// `finish_task`.
#[tokio::test]
async fn session_path_registers_recall_session_tool() {
    let registry = Arc::new(SessionRegistry::new());
    let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
    let agents = agents_dir();
    let project = tempfile::tempdir().expect("project tempdir");

    let mock = Arc::new(SchemaCapturingLlm::new());
    let llm: Arc<dyn InferenceAdapter> = Arc::clone(&mock) as Arc<dyn InferenceAdapter>;
    let p = params(&agents, &project, &session.id);

    spawn_task_run(Arc::clone(&registry), llm, p).expect("run must start");
    wait_for_terminal(&registry, &session.id).await;

    let names = mock.tool_names.lock().expect("tool_names lock").clone();
    assert!(
        names.contains(&"recall_session".to_string()),
        "daemon-session path must register recall_session; got {names:?}"
    );
    assert!(
        names.contains(&"finish_task".to_string()),
        "sanity: finish_task must still be registered alongside it; got {names:?}"
    );
}