everruns-core 0.22.0

Transport-neutral agent execution contracts for Everruns
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
// Canonical resolved execution snapshot (EVE-872).
//
// Decision: host turn execution consumes this neutral, value-first projection
// instead of stored Agent/Harness/Session aggregates (the session arrives as the portable `ExecutionSession` projection, EVE-882). Both the Framework
// in-process runtime and the hosted workers build the same value here, so
// harness → agent → session precedence is applied by one code path
// (`AgentConfigOverlay` merge semantics) regardless of which host executes the
// turn. Credentials, database lifecycle fields, organization records,
// timestamps, UI metadata, and CRUD status are excluded by construction, so
// Debug/serialization of this value is secret-free without redaction logic.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use crate::agent_definition::AgentDefinition;
use crate::capability_types::AgentCapabilityConfig;
use crate::config_layer::AgentConfigOverlay;
use crate::error::{AgentLoopError, Result};
use crate::harness_definition::HarnessDefinition;
use crate::mcp_server::{
    McpProtocolMode, McpServerAuthMode, McpServerTransportType, ScopedMcpServer,
};
use crate::network_access::NetworkAccessList;
use crate::session::ExecutionSession;
use crate::session_file::InitialFile;
use crate::tool_types::ToolDefinition;
use crate::typed_id::{AgentId, HarnessId, ModelId, SessionId, WorkspaceId};

/// Non-secret MCP scope entry retained by the execution snapshot.
///
/// Scoped MCP server configs can carry literal credentials in header and env
/// values (e.g. `Authorization: Bearer …`). The snapshot keeps the scope —
/// which servers exist and how they authenticate — but only the *names* of
/// headers and env vars. Execution resolves live connections (including
/// credential material) through the host's MCP seam, never from this value.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SnapshotMcpServer {
    pub transport_type: McpServerTransportType,
    /// Header names only; header values never enter the snapshot.
    pub header_names: Vec<String>,
    /// Env var names only; env values never enter the snapshot.
    pub env_names: Vec<String>,
    pub auth_mode: McpServerAuthMode,
    pub protocol_mode: McpProtocolMode,
    pub oauth_provider_id: Option<String>,
    pub tool_discovery: bool,
}

impl From<&ScopedMcpServer> for SnapshotMcpServer {
    fn from(server: &ScopedMcpServer) -> Self {
        let mut header_names: Vec<String> = server.headers.keys().cloned().collect();
        header_names.sort();
        let mut env_names: Vec<String> = server.env.keys().cloned().collect();
        env_names.sort();
        Self {
            transport_type: server.transport_type.clone(),
            header_names,
            env_names,
            auth_mode: server.auth_mode.clone(),
            protocol_mode: server.protocol_mode,
            oauth_provider_id: server.oauth_provider_id.clone(),
            tool_discovery: server.tool_discovery,
        }
    }
}

/// Canonical resolved execution value for one session's turn execution.
///
/// Contains only turn-relevant configuration plus the typed correlation
/// values execution needs. Produced by [`ResolvedExecutionSnapshot::project`]
/// — the platform projection boundary where missing, mismatched, or inactive
/// stored records fail before host execution begins.
///
/// Field order is fixed and map fields are `BTreeMap`s, so serialization of
/// equal values is byte-identical (deterministic).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResolvedExecutionSnapshot {
    // --- Typed session correlation values required by execution ---
    pub session_id: SessionId,
    pub workspace_id: WorkspaceId,
    pub harness_id: HarnessId,
    pub agent_id: Option<AgentId>,
    /// Public (`org_…`) organization id used for execution scoping. This is a
    /// correlation value, not the organization record.
    pub organization_id: String,

    // --- Effective configuration (harness → agent → session, applied once) ---
    /// Effective instructions (merged system prompt, session goal included).
    pub instructions: Option<String>,
    /// Effective model specification; `None` selects the host default model.
    pub default_model_id: Option<ModelId>,
    /// Configured capability references with per-layer config merged.
    pub capabilities: Vec<AgentCapabilityConfig>,
    /// Explicitly configured tools (client-side or capability-provided).
    pub tools: Vec<ToolDefinition>,
    /// Effective initial workspace files.
    pub initial_files: Vec<InitialFile>,
    /// Effective scoped MCP servers, credential values excluded.
    pub mcp_servers: BTreeMap<String, SnapshotMcpServer>,
    /// Effective workspace network policy.
    pub network_access: Option<NetworkAccessList>,
    /// Maximum reason iterations per turn.
    pub max_iterations: Option<usize>,
    /// Request-level parallel tool calling preference.
    pub parallel_tool_calls: Option<bool>,

    // --- Non-secret execution metadata ---
    pub locale: Option<String>,
    pub tags: Vec<String>,
    pub blueprint_id: Option<String>,
    pub blueprint_config: Option<serde_json::Value>,
    /// Cumulative LLM usage projected from the session for turn accounting.
    pub cumulative_usage: Option<crate::events::TokenUsage>,
    /// Embedder metadata folded from the harness chain (root base, leaf wins).
    pub embedder_metadata: BTreeMap<String, String>,
}

impl ResolvedExecutionSnapshot {
    /// Project loaded records into the canonical execution value.
    ///
    /// This is the execution projection boundary: it fails when a referenced
    /// agent is missing or does not match the session's agent id. Harness
    /// lifecycle and inheritance validation happen one step earlier, at the
    /// host loading seam (EVE-881): parent-chain loading, cycle/error handling,
    /// and archived/deleted validation run before only the effective,
    /// executable [`HarnessDefinition`] reaches this projection. Agent
    /// lifecycle validation likewise fails at that host seam (EVE-877). Host
    /// execution never sees a snapshot built from broken record wiring.
    ///
    /// Precedence is applied exactly once, through the same
    /// [`AgentConfigOverlay`] merge semantics the runtime capability
    /// resolution uses: harness → agent → session, leaf wins.
    pub fn project(
        harness: &HarnessDefinition,
        agent: Option<&AgentDefinition>,
        session: &ExecutionSession,
    ) -> Result<Self> {
        let agent = match (session.agent_id, agent) {
            (Some(agent_id), Some(agent)) => {
                if agent.id != agent_id {
                    return Err(AgentLoopError::config(format!(
                        "session {} references agent {} but agent {} was provided",
                        session.id, agent_id, agent.id
                    )));
                }
                Some(agent)
            }
            (Some(agent_id), None) => {
                return Err(AgentLoopError::agent_not_found(agent_id));
            }
            (None, _) => None,
        };

        let agent_layers = agent.into_iter().map(AgentConfigOverlay::from);
        let effective = AgentConfigOverlay::fold(
            [AgentConfigOverlay::from(harness)]
                .into_iter()
                .chain(agent_layers)
                .chain([AgentConfigOverlay::from(session)]),
        );

        // Chain folding (root base, leaf wins) already happened at the platform
        // seam; the definition carries the effective metadata.
        let embedder_metadata = harness
            .embedder_metadata
            .iter()
            .map(|(key, value)| (key.clone(), value.clone()))
            .collect();

        Ok(Self {
            session_id: session.id,
            workspace_id: session.workspace_id,
            harness_id: session.harness_id,
            agent_id: session.agent_id,
            organization_id: session.organization_id.clone(),
            instructions: effective.system_prompt,
            default_model_id: effective.default_model_id,
            capabilities: effective.capabilities,
            tools: effective.tools,
            initial_files: effective.initial_files,
            mcp_servers: effective
                .mcp_servers
                .iter()
                .map(|(name, server)| (name.clone(), SnapshotMcpServer::from(server)))
                .collect(),
            network_access: effective.network_access,
            max_iterations: effective.max_iterations,
            parallel_tool_calls: effective.parallel_tool_calls,
            locale: session.locale.clone(),
            tags: session.tags.clone(),
            blueprint_id: session.blueprint_id.clone(),
            blueprint_config: session.blueprint_config.clone(),
            cumulative_usage: session.usage.clone(),
            embedder_metadata,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::network_access::NetworkAccessList;
    use std::collections::HashMap;

    fn harness() -> HarnessDefinition {
        HarnessDefinition {
            capabilities: vec![AgentCapabilityConfig::new("session_file_system")],
            ..HarnessDefinition::new("base", "Harness prompt.")
        }
    }

    fn agent(agent_id: AgentId, _harness_id: HarnessId) -> AgentDefinition {
        AgentDefinition {
            max_iterations: Some(8),
            display_name: Some("Agent".into()),
            ..AgentDefinition::new(agent_id, "agent", "Agent prompt.")
        }
    }

    fn session(
        session_id: SessionId,
        harness_id: HarnessId,
        agent_id: Option<AgentId>,
    ) -> ExecutionSession {
        ExecutionSession {
            agent_id,
            title: Some("UI-TITLE-MARKER".into()),
            locale: Some("en-US".into()),
            tags: vec!["tag-a".into()],
            ..ExecutionSession::with_own_workspace(session_id, harness_id)
        }
    }

    fn ids() -> (HarnessId, AgentId, SessionId) {
        (
            HarnessId::from_seed(11),
            AgentId::from_seed(11),
            SessionId::from_seed(11),
        )
    }

    fn file(path: &str, content: &str) -> InitialFile {
        InitialFile {
            path: path.into(),
            content: content.into(),
            encoding: "text".into(),
            is_readonly: false,
        }
    }

    // --- Precedence matrix: harness → agent → session, leaf wins ---

    #[test]
    fn precedence_instructions_concatenate_root_to_leaf() {
        let (harness_id, agent_id, session_id) = ids();
        let harness = harness();
        let agent = agent(agent_id, harness_id);
        let mut session = session(session_id, harness_id, Some(agent_id));
        session.system_prompt = Some("Session prompt.".into());

        let snapshot =
            ResolvedExecutionSnapshot::project(&harness, Some(&agent), &session).unwrap();
        assert_eq!(
            snapshot.instructions.as_deref(),
            Some("Harness prompt.\n\nAgent prompt.\n\nSession prompt.")
        );
    }

    #[test]
    fn precedence_model_leaf_layer_wins() {
        let (harness_id, agent_id, session_id) = ids();
        let mut harness = harness();
        harness.default_model_id = Some(ModelId::from_seed(1));
        let mut agent = agent(agent_id, harness_id);
        agent.default_model_id = Some(ModelId::from_seed(2));
        let mut session = session(session_id, harness_id, Some(agent_id));

        let snapshot =
            ResolvedExecutionSnapshot::project(&harness, Some(&agent), &session).unwrap();
        assert_eq!(snapshot.default_model_id, Some(ModelId::from_seed(2)));

        session.model_id = Some(ModelId::from_seed(3));
        let snapshot =
            ResolvedExecutionSnapshot::project(&harness, Some(&agent), &session).unwrap();
        assert_eq!(snapshot.default_model_id, Some(ModelId::from_seed(3)));
        session.model_id = None;
        session.agent_id = None;
        let snapshot = ResolvedExecutionSnapshot::project(&harness, None, &session).unwrap();
        assert_eq!(snapshot.default_model_id, Some(ModelId::from_seed(1)));
        harness.default_model_id = None;
        assert_eq!(
            ResolvedExecutionSnapshot::project(&harness, None, &session)
                .unwrap()
                .default_model_id,
            None
        );
    }

    #[test]
    fn precedence_capabilities_override_by_id() {
        let (harness_id, agent_id, session_id) = ids();
        let mut harness = harness();
        harness.capabilities = vec![AgentCapabilityConfig::with_config(
            "web_fetch",
            serde_json::json!({"enable_file_download": true}),
        )];
        let mut agent = agent(agent_id, harness_id);
        agent.capabilities = vec![AgentCapabilityConfig::with_config(
            "current_time",
            serde_json::json!({"zone":"UTC"}),
        )];
        let mut session = session(session_id, harness_id, Some(agent_id));
        session.capabilities = vec![AgentCapabilityConfig::with_config(
            "web_fetch",
            serde_json::json!({"enable_file_download": false}),
        )];

        let snapshot =
            ResolvedExecutionSnapshot::project(&harness, Some(&agent), &session).unwrap();
        assert_eq!(snapshot.capabilities.len(), 2);
        assert_eq!(
            snapshot.capabilities[0],
            AgentCapabilityConfig::with_config(
                "web_fetch",
                serde_json::json!({"enable_file_download": false})
            )
        );
        assert_eq!(
            snapshot.capabilities[1],
            AgentCapabilityConfig::with_config("current_time", serde_json::json!({"zone":"UTC"}))
        );
    }

    #[test]
    fn capability_ref_round_trips_framework_persistence_and_worker_resolution() {
        // EVE-873: one neutral reference/config representation. A Framework
        // `CapabilityRef` serializes to the persisted attachment shape, loads
        // back as `AgentCapabilityConfig` (the same type), and survives
        // snapshot projection (the worker resolution input) unchanged.
        let framework_ref = everruns_capability::CapabilityRef::new("web_fetch")
            .config(serde_json::json!({"enable_file_download": true}));
        let persisted = serde_json::to_value(&framework_ref).unwrap();
        assert_eq!(
            persisted,
            serde_json::json!({
                "ref": "web_fetch",
                "config": {"enable_file_download": true}
            }),
            "wire shape is the persisted attachment row shape"
        );

        let attachment: AgentCapabilityConfig = serde_json::from_value(persisted).unwrap();
        assert_eq!(attachment, framework_ref);

        let (harness_id, agent_id, session_id) = ids();
        let mut harness = harness();
        harness.capabilities = vec![attachment.clone()];
        let agent = agent(agent_id, harness_id);
        let session = session(session_id, harness_id, Some(agent_id));
        let snapshot =
            ResolvedExecutionSnapshot::project(&harness, Some(&agent), &session).unwrap();
        assert_eq!(snapshot.capabilities, vec![framework_ref.clone()]);
        assert_eq!(
            serde_json::to_value(&snapshot.capabilities[0]).unwrap(),
            serde_json::to_value(&framework_ref).unwrap()
        );
    }

    #[test]
    fn snapshot_debug_redacts_capability_config_values() {
        // Attachment rows flow through logs and error contexts; their Debug
        // output must never leak config payloads (which may carry handles or
        // misplaced credentials).
        let attachment = AgentCapabilityConfig::with_config(
            "vendor.search",
            serde_json::json!({"api_key": "sk-super-secret"}),
        );
        let (harness_id, _, session_id) = ids();
        let mut harness = harness();
        harness.capabilities = vec![attachment];
        let snapshot = ResolvedExecutionSnapshot::project(
            &harness,
            None,
            &session(session_id, harness_id, None),
        )
        .unwrap();
        let debug = format!("{snapshot:?}");
        assert!(debug.contains("vendor.search"));
        assert!(!debug.contains("sk-super-secret"));
        assert!(!debug.contains("api_key"));
    }

    #[test]
    fn precedence_initial_files_override_by_path() {
        let (harness_id, agent_id, session_id) = ids();
        let mut harness = harness();
        harness.initial_files = vec![file("/config.txt", "harness"), file("/keep.txt", "keep")];
        let mut agent = agent(agent_id, harness_id);
        agent.initial_files = vec![file("config.txt", "agent")];
        agent.initial_files[0].is_readonly = true;
        agent.initial_files[0].encoding = "base64".into();
        agent.initial_files[0].content = "YWdlbnQ=".into();
        let session = session(session_id, harness_id, Some(agent_id));

        let snapshot =
            ResolvedExecutionSnapshot::project(&harness, Some(&agent), &session).unwrap();
        assert_eq!(
            snapshot.initial_files,
            vec![
                agent.initial_files[0].clone(),
                harness.initial_files[1].clone()
            ]
        );
    }

    #[test]
    fn precedence_mcp_servers_override_by_name() {
        let (harness_id, agent_id, session_id) = ids();
        let mut harness = harness();
        harness.mcp_servers.insert(
            "docs".into(),
            ScopedMcpServer {
                url: "https://harness.example.com/mcp".into(),
                ..Default::default()
            },
        );
        harness
            .mcp_servers
            .insert("retained".into(), ScopedMcpServer::default());
        let agent = agent(agent_id, harness_id);
        let mut session = session(session_id, harness_id, Some(agent_id));
        session.mcp_servers.insert(
            "docs".into(),
            ScopedMcpServer {
                url: "https://session.example.com/mcp".into(),
                transport_type: McpServerTransportType::Stdio,
                headers: [
                    ("Z-Header".into(), "z-value".into()),
                    ("A-Header".into(), "a-value".into()),
                ]
                .into(),
                env: [("Z_ENV".into(), "z".into()), ("A_ENV".into(), "a".into())].into(),
                auth_mode: McpServerAuthMode::OAuth,
                protocol_mode: McpProtocolMode::V2025June,
                oauth_provider_id: Some("session-provider".into()),
                tool_discovery: false,
                ..Default::default()
            },
        );

        let snapshot =
            ResolvedExecutionSnapshot::project(&harness, Some(&agent), &session).unwrap();
        assert_eq!(
            snapshot.mcp_servers,
            BTreeMap::from([
                (
                    "docs".into(),
                    SnapshotMcpServer {
                        transport_type: McpServerTransportType::Stdio,
                        header_names: vec!["A-Header".into(), "Z-Header".into()],
                        env_names: vec!["A_ENV".into(), "Z_ENV".into()],
                        auth_mode: McpServerAuthMode::OAuth,
                        protocol_mode: McpProtocolMode::V2025June,
                        oauth_provider_id: Some("session-provider".into()),
                        tool_discovery: false,
                    }
                ),
                (
                    "retained".into(),
                    SnapshotMcpServer {
                        transport_type: McpServerTransportType::Http,
                        header_names: vec![],
                        env_names: vec![],
                        auth_mode: McpServerAuthMode::None,
                        protocol_mode: McpProtocolMode::Auto,
                        oauth_provider_id: None,
                        tool_discovery: true,
                    }
                ),
            ])
        );
    }

    #[test]
    fn precedence_network_access_narrows() {
        let (harness_id, agent_id, session_id) = ids();
        let mut harness = harness();
        harness.network_access = Some(NetworkAccessList::allow_only([
            "*.example.com",
            "api.github.com",
        ]));
        harness
            .network_access
            .as_mut()
            .unwrap()
            .blocked
            .push("private.example.com".into());
        let agent = agent(agent_id, harness_id);
        let mut session = session(session_id, harness_id, Some(agent_id));
        session.network_access = Some(NetworkAccessList {
            allowed: vec!["api.example.com".into(), "outside.net".into()],
            blocked: vec!["blocked.example.com".into()],
        });

        let snapshot =
            ResolvedExecutionSnapshot::project(&harness, Some(&agent), &session).unwrap();
        let acl = snapshot.network_access.unwrap();
        assert_eq!(
            acl,
            NetworkAccessList {
                allowed: vec!["api.example.com".into()],
                blocked: vec!["private.example.com".into(), "blocked.example.com".into()]
            }
        );
        assert!(acl.is_url_allowed("https://api.example.com"));
        assert!(!acl.is_url_allowed("https://outside.net"));
    }

    #[test]
    fn precedence_iteration_controls_leaf_wins() {
        let (harness_id, agent_id, session_id) = ids();
        let harness = harness();
        let mut agent = agent(agent_id, harness_id);
        agent.max_iterations = Some(40);
        agent.parallel_tool_calls = Some(true);
        let mut session = session(session_id, harness_id, Some(agent_id));
        session.max_iterations = Some(0);
        session.parallel_tool_calls = Some(false);

        let snapshot =
            ResolvedExecutionSnapshot::project(&harness, Some(&agent), &session).unwrap();
        assert_eq!(snapshot.max_iterations, Some(0));
        assert_eq!(snapshot.parallel_tool_calls, Some(false));
    }

    #[test]
    fn correlation_values_are_copied() {
        let (harness_id, agent_id, session_id) = ids();
        let mut harness = harness();
        harness.embedder_metadata = [("embedder".into(), "fixture-host".into())].into();
        let agent = agent(agent_id, harness_id);
        let mut session = session(session_id, harness_id, Some(agent_id));
        session.workspace_id = WorkspaceId::from_seed(71);
        session.organization_id = "org_00000000000000000000000000000042".into();
        session.blueprint_id = Some("review-blueprint".into());
        session.blueprint_config = Some(serde_json::json!({"region":"eu","enabled":false}));
        session.usage = Some(crate::events::TokenUsage {
            input_tokens: 13,
            output_tokens: 29,
            cache_read_tokens: Some(7),
            cache_creation_tokens: Some(3),
            actual_cost_usd: Some(0.25),
            estimated_cost_usd: Some(0.5),
            effective_cost_usd: Some(0.75),
        });

        let snapshot =
            ResolvedExecutionSnapshot::project(&harness, Some(&agent), &session).unwrap();
        assert_eq!(snapshot.session_id, session_id);
        assert_eq!(snapshot.workspace_id, session.workspace_id);
        assert_eq!(snapshot.harness_id, harness_id);
        assert_eq!(snapshot.agent_id, Some(agent_id));
        assert_eq!(snapshot.organization_id, session.organization_id);
        assert_eq!(snapshot.locale.as_deref(), Some("en-US"));
        assert_eq!(snapshot.tags, vec!["tag-a".to_string()]);
        assert_eq!(snapshot.blueprint_id, session.blueprint_id);
        assert_eq!(snapshot.blueprint_config, session.blueprint_config);
        assert_eq!(
            serde_json::to_value(snapshot.cumulative_usage).unwrap(),
            serde_json::to_value(session.usage).unwrap()
        );
        assert_eq!(
            snapshot.embedder_metadata,
            BTreeMap::from([("embedder".into(), "fixture-host".into())])
        );
    }

    // --- Projection failures ---
    //
    // Harness lifecycle and inheritance failures (empty chain, chain/leaf
    // mismatch, archived/deleted records, cycles) moved to the platform
    // loading seam (EVE-881); they are covered by the `everruns-platform`
    // `resolve_execution_harness` tests and the hosted store adapters.

    #[test]
    fn projection_fails_on_missing_agent() {
        let (harness_id, agent_id, session_id) = ids();
        let harness = harness();
        let session = session(session_id, harness_id, Some(agent_id));
        assert!(
            matches!(ResolvedExecutionSnapshot::project(&harness, None, &session), Err(AgentLoopError::AgentNotFound(id)) if id == agent_id)
        );
    }

    #[test]
    fn projection_fails_on_mismatched_agent() {
        let (harness_id, agent_id, session_id) = ids();
        let harness = harness();
        let other_agent = agent(AgentId::from_seed(99), harness_id);
        let session = session(session_id, harness_id, Some(agent_id));
        match ResolvedExecutionSnapshot::project(&harness, Some(&other_agent), &session)
            .unwrap_err()
        {
            AgentLoopError::Configuration(message) => assert_eq!(
                message,
                format!(
                    "session {session_id} references agent {agent_id} but agent {} was provided",
                    other_agent.id
                )
            ),
            other => panic!("wrong projection error: {other:?}"),
        }
    }

    #[test]
    fn snapshot_excludes_platform_metadata_and_credential_values() {
        let (harness_id, agent_id, session_id) = ids();
        let harness = harness();
        let mut agent = agent(agent_id, harness_id);
        agent.description = Some("UI-PREVIEW-MARKER".into());
        let mut session = session(session_id, harness_id, Some(agent_id));
        session.mcp_servers.insert(
            "docs".into(),
            ScopedMcpServer {
                url: "https://user:SECRET-URL-MARKER@mcp.example.com".into(),
                headers: [(
                    "Authorization".to_string(),
                    "Bearer SECRET-HEADER-MARKER".to_string(),
                )]
                .into_iter()
                .collect(),
                env: [("API_KEY".to_string(), "SECRET-ENV-MARKER".to_string())]
                    .into_iter()
                    .collect(),
                command: Some("SECRET-COMMAND-MARKER".into()),
                args: vec!["--api-key=SECRET-ARG-MARKER".into()],
                ..Default::default()
            },
        );

        let snapshot =
            ResolvedExecutionSnapshot::project(&harness, Some(&agent), &session).unwrap();

        let serialized = serde_json::to_string(&snapshot).unwrap();
        let debugged = format!("{snapshot:?}");
        for surface in [serialized.as_str(), debugged.as_str()] {
            // Credential values from scoped MCP config never appear.
            assert!(!surface.contains("SECRET-HEADER-MARKER"), "{surface}");
            assert!(!surface.contains("SECRET-ENV-MARKER"), "{surface}");
            assert!(!surface.contains("SECRET-URL-MARKER"), "{surface}");
            assert!(!surface.contains("SECRET-COMMAND-MARKER"), "{surface}");
            assert!(!surface.contains("SECRET-ARG-MARKER"), "{surface}");
            // UI/platform-only metadata never appears.
            assert!(!surface.contains("UI-TITLE-MARKER"), "{surface}");
            assert!(!surface.contains("UI-PREVIEW-MARKER"), "{surface}");
        }

        // Non-secret scope survives: server name and credential field names.
        let docs = snapshot.mcp_servers.get("docs").unwrap();
        assert_eq!(docs.header_names, vec!["Authorization".to_string()]);
        assert_eq!(docs.env_names, vec!["API_KEY".to_string()]);
    }

    #[test]
    fn snapshot_serialization_is_deterministic_and_round_trips() {
        let (harness_id, agent_id, session_id) = ids();
        let mut harness = harness();
        harness.embedder_metadata = HashMap::from([
            ("zeta".to_string(), "z".to_string()),
            ("alpha".to_string(), "a".to_string()),
        ]);
        let agent = agent(agent_id, harness_id);
        let session = session(session_id, harness_id, Some(agent_id));

        let first = ResolvedExecutionSnapshot::project(&harness, Some(&agent), &session).unwrap();
        // Rebuild independent input maps in opposite insertion order, not the
        // same HashMap twice (whose iteration order stays stable).
        let mut reversed = harness.clone();
        reversed.embedder_metadata =
            HashMap::from([("alpha".into(), "a".into()), ("zeta".into(), "z".into())]);
        let second = ResolvedExecutionSnapshot::project(&reversed, Some(&agent), &session).unwrap();

        let first_json = serde_json::to_string(&first).unwrap();
        let second_json = serde_json::to_string(&second).unwrap();
        assert_eq!(first_json, second_json);

        let round_tripped: ResolvedExecutionSnapshot = serde_json::from_str(&first_json).unwrap();
        assert_eq!(serde_json::to_string(&round_tripped).unwrap(), first_json);

        // Map metadata serializes in sorted key order regardless of input order.
        let alpha = first_json.find("alpha").unwrap();
        let zeta = first_json.find("zeta").unwrap();
        assert!(alpha < zeta);
    }
    #[test]
    fn unreferenced_agent_cannot_contribute_configuration() {
        let (harness_id, agent_id, session_id) = ids();
        let harness = harness();
        let agent = agent(agent_id, harness_id);
        let session = session(session_id, harness_id, None);
        let without = ResolvedExecutionSnapshot::project(&harness, None, &session).unwrap();
        let with_unreferenced =
            ResolvedExecutionSnapshot::project(&harness, Some(&agent), &session).unwrap();
        assert_eq!(
            serde_json::to_value(with_unreferenced).unwrap(),
            serde_json::to_value(without).unwrap()
        );
    }
}