opensymphony 2.3.3

A Rust implementation of the OpenAI Symphony orchestration design
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
//! OpenHands → OpenSymphony event normalization contract tests.
//!
//! These tests exercise the [`normalize_event`](opensymphony_openhands::normalize_event)
//! entry point against synthetic OpenHands event envelopes and assert that:
//!
//! - Every `KnownEvent` variant produces a typed `EventKind` envelope.
//! - Unknown event kinds are preserved through `EventKind::Unknown` plus the
//!   raw payload reference, so diagnostics and forward compatibility continue
//!   to work.
//! - Unknown envelopes never fail the surrounding run; the function is total.
//! - REST history plus WebSocket event reconciliation produce the same
//!   output as a stream that received the events in one go.

use chrono::{Duration as ChronoDuration, Utc};
use serde_json::{Value, json};
use uuid::Uuid;

use crate::opensymphony_domain::ConversationId;
use crate::opensymphony_gateway_schema::event_journal::EventKind;
use crate::opensymphony_openhands::{
    EventEnvelope, NormalizationContext, NormalizedEvent, UNKNOWN_RAW_REF_PREFIX, normalize_event,
};

fn conversation_id() -> ConversationId {
    ConversationId::new("conv-norm-1").expect("valid id")
}

fn context() -> NormalizationContext {
    NormalizationContext::new("openhands-agent-server-v1", conversation_id()).expect("ctx")
}

fn state_update_envelope(id: &str) -> EventEnvelope {
    EventEnvelope::new(
        id,
        Utc::now(),
        "runtime",
        "ConversationStateUpdateEvent",
        json!({
            "execution_status": "running",
            "state_delta": { "execution_status": "running" },
        }),
    )
}

fn message_envelope(id: &str, role: &str, text: &str) -> EventEnvelope {
    EventEnvelope::new(
        id,
        Utc::now(),
        if role == "user" { "user" } else { "agent" },
        "MessageEvent",
        json!({
            "role": role,
            "content": [{ "type": "text", "text": text }],
        }),
    )
}

fn action_envelope(id: &str, tool: &str, command: &str) -> EventEnvelope {
    EventEnvelope::new(
        id,
        Utc::now(),
        "agent",
        "ActionEvent",
        json!({
            "action": {
                "action": "run",
                "tool_name": tool,
                "message": format!("Running `{command}`"),
                "arguments": { "command": command },
            }
        }),
    )
}

fn observation_envelope(id: &str, exit_code: i64, stdout: &str) -> EventEnvelope {
    EventEnvelope::new(
        id,
        Utc::now(),
        "agent",
        "ObservationEvent",
        json!({
            "observation": {
                "observation_id": "obs-1",
                "tool_name": "run",
                "exit_code": exit_code,
                "output": stdout,
                "content": [{ "type": "text", "text": stdout }],
            }
        }),
    )
}

fn llm_completion_envelope(id: &str, model: &str, prompt: u64, completion: u64) -> EventEnvelope {
    EventEnvelope::new(
        id,
        Utc::now(),
        "llm",
        "LLMCompletionLogEvent",
        json!({
            "model": model,
            "tokens": prompt + completion,
            "usage": {
                "prompt_tokens": prompt,
                "completion_tokens": completion,
            },
        }),
    )
}

fn conversation_error_envelope(id: &str, message: &str) -> EventEnvelope {
    EventEnvelope::new(
        id,
        Utc::now(),
        "runtime",
        "ConversationErrorEvent",
        json!({ "message": message }),
    )
}

fn unknown_envelope(id: &str, kind: &str) -> EventEnvelope {
    EventEnvelope::new(
        id,
        Utc::now(),
        "runtime",
        kind,
        json!({ "structure": "future", "data": ["a", "b"] }),
    )
}

#[test]
fn empty_source_routes_to_unknown_with_harness_actor() {
    let envelope = EventEnvelope::new(
        "evt-empty",
        Utc::now(),
        "",
        "MessageEvent",
        json!({ "role": "user", "content": [] }),
    );
    let normalized = normalize_event(&envelope, &context());
    match normalized.record.kind {
        EventKind::Unknown { raw_kind } => assert_eq!(raw_kind, "MessageEvent"),
        other => panic!("expected Unknown, got {other:?}"),
    }
    assert!(
        normalized
            .record
            .summary
            .contains("source_missing envelope kind=MessageEvent"),
        "summary should explain the missing source"
    );
    assert_eq!(
        normalized.record.actor.actor_id(),
        "openhands-agent-server-v1"
    );
    assert_eq!(
        normalized.raw_payload,
        json!({ "role": "user", "content": [] })
    );
}

#[test]
fn state_update_normalizes_with_typed_kind() {
    let normalized = normalize_event(&state_update_envelope("evt-su"), &context());
    assert!(matches!(
        normalized.record.kind,
        EventKind::HarnessConversationStateUpdate
    ));
    assert_eq!(normalized.record.summary, "runtime status: running");
    assert!(
        normalized
            .record
            .entity_refs
            .iter()
            .any(|er| er.id == "conv-norm-1")
    );
}

#[test]
fn message_event_user_role_normalizes() {
    let envelope = message_envelope("evt-user", "user", "hello");
    let normalized = normalize_event(&envelope, &context());
    match normalized.record.kind.clone() {
        EventKind::HarnessEventNormalized { source_kind } => {
            assert_eq!(source_kind, "MessageEvent")
        }
        other => panic!("expected HarnessEventNormalized, got {other:?}"),
    }
    assert_eq!(normalized.record.summary, "hello");
}

#[test]
fn message_event_assistant_role_normalizes() {
    let envelope = message_envelope("evt-asst", "assistant", "world");
    let normalized = normalize_event(&envelope, &context());
    assert_eq!(normalized.record.summary, "world");
}

#[test]
fn action_event_normalizes_into_tool_call() {
    let envelope = action_envelope("evt-act", "terminal", "ls -la");
    let normalized = normalize_event(&envelope, &context());
    assert!(matches!(normalized.record.kind, EventKind::HarnessToolCall));
    let payload = normalized.record.payload.expect("tool call payload");
    assert_eq!(
        payload.get("tool_name").and_then(Value::as_str),
        Some("terminal")
    );
    assert_eq!(
        payload
            .get("arguments")
            .and_then(|a| a.get("command"))
            .and_then(Value::as_str),
        Some("ls -la"),
    );
    assert_eq!(
        payload.get("action_id").and_then(Value::as_str),
        Some("evt-act"),
        "action_id must propagate so the action/observation chain stays correlatable"
    );
    assert_eq!(normalized.record.summary, "Running `ls -la`");
}

/// Round-6 AI review (`tool_call` payload misses `action_id`): the reviewer
/// flagged a hypothetical tool-call test that lacked the `action_id`
/// propagation assertion. The general `action_event_normalizes_into_tool_call`
/// test above already asserts `action_id` (see line ~215), but this more
/// targeted regression pins the exact invariant the reviewer asked for — an
/// `ActionEvent` envelope with id `evt-action` produces a `HarnessToolCall`
/// payload whose `action_id` is the envelope id, so `tool_name`, `arguments`,
/// and `action_id` all surface on the same record.
#[test]
fn action_event_normalizes_tool_call_with_arguments() {
    let envelope = action_envelope("evt-action", "terminal", "ls -la");
    let normalized = normalize_event(&envelope, &context());
    assert!(
        matches!(normalized.record.kind, EventKind::HarnessToolCall),
        "envelope id evt-action must normalize to HarnessToolCall"
    );
    let payload = normalized.record.payload.expect("tool call payload");
    assert_eq!(
        payload.get("tool_name").and_then(Value::as_str),
        Some("terminal"),
        "tool_name must match the action envelope's tool"
    );
    assert_eq!(
        payload
            .get("arguments")
            .and_then(|a| a.get("command"))
            .and_then(Value::as_str),
        Some("ls -la"),
        "arguments.command must round-trip from the envelope payload"
    );
    assert_eq!(
        payload.get("action_id").and_then(Value::as_str),
        Some("evt-action"),
        "action_id must propagate from the envelope id to the normalized payload"
    );
    assert_eq!(normalized.record.summary, "Running `ls -la`");
}

#[test]
fn observation_event_normalizes_into_tool_result() {
    let envelope = observation_envelope("evt-obs", 0, "ok\n");
    let normalized = normalize_event(&envelope, &context());
    assert!(matches!(
        normalized.record.kind,
        EventKind::HarnessToolResult
    ));
    let payload = normalized.record.payload.expect("tool result payload");
    assert_eq!(payload.get("exit_code").and_then(Value::as_i64), Some(0));
    assert_eq!(
        payload.get("tool_name").and_then(Value::as_str),
        Some("run")
    );
}

#[test]
fn llm_completion_log_extracts_token_usage() {
    let envelope = llm_completion_envelope("evt-llm", "openai/gpt-5.4", 12, 34);
    let normalized = normalize_event(&envelope, &context());
    match normalized.record.kind.clone() {
        EventKind::HarnessEventNormalized { source_kind } => {
            assert_eq!(source_kind, "LLMCompletionLogEvent");
        }
        other => panic!("expected HarnessEventNormalized, got {other:?}"),
    }
    let payload = normalized.record.payload.expect("usage payload");
    assert_eq!(
        payload
            .get("usage")
            .and_then(|u| u.get("prompt"))
            .and_then(Value::as_u64),
        Some(12)
    );
    assert_eq!(
        payload
            .get("usage")
            .and_then(|u| u.get("completion"))
            .and_then(Value::as_u64),
        Some(34)
    );
    assert_eq!(normalized.record.summary, "llm completion (openai/gpt-5.4)");
}

#[test]
fn conversation_error_normalizes_with_summary() {
    let envelope = conversation_error_envelope("evt-err", "boom");
    let normalized = normalize_event(&envelope, &context());
    match normalized.record.kind.clone() {
        EventKind::HarnessEventNormalized { source_kind } => {
            assert_eq!(source_kind, "ConversationErrorEvent");
        }
        other => panic!("expected HarnessEventNormalized, got {other:?}"),
    }
    assert_eq!(normalized.record.summary, "conversation error: boom");
}

#[test]
fn unknown_event_retains_raw_payload_and_ref() {
    let envelope = unknown_envelope("evt-u", "BrandNewEventType");
    let normalized = normalize_event(&envelope, &context());
    match &normalized.record.kind {
        EventKind::Unknown { raw_kind } => assert_eq!(raw_kind, "BrandNewEventType"),
        other => panic!("expected EventKind::Unknown, got {other:?}"),
    }
    assert!(
        normalized
            .raw_payload_ref
            .as_deref()
            .unwrap_or_default()
            .starts_with(UNKNOWN_RAW_REF_PREFIX),
        "unknown events must carry a synthetic raw_payload_ref"
    );
    let raw_payload = &normalized.raw_payload;
    assert_eq!(
        raw_payload.get("structure").and_then(Value::as_str),
        Some("future")
    );
}

#[test]
fn unknown_event_is_total_under_empty_or_malformed_payloads() {
    struct Case {
        name: &'static str,
        envelope: EventEnvelope,
    }
    let now = Utc::now();
    let cases = vec![
        Case {
            name: "missing payload",
            envelope: EventEnvelope::new("evt-empty", now, "runtime", "FutureEvent", Value::Null),
        },
        Case {
            name: "scalar payload",
            envelope: EventEnvelope::new("evt-scalar", now, "runtime", "FutureEvent", json!(42)),
        },
        Case {
            name: "empty object payload",
            envelope: EventEnvelope::new("evt-empty-obj", now, "runtime", "FutureEvent", json!({})),
        },
    ];
    for case in cases {
        let normalized = normalize_event(&case.envelope, &context());
        assert!(
            matches!(normalized.record.kind, EventKind::Unknown { .. }),
            "{name}: expected EventKind::Unknown",
            name = case.name
        );
    }
}

#[test]
fn normalization_preserve_event_id_for_dedupe() {
    let envelope = state_update_envelope("evt-dupe");
    let first = normalize_event(&envelope, &context());
    let second = normalize_event(&envelope, &context());
    assert_eq!(first.record.event_id, second.record.event_id);
    assert!(first.record.is_duplicate_of(&second.record));
}

#[test]
fn reconciliation_rest_then_ws_produces_same_envelope() {
    let ctx = context();
    let envelope = state_update_envelope("evt-rec");
    let from_rest = normalize_event(&envelope, &ctx);
    let from_ws = normalize_event(&envelope, &ctx);
    assert_eq!(from_rest.record.event_id, from_ws.record.event_id);
    assert_eq!(from_rest.record.summary, from_ws.record.summary);
    assert_eq!(from_rest.record.entity_refs, from_ws.record.entity_refs);
}

#[test]
fn correlation_id_propagates_into_normalized_envelope() {
    let ctx = NormalizationContext::new("openhands-agent-server-v1", conversation_id())
        .expect("ctx")
        .with_correlation_id("corr-prop-x");
    let envelope = state_update_envelope("evt-corr");
    let normalized = normalize_event(&envelope, &ctx);
    assert_eq!(
        normalized.record.correlation_id.as_deref(),
        Some("corr-prop-x")
    );
}

#[test]
fn raw_payload_for_known_events_is_the_envelope_payload() {
    let envelope = state_update_envelope("evt-known");
    let normalized: NormalizedEvent = normalize_event(&envelope, &context());
    // Typed variants do not emit a synthetic `raw://openhands/unknown/...` ref.
    assert!(normalized.raw_payload_ref.is_none());
    // Raw payload is preserved in normalized.raw_payload for diagnostics.
    let raw_payload = &normalized.raw_payload;
    assert_eq!(
        raw_payload.get("execution_status").and_then(Value::as_str),
        Some("running"),
    );
}

#[test]
fn unknown_keeps_payload_for_diagnostics_under_user_source() {
    let envelope = EventEnvelope::new(
        "evt-user-unknown",
        Utc::now() - ChronoDuration::seconds(2),
        "user",
        "CustomUserEvent",
        json!({ "freeform": { "note": "future-proof" } }),
    );
    let normalized = normalize_event(&envelope, &context());
    assert!(matches!(normalized.record.kind, EventKind::Unknown { .. }));
    assert!(
        normalized
            .raw_payload_ref
            .as_deref()
            .unwrap_or_default()
            .starts_with(UNKNOWN_RAW_REF_PREFIX)
    );
}

#[test]
fn invalid_correlation_id_caller_keeps_event_id_stable() {
    let ctx_bad = NormalizationContext::new("openhands-agent-server-v1", conversation_id())
        .expect("ctx")
        .with_correlation_id(Uuid::nil().to_string());
    let envelope = observation_envelope("evt-tool-result", 0, "ok");
    let normalized = normalize_event(&envelope, &ctx_bad);
    assert_eq!(normalized.record.event_id, "evt-tool-result");
}