roboticus-api 0.11.4

HTTP routes, WebSocket, auth, rate limiting, and dashboard for the Roboticus agent runtime
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
//! Re-export shim — pipeline orchestrator lives in roboticus_pipeline::run.

pub(in super::super) use roboticus_pipeline::run::run_pipeline;

#[cfg(test)]
mod tests {
    use roboticus_pipeline::config::*;
    use roboticus_pipeline::context::inference::annotate_mcp_calls_from_react_trace;
    use roboticus_pipeline::decomposition::{
        DecompositionDecision, DelegationPlan, SpecialistProposal,
    };
    use roboticus_pipeline::flight_recorder::{ReactStep, ReactTrace, ToolSource};
    use roboticus_pipeline::stage_deps::TaskStateDeps;
    use roboticus_pipeline::task_state::{
        build_task_state_input, resolve_specialist_creation_for_task,
    };
    use roboticus_pipeline::trace::{PipelineTrace, SpanOutcome};

    // ── Preset field verification ─────────────────────────────────────

    #[test]
    fn api_preset_enables_all_core_features() {
        let cfg = PipelineConfig::api();
        assert!(cfg.injection_defense);
        assert!(cfg.dedup_tracking);
        assert!(cfg.decomposition_gate);
        assert!(cfg.delegated_execution);
        assert!(cfg.shortcuts_enabled);
        assert!(cfg.cache_enabled);
        assert!(cfg.post_turn_ingest);
        assert!(cfg.nickname_refinement);
        assert!(cfg.inject_diagnostics);
        assert!(!cfg.specialist_controls); // API doesn't have specialist controls
        assert_eq!(cfg.inference_mode, InferenceMode::Standard);
        assert_eq!(cfg.guard_set, GuardSetPreset::Full);
        assert_eq!(cfg.cache_guard_set, GuardSetPreset::Cached);
        assert_eq!(cfg.authority_mode, AuthorityMode::ApiClaim);
        assert_eq!(cfg.channel_label, "api");
        assert_eq!(cfg.session_resolution, SessionResolutionMode::FromBody);
    }

    #[tokio::test]
    async fn auto_composition_creates_missing_skills_and_subagent_for_task_turn() {
        let state = crate::api::routes::tests::test_state();
        {
            let mut cfg = state.config.write().await;
            cfg.agent.composition_policy = roboticus_core::config::CompositionPolicy::Autonomous;
        }
        let proposal = SpecialistProposal {
            name: "finance-specialist".into(),
            display_name: "Finance Specialist".into(),
            description: "Handles finance planning tasks".into(),
            skills: vec!["forecasting".into(), "pricing".into()],
            model: "auto".into(),
        };
        let decision = DecompositionDecision::RequiresSpecialistCreation {
            proposal,
            rationale: "no specialist fit".into(),
        };
        let mut trace = PipelineTrace::new("turn-auto-compose", "api");

        let am_deps = roboticus_pipeline::stage_deps::ActionMappingDeps {
            core: &state,
            reasoning: &state,
            tooling: &state,
            tool_executor: &state,
        };
        let (resolved, workflow_note) = resolve_specialist_creation_for_task(
            &am_deps,
            "turn-auto-compose",
            "api",
            roboticus_core::InputAuthority::Creator,
            "session-auto-compose",
            "Research pricing and forecast revenue and draft a rollout plan",
            decision,
            &mut trace,
        )
        .await;

        assert!(!matches!(
            resolved,
            DecompositionDecision::RequiresSpecialistCreation { .. }
        ));
        assert!(
            workflow_note.is_some()
                || matches!(resolved, DecompositionDecision::Centralized { .. })
        );

        let skills = roboticus_db::skills::list_skills(&state.db).expect("list skills");
        assert!(skills.iter().any(|s| s.name == "forecasting"));
        assert!(skills.iter().any(|s| s.name == "pricing"));

        let agents = roboticus_db::agents::list_sub_agents(&state.db).expect("list subagents");
        let subagent = agents
            .iter()
            .find(|a| a.name == "finance-specialist")
            .expect("finance specialist created");
        let skills_json = subagent.skills_json.as_deref().unwrap_or("[]");
        assert!(skills_json.contains("forecasting"));
        assert!(skills_json.contains("pricing"));
    }

    #[test]
    fn planner_selects_compose_subagent_for_explicit_empty_roster_workflow() {
        // Replaces: task_operating_state_requests_specialist_for_explicit_empty_roster_workflow
        // Uses new agent types directly.
        use roboticus_agent::action_planner::PlannedAction;
        use roboticus_agent::task_state::{TaskClassification, TaskStateInput};

        let input = TaskStateInput {
            user_content:
                "Introspect what you need, compose a specialist, then delegate this task.".into(),
            intents: vec!["Delegation".into()],
            authority: "Creator".into(),
            retrieval_metrics: None,
            tool_search_stats: None,
            mcp_tools_available: false,
            taskable_agent_count: 0,
            fit_agent_count: 0,
            fit_agent_names: vec![],
            enabled_skill_count: 0,
            matching_skill_count: 0,
            missing_skills: vec![],
            remaining_budget_tokens: 8000,
            provider_breaker_open: false,
            inference_mode: "standard".into(),
            decomposition_proposal: None,
            explicit_specialist_workflow: true,
            named_tool_match: false,
            recent_response_skeletons: vec![],
            recent_user_message_lengths: vec![],
            self_echo_fragments: vec![],
            declared_action: None,
            previous_turn_had_protocol_issues: false,
            normalization_retry_streak: 0,
        };
        let state = roboticus_agent::task_state::synthesize(&input);
        let plan = roboticus_agent::action_planner::plan(&state, &input);

        assert_eq!(state.classification, TaskClassification::Task);
        assert_eq!(state.roster_fit.taskable_count, 0);
        assert_eq!(plan.selected, PlannedAction::ComposeSubagent);
    }

    #[test]
    fn planner_selects_answer_directly_for_conversation() {
        // Replaces: task_operating_state_keeps_conversation_direct
        use roboticus_agent::action_planner::PlannedAction;
        use roboticus_agent::task_state::{TaskClassification, TaskStateInput};

        let input = TaskStateInput {
            user_content: "Thanks, that makes sense.".into(),
            intents: vec![],
            authority: "Creator".into(),
            retrieval_metrics: None,
            tool_search_stats: None,
            mcp_tools_available: false,
            taskable_agent_count: 0,
            fit_agent_count: 0,
            fit_agent_names: vec![],
            enabled_skill_count: 0,
            matching_skill_count: 0,
            missing_skills: vec![],
            remaining_budget_tokens: 8000,
            provider_breaker_open: false,
            inference_mode: "standard".into(),
            decomposition_proposal: None,
            explicit_specialist_workflow: false,
            named_tool_match: false,
            recent_response_skeletons: vec![],
            recent_user_message_lengths: vec![],
            self_echo_fragments: vec![],
            declared_action: None,
            previous_turn_had_protocol_issues: false,
            normalization_retry_streak: 0,
        };
        let state = roboticus_agent::task_state::synthesize(&input);
        let plan = roboticus_agent::action_planner::plan(&state, &input);

        assert_eq!(state.classification, TaskClassification::Conversation);
        assert_eq!(plan.selected, PlannedAction::AnswerDirectly);
    }

    #[test]
    fn build_task_state_input_compose_subagent_with_centralized_gate() {
        // Replaces: task_execution_plan_promotes_explicit_empty_roster_workflow_into_composition
        // Verifies build_task_state_input + planner selects ComposeSubagent when
        // explicit workflow + empty roster + Creator authority.
        use roboticus_agent::action_planner::PlannedAction;
        use roboticus_agent::task_state::TaskStateInput;

        let input = TaskStateInput {
            user_content: "Compose a specialist and delegate this task".into(),
            intents: vec!["Delegation".into()],
            authority: "Creator".into(),
            retrieval_metrics: None,
            tool_search_stats: None,
            mcp_tools_available: false,
            taskable_agent_count: 0,
            fit_agent_count: 0,
            fit_agent_names: vec![],
            enabled_skill_count: 10,
            matching_skill_count: 0,
            missing_skills: vec![],
            remaining_budget_tokens: 8000,
            provider_breaker_open: false,
            inference_mode: "standard".into(),
            decomposition_proposal: Some(roboticus_agent::task_state::DecompositionProposal {
                should_delegate: false,
                rationale: "single-step".into(),
                utility_margin: -0.1,
            }),
            explicit_specialist_workflow: true,
            named_tool_match: false,
            recent_response_skeletons: vec![],
            recent_user_message_lengths: vec![],
            self_echo_fragments: vec![],
            declared_action: None,
            previous_turn_had_protocol_issues: false,
            normalization_retry_streak: 0,
        };
        let state = roboticus_agent::task_state::synthesize(&input);
        let plan = roboticus_agent::action_planner::plan(&state, &input);

        assert_eq!(plan.selected, PlannedAction::ComposeSubagent);
    }

    #[test]
    fn build_task_state_input_conversation_is_non_compositional() {
        // Replaces: task_execution_plan_keeps_conversation_non_compositional
        use roboticus_agent::action_planner::PlannedAction;
        use roboticus_agent::task_state::TaskStateInput;

        let input = TaskStateInput {
            user_content: "Thanks".into(),
            intents: vec![],
            authority: "Creator".into(),
            retrieval_metrics: None,
            tool_search_stats: None,
            mcp_tools_available: false,
            taskable_agent_count: 0,
            fit_agent_count: 0,
            fit_agent_names: vec![],
            enabled_skill_count: 10,
            matching_skill_count: 0,
            missing_skills: vec![],
            remaining_budget_tokens: 8000,
            provider_breaker_open: false,
            inference_mode: "standard".into(),
            decomposition_proposal: None,
            explicit_specialist_workflow: false,
            named_tool_match: false,
            recent_response_skeletons: vec![],
            recent_user_message_lengths: vec![],
            self_echo_fragments: vec![],
            declared_action: None,
            previous_turn_had_protocol_issues: false,
            normalization_retry_streak: 0,
        };
        let state = roboticus_agent::task_state::synthesize(&input);
        let plan = roboticus_agent::action_planner::plan(&state, &input);

        assert_eq!(plan.selected, PlannedAction::AnswerDirectly);
    }

    #[tokio::test]
    async fn build_task_state_input_prefers_delegation_for_explicit_matching_specialists() {
        // Replaces: task_operating_state_prefers_delegation_for_explicit_matching_specialists
        // Uses a prompt whose capability tokens (revenue, pricing, freelancers) match the
        // seeded agent's skills, producing zero missing_skills so the planner reaches
        // DelegateToSpecialist instead of ComposeSkill.
        use roboticus_agent::action_planner::PlannedAction;
        use roboticus_agent::task_state::TaskClassification;

        let state = crate::api::routes::tests::test_state();
        let agent = roboticus_db::agents::SubAgentRow {
            id: "test-revenue-strategist".into(),
            name: "revenue-strategist".into(),
            display_name: Some("Revenue Strategist".into()),
            model: "auto".into(),
            fallback_models_json: Some("[]".into()),
            role: "Subagent".into(),
            description: Some("Handles freelancer revenue strategy".into()),
            skills_json: Some(r#"["revenue","pricing","freelancers"]"#.into()),
            enabled: true,
            session_count: 0,
            last_used_at: None,
        };
        roboticus_db::agents::upsert_sub_agent(&state.db, &agent).expect("seed subagent");
        // Manually inject Delegation intent — these tests verify planner logic,
        // not the semantic classifier.
        let intents = vec![roboticus_pipeline::intent_registry::Intent::Delegation];
        let gate_decision = DecompositionDecision::Delegated(DelegationPlan {
            subtasks: vec!["test task".into()],
            rationale: "test delegation".into(),
            expected_utility_margin: 0.5,
        });

        let task_deps = TaskStateDeps {
            core: &state,
            reasoning: &state,
            tooling: &state,
        };
        let task_input = build_task_state_input(
            &task_deps,
            "test-session",
            "revenue pricing",
            &intents,
            roboticus_core::InputAuthority::Creator,
            Some(&gate_decision),
            "standard",
        )
        .await;
        let task_state = roboticus_agent::task_state::synthesize(&task_input);
        let plan = roboticus_agent::action_planner::plan(&task_state, &task_input);

        assert_eq!(task_state.classification, TaskClassification::Task);
        assert_eq!(task_state.roster_fit.taskable_count, 1);
        assert_eq!(task_state.roster_fit.fit_count, 1);
        assert!(
            matches!(
                plan.selected,
                PlannedAction::DelegateToSpecialist | PlannedAction::ComposeSkill
            ),
            "planner should act on roster fit: got {:?}",
            plan.selected
        );
    }

    #[tokio::test]
    async fn build_task_state_input_counts_name_and_description_tokens_for_specialist_fit() {
        // Replaces: task_operating_state_counts_name_and_description_tokens_for_specialist_fit
        // Prompt uses "saas ideas freelancers" which matches the seeded agent's description
        // tokens, producing zero missing_skills.
        use roboticus_agent::action_planner::PlannedAction;
        use roboticus_agent::task_state::TaskClassification;

        let state = crate::api::routes::tests::test_state();
        let agent = roboticus_db::agents::SubAgentRow {
            id: "test-saas-ideator".into(),
            name: "saas-ideator".into(),
            display_name: Some("SaaS Ideator".into()),
            model: "auto".into(),
            fallback_models_json: Some("[]".into()),
            role: "Subagent".into(),
            description: Some("Generates SaaS ideas for freelancers".into()),
            skills_json: Some(r#"["typescript","python"]"#.into()),
            enabled: true,
            session_count: 0,
            last_used_at: None,
        };
        roboticus_db::agents::upsert_sub_agent(&state.db, &agent).expect("seed subagent");
        // Manually inject Delegation intent — tests verify planner logic, not classifier.
        let intents = vec![roboticus_pipeline::intent_registry::Intent::Delegation];

        let gate_decision = DecompositionDecision::Delegated(DelegationPlan {
            subtasks: vec!["test task".into()],
            rationale: "test delegation".into(),
            expected_utility_margin: 0.5,
        });
        let task_deps = TaskStateDeps {
            core: &state,
            reasoning: &state,
            tooling: &state,
        };
        let task_input = build_task_state_input(
            &task_deps,
            "test-session",
            "saas ideas freelancers",
            &intents,
            roboticus_core::InputAuthority::Creator,
            Some(&gate_decision),
            "standard",
        )
        .await;
        let task_state = roboticus_agent::task_state::synthesize(&task_input);
        let plan = roboticus_agent::action_planner::plan(&task_state, &task_input);

        assert_eq!(task_state.classification, TaskClassification::Task);
        assert_eq!(task_state.roster_fit.taskable_count, 1);
        assert_eq!(task_state.roster_fit.fit_count, 1);
        assert!(
            matches!(
                plan.selected,
                PlannedAction::DelegateToSpecialist | PlannedAction::ComposeSkill
            ),
            "planner should act on roster fit: got {:?}",
            plan.selected
        );
    }

    #[tokio::test]
    async fn build_task_state_input_treats_explicit_specialist_workflow_as_task() {
        // Verifies that a delegation-intent turn is classified as Task.
        // Note: explicit_specialist_workflow detection requires neural embeddings
        // to reach the 0.80 threshold; n-gram fallback cannot reliably hit it.
        // The classification still works via the Delegation intent in TASK_INTENTS.
        use roboticus_agent::task_state::TaskClassification;

        let state = crate::api::routes::tests::test_state();
        let intents = vec![roboticus_pipeline::intent_registry::Intent::Delegation];

        let task_deps = TaskStateDeps {
            core: &state,
            reasoning: &state,
            tooling: &state,
        };
        let task_input = build_task_state_input(
            &task_deps,
            "test-session",
            "delegate this to a specialist",
            &intents,
            roboticus_core::InputAuthority::Creator,
            None,
            "standard",
        )
        .await;
        let task_state = roboticus_agent::task_state::synthesize(&task_input);

        assert_eq!(task_state.classification, TaskClassification::Task);
        // explicit_specialist_workflow requires neural embeddings at 0.80 threshold;
        // n-gram fallback may not hit it, so we only assert classification here.
    }

    #[test]
    fn build_task_state_input_delegates_when_explicit_workflow_and_fit_agents() {
        // Replaces: task_execution_plan_promotes_explicit_matching_specialists_into_delegation
        use roboticus_agent::action_planner::PlannedAction;
        use roboticus_agent::task_state::{DecompositionProposal, TaskStateInput};

        let input = TaskStateInput {
            user_content:
                "Use the best existing specialists if they fit, otherwise compose what is missing."
                    .into(),
            intents: vec!["Delegation".into()],
            authority: "Creator".into(),
            retrieval_metrics: None,
            tool_search_stats: None,
            mcp_tools_available: false,
            taskable_agent_count: 2,
            fit_agent_count: 1,
            fit_agent_names: vec!["revenue-strategist".into()],
            enabled_skill_count: 10,
            matching_skill_count: 0,
            missing_skills: vec![],
            remaining_budget_tokens: 8000,
            provider_breaker_open: false,
            inference_mode: "standard".into(),
            decomposition_proposal: Some(DecompositionProposal {
                should_delegate: false,
                rationale: "single-step".into(),
                utility_margin: -0.1,
            }),
            explicit_specialist_workflow: true,
            named_tool_match: false,
            recent_response_skeletons: vec![],
            recent_user_message_lengths: vec![],
            self_echo_fragments: vec![],
            declared_action: None,
            previous_turn_had_protocol_issues: false,
            normalization_retry_streak: 0,
        };
        let state = roboticus_agent::task_state::synthesize(&input);
        let plan = roboticus_agent::action_planner::plan(&state, &input);

        assert!(
            matches!(
                plan.selected,
                PlannedAction::DelegateToSpecialist | PlannedAction::ComposeSkill
            ),
            "planner should act on roster fit: got {:?}",
            plan.selected
        );
    }

    #[test]
    fn streaming_preset_has_full_feature_parity() {
        let cfg = PipelineConfig::streaming();
        assert!(cfg.injection_defense);
        assert!(cfg.dedup_tracking);
        // Full feature parity: decomposition, delegation, shortcuts all enabled
        assert!(cfg.decomposition_gate);
        assert!(cfg.delegated_execution);
        assert!(cfg.shortcuts_enabled);
        assert!(!cfg.specialist_controls);
        // Streaming mode with reduced guards
        assert_eq!(cfg.inference_mode, InferenceMode::Streaming);
        assert_eq!(cfg.guard_set, GuardSetPreset::Streaming);
        assert_eq!(cfg.cache_guard_set, GuardSetPreset::None);
        // No nickname refinement on streaming
        assert!(!cfg.nickname_refinement);
        // But post-turn ingest and cache are on
        assert!(cfg.post_turn_ingest);
        assert!(cfg.cache_enabled);
        // Authority via ApiClaim (same as API endpoint)
        assert_eq!(cfg.authority_mode, AuthorityMode::ApiClaim);
        assert_eq!(cfg.channel_label, "api-stream");
    }

    #[test]
    fn channel_preset_enables_specialist_controls() {
        let cfg = PipelineConfig::channel("telegram");
        assert!(cfg.injection_defense);
        assert!(cfg.dedup_tracking);
        assert!(cfg.decomposition_gate);
        assert!(cfg.delegated_execution);
        assert!(cfg.shortcuts_enabled);
        assert!(cfg.specialist_controls); // only channel has this
        assert!(cfg.cache_enabled);
        assert!(cfg.post_turn_ingest);
        assert!(!cfg.nickname_refinement); // channels don't refine nicknames
        assert!(!cfg.inject_diagnostics); // channels don't inject diagnostics
        assert_eq!(cfg.inference_mode, InferenceMode::Standard);
        assert_eq!(cfg.guard_set, GuardSetPreset::Full);
        assert_eq!(cfg.cache_guard_set, GuardSetPreset::Cached);
        assert_eq!(cfg.authority_mode, AuthorityMode::ChannelClaim);
        assert_eq!(cfg.channel_label, "telegram");
        assert_eq!(
            cfg.session_resolution,
            SessionResolutionMode::FromChannel {
                platform: "telegram".into()
            }
        );
    }

    #[test]
    fn channel_preset_uses_platform_as_label() {
        let telegram = PipelineConfig::channel("telegram");
        assert_eq!(telegram.channel_label, "telegram");

        let discord = PipelineConfig::channel("discord");
        assert_eq!(discord.channel_label, "discord");

        let email = PipelineConfig::channel("email");
        assert_eq!(email.channel_label, "email");
    }

    #[test]
    fn cron_preset_has_injection_defense() {
        let cfg = PipelineConfig::cron();
        // SECURITY FIX: injection defense was missing from scheduled_tasks.rs
        assert!(cfg.injection_defense);
        // No dedup for cron (scheduler guarantees uniqueness)
        assert!(!cfg.dedup_tracking);
        assert!(cfg.decomposition_gate);
        assert!(!cfg.delegated_execution); // cron doesn't pre-execute delegation
        assert!(!cfg.shortcuts_enabled); // cron tasks are machine-generated; ack shortcuts don't apply
        assert!(!cfg.specialist_controls);
        assert!(cfg.cache_enabled);
        assert!(cfg.post_turn_ingest);
        assert!(!cfg.nickname_refinement);
        assert!(!cfg.inject_diagnostics);
        assert_eq!(cfg.inference_mode, InferenceMode::Standard);
        assert_eq!(cfg.guard_set, GuardSetPreset::Full);
        assert_eq!(cfg.cache_guard_set, GuardSetPreset::Cached);
        assert_eq!(cfg.authority_mode, AuthorityMode::SelfGenerated);
        assert_eq!(cfg.channel_label, "cron");
        assert_eq!(cfg.session_resolution, SessionResolutionMode::Dedicated);
    }

    #[test]
    fn mcp_react_steps_annotate_pipeline_trace() {
        let mut pipeline_trace = PipelineTrace::new("turn-mcp", "api");
        pipeline_trace.begin_stage("inference");

        let mut react_trace = ReactTrace::new("turn-mcp");
        react_trace.record(ReactStep::ToolCall {
            tool_name: "github::create_issue".into(),
            parameters_redacted: false,
            result_summary: "created".into(),
            duration_ms: 275,
            success: true,
            source: ToolSource::Mcp {
                server: "github".into(),
            },
        });

        annotate_mcp_calls_from_react_trace(&mut pipeline_trace, &react_trace);
        pipeline_trace.end_stage(SpanOutcome::Ok);

        let span = &pipeline_trace.stages[0];
        assert_eq!(
            span.annotations.get("mcp.server"),
            Some(&serde_json::json!("github"))
        );
        assert_eq!(
            span.annotations.get("mcp.tool"),
            Some(&serde_json::json!("github::create_issue"))
        );
        assert_eq!(
            span.annotations.get("mcp.duration_ms"),
            Some(&serde_json::json!(275))
        );
        assert_eq!(
            span.annotations.get("mcp.success"),
            Some(&serde_json::json!(true))
        );
    }

    // ── Guard set resolution ──────────────────────────────────────────

    #[test]
    fn guard_set_presets_resolve_to_non_empty_chains() {
        let full = GuardSetPreset::Full.resolve();
        assert!(!full.is_empty());

        let cached = GuardSetPreset::Cached.resolve();
        assert!(!cached.is_empty());

        let streaming = GuardSetPreset::Streaming.resolve();
        assert!(!streaming.is_empty());
    }

    #[test]
    fn guard_set_none_resolves_to_empty_chain() {
        let none = GuardSetPreset::None.resolve();
        assert!(none.is_empty());
    }

    // ── Predicate methods ─────────────────────────────────────────────

    #[test]
    fn api_predicates() {
        let cfg = PipelineConfig::api();
        assert!(cfg.is_standard_inference());
        assert!(!cfg.is_streaming_inference());
        assert!(cfg.enforces_authority());
        assert!(cfg.can_execute_tools());
        assert!(cfg.resolves_session_from_body());
        assert!(!cfg.is_channel());
        assert!(!cfg.is_cron());
    }

    #[test]
    fn streaming_predicates() {
        let cfg = PipelineConfig::streaming();
        assert!(!cfg.is_standard_inference());
        assert!(cfg.is_streaming_inference());
        // Streaming now uses ApiClaim (full parity) — authority IS enforced
        assert!(cfg.enforces_authority());
        assert!(!cfg.can_execute_tools()); // streaming still can't do ReAct
        assert!(cfg.resolves_session_from_body());
        assert!(!cfg.is_channel());
        assert!(!cfg.is_cron());
    }

    #[test]
    fn channel_predicates() {
        let cfg = PipelineConfig::channel("telegram");
        assert!(cfg.is_standard_inference());
        assert!(!cfg.is_streaming_inference());
        assert!(cfg.enforces_authority());
        assert!(cfg.can_execute_tools());
        assert!(!cfg.resolves_session_from_body());
        assert!(cfg.is_channel());
        assert!(!cfg.is_cron());
    }

    #[test]
    fn cron_predicates() {
        let cfg = PipelineConfig::cron();
        assert!(cfg.is_standard_inference());
        assert!(!cfg.is_streaming_inference());
        // Cron uses SelfGenerated — authority not enforced (trusted internal caller)
        assert!(!cfg.enforces_authority());
        assert!(cfg.can_execute_tools());
        assert!(!cfg.resolves_session_from_body());
        assert!(!cfg.is_channel());
        assert!(cfg.is_cron());
    }

    // ── Security invariants ───────────────────────────────────────────

    #[test]
    fn all_presets_have_injection_defense() {
        // Every entry point MUST have injection defense. This is a
        // security-critical invariant.
        assert!(PipelineConfig::api().injection_defense);
        assert!(PipelineConfig::streaming().injection_defense);
        assert!(PipelineConfig::channel("test").injection_defense);
        assert!(PipelineConfig::cron().injection_defense);
    }

    /// Streaming is a delivery format only; pre-inference work must stay in
    /// lockstep with the JSON API (ARCHITECTURE.md §4).
    #[test]
    fn api_and_streaming_share_pre_inference_stage_flags() {
        let api = PipelineConfig::api();
        let stream = PipelineConfig::streaming();
        assert_eq!(api.decomposition_gate, stream.decomposition_gate);
        assert_eq!(api.delegated_execution, stream.delegated_execution);
        assert_eq!(api.shortcuts_enabled, stream.shortcuts_enabled);
        assert_eq!(api.injection_defense, stream.injection_defense);
        assert_eq!(api.skill_first_enabled, stream.skill_first_enabled);
        assert_eq!(
            api.short_followup_expansion,
            stream.short_followup_expansion
        );
    }

    #[test]
    fn all_presets_have_post_turn_ingest() {
        // Memory ingestion should never be skipped — it's essential for
        // episodic memory continuity.
        assert!(PipelineConfig::api().post_turn_ingest);
        assert!(PipelineConfig::streaming().post_turn_ingest);
        assert!(PipelineConfig::channel("test").post_turn_ingest);
        assert!(PipelineConfig::cron().post_turn_ingest);
    }

    #[test]
    fn standard_inference_paths_have_full_guards() {
        // All standard inference paths must use the Full guard set.
        let api = PipelineConfig::api();
        let channel = PipelineConfig::channel("telegram");
        let cron = PipelineConfig::cron();

        for cfg in [&api, &channel, &cron] {
            assert_eq!(cfg.inference_mode, InferenceMode::Standard);
            assert_eq!(cfg.guard_set, GuardSetPreset::Full);
            assert_eq!(cfg.cache_guard_set, GuardSetPreset::Cached);
        }
    }

    #[test]
    fn only_api_has_nickname_refinement() {
        assert!(PipelineConfig::api().nickname_refinement);
        assert!(!PipelineConfig::streaming().nickname_refinement);
        assert!(!PipelineConfig::channel("test").nickname_refinement);
        assert!(!PipelineConfig::cron().nickname_refinement);
    }

    #[test]
    fn only_channel_has_specialist_controls() {
        assert!(!PipelineConfig::api().specialist_controls);
        assert!(!PipelineConfig::streaming().specialist_controls);
        assert!(PipelineConfig::channel("test").specialist_controls);
        assert!(!PipelineConfig::cron().specialist_controls);
    }

    #[test]
    fn streaming_uses_streaming_inference_mode() {
        let cfg = PipelineConfig::streaming();
        // Streaming uses InferenceMode::Streaming — but the pipeline arm now
        // falls back to non-streaming inference when tools are present. The
        // can_execute_tools() helper reflects the mode enum, not runtime
        // behavior; runtime tool execution is gated by prepared.request.tools.
        assert_eq!(cfg.inference_mode, InferenceMode::Streaming);
        // Decomposition, delegation, and shortcuts all run PRE-inference
        assert!(cfg.shortcuts_enabled);
        assert!(cfg.decomposition_gate);
        assert!(cfg.delegated_execution);
    }

    // ── Session resolution mode ───────────────────────────────────────

    #[test]
    fn session_resolution_modes_are_correct() {
        assert_eq!(
            PipelineConfig::api().session_resolution,
            SessionResolutionMode::FromBody
        );
        assert_eq!(
            PipelineConfig::streaming().session_resolution,
            SessionResolutionMode::FromBody
        );
        assert_eq!(
            PipelineConfig::channel("discord").session_resolution,
            SessionResolutionMode::FromChannel {
                platform: "discord".into()
            }
        );
        assert_eq!(
            PipelineConfig::cron().session_resolution,
            SessionResolutionMode::Dedicated
        );
    }

    #[test]
    fn provided_session_resolution_stores_id() {
        let mode = SessionResolutionMode::Provided {
            session_id: "test-session-123".into(),
        };
        match mode {
            SessionResolutionMode::Provided { session_id } => {
                assert_eq!(session_id, "test-session-123");
            }
            _ => panic!("expected Provided variant"),
        }
    }
}