nika 0.20.0

Semantic YAML workflow engine for AI tasks - DAG execution, MCP integration, multi-provider LLM support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
//! EventLog - Event sourcing implementation (v0.4)
//!
//! Provides full audit trail with replay capability.
//! - Event: envelope with id + timestamp + kind
//! - EventKind: 16+ variants across 5 levels (workflow/task/fine-grained/MCP/context)
//! - EventLog: thread-safe, append-only log
//!
//! ## v0.4.1 Changes
//! - Added `AgentTurnMetadata` for reasoning capture (thinking, tokens, stop_reason)
//! - Updated `AgentTurn` variant to include optional metadata

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::Instant;

use parking_lot::RwLock; // 2-3x faster than std::sync::RwLock
use tokio::sync::broadcast;

use serde::{Deserialize, Serialize};
use serde_json::Value;

// ═══════════════════════════════════════════════════════════════
// Helper structs for ContextAssembled event
// ═══════════════════════════════════════════════════════════════

/// A source included in the assembled context
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ContextSource {
    /// Node/source identifier
    pub node: String,
    /// Token count for this source
    pub tokens: u32,
}

/// An item excluded from context assembly
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ExcludedItem {
    /// Node/source identifier
    pub node: String,
    /// Reason for exclusion
    pub reason: String,
}

// ═══════════════════════════════════════════════════════════════
// AgentTurnMetadata for Reasoning Capture (v0.4.1)
// ═══════════════════════════════════════════════════════════════

/// Agent turn response metadata for observability (v0.4.1)
///
/// Captures detailed information about each agent turn, including:
/// - Thinking content (if Claude extended thinking is enabled)
/// - Response text
/// - Token usage
/// - Stop reason
///
/// ## Note on Thinking Capture
/// Full thinking block capture requires using rig's streaming API or
/// direct completion requests. When using `agent.prompt()`, thinking
/// is not available (will be `None`).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AgentTurnMetadata {
    /// Thinking content from Claude's extended thinking (if enabled)
    ///
    /// This field is populated when using streaming completion or
    /// direct completion API. It's `None` when using Agent::prompt().
    #[serde(skip_serializing_if = "Option::is_none")]
    pub thinking: Option<String>,

    /// Main response text from the agent
    pub response_text: String,

    /// Input tokens used for this turn
    pub input_tokens: u32,

    /// Output tokens generated for this turn
    pub output_tokens: u32,

    /// Cache read tokens (Anthropic prompt caching)
    #[serde(default)]
    pub cache_read_tokens: u32,

    /// Stop reason: "end_turn", "tool_use", "max_tokens", "stop_sequence"
    pub stop_reason: String,
}

impl AgentTurnMetadata {
    /// Create metadata for a simple text response (no thinking)
    pub fn text_only(response: impl Into<String>, stop_reason: impl Into<String>) -> Self {
        Self {
            thinking: None,
            response_text: response.into(),
            input_tokens: 0,
            output_tokens: 0,
            cache_read_tokens: 0,
            stop_reason: stop_reason.into(),
        }
    }

    /// Create metadata with token usage
    pub fn with_usage(
        response: impl Into<String>,
        input_tokens: u32,
        output_tokens: u32,
        stop_reason: impl Into<String>,
    ) -> Self {
        Self {
            thinking: None,
            response_text: response.into(),
            input_tokens,
            output_tokens,
            cache_read_tokens: 0,
            stop_reason: stop_reason.into(),
        }
    }

    /// Total tokens (input + output)
    pub fn total_tokens(&self) -> u32 {
        self.input_tokens + self.output_tokens
    }

    /// Check if thinking was captured
    pub fn has_thinking(&self) -> bool {
        self.thinking.is_some()
    }
}

/// Single event in the workflow execution log
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Event {
    /// Monotonic sequence ID (for ordering)
    pub id: u64,
    /// Time since workflow start (ms)
    pub timestamp_ms: u64,
    /// Event type and data
    pub kind: EventKind,
}

/// All possible event types (3 levels)
///
/// Uses `Arc<str>` for task_id fields to enable zero-cost cloning.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum EventKind {
    // ═══════════════════════════════════════════
    // WORKFLOW LEVEL
    // ═══════════════════════════════════════════
    WorkflowStarted {
        task_count: usize,
        /// Unique generation ID for this execution
        generation_id: String,
        /// Hash of workflow file for cache invalidation
        workflow_hash: String,
        /// Nika version
        nika_version: String,
    },
    WorkflowCompleted {
        final_output: Arc<Value>,
        total_duration_ms: u64,
    },
    WorkflowFailed {
        error: String,
        failed_task: Option<Arc<str>>,
    },
    /// Workflow was cancelled by user (v0.5.2)
    WorkflowAborted {
        /// Reason for abort (e.g., "User cancelled", "Timeout")
        reason: String,
        /// Duration before abort (ms)
        duration_ms: u64,
        /// Tasks that were still running when aborted
        running_tasks: Vec<Arc<str>>,
    },
    /// Workflow execution paused (v0.5.2+)
    WorkflowPaused,
    /// Workflow execution resumed (v0.5.2+)
    WorkflowResumed,

    // ═══════════════════════════════════════════
    // TASK LEVEL
    // ═══════════════════════════════════════════
    TaskScheduled {
        task_id: Arc<str>,
        dependencies: Vec<Arc<str>>,
    },
    /// Task execution begins with resolved inputs from use: block
    TaskStarted {
        task_id: Arc<str>,
        /// Verb type (infer, exec, fetch, invoke, agent)
        verb: Arc<str>,
        /// Resolved inputs from ResolvedBindings (what the task receives)
        inputs: Value,
    },
    TaskCompleted {
        task_id: Arc<str>,
        output: Arc<Value>,
        duration_ms: u64,
    },
    TaskFailed {
        task_id: Arc<str>,
        error: String,
        duration_ms: u64,
    },

    // ═══════════════════════════════════════════
    // FINE-GRAINED (template/provider)
    // ═══════════════════════════════════════════
    TemplateResolved {
        task_id: Arc<str>,
        template: String,
        result: String,
    },
    ProviderCalled {
        task_id: Arc<str>,
        provider: String,
        model: String,
        prompt_len: usize,
    },
    ProviderResponded {
        task_id: Arc<str>,
        /// API request ID (for debugging with provider)
        request_id: Option<String>,
        /// Input tokens
        input_tokens: u32,
        /// Output tokens
        output_tokens: u32,
        /// Cache read tokens (if any)
        cache_read_tokens: u32,
        /// Time to first token (ms), if known
        ttft_ms: Option<u64>,
        /// Finish reason
        finish_reason: String,
        /// Estimated cost in USD
        cost_usd: f64,
    },

    // ═══════════════════════════════════════════
    // CONTEXT ASSEMBLY (v0.2)
    // ═══════════════════════════════════════════
    /// Context assembly event for observability
    ContextAssembled {
        task_id: Arc<str>,
        /// Sources included in context
        sources: Vec<ContextSource>,
        /// Items excluded (with reasons)
        excluded: Vec<ExcludedItem>,
        /// Total tokens in assembled context
        total_tokens: u32,
        /// Budget utilization percentage
        budget_used_pct: f32,
        /// Was context truncated?
        truncated: bool,
    },

    // ═══════════════════════════════════════════
    // MCP EVENTS (v0.2, enhanced v0.5.2)
    // ═══════════════════════════════════════════
    /// MCP tool call or resource read initiated
    McpInvoke {
        task_id: Arc<str>,
        /// Unique call ID for correlating with McpResponse
        call_id: String,
        mcp_server: String,
        tool: Option<String>,
        resource: Option<String>,
        /// Full params passed to MCP tool (for TUI display)
        #[serde(skip_serializing_if = "Option::is_none")]
        params: Option<Value>,
    },
    /// MCP operation completed
    McpResponse {
        task_id: Arc<str>,
        /// Correlates with McpInvoke.call_id
        call_id: String,
        output_len: usize,
        /// Duration of MCP call in milliseconds
        duration_ms: u64,
        /// Whether response came from cache
        cached: bool,
        /// Whether MCP tool returned an error
        is_error: bool,
        /// Full response JSON (for TUI display)
        #[serde(skip_serializing_if = "Option::is_none")]
        response: Option<Value>,
    },
    /// MCP server connection established (v0.7.0)
    McpConnected {
        /// Name of the connected MCP server
        server_name: String,
    },
    /// MCP server connection failed (v0.7.0)
    McpError {
        /// Name of the MCP server
        server_name: String,
        /// Error description
        error: String,
    },
    /// MCP operation retry attempt (v0.11.0: now emitted)
    ///
    /// Emitted when MCP tool calls fail with connection errors and are retried.
    /// Use `McpClient::call_tool_with_retry_events()` for observable retry tracking.
    /// TUI handlers display this event with attempt count and error details.
    McpRetry {
        /// Task ID initiating the retry
        task_id: Arc<str>,
        /// Name of the MCP server
        server_name: String,
        /// Tool or resource being retried
        operation: String,
        /// Current attempt number (1-based)
        attempt: u32,
        /// Max attempts configured
        max_attempts: u32,
        /// Error that triggered the retry
        error: String,
    },

    // ═══════════════════════════════════════════
    // AGENT EVENTS (v0.4)
    // ═══════════════════════════════════════════
    /// Agent loop started
    AgentStart {
        task_id: Arc<str>,
        max_turns: u32,
        mcp_servers: Vec<String>,
    },
    /// Agent turn event with optional metadata (v0.4.1)
    ///
    /// When `metadata` is present, it contains:
    /// - Response text
    /// - Token usage (input/output/cache)
    /// - Stop reason
    /// - Thinking content (if using streaming API)
    AgentTurn {
        task_id: Arc<str>,
        turn_index: u32,
        /// Event kind: "started", "continue", "natural_completion", "stop_condition_met"
        kind: String,
        /// Turn metadata including response text, tokens, thinking (v0.4.1)
        #[serde(skip_serializing_if = "Option::is_none")]
        metadata: Option<AgentTurnMetadata>,
    },
    /// Agent loop completed (reached stop condition or max turns)
    AgentComplete {
        task_id: Arc<str>,
        turns: u32,
        stop_reason: String,
    },

    // ═══════════════════════════════════════════
    // NESTED AGENT EVENTS (v0.5 - MVP 8 Phase 2)
    // ═══════════════════════════════════════════
    /// A sub-agent was spawned by a parent agent
    AgentSpawned {
        /// ID of the parent task that spawned the child
        parent_task_id: Arc<str>,
        /// ID of the newly spawned child task
        child_task_id: Arc<str>,
        /// Current depth level (1 = root agent spawning first child)
        depth: u32,
    },

    // ═══════════════════════════════════════════
    // BUILTIN TOOL EVENTS (v0.9.3)
    // ═══════════════════════════════════════════
    /// Log event emitted by nika:log builtin tool
    Log {
        /// Log level: trace, debug, info, warn, error
        level: String,
        /// Log message
        message: String,
        /// Optional task context
        #[serde(skip_serializing_if = "Option::is_none")]
        task_id: Option<Arc<str>>,
    },

    /// Custom event emitted by nika:emit builtin tool
    Custom {
        /// Event name/type
        name: String,
        /// Event payload (arbitrary JSON)
        payload: Value,
        /// Optional task context
        #[serde(skip_serializing_if = "Option::is_none")]
        task_id: Option<Arc<str>>,
    },

    // ═══════════════════════════════════════════
    // ARTIFACT EVENTS (v0.18)
    // ═══════════════════════════════════════════
    /// Artifact successfully written to disk
    ArtifactWritten {
        /// Task that produced this artifact
        task_id: Arc<str>,
        /// Final resolved path
        path: String,
        /// Size in bytes
        size: u64,
        /// Output format (text, json)
        format: String,
    },
    /// Artifact write failed
    ArtifactFailed {
        /// Task that produced this artifact
        task_id: Arc<str>,
        /// Intended path
        path: String,
        /// Error reason
        reason: String,
    },
}

impl EventKind {
    /// Extract task_id if event is task-related
    #[allow(dead_code)] // Used in tests and future replay
    pub fn task_id(&self) -> Option<&str> {
        match self {
            Self::TaskScheduled { task_id, .. }
            | Self::TaskStarted { task_id, .. }
            | Self::TaskCompleted { task_id, .. }
            | Self::TaskFailed { task_id, .. }
            | Self::TemplateResolved { task_id, .. }
            | Self::ProviderCalled { task_id, .. }
            | Self::ProviderResponded { task_id, .. }
            | Self::ContextAssembled { task_id, .. }
            | Self::McpInvoke { task_id, .. }
            | Self::McpResponse { task_id, .. }
            | Self::McpRetry { task_id, .. }  // P2 Fix: Added McpRetry
            | Self::AgentStart { task_id, .. }
            | Self::AgentTurn { task_id, .. }
            | Self::AgentComplete { task_id, .. }
            | Self::ArtifactWritten { task_id, .. }
            | Self::ArtifactFailed { task_id, .. } => Some(task_id),
            // AgentSpawned uses parent_task_id as the primary task reference
            Self::AgentSpawned { parent_task_id, .. } => Some(parent_task_id),
            // Log and Custom may optionally have task_id
            Self::Log { task_id, .. } | Self::Custom { task_id, .. } => {
                task_id.as_ref().map(|s| s.as_ref())
            }
            Self::WorkflowStarted { .. }
            | Self::WorkflowCompleted { .. }
            | Self::WorkflowFailed { .. }
            | Self::WorkflowAborted { .. }
            | Self::WorkflowPaused
            | Self::WorkflowResumed
            | Self::McpConnected { .. }
            | Self::McpError { .. } => None,
        }
    }

    /// Check if this is a workflow-level event
    #[allow(dead_code)] // Used in tests and future replay
    pub fn is_workflow_event(&self) -> bool {
        matches!(
            self,
            Self::WorkflowStarted { .. }
                | Self::WorkflowCompleted { .. }
                | Self::WorkflowFailed { .. }
                | Self::WorkflowAborted { .. }
                | Self::WorkflowPaused
                | Self::WorkflowResumed
        )
    }
}

/// Thread-safe, append-only event log
///
/// Optionally supports real-time event broadcasting for TUI integration.
/// Use `new_with_broadcast()` to create an EventLog that sends events
/// to subscribers via tokio broadcast channel.
#[derive(Clone)]
pub struct EventLog {
    events: Arc<RwLock<Vec<Event>>>,
    start_time: Instant,
    next_id: Arc<AtomicU64>,
    /// Optional broadcast sender for TUI real-time updates
    broadcast_tx: Option<broadcast::Sender<Event>>,
}

impl EventLog {
    /// Create a new event log (call at workflow start)
    pub fn new() -> Self {
        Self {
            events: Arc::new(RwLock::new(Vec::new())),
            start_time: Instant::now(),
            next_id: Arc::new(AtomicU64::new(0)),
            broadcast_tx: None,
        }
    }

    /// Create a new event log with broadcast channel for TUI (v0.4.1)
    ///
    /// Returns (EventLog, Receiver) tuple. Pass the receiver to TUI App.
    /// P1 Fix: Increase channel capacity from 256 to 512 events (buffer for TUI lag + fast providers).
    pub fn new_with_broadcast() -> (Self, broadcast::Receiver<Event>) {
        let (tx, rx) = broadcast::channel(512);
        let event_log = Self {
            events: Arc::new(RwLock::new(Vec::new())),
            start_time: Instant::now(),
            next_id: Arc::new(AtomicU64::new(0)),
            broadcast_tx: Some(tx),
        };
        (event_log, rx)
    }

    /// Subscribe to event broadcasts (for additional TUI observers)
    ///
    /// Returns None if this EventLog was not created with `new_with_broadcast()`.
    #[allow(dead_code)]
    pub fn subscribe(&self) -> Option<broadcast::Receiver<Event>> {
        self.broadcast_tx.as_ref().map(|tx| tx.subscribe())
    }

    /// Emit an event (thread-safe, returns event ID)
    ///
    /// If broadcast channel is configured, also sends to subscribers.
    pub fn emit(&self, kind: EventKind) -> u64 {
        let id = self.next_id.fetch_add(1, Ordering::SeqCst);
        let event = Event {
            id,
            timestamp_ms: self.start_time.elapsed().as_millis() as u64,
            kind,
        };

        self.events.write().push(event.clone()); // parking_lot: no unwrap needed

        // Broadcast to TUI if configured (ignore errors - TUI might be closed)
        if let Some(ref tx) = self.broadcast_tx {
            let _ = tx.send(event);
        }

        id
    }

    /// Get all events (cloned - use `with_events` for zero-copy access)
    #[allow(dead_code)] // Used in tests and future export
    pub fn events(&self) -> Vec<Event> {
        self.events.read().clone()
    }

    /// Zero-copy access to events via callback
    ///
    /// Holds read lock for duration of callback - keep it short.
    /// Use this instead of `events()` when you don't need ownership.
    #[allow(dead_code)] // Used in optimized filter methods
    pub fn with_events<T>(&self, f: impl FnOnce(&[Event]) -> T) -> T {
        f(&self.events.read())
    }

    /// Filter events by task ID (zero-copy filtering)
    #[allow(dead_code)] // Used in tests and future debugging
    pub fn filter_task(&self, task_id: &str) -> Vec<Event> {
        self.with_events(|events| {
            events
                .iter()
                .filter(|e| e.kind.task_id() == Some(task_id))
                .cloned()
                .collect()
        })
    }

    /// Filter workflow-level events only (zero-copy filtering)
    #[allow(dead_code)] // Used in tests and future export
    pub fn workflow_events(&self) -> Vec<Event> {
        self.with_events(|events| {
            events
                .iter()
                .filter(|e| e.kind.is_workflow_event())
                .cloned()
                .collect()
        })
    }

    /// Count events for a specific task (no allocation)
    #[allow(dead_code)] // Used in tests and future metrics
    pub fn count_task(&self, task_id: &str) -> usize {
        self.with_events(|events| {
            events
                .iter()
                .filter(|e| e.kind.task_id() == Some(task_id))
                .count()
        })
    }

    /// Serialize to JSON for persistence/debugging
    #[allow(dead_code)] // Used in tests and future export
    pub fn to_json(&self) -> Value {
        self.with_events(|events| serde_json::to_value(events).unwrap_or(Value::Null))
    }

    /// Number of events
    #[allow(dead_code)] // Used in tests
    pub fn len(&self) -> usize {
        self.events.read().len()
    }

    /// Check if empty
    #[allow(dead_code)] // Used in tests
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl Default for EventLog {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for EventLog {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EventLog")
            .field("len", &self.len())
            .finish()
    }
}

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

    /// Use actual package version in tests to avoid version drift
    const TEST_VERSION: &str = env!("CARGO_PKG_VERSION");

    // ═══════════════════════════════════════════════════════════════
    // Test helpers
    // ═══════════════════════════════════════════════════════════════

    /// Create a WorkflowStarted event with test defaults
    fn workflow_started(task_count: usize) -> EventKind {
        EventKind::WorkflowStarted {
            task_count,
            generation_id: "test-gen-123".to_string(),
            workflow_hash: "abc123".to_string(),
            nika_version: TEST_VERSION.to_string(),
        }
    }

    /// Create a ProviderResponded event with test defaults
    fn provider_responded(task_id: &str, input_tokens: u32, output_tokens: u32) -> EventKind {
        EventKind::ProviderResponded {
            task_id: Arc::from(task_id),
            request_id: Some("req-456".to_string()),
            input_tokens,
            output_tokens,
            cache_read_tokens: 0,
            ttft_ms: Some(150),
            finish_reason: "stop".to_string(),
            cost_usd: 0.001,
        }
    }

    // ═══════════════════════════════════════════════════════════════
    // Event + EventKind tests
    // ═══════════════════════════════════════════════════════════════

    #[test]
    fn eventkind_task_id_extraction() {
        let started = EventKind::TaskStarted {
            verb: "infer".into(),
            task_id: "task1".into(),
            inputs: json!({}),
        };
        assert_eq!(started.task_id(), Some("task1"));

        let workflow = workflow_started(5);
        assert_eq!(workflow.task_id(), None);
    }

    #[test]
    fn eventkind_is_workflow_event() {
        assert!(workflow_started(3).is_workflow_event());
        assert!(EventKind::WorkflowCompleted {
            final_output: Arc::new(json!("done")),
            total_duration_ms: 1000,
        }
        .is_workflow_event());
        assert!(!EventKind::TaskStarted {
            verb: "infer".into(),
            task_id: "t1".into(),
            inputs: json!({}),
        }
        .is_workflow_event());
    }

    #[test]
    fn eventkind_serializes_with_type_tag() {
        let kind = EventKind::TaskCompleted {
            task_id: "greet".into(),
            output: Arc::new(json!({"message": "Hello"})),
            duration_ms: 150,
        };

        let json = serde_json::to_value(&kind).unwrap();
        assert_eq!(json["type"], "task_completed");
        assert_eq!(json["task_id"], "greet");
        assert_eq!(json["output"]["message"], "Hello");
    }

    #[test]
    fn eventkind_deserializes_from_tagged_json() {
        let json = json!({
            "type": "task_started",
            "task_id": "analyze",
            "verb": "infer",
            "inputs": {"weather": "sunny"}
        });

        let kind: EventKind = serde_json::from_value(json).unwrap();
        assert_eq!(
            kind,
            EventKind::TaskStarted {
                task_id: "analyze".into(),
                verb: "infer".into(),
                inputs: json!({"weather": "sunny"}),
            }
        );
    }

    // ═══════════════════════════════════════════════════════════════
    // EventLog tests
    // ═══════════════════════════════════════════════════════════════

    #[test]
    fn eventlog_new_starts_empty() {
        let log = EventLog::new();
        assert!(log.is_empty());
        assert_eq!(log.len(), 0);
    }

    #[test]
    fn eventlog_emit_returns_monotonic_ids() {
        let log = EventLog::new();

        let id1 = log.emit(workflow_started(3));
        let id2 = log.emit(EventKind::TaskStarted {
            verb: "infer".into(),
            task_id: "t1".into(),
            inputs: json!({}),
        });
        let id3 = log.emit(EventKind::TaskStarted {
            verb: "infer".into(),
            task_id: "t2".into(),
            inputs: json!({}),
        });

        assert_eq!(id1, 0);
        assert_eq!(id2, 1);
        assert_eq!(id3, 2);
        assert_eq!(log.len(), 3);
    }

    #[test]
    fn eventlog_events_returns_all() {
        let log = EventLog::new();
        log.emit(workflow_started(2));
        log.emit(EventKind::TaskStarted {
            verb: "infer".into(),
            task_id: "t1".into(),
            inputs: json!({}),
        });

        let events = log.events();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].id, 0);
        assert_eq!(events[1].id, 1);
    }

    #[test]
    fn eventlog_filter_task_returns_only_matching() {
        let log = EventLog::new();
        log.emit(workflow_started(2));
        log.emit(EventKind::TaskStarted {
            verb: "infer".into(),
            task_id: "alpha".into(),
            inputs: json!({}),
        });
        log.emit(EventKind::TaskStarted {
            verb: "infer".into(),
            task_id: "beta".into(),
            inputs: json!({}),
        });
        log.emit(EventKind::TaskCompleted {
            task_id: "alpha".into(),
            output: Arc::new(json!("result")),
            duration_ms: 100,
        });

        let alpha_events = log.filter_task("alpha");
        assert_eq!(alpha_events.len(), 2); // Started + Completed
        assert!(alpha_events
            .iter()
            .all(|e| e.kind.task_id() == Some("alpha")));

        let beta_events = log.filter_task("beta");
        assert_eq!(beta_events.len(), 1);
    }

    #[test]
    fn eventlog_workflow_events_returns_only_workflow() {
        let log = EventLog::new();
        log.emit(workflow_started(1));
        log.emit(EventKind::TaskStarted {
            verb: "infer".into(),
            task_id: "t1".into(),
            inputs: json!({}),
        });
        log.emit(EventKind::WorkflowCompleted {
            final_output: Arc::new(json!("done")),
            total_duration_ms: 500,
        });

        let wf_events = log.workflow_events();
        assert_eq!(wf_events.len(), 2);
        assert!(wf_events.iter().all(|e| e.kind.is_workflow_event()));
    }

    #[test]
    fn eventlog_to_json() {
        let log = EventLog::new();
        log.emit(EventKind::TaskStarted {
            verb: "infer".into(),
            task_id: "task1".into(),
            inputs: json!({}),
        });

        let json = log.to_json();
        assert!(json.is_array());
        assert_eq!(json.as_array().unwrap().len(), 1);
        assert_eq!(json[0]["kind"]["type"], "task_started");
    }

    #[test]
    fn eventlog_is_clone() {
        let log = EventLog::new();
        log.emit(workflow_started(1));

        let cloned = log.clone();
        assert_eq!(cloned.len(), 1);

        // Cloned shares the same underlying data (Arc)
        log.emit(EventKind::TaskStarted {
            verb: "infer".into(),
            task_id: "t1".into(),
            inputs: json!({}),
        });
        assert_eq!(cloned.len(), 2);
    }

    #[test]
    fn eventlog_thread_safe_concurrent_emits() {
        use std::thread;

        let log = EventLog::new();

        let handles: Vec<_> = (0..10)
            .map(|i| {
                let log = log.clone();
                thread::spawn(move || {
                    log.emit(EventKind::TaskStarted {
                        verb: "infer".into(),
                        task_id: Arc::from(format!("task{}", i)),
                        inputs: json!({}),
                    })
                })
            })
            .collect();

        for h in handles {
            h.join().unwrap();
        }

        assert_eq!(log.len(), 10);

        // All IDs should be unique
        let events = log.events();
        let mut ids: Vec<u64> = events.iter().map(|e| e.id).collect();
        ids.sort();
        ids.dedup();
        assert_eq!(ids.len(), 10);
    }

    #[test]
    fn event_timestamp_is_relative() {
        let log = EventLog::new();

        // First event should have small timestamp
        log.emit(workflow_started(1));

        std::thread::sleep(std::time::Duration::from_millis(10));

        log.emit(EventKind::TaskStarted {
            verb: "infer".into(),
            task_id: "t1".into(),
            inputs: json!({}),
        });

        let events = log.events();
        assert!(events[1].timestamp_ms >= events[0].timestamp_ms);
    }

    // ═══════════════════════════════════════════════════════════════
    // TaskStarted captures resolved inputs
    // ═══════════════════════════════════════════════════════════════

    #[test]
    fn task_started_captures_full_context() {
        let log = EventLog::new();

        let inputs = json!({
            "weather": "sunny",
            "temperature": 25,
            "nested": {"key": "value"}
        });

        log.emit(EventKind::TaskStarted {
            verb: "infer".into(),
            task_id: "analyze".into(),
            inputs: inputs.clone(),
        });

        let events = log.filter_task("analyze");
        assert_eq!(events.len(), 1);

        if let EventKind::TaskStarted {
            inputs: captured, ..
        } = &events[0].kind
        {
            assert_eq!(captured, &inputs);
            assert_eq!(captured["weather"], "sunny");
            assert_eq!(captured["nested"]["key"], "value");
        } else {
            panic!("Expected TaskStarted event");
        }
    }

    // ═══════════════════════════════════════════════════════════════
    // Enhanced event tests (v0.2 - generation_id, token tracking)
    // ═══════════════════════════════════════════════════════════════

    #[test]
    fn workflow_started_includes_generation_id() {
        let log = EventLog::new();
        log.emit(EventKind::WorkflowStarted {
            task_count: 3,
            generation_id: "gen-abc-123".to_string(),
            workflow_hash: "sha256:deadbeef".to_string(),
            nika_version: TEST_VERSION.to_string(),
        });

        let events = log.events();
        if let EventKind::WorkflowStarted {
            generation_id,
            workflow_hash,
            nika_version,
            ..
        } = &events[0].kind
        {
            assert_eq!(generation_id, "gen-abc-123");
            assert_eq!(workflow_hash, "sha256:deadbeef");
            assert_eq!(nika_version, TEST_VERSION);
        } else {
            panic!("Expected WorkflowStarted event");
        }
    }

    #[test]
    fn provider_responded_tracks_detailed_tokens() {
        let log = EventLog::new();
        log.emit(EventKind::ProviderResponded {
            task_id: "infer_task".into(),
            request_id: Some("req-xyz-789".to_string()),
            input_tokens: 500,
            output_tokens: 150,
            cache_read_tokens: 200,
            ttft_ms: Some(85),
            finish_reason: "stop".to_string(),
            cost_usd: 0.0025,
        });

        let events = log.filter_task("infer_task");
        assert_eq!(events.len(), 1);

        if let EventKind::ProviderResponded {
            request_id,
            input_tokens,
            output_tokens,
            cache_read_tokens,
            ttft_ms,
            finish_reason,
            cost_usd,
            ..
        } = &events[0].kind
        {
            assert_eq!(request_id, &Some("req-xyz-789".to_string()));
            assert_eq!(*input_tokens, 500);
            assert_eq!(*output_tokens, 150);
            assert_eq!(*cache_read_tokens, 200);
            assert_eq!(*ttft_ms, Some(85));
            assert_eq!(finish_reason, "stop");
            assert!((*cost_usd - 0.0025).abs() < f64::EPSILON);
        } else {
            panic!("Expected ProviderResponded event");
        }
    }

    #[test]
    fn context_assembled_tracks_sources() {
        let log = EventLog::new();

        let sources = vec![
            ContextSource {
                node: "system_prompt".to_string(),
                tokens: 200,
            },
            ContextSource {
                node: "user_input".to_string(),
                tokens: 50,
            },
            ContextSource {
                node: "examples".to_string(),
                tokens: 300,
            },
        ];

        let excluded = vec![ExcludedItem {
            node: "large_history".to_string(),
            reason: "exceeded budget".to_string(),
        }];

        log.emit(EventKind::ContextAssembled {
            task_id: "assemble_task".into(),
            sources: sources.clone(),
            excluded: excluded.clone(),
            total_tokens: 550,
            budget_used_pct: 55.0,
            truncated: false,
        });

        let events = log.filter_task("assemble_task");
        assert_eq!(events.len(), 1);

        if let EventKind::ContextAssembled {
            sources: s,
            excluded: e,
            total_tokens,
            budget_used_pct,
            truncated,
            ..
        } = &events[0].kind
        {
            assert_eq!(s.len(), 3);
            assert_eq!(s[0].node, "system_prompt");
            assert_eq!(s[0].tokens, 200);
            assert_eq!(e.len(), 1);
            assert_eq!(e[0].reason, "exceeded budget");
            assert_eq!(*total_tokens, 550);
            assert!((*budget_used_pct - 55.0).abs() < f32::EPSILON);
            assert!(!*truncated);
        } else {
            panic!("Expected ContextAssembled event");
        }
    }

    #[test]
    fn context_source_and_excluded_item_serialize() {
        let source = ContextSource {
            node: "test_node".to_string(),
            tokens: 100,
        };
        let json = serde_json::to_value(&source).unwrap();
        assert_eq!(json["node"], "test_node");
        assert_eq!(json["tokens"], 100);

        let excluded = ExcludedItem {
            node: "big_file".to_string(),
            reason: "too large".to_string(),
        };
        let json = serde_json::to_value(&excluded).unwrap();
        assert_eq!(json["node"], "big_file");
        assert_eq!(json["reason"], "too large");
    }

    #[test]
    fn provider_responded_helper_creates_valid_event() {
        let event = provider_responded("test_task", 100, 50);
        assert_eq!(event.task_id(), Some("test_task"));

        if let EventKind::ProviderResponded {
            input_tokens,
            output_tokens,
            ..
        } = event
        {
            assert_eq!(input_tokens, 100);
            assert_eq!(output_tokens, 50);
        } else {
            panic!("Expected ProviderResponded event");
        }
    }

    // ═══════════════════════════════════════════════════════════════
    // AgentTurnMetadata tests (v0.4.1)
    // ═══════════════════════════════════════════════════════════════

    #[test]
    fn agent_turn_metadata_text_only() {
        let metadata = AgentTurnMetadata::text_only("Hello world", "end_turn");

        assert_eq!(metadata.response_text, "Hello world");
        assert_eq!(metadata.stop_reason, "end_turn");
        assert_eq!(metadata.input_tokens, 0);
        assert_eq!(metadata.output_tokens, 0);
        assert_eq!(metadata.cache_read_tokens, 0);
        assert!(!metadata.has_thinking());
        assert_eq!(metadata.total_tokens(), 0);
    }

    #[test]
    fn agent_turn_metadata_with_usage() {
        let metadata = AgentTurnMetadata::with_usage("Response", 100, 50, "tool_use");

        assert_eq!(metadata.response_text, "Response");
        assert_eq!(metadata.stop_reason, "tool_use");
        assert_eq!(metadata.input_tokens, 100);
        assert_eq!(metadata.output_tokens, 50);
        assert_eq!(metadata.total_tokens(), 150);
        assert!(!metadata.has_thinking());
    }

    #[test]
    fn agent_turn_metadata_with_thinking() {
        let metadata = AgentTurnMetadata {
            thinking: Some("Let me think about this...".to_string()),
            response_text: "Here's my answer".to_string(),
            input_tokens: 200,
            output_tokens: 100,
            cache_read_tokens: 50,
            stop_reason: "end_turn".to_string(),
        };

        assert!(metadata.has_thinking());
        assert_eq!(
            metadata.thinking.as_ref().unwrap(),
            "Let me think about this..."
        );
        assert_eq!(metadata.total_tokens(), 300);
    }

    #[test]
    fn agent_turn_metadata_serializes() {
        let metadata = AgentTurnMetadata::with_usage("Test response", 100, 50, "end_turn");
        let json = serde_json::to_value(&metadata).unwrap();

        assert_eq!(json["response_text"], "Test response");
        assert_eq!(json["input_tokens"], 100);
        assert_eq!(json["output_tokens"], 50);
        assert_eq!(json["stop_reason"], "end_turn");
        // thinking should be skipped when None
        assert!(json.get("thinking").is_none());
    }

    #[test]
    fn agent_turn_metadata_with_thinking_serializes() {
        let metadata = AgentTurnMetadata {
            thinking: Some("My thoughts".to_string()),
            response_text: "My response".to_string(),
            input_tokens: 50,
            output_tokens: 25,
            cache_read_tokens: 0,
            stop_reason: "end_turn".to_string(),
        };
        let json = serde_json::to_value(&metadata).unwrap();

        assert_eq!(json["thinking"], "My thoughts");
        assert_eq!(json["response_text"], "My response");
    }

    #[test]
    fn agent_turn_with_metadata_serializes() {
        let log = EventLog::new();

        let metadata = AgentTurnMetadata::with_usage("Agent response", 100, 50, "end_turn");

        log.emit(EventKind::AgentTurn {
            task_id: "agent_task".into(),
            turn_index: 1,
            kind: "end_turn".to_string(), // Canonical snake_case (v0.4.1)
            metadata: Some(metadata),
        });

        let events = log.filter_task("agent_task");
        assert_eq!(events.len(), 1);

        if let EventKind::AgentTurn {
            metadata: Some(m), ..
        } = &events[0].kind
        {
            assert_eq!(m.response_text, "Agent response");
            assert_eq!(m.total_tokens(), 150);
        } else {
            panic!("Expected AgentTurn with metadata");
        }
    }

    #[test]
    fn agent_turn_without_metadata_serializes() {
        let log = EventLog::new();

        log.emit(EventKind::AgentTurn {
            task_id: "agent_task".into(),
            turn_index: 1,
            kind: "started".to_string(),
            metadata: None,
        });

        let events = log.filter_task("agent_task");
        assert_eq!(events.len(), 1);

        if let EventKind::AgentTurn { metadata, kind, .. } = &events[0].kind {
            assert!(metadata.is_none());
            assert_eq!(kind, "started");
        } else {
            panic!("Expected AgentTurn without metadata");
        }
    }
}