Skip to main content

switchyard_protocol/
metadata.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Correlation metadata and harness header normalization.
5//!
6//! [`Metadata`] is the correlation/routing envelope carried alongside a request or
7//! response. [`Metadata::from_headers`] normalizes host-specific HTTP headers into
8//! that neutral shape.
9
10use std::{collections::BTreeMap, str::FromStr as _};
11
12use crate::WireFormat;
13
14// Dotted paths addressing fields inside Codex's turn-metadata header JSON value.
15const CODEX_SESSION_ID_PATH: &str = "x-codex-turn-metadata.session_id";
16const CODEX_THREAD_ID_PATH: &str = "x-codex-turn-metadata.thread_id";
17const CODEX_PARENT_THREAD_ID_PATH: &str = "x-codex-turn-metadata.parent_thread_id";
18const CODEX_TURN_ID_PATH: &str = "x-codex-turn-metadata.turn_id";
19const CODEX_SUBAGENT_KIND_PATH: &str = "x-codex-turn-metadata.subagent_kind";
20const CODEX_AGENT_ROLE_PATH: &str = "x-codex-turn-metadata.agent_role";
21const CODEX_TASK_ID_PATH: &str = "x-codex-turn-metadata.task_id";
22const CODEX_TASK_KIND_PATH: &str = "x-codex-turn-metadata.task_kind";
23
24// Explicit Switchyard override headers; these take precedence over harness-native headers.
25const SWITCHYARD_SESSION_ID_HEADER: &str = "x-switchyard-session-id";
26const SWITCHYARD_AGENT_ID_HEADER: &str = "x-switchyard-agent-id";
27const SWITCHYARD_PARENT_AGENT_ID_HEADER: &str = "x-switchyard-parent-agent-id";
28const SWITCHYARD_IS_SUBAGENT_HEADER: &str = "x-switchyard-is-subagent";
29const SWITCHYARD_AGENT_KIND_HEADER: &str = "x-switchyard-agent-kind";
30const SWITCHYARD_AGENT_ROLE_HEADER: &str = "x-switchyard-agent-role";
31const SWITCHYARD_TASK_ID_HEADER: &str = "x-switchyard-task-id";
32const SWITCHYARD_TASK_KIND_HEADER: &str = "x-switchyard-task-kind";
33const SWITCHYARD_TURN_ID_HEADER: &str = "x-switchyard-turn-id";
34const SWITCHYARD_REQUEST_ID_HEADER: &str = "x-switchyard-request-id";
35const SWITCHYARD_SESSION_FINAL_HEADER: &str = "x-switchyard-session-final";
36
37// Correlation-header aliases used by integrating hosts.
38const RELAY_SESSION_ID_HEADER: &str = "x-nemo-relay-session-id";
39const RELAY_SUBAGENT_ID_HEADER: &str = "x-nemo-relay-subagent-id";
40
41// Additional correlation-header aliases used by integrating hosts.
42const DYNAMO_SESSION_ID_HEADER: &str = "x-dynamo-session-id";
43const DYNAMO_PARENT_SESSION_ID_HEADER: &str = "x-dynamo-parent-session-id";
44const DYNAMO_SESSION_FINAL_HEADER: &str = "x-dynamo-session-final";
45
46// Codex compatibility projection of its parent thread id.
47const CODEX_PARENT_THREAD_ID_HEADER: &str = "x-codex-parent-thread-id";
48
49// OpenAI subagent marker.
50const OPENAI_SUBAGENT_HEADER: &str = "x-openai-subagent";
51
52// Claude Code agent-lineage headers.
53const CLAUDE_SESSION_ID_HEADER: &str = "x-claude-code-session-id";
54const CLAUDE_AGENT_ID_HEADER: &str = "x-claude-code-agent-id";
55const CLAUDE_PARENT_AGENT_ID_HEADER: &str = "x-claude-code-parent-agent-id";
56
57// OpenCode session header — used for session_id correlation only (not a routing signal).
58const OPENCODE_SESSION_ID_HEADER: &str = "x-session-id";
59
60// Generic Codex-compatible correlation headers.
61const SESSION_ID_HEADER: &str = "session-id";
62const THREAD_ID_HEADER: &str = "thread-id";
63const TASK_ID_HEADER: &str = "x-task-id";
64const REQUEST_ID_HEADER: &str = "x-request-id";
65const CLIENT_REQUEST_ID_HEADER: &str = "x-client-request-id";
66
67/// Harness-defined sub-agent kinds that carry delegated user work rather than
68/// harness maintenance (`compact`, `memory_consolidation`, ...). Unknown kinds
69/// are excluded deliberately; extend with captured request fixtures.
70const SUBAGENT_WORK_KINDS: &[&str] = &["collab_spawn", "review"];
71
72/// Ordered candidate lookup paths for each correlation field, keyed by the field's
73/// canonical `x-switchyard-*` header name.
74type HeaderConfig = [(&'static str, &'static [&'static str])];
75
76/// Precedence of harness headers for each correlation field. See [`HeaderConfig`].
77const HEADER_CONFIG: &HeaderConfig = &[
78    (
79        SWITCHYARD_SESSION_ID_HEADER,
80        &[
81            SWITCHYARD_SESSION_ID_HEADER,
82            CLAUDE_SESSION_ID_HEADER,
83            RELAY_SESSION_ID_HEADER,
84            OPENCODE_SESSION_ID_HEADER,
85            CODEX_SESSION_ID_PATH,
86            SESSION_ID_HEADER,
87        ],
88    ),
89    (
90        SWITCHYARD_AGENT_ID_HEADER,
91        &[
92            SWITCHYARD_AGENT_ID_HEADER,
93            CLAUDE_AGENT_ID_HEADER,
94            RELAY_SUBAGENT_ID_HEADER,
95            DYNAMO_SESSION_ID_HEADER,
96            CODEX_THREAD_ID_PATH,
97            THREAD_ID_HEADER,
98        ],
99    ),
100    (
101        SWITCHYARD_PARENT_AGENT_ID_HEADER,
102        &[
103            SWITCHYARD_PARENT_AGENT_ID_HEADER,
104            DYNAMO_PARENT_SESSION_ID_HEADER,
105            CODEX_PARENT_THREAD_ID_PATH,
106            CODEX_PARENT_THREAD_ID_HEADER,
107        ],
108    ),
109    (
110        SWITCHYARD_AGENT_KIND_HEADER,
111        &[
112            SWITCHYARD_AGENT_KIND_HEADER,
113            CODEX_SUBAGENT_KIND_PATH,
114            OPENAI_SUBAGENT_HEADER,
115        ],
116    ),
117    (
118        SWITCHYARD_AGENT_ROLE_HEADER,
119        &[SWITCHYARD_AGENT_ROLE_HEADER, CODEX_AGENT_ROLE_PATH],
120    ),
121    (
122        SWITCHYARD_TASK_ID_HEADER,
123        &[
124            SWITCHYARD_TASK_ID_HEADER,
125            CODEX_TASK_ID_PATH,
126            TASK_ID_HEADER,
127        ],
128    ),
129    (
130        SWITCHYARD_TASK_KIND_HEADER,
131        &[SWITCHYARD_TASK_KIND_HEADER, CODEX_TASK_KIND_PATH],
132    ),
133    (
134        SWITCHYARD_TURN_ID_HEADER,
135        &[SWITCHYARD_TURN_ID_HEADER, CODEX_TURN_ID_PATH],
136    ),
137    (
138        SWITCHYARD_REQUEST_ID_HEADER,
139        &[
140            SWITCHYARD_REQUEST_ID_HEADER,
141            REQUEST_ID_HEADER,
142            CLIENT_REQUEST_ID_HEADER,
143        ],
144    ),
145    (
146        SWITCHYARD_SESSION_FINAL_HEADER,
147        &[SWITCHYARD_SESSION_FINAL_HEADER, DYNAMO_SESSION_FINAL_HEADER],
148    ),
149];
150
151/// Correlation and routing metadata attached to a request or response.
152///
153/// All fields are optional (or default-empty); algorithms and observers use whichever
154/// are present (e.g. to key per-session state or emit correlated telemetry). The
155/// agent-lineage fields (`parent_agent_id`, `is_subagent`, `agent_kind`, `agent_role`,
156/// `task_kind`, `turn_id`, `session_final`) are populated for requests from a coding
157/// agent. `extra_metadata` is a free-form escape hatch for host-specific keys.
158#[derive(Clone, Default)]
159pub struct Metadata {
160    /// Stable id for a multi-request session/conversation.
161    pub session_id: Option<String>,
162    /// Id of the agent making the request.
163    pub agent_id: Option<String>,
164    /// Id of the parent agent, when this request comes from a child agent.
165    pub parent_agent_id: Option<String>,
166    /// Whether the harness identified this request as coming from a child agent.
167    pub is_subagent: bool,
168    /// Whether this request carries delegated sub-agent *work* and should be
169    /// routed to the sub-agent target. Computed from raw harness signals only,
170    /// independent of [`Self::agent_kind`], which may be set by an unrelated
171    /// operator label (`x-switchyard-agent-kind`).
172    pub is_delegated_work: bool,
173    /// Harness-defined kind of agent call, such as `collab_spawn` or `review`.
174    pub agent_kind: Option<String>,
175    /// Semantic agent role, such as `explorer`, `worker`, or `reviewer`.
176    pub agent_role: Option<String>,
177    /// Id of the task the request belongs to.
178    pub task_id: Option<String>,
179    /// Semantic task class supplied by the harness.
180    pub task_kind: Option<String>,
181    /// Id of the current agent turn.
182    pub turn_id: Option<String>,
183    /// Whether the harness signalled this is the session's final request (e.g. the
184    /// host may evict per-session state). `None` when the harness said nothing.
185    pub session_final: Option<bool>,
186    /// External trace/request id for joining with the host's telemetry.
187    pub correlation_id: Option<String>,
188    /// Arbitrary host-defined key/value metadata.
189    pub extra_metadata: Option<BTreeMap<String, String>>,
190    /// HTTP headers to attach when forwarding the request/response, if any.
191    pub http_headers: Option<http::HeaderMap>,
192    /// The wire format the request/response was originally encoded in, if known.
193    pub wire_format: Option<WireFormat>,
194}
195
196impl Metadata {
197    /// Create Metadata
198    pub fn from_headers(headers: &http::HeaderMap) -> Self {
199        let (parent_agent_id, is_subagent, is_delegated_work) = parse_sub_agent(headers);
200
201        Metadata {
202            session_id: sy_header(headers, SWITCHYARD_SESSION_ID_HEADER),
203            agent_id: sy_header(headers, SWITCHYARD_AGENT_ID_HEADER),
204            parent_agent_id,
205            is_subagent,
206            is_delegated_work,
207            agent_kind: sy_header(headers, SWITCHYARD_AGENT_KIND_HEADER),
208            agent_role: sy_header(headers, SWITCHYARD_AGENT_ROLE_HEADER),
209            task_id: sy_header(headers, SWITCHYARD_TASK_ID_HEADER),
210            task_kind: sy_header(headers, SWITCHYARD_TASK_KIND_HEADER),
211            turn_id: sy_header(headers, SWITCHYARD_TURN_ID_HEADER),
212            session_final: sy_header(headers, SWITCHYARD_SESSION_FINAL_HEADER)
213                .as_deref()
214                .and_then(parse_bool),
215            correlation_id: sy_header(headers, SWITCHYARD_REQUEST_ID_HEADER),
216            ..Metadata::default()
217        }
218    }
219
220    /// Whether this request should be routed to the sub-agent target.
221    ///
222    /// Returns `self.is_delegated_work`, which is computed in `parse_sub_agent`
223    /// from raw harness signals only — independent of `agent_kind`, which may
224    /// be populated by an unrelated operator label (`x-switchyard-agent-kind`).
225    pub fn is_subagent_work(&self) -> bool {
226        self.is_delegated_work
227    }
228}
229
230/// Returns `(parent_agent_id, is_subagent, is_delegated_work)` from the headers.
231///
232/// Recognized sub-agent signals include `x-claude-code-agent-id`,
233/// `x-openai-subagent`, `x-codex-turn-metadata.subagent_kind`, and explicit
234/// `x-switchyard-is-subagent`. Other host correlation and parent-session headers
235/// may populate metadata but do not drive sub-agent classification.
236///
237/// `is_delegated_work` is computed from raw harness signals, not from `agent_kind`,
238/// which may be set by an unrelated operator label (`x-switchyard-agent-kind`).
239fn parse_sub_agent(headers: &http::HeaderMap) -> (Option<String>, bool, bool) {
240    let explicit = header(headers, SWITCHYARD_IS_SUBAGENT_HEADER).and_then(parse_bool);
241
242    let (claude_parent, claude_subagent) = claude_lineage(headers);
243
244    // Harness routing signal: Codex turn-metadata kind or flat OpenAI subagent header.
245    // `x-switchyard-agent-kind` (operator semantic label) is intentionally excluded.
246    let harness_kind = resolve_path(headers, CODEX_SUBAGENT_KIND_PATH)
247        .or_else(|| header(headers, OPENAI_SUBAGENT_HEADER).map(str::to_string));
248
249    // Resolve the parent through the configured header precedence, then fall back
250    // to the native agent session the child was spawned under.
251    let parent = sy_header(headers, SWITCHYARD_PARENT_AGENT_ID_HEADER)
252        .or_else(|| claude_parent.map(str::to_string));
253
254    let is_subagent = explicit.unwrap_or(claude_subagent || harness_kind.is_some());
255
256    let is_delegated_work = match explicit {
257        Some(false) => false,
258        Some(true) => harness_kind
259            .as_deref()
260            .map(|k| SUBAGENT_WORK_KINDS.contains(&k))
261            .unwrap_or(true),
262        None => {
263            claude_subagent
264                || harness_kind
265                    .as_deref()
266                    .is_some_and(|k| SUBAGENT_WORK_KINDS.contains(&k))
267        }
268    };
269
270    (parent, is_subagent, is_delegated_work)
271}
272
273/// Claude Code's `(parent_agent, is_subagent)` from its native lineage headers.
274///
275/// Claude Code only sends `x-claude-code-agent-id` for spawned sub-agents and
276/// teammates; root agents omit it. Any non-empty value is therefore a
277/// sub-agent signal. The parent is the explicit parent-agent header when
278/// present, else the session the child was spawned under.
279fn claude_lineage(headers: &http::HeaderMap) -> (Option<&str>, bool) {
280    let session = header(headers, CLAUDE_SESSION_ID_HEADER);
281    let agent = header(headers, CLAUDE_AGENT_ID_HEADER);
282    let is_subagent = agent.is_some();
283    let parent = is_subagent
284        .then(|| header(headers, CLAUDE_PARENT_AGENT_ID_HEADER).or(session))
285        .flatten();
286    (parent, is_subagent)
287}
288
289/// Parses the common textual spellings of a boolean header value.
290fn parse_bool(value: &str) -> Option<bool> {
291    match value.trim().to_ascii_lowercase().as_str() {
292        "1" | "true" | "yes" | "on" => Some(true),
293        "0" | "false" | "no" | "off" => Some(false),
294        _ => None,
295    }
296}
297
298/// Resolves the logical field `key` against `headers` using [`HEADER_CONFIG`]'s paths.
299///
300/// Returns the value of the first configured path that resolves, or `None` when the
301/// field is absent from [`HEADER_CONFIG`] or nothing resolves. Descending into JSON
302/// yields owned values, so the result is a `String` rather than a borrow of `headers`.
303fn sy_header(headers: &http::HeaderMap, key: &str) -> Option<String> {
304    let (_, paths) = HEADER_CONFIG
305        .iter()
306        .find(|(field, _)| field.eq_ignore_ascii_case(key))?;
307    paths.iter().find_map(|path| resolve_path(headers, path))
308}
309
310/// Follows one dotted path, descending through a JSON-object header value.
311/// Do not use if you expect multiple values for this header.
312fn resolve_path(headers: &http::HeaderMap, path: &str) -> Option<String> {
313    let (header_name, nested) = match path.split_once('.') {
314        Some((name, rest)) => (name, Some(rest)),
315        None => (path, None),
316    };
317    let raw = headers.get(header_name)?.to_str().ok().map(|s| s.trim())?;
318    if raw.is_empty() {
319        return None;
320    }
321
322    // A bare header name resolves to its value verbatim; no JSON parsing needed.
323    let Some(nested) = nested else {
324        return Some(raw.to_string());
325    };
326
327    // Nested path: parse the header value as JSON and descend key by key.
328    let mut current: serde_json::Value = serde_json::from_str(raw).ok()?;
329    for segment in nested.split('.') {
330        current = current.as_object()?.get(segment)?.clone();
331    }
332
333    match current {
334        serde_json::Value::String(s) => {
335            let value = s.trim();
336            (!value.is_empty()).then(|| value.to_string())
337        }
338        serde_json::Value::Null => None,
339        leaf => Some(leaf.to_string()),
340    }
341}
342
343fn header<'a>(headers: &'a http::HeaderMap, key: &str) -> Option<&'a str> {
344    headers
345        .get(key)
346        .and_then(|s| s.to_str().ok())
347        .map(str::trim)
348        .filter(|s| !s.is_empty())
349}
350
351/// Utility to convert a slice of string pairs into an `http::HeaderMap`.
352pub fn slice_to_header_map(sl: &[(&str, &str)]) -> http::HeaderMap {
353    let mut m = http::HeaderMap::with_capacity(sl.len());
354    for (k, v) in sl {
355        m.insert(
356            http::HeaderName::from_str(k).unwrap(),
357            (*v).try_into().unwrap(),
358        );
359    }
360    m
361}
362
363#[cfg(test)]
364mod tests {
365    use super::*;
366
367    /// Header carrying Codex's structured turn metadata as a JSON object.
368    const CODEX_TURN_METADATA_HEADER: &str = "x-codex-turn-metadata";
369
370    fn metadata(headers: &[(&str, &str)]) -> Metadata {
371        Metadata::from_headers(&slice_to_header_map(headers))
372    }
373
374    #[test]
375    fn normalizes_codex_metadata_and_lineage() {
376        let child_body = serde_json::json!({
377            "session_id": "root-session",
378            "thread_id": "child-agent",
379            "parent_thread_id": "root-agent",
380            "turn_id": "turn-7",
381            "subagent_kind": "collab_spawn",
382        })
383        .to_string();
384        let child = metadata(&[(CODEX_TURN_METADATA_HEADER, child_body.as_str())]);
385        assert_eq!(child.session_id.as_deref(), Some("root-session"));
386        assert_eq!(child.agent_id.as_deref(), Some("child-agent"));
387        assert_eq!(child.parent_agent_id.as_deref(), Some("root-agent"));
388        assert!(child.is_subagent);
389
390        let root_body = serde_json::json!({
391            "session_id": "root-session",
392            "thread_id": "root-agent",
393            "turn_id": "turn-1",
394        })
395        .to_string();
396        let root = metadata(&[(CODEX_TURN_METADATA_HEADER, root_body.as_str())]);
397        assert!(!root.is_subagent);
398
399        // Parent-thread-id is correlation data, not a routing signal. A Codex
400        // turn that carries a parent thread id but no `x-openai-subagent` must
401        // not be treated as sub-agent work.
402        let correlated_body = serde_json::json!({
403            "session_id": "root-session",
404            "thread_id": "child-thread",
405            "parent_thread_id": "root-thread",
406            "turn_id": "turn-3",
407        })
408        .to_string();
409        let correlated = metadata(&[(CODEX_TURN_METADATA_HEADER, correlated_body.as_str())]);
410        assert_eq!(correlated.parent_agent_id.as_deref(), Some("root-thread"));
411        assert!(!correlated.is_subagent);
412        assert!(!correlated.is_subagent_work());
413    }
414
415    #[test]
416    fn normalizes_claude_code_metadata_and_lineage() {
417        // Claude Code identifies a session with `x-claude-code-session-id`; session
418        // affinity keys on it so a whole CLI session pins to one tier.
419        let session = metadata(&[(
420            "x-claude-code-session-id",
421            "fb46caae-eac6-4f5f-83fd-8fc8f5743abb",
422        )]);
423        assert_eq!(
424            session.session_id.as_deref(),
425            Some("fb46caae-eac6-4f5f-83fd-8fc8f5743abb")
426        );
427
428        // Any non-empty agent id is a child agent. Without an explicit parent
429        // header the parent is inferred to be the session it was spawned under.
430        let child = metadata(&[
431            ("x-claude-code-session-id", "claude-session"),
432            ("x-claude-code-agent-id", "claude-agent"),
433        ]);
434        assert_eq!(child.session_id.as_deref(), Some("claude-session"));
435        assert_eq!(child.agent_id.as_deref(), Some("claude-agent"));
436        assert_eq!(child.parent_agent_id.as_deref(), Some("claude-session"));
437        assert!(child.is_subagent);
438
439        let child_without_session = metadata(&[("x-claude-code-agent-id", "claude-agent")]);
440        assert_eq!(
441            child_without_session.agent_id.as_deref(),
442            Some("claude-agent")
443        );
444        assert_eq!(child_without_session.parent_agent_id, None);
445        assert!(child_without_session.is_subagent);
446
447        let explicit_parent = metadata(&[
448            ("x-claude-code-session-id", "claude-session"),
449            ("x-claude-code-agent-id", "claude-agent"),
450            ("x-claude-code-parent-agent-id", "claude-parent-agent"),
451        ]);
452        assert_eq!(
453            explicit_parent.parent_agent_id.as_deref(),
454            Some("claude-parent-agent")
455        );
456
457        // Root agents omit x-claude-code-agent-id entirely. A stray parent-agent
458        // header without an agent-id must not mark the request as a child.
459        let root = metadata(&[
460            ("x-claude-code-session-id", "claude-session"),
461            ("x-claude-code-parent-agent-id", "claude-parent-agent"),
462        ]);
463        assert_eq!(root.session_id.as_deref(), Some("claude-session"));
464        assert_eq!(root.agent_id, None);
465        assert_eq!(root.parent_agent_id, None);
466        assert!(!root.is_subagent);
467    }
468
469    #[test]
470    fn normalizes_correlation_and_session_headers_without_routing() {
471        // Integrating-host headers are correlation data, not routing signals.
472        let relay = metadata(&[
473            ("x-nemo-relay-session-id", "relay-session"),
474            ("x-nemo-relay-subagent-id", "relay-child"),
475            ("x-dynamo-parent-session-id", "relay-parent"),
476        ]);
477        assert_eq!(relay.session_id.as_deref(), Some("relay-session"));
478        assert_eq!(relay.agent_id.as_deref(), Some("relay-child"));
479        assert_eq!(relay.parent_agent_id.as_deref(), Some("relay-parent"));
480        assert!(!relay.is_subagent);
481        assert!(!relay.is_subagent_work());
482
483        let opencode = metadata(&[
484            ("x-session-id", "opencode-run"),
485            ("x-parent-session-id", "opencode-parent"),
486        ]);
487        assert_eq!(opencode.session_id.as_deref(), Some("opencode-run"));
488        assert_eq!(opencode.parent_agent_id, None);
489        assert!(!opencode.is_subagent);
490
491        let codex_session = metadata(&[
492            ("session-id", "codex-run"),
493            ("x-parent-session-id", "stray-parent"),
494        ]);
495        assert_eq!(codex_session.session_id.as_deref(), Some("codex-run"));
496        assert_eq!(codex_session.parent_agent_id, None);
497        assert!(!codex_session.is_subagent);
498
499        let final_session = metadata(&[
500            ("x-dynamo-session-id", "generic-run"),
501            ("x-dynamo-parent-session-id", "generic-parent"),
502            ("x-dynamo-session-final", "true"),
503        ]);
504        assert_eq!(final_session.agent_id.as_deref(), Some("generic-run"));
505        assert_eq!(
506            final_session.parent_agent_id.as_deref(),
507            Some("generic-parent")
508        );
509        assert_eq!(final_session.session_final, Some(true));
510
511        let active_session = metadata(&[
512            ("x-dynamo-session-id", "generic-run"),
513            ("x-dynamo-session-final", "false"),
514        ]);
515        assert_eq!(active_session.session_final, Some(false));
516    }
517
518    #[test]
519    fn sy_header_resolves_paths_in_order_and_descends_into_json() {
520        // Only the JSON-nested Codex path is present, so descent supplies the value.
521        let body = serde_json::json!({ "session_id": "codex-session" }).to_string();
522        let headers = slice_to_header_map(&[(CODEX_TURN_METADATA_HEADER, body.as_str())]);
523        assert_eq!(
524            sy_header(&headers, SWITCHYARD_SESSION_ID_HEADER).as_deref(),
525            Some("codex-session")
526        );
527
528        // The explicit Switchyard header outranks the Codex path when both resolve.
529        let headers = slice_to_header_map(&[
530            (SWITCHYARD_SESSION_ID_HEADER, "explicit"),
531            (CODEX_TURN_METADATA_HEADER, body.as_str()),
532        ]);
533        assert_eq!(
534            sy_header(&headers, SWITCHYARD_SESSION_ID_HEADER).as_deref(),
535            Some("explicit")
536        );
537
538        // Nothing resolves for an empty header set or an unknown field.
539        assert_eq!(
540            sy_header(&http::HeaderMap::new(), SWITCHYARD_SESSION_ID_HEADER),
541            None
542        );
543        assert_eq!(sy_header(&headers, "x-not-a-field"), None);
544    }
545
546    // Blank nested metadata must not mask a valid lower-priority session header.
547    #[test]
548    fn nested_metadata_strings_match_flat_header_normalization() {
549        let body = serde_json::json!({ "session_id": "  codex-session  " }).to_string();
550        let headers = slice_to_header_map(&[(CODEX_TURN_METADATA_HEADER, body.as_str())]);
551        assert_eq!(
552            sy_header(&headers, SWITCHYARD_SESSION_ID_HEADER).as_deref(),
553            Some("codex-session")
554        );
555
556        let blank_body = serde_json::json!({ "session_id": "   " }).to_string();
557        let headers = slice_to_header_map(&[
558            (CODEX_TURN_METADATA_HEADER, blank_body.as_str()),
559            (SESSION_ID_HEADER, "fallback-session"),
560        ]);
561        assert_eq!(
562            sy_header(&headers, SWITCHYARD_SESSION_ID_HEADER).as_deref(),
563            Some("fallback-session")
564        );
565    }
566
567    #[test]
568    fn subagent_routing_honors_explicit_signals_and_delegated_work_kinds() {
569        // Explicit `false` wins over presence-based inference even when no
570        // parent id accompanies it; the flag decides in both directions.
571        let explicitly_root = metadata(&[
572            ("x-switchyard-is-subagent", "false"),
573            ("x-openai-subagent", "review"),
574        ]);
575        assert!(!explicitly_root.is_subagent);
576
577        let explicitly_child = metadata(&[("x-switchyard-is-subagent", "true")]);
578        assert!(explicitly_child.is_subagent);
579
580        let child_with_parent = metadata(&[
581            ("x-switchyard-is-subagent", "false"),
582            ("x-switchyard-parent-agent-id", "parent"),
583        ]);
584        assert!(!child_with_parent.is_subagent);
585
586        // Operator labels do not filter routing signals from the harness.
587        let with_openai = metadata(&[
588            ("x-openai-subagent", "review"),
589            ("x-switchyard-agent-kind", "researcher"),
590        ]);
591        assert!(with_openai.is_subagent);
592        assert!(with_openai.is_subagent_work());
593
594        let with_explicit = metadata(&[
595            ("x-switchyard-is-subagent", "true"),
596            ("x-switchyard-agent-kind", "researcher"),
597        ]);
598        assert!(with_explicit.is_subagent);
599        assert!(with_explicit.is_subagent_work());
600
601        // Kindless lineage (Claude Code child agent) counts as delegated work.
602        let claude_child = metadata(&[
603            ("x-claude-code-session-id", "root"),
604            ("x-claude-code-agent-id", "worker"),
605        ]);
606        assert!(claude_child.is_subagent_work());
607
608        // Codex delegated-work kinds route as sub-agent work.
609        let review = metadata(&[("x-openai-subagent", "review")]);
610        assert!(review.is_subagent_work());
611
612        // Harness maintenance and unknown kinds stay on normal routing even
613        // though the lineage fact still marks them as child-agent requests.
614        for kind in ["compact", "memory_consolidation", "brand_new_kind"] {
615            let request = metadata(&[("x-openai-subagent", kind)]);
616            assert!(request.is_subagent, "{kind} keeps the lineage fact");
617            assert!(!request.is_subagent_work(), "{kind} is not routed as work");
618        }
619
620        // A non-subagent request is never work, whatever its kind says.
621        assert!(!Metadata::default().is_subagent_work());
622    }
623}