sema-workflow 1.36.0

Sequential dynamic-workflow runtime + frozen JSONL run-directory journal for Sema
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
//! The FROZEN workflow event vocabulary.
//!
//! Determinism is NOT free: `serde_json` is built without `preserve_order` in this
//! workspace (root `Cargo.toml`), so any *map*-encoded event would emit keys in
//! alphabetical order — a fragile basis for a byte-identical golden. We therefore
//! encode events as a `#[derive(Serialize)]` enum with an internal `event` tag and
//! explicit per-variant field declarations: serde emits struct fields in *source
//! declaration order*, which is stable and reviewable. Do NOT replace this with a
//! `serde_json::Map`.
//!
//! Tag values carry dots (`run.started`), which `rename_all = "snake_case"` cannot
//! produce, so every variant pins its tag with an explicit `#[serde(rename = "…")]`.
//!
//! Field ordering convention: `seq` then `ts` lead every variant (so a human or
//! `jq` scan sees ordering+time first), followed by the variant-specific payload.
//!
//! Existing variants are FROZEN. Additive variants are allowed. Fields added to an
//! existing variant must be append-only and optional/skippable so old goldens remain
//! valid.

use serde::Serialize;

/// One journaled workflow event. Serialized as a single JSON object per line via
/// [`crate::Journal::write`]. The `event` tag discriminates the variant.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "event")]
pub enum WorkflowEvent {
    /// First line of every run. Records the workflow identity and the inputs/budget
    /// snapshot so the journal is self-describing without args.json/metadata.json.
    #[serde(rename = "run.started")]
    RunStarted {
        seq: u64,
        ts: String,
        /// `defworkflow` name.
        workflow: String,
        /// Run identity (the `<run-id>` directory name).
        run_id: String,
        /// Per-run code-version hash (a source hash, folded into resume content-keys so
        /// an edited workflow re-runs). Currently emitted empty here — the live value is
        /// carried via the `SEMA_WORKFLOW_CODE_VERSION` seam + `metadata.json`.
        #[serde(default, skip_serializing_if = "String::is_empty")]
        code_version: String,
        /// The run's `--args` input as a JSON string (the dashboard shows it on the
        /// run.started stream row). Empty when no args were supplied.
        #[serde(default, skip_serializing_if = "String::is_empty")]
        args_json: String,
        /// The workflow's declared phase plan (`defworkflow` meta `:phases`), so the
        /// dashboard can render ALL phases up front (pending → running → done) instead
        /// of only those that have started. Declared LAST (append-only); an empty plan
        /// is skipped, keeping pre-existing goldens byte-identical.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        phases: Vec<String>,
    },

    /// A `phase` opened. Paired with exactly one [`Self::PhaseEnded`] (emitted even on
    /// the error path).
    #[serde(rename = "phase.started")]
    PhaseStarted { seq: u64, ts: String, phase: String },

    /// A `phase` closed. `status` is `"success"` or `"failed"`. `dur_ms` is `0` under
    /// the fixed-timestamp test seam.
    #[serde(rename = "phase.ended")]
    PhaseEnded {
        seq: u64,
        ts: String,
        phase: String,
        status: String,
        dur_ms: u64,
    },

    /// An agent leaf began executing. `agent_id` is the per-invocation correlation
    /// key (e.g. `write-article_2`); `agent_name` is the role label; `model` is the
    /// LLM model (empty until known — it is filled on [`Self::AgentResult`]).
    #[serde(rename = "agent.started")]
    AgentStarted {
        seq: u64,
        ts: String,
        agent_id: String,
        agent_name: String,
        #[serde(default, skip_serializing_if = "String::is_empty")]
        model: String,
        /// The user prompt sent to the model, captured + length-capped, so the viewer can
        /// show what the agent was asked (the input counterpart to `agent.result.output`).
        /// Present for `agent`-macro leaves (which inject the resolved prompt); a
        /// hand-wrapped `workflow/step` given a bare label has no prompt to capture, so
        /// the field is empty. Declared LAST (append-only) and skipped when empty, so
        /// pre-existing goldens stay byte-identical.
        #[serde(default, skip_serializing_if = "String::is_empty")]
        prompt: String,
    },

    /// An agent leaf produced a result. `status` is `"ok"`/`"failed"`. `output` is an
    /// OPAQUE string/digest only. `model` is the model the call used (from usage),
    /// filled here because it is unknown when the agent started.
    #[serde(rename = "agent.result")]
    AgentResult {
        seq: u64,
        ts: String,
        agent_id: String,
        status: String,
        /// Opaque agent output (string or digest). Never a structured/typed field.
        output: String,
        dur_ms: u64,
        #[serde(default, skip_serializing_if = "String::is_empty")]
        model: String,
    },

    /// An agent invoked a tool. Names + opaque argument digest only.
    #[serde(rename = "agent.tool_call")]
    AgentToolCall {
        seq: u64,
        ts: String,
        agent_id: String,
        tool_name: String,
        /// Opaque digest of the call arguments (a `"gated"` sentinel = not captured).
        #[serde(default, skip_serializing_if = "String::is_empty")]
        args_json: String,
    },

    /// A tool handler returned successfully. The result is an opaque digest or
    /// gated sentinel; raw tool output never enters the workflow journal.
    #[serde(rename = "agent.tool_result")]
    AgentToolResult {
        seq: u64,
        ts: String,
        agent_id: String,
        tool_name: String,
        result_digest: String,
    },

    /// A `checkpoint` recorded a keyed step value. The value itself is NOT stored in
    /// the event stream — only a (lossy) digest — and a `content_key` resume hash.
    #[serde(rename = "checkpoint")]
    Checkpoint {
        seq: u64,
        ts: String,
        /// `start_seq` of the enclosing phase (the dashboard nests it there).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        phase_seq: Option<u64>,
        /// Checkpoint key (the `:k` of `(checkpoint :k v)`), as a bare name.
        key: String,
        /// Stable resume key (hash of inputs + code version); short hex.
        #[serde(default, skip_serializing_if = "String::is_empty")]
        content_key: String,
        /// Opaque digest of the recorded value (the resume identity).
        value_digest: String,
        /// The recorded value itself, rendered + length-capped, so the dashboard can
        /// show what was checkpointed (not just a hash). Empty if not captured.
        #[serde(default, skip_serializing_if = "String::is_empty")]
        value: String,
    },

    /// A budget / usage observation. Per-event (never a mutated counter) so summing
    /// over events never double-charges. Carries an `agent_id` when the usage is
    /// attributable to one agent leaf (the only way per-agent tokens are shown).
    #[serde(rename = "budget")]
    Budget {
        seq: u64,
        ts: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        agent_id: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        phase_seq: Option<u64>,
        input_tokens: u64,
        output_tokens: u64,
        /// `None` when pricing is unknown for the model (genuinely absent, not 0).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        cost_usd: Option<f64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        budget_limit: Option<u64>,
    },

    /// Last line of every run. `status` mirrors the `{:status …}` envelope's status
    /// (`"success"`, `"failed"`, `"needs-auth"`, `"needs-approval"`, or
    /// `"rejected"`); `reason` carries the terminal reason when present.
    #[serde(rename = "run.ended")]
    RunEnded {
        seq: u64,
        ts: String,
        status: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        reason: Option<String>,
        dur_ms: u64,
    },

    /// A declared `:mcp` server's auth requirement could not be satisfied from the
    /// token store (the headless-precursor gate; see
    /// `docs/plans/2026-06-24-workflow-mcp-auth.md` §3/§6). Emitted during the
    /// implicit auth-resolution step before the first user `phase` runs. Redaction
    /// rule: alias + scopes + expiry only, NEVER token material — `server` is the
    /// workflow's declared ALIAS for the server (e.g. `"asana"`), never a token,
    /// header, or URL with credentials. Declared LAST (append-only); this variant is
    /// never emitted in old runs, so pre-existing goldens stay byte-identical.
    #[serde(rename = "auth.required")]
    AuthRequired {
        seq: u64,
        ts: String,
        /// The workflow's declared alias for the server (e.g. `"asana"`), never a
        /// token, header, or URL with credentials.
        server: String,
        /// The `:mcp` spec's requested OAuth scopes.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        scopes: Vec<String>,
        /// The `:mcp` spec's `:tools` least-privilege manifest.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        tools: Vec<String>,
        /// Where the resulting session would be persisted once granted: one of
        /// `"keyring"`, `"workflow"`, `"run"`, `"none"`.
        persist: String,
    },

    /// A declared server's auth gate cleared: a usable session (cached, refreshed, or
    /// freshly consented) is now available, so the run can proceed. Redaction rule:
    /// alias + scopes + expiry only, NEVER token material.
    #[serde(rename = "auth.granted")]
    AuthGranted {
        seq: u64,
        ts: String,
        /// The workflow's declared alias for the server, never a token, header, or
        /// URL with credentials.
        server: String,
        /// The `:mcp` spec's requested OAuth scopes.
        #[serde(default, skip_serializing_if = "Vec::is_empty")]
        scopes: Vec<String>,
        /// Absolute unix-seconds expiry of the granted session; `None` when the
        /// session doesn't expire (or the provider didn't report one).
        #[serde(default, skip_serializing_if = "Option::is_none")]
        expires_at: Option<u64>,
        /// One of `"cached"`, `"refreshed"`, `"consented"`.
        source: String,
    },

    /// A declared server's auth flow could not complete (consent refused, discovery
    /// failed, callback timed out, …); the run ends `{:status :failed :reason :auth}`.
    /// Redaction rule: alias + reason only, NEVER token material.
    #[serde(rename = "auth.failed")]
    AuthFailed {
        seq: u64,
        ts: String,
        /// The workflow's declared alias for the server, never a token, header, or
        /// URL with credentials.
        server: String,
        /// Short opaque failure label/message (e.g. `"consent_denied"`), never token
        /// material.
        reason: String,
    },

    /// A policy layer allowed one protected model or tool boundary.
    #[serde(rename = "policy.checked")]
    PolicyChecked {
        seq: u64,
        ts: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        phase_seq: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        agent_id: Option<String>,
        policy: String,
        policy_digest: String,
        boundary: String,
        subject: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        subject_digest: Option<String>,
        rule: String,
        source: String,
    },

    /// A deterministic policy rule observed content in audit-only mode.
    #[serde(rename = "policy.flagged")]
    PolicyFlagged {
        seq: u64,
        ts: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        phase_seq: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        agent_id: Option<String>,
        policy: String,
        policy_digest: String,
        boundary: String,
        subject: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        subject_digest: Option<String>,
        rule: String,
        label: String,
        count: usize,
        action: String,
        source: String,
    },

    /// A deterministic policy rule mechanically redacted one or more spans.
    #[serde(rename = "policy.redacted")]
    PolicyRedacted {
        seq: u64,
        ts: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        phase_seq: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        agent_id: Option<String>,
        policy: String,
        policy_digest: String,
        boundary: String,
        subject: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        subject_digest: Option<String>,
        rule: String,
        label: String,
        count: usize,
        source: String,
    },

    /// A policy layer denied one protected model or tool boundary.
    #[serde(rename = "policy.violation")]
    PolicyViolation {
        seq: u64,
        ts: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        phase_seq: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        agent_id: Option<String>,
        policy: String,
        policy_digest: String,
        boundary: String,
        subject: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        subject_digest: Option<String>,
        rule: String,
        action: String,
        reason: String,
        source: String,
    },

    /// A trusted lexical `policy/without` scope bypassed the effective policy stack.
    #[serde(rename = "policy.bypassed")]
    PolicyBypassed {
        seq: u64,
        ts: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        phase_seq: Option<u64>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        agent_id: Option<String>,
        policy: String,
        policy_digest: String,
        boundary: String,
        subject: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        subject_digest: Option<String>,
        rule: String,
        reason: String,
        source: String,
    },

    /// A durable explicit approval request stopped workflow evaluation.
    #[serde(rename = "approval.requested")]
    ApprovalRequested {
        seq: u64,
        ts: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        phase_seq: Option<u64>,
        approval_id: String,
        request_digest: String,
        key: String,
        reason: String,
        subject_digest: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        preview: Option<String>,
    },

    /// An approved durable decision was observed while replaying the gate.
    #[serde(rename = "approval.granted")]
    ApprovalGranted {
        seq: u64,
        ts: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        phase_seq: Option<u64>,
        approval_id: String,
        decision_id: String,
        actor: String,
        provenance: String,
    },

    /// A rejected durable decision was observed while replaying the gate.
    #[serde(rename = "approval.rejected")]
    ApprovalRejected {
        seq: u64,
        ts: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        phase_seq: Option<u64>,
        approval_id: String,
        decision_id: String,
        actor: String,
        provenance: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        reason: Option<String>,
    },

    /// Execution crossed an explicit gate after observing an approved decision.
    #[serde(rename = "approval.applied")]
    ApprovalApplied {
        seq: u64,
        ts: String,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        phase_seq: Option<u64>,
        approval_id: String,
        decision_id: String,
    },
}

impl WorkflowEvent {
    pub fn kind(&self) -> &'static str {
        match self {
            Self::RunStarted { .. } => "run.started",
            Self::PhaseStarted { .. } => "phase.started",
            Self::PhaseEnded { .. } => "phase.ended",
            Self::AgentStarted { .. } => "agent.started",
            Self::AgentResult { .. } => "agent.result",
            Self::AgentToolCall { .. } => "agent.tool_call",
            Self::AgentToolResult { .. } => "agent.tool_result",
            Self::Checkpoint { .. } => "checkpoint",
            Self::Budget { .. } => "budget",
            Self::RunEnded { .. } => "run.ended",
            Self::AuthRequired { .. } => "auth.required",
            Self::AuthGranted { .. } => "auth.granted",
            Self::AuthFailed { .. } => "auth.failed",
            Self::PolicyChecked { .. } => "policy.checked",
            Self::PolicyFlagged { .. } => "policy.flagged",
            Self::PolicyRedacted { .. } => "policy.redacted",
            Self::PolicyViolation { .. } => "policy.violation",
            Self::PolicyBypassed { .. } => "policy.bypassed",
            Self::ApprovalRequested { .. } => "approval.requested",
            Self::ApprovalGranted { .. } => "approval.granted",
            Self::ApprovalRejected { .. } => "approval.rejected",
            Self::ApprovalApplied { .. } => "approval.applied",
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The tag must come FIRST and carry the dotted name; field order is declaration
    /// order (NOT alphabetical). This pins the wire shape the golden depends on.
    #[test]
    fn run_started_wire_shape() {
        let ev = WorkflowEvent::RunStarted {
            seq: 0,
            ts: "0".into(),
            workflow: "hello-wf".into(),
            run_id: "wf_test_0001".into(),
            code_version: String::new(), // skipped when empty
            args_json: String::new(),    // skipped when empty
            phases: Vec::new(),          // skipped when empty
        };
        let line = serde_json::to_string(&ev).unwrap();
        assert_eq!(
            line,
            r#"{"event":"run.started","seq":0,"ts":"0","workflow":"hello-wf","run_id":"wf_test_0001"}"#
        );
    }

    #[test]
    fn agent_events_use_agent_id() {
        let started = WorkflowEvent::AgentStarted {
            seq: 5,
            ts: "0".into(),
            agent_id: "auditor_1".into(),
            agent_name: "auditor".into(),
            model: String::new(),
            prompt: String::new(), // empty ⇒ skipped, so the wire shape is unchanged
        };
        assert_eq!(
            serde_json::to_string(&started).unwrap(),
            r#"{"event":"agent.started","seq":5,"ts":"0","agent_id":"auditor_1","agent_name":"auditor"}"#
        );
        let budget = WorkflowEvent::Budget {
            seq: 9,
            ts: "0".into(),
            agent_id: Some("auditor_1".into()),
            phase_seq: Some(4),
            input_tokens: 3120,
            output_tokens: 880,
            cost_usd: Some(0.0041),
            budget_limit: Some(250000),
        };
        let line = serde_json::to_string(&budget).unwrap();
        assert!(
            line.contains(r#""agent_id":"auditor_1""#) && line.contains(r#""input_tokens":3120"#)
        );
    }

    #[test]
    fn phase_ended_carries_status_and_dur() {
        let ev = WorkflowEvent::PhaseEnded {
            seq: 3,
            ts: "0".into(),
            phase: "Inventory".into(),
            status: "success".into(),
            dur_ms: 0,
        };
        let line = serde_json::to_string(&ev).unwrap();
        assert_eq!(
            line,
            r#"{"event":"phase.ended","seq":3,"ts":"0","phase":"Inventory","status":"success","dur_ms":0}"#
        );
    }

    #[test]
    fn checkpoint_digest_only() {
        let ev = WorkflowEvent::Checkpoint {
            seq: 2,
            ts: "0".into(),
            phase_seq: Some(1),
            key: "files".into(),
            content_key: "ck_4d2f8a1c".into(),
            value_digest: "abc123".into(),
            value: String::new(), // skipped when empty
        };
        let line = serde_json::to_string(&ev).unwrap();
        assert_eq!(
            line,
            r#"{"event":"checkpoint","seq":2,"ts":"0","phase_seq":1,"key":"files","content_key":"ck_4d2f8a1c","value_digest":"abc123"}"#
        );
    }

    #[test]
    fn auth_required_wire_shape() {
        let ev = WorkflowEvent::AuthRequired {
            seq: 4,
            ts: "0".into(),
            server: "asana".into(),
            scopes: vec!["default".into()],
            tools: vec!["create_task".into(), "search_tasks".into()],
            persist: "workflow".into(),
        };
        let line = serde_json::to_string(&ev).unwrap();
        assert_eq!(
            line,
            r#"{"event":"auth.required","seq":4,"ts":"0","server":"asana","scopes":["default"],"tools":["create_task","search_tasks"],"persist":"workflow"}"#
        );
    }

    #[test]
    fn auth_required_skips_empty_scopes_and_tools() {
        let ev = WorkflowEvent::AuthRequired {
            seq: 4,
            ts: "0".into(),
            server: "fs".into(),
            scopes: Vec::new(),
            tools: Vec::new(),
            persist: "none".into(),
        };
        let line = serde_json::to_string(&ev).unwrap();
        // scopes and tools are empty → both skipped.
        assert_eq!(
            line,
            r#"{"event":"auth.required","seq":4,"ts":"0","server":"fs","persist":"none"}"#
        );
    }

    #[test]
    fn auth_granted_wire_shape() {
        let ev = WorkflowEvent::AuthGranted {
            seq: 6,
            ts: "0".into(),
            server: "asana".into(),
            scopes: vec!["default".into()],
            expires_at: Some(1_800_000_000),
            source: "consented".into(),
        };
        let line = serde_json::to_string(&ev).unwrap();
        assert_eq!(
            line,
            r#"{"event":"auth.granted","seq":6,"ts":"0","server":"asana","scopes":["default"],"expires_at":1800000000,"source":"consented"}"#
        );
    }

    #[test]
    fn auth_granted_skips_empty_scopes_and_none_expiry() {
        let ev = WorkflowEvent::AuthGranted {
            seq: 6,
            ts: "0".into(),
            server: "asana".into(),
            scopes: Vec::new(),
            expires_at: None,
            source: "cached".into(),
        };
        let line = serde_json::to_string(&ev).unwrap();
        // scopes is empty and expires_at is None → both skipped.
        assert_eq!(
            line,
            r#"{"event":"auth.granted","seq":6,"ts":"0","server":"asana","source":"cached"}"#
        );
    }

    #[test]
    fn auth_failed_wire_shape() {
        let ev = WorkflowEvent::AuthFailed {
            seq: 7,
            ts: "0".into(),
            server: "asana".into(),
            reason: "consent_denied".into(),
        };
        let line = serde_json::to_string(&ev).unwrap();
        assert_eq!(
            line,
            r#"{"event":"auth.failed","seq":7,"ts":"0","server":"asana","reason":"consent_denied"}"#
        );
    }

    #[test]
    fn policy_events_are_additive_and_keep_tool_arguments_opaque() {
        let checked = WorkflowEvent::PolicyChecked {
            seq: 8,
            ts: "0".into(),
            phase_seq: Some(2),
            agent_id: Some("coder_1".into()),
            policy: "safe".into(),
            policy_digest: "policy-sha".into(),
            boundary: "tool".into(),
            subject: "read-file".into(),
            subject_digest: Some("args-sha".into()),
            rule: "tools.read-file.allow".into(),
            source: "live".into(),
        };
        assert_eq!(
            serde_json::to_string(&checked).unwrap(),
            r#"{"event":"policy.checked","seq":8,"ts":"0","phase_seq":2,"agent_id":"coder_1","policy":"safe","policy_digest":"policy-sha","boundary":"tool","subject":"read-file","subject_digest":"args-sha","rule":"tools.read-file.allow","source":"live"}"#
        );

        let violation = WorkflowEvent::PolicyViolation {
            seq: 9,
            ts: "0".into(),
            phase_seq: None,
            agent_id: None,
            policy: "safe".into(),
            policy_digest: "policy-sha".into(),
            boundary: "model".into(),
            subject: "openai/gpt-5".into(),
            subject_digest: None,
            rule: "models.default-deny".into(),
            action: "fail".into(),
            reason: "not allowlisted".into(),
            source: "cache".into(),
        };
        let line = serde_json::to_string(&violation).unwrap();
        assert_eq!(
            line,
            r#"{"event":"policy.violation","seq":9,"ts":"0","policy":"safe","policy_digest":"policy-sha","boundary":"model","subject":"openai/gpt-5","rule":"models.default-deny","action":"fail","reason":"not allowlisted","source":"cache"}"#
        );
        assert!(
            !line.contains("args_json"),
            "policy events must never expose raw tool arguments"
        );
    }
}