zig-core 0.6.1

Core library for zig — workflow orchestration engine for AI coding agents
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
//! Zig session log: a recorded execution of `zig run`.
//!
//! A *zig session* is the parent layer above the zag session log: one zig
//! session orchestrates many child zag sessions (one per workflow step).
//! This module owns the writer, event schema, and on-disk index.
//!
//! Mirrors zag's session logging architecture so the two stay structurally
//! aligned and conceptually transferable. Key analogs:
//!
//! - `SessionWriter`        ↔ `zag-agent/src/session_log.rs:344` `SessionLogWriter`
//! - `SessionCoordinator`   ↔ `zag-agent/src/session_log.rs:565` `SessionLogCoordinator`
//! - `SessionLogEvent`      ↔ `zag-agent/src/session_log.rs:182` `AgentLogEvent`
//! - `SessionLogIndex`      ↔ `zag-agent/src/session_log.rs:197` `SessionLogIndex`
//! - `GlobalSessionIndex`   ↔ `zag-agent/src/session_log.rs:225` `GlobalSessionIndex`
//!
//! On-disk layout (mirrors `~/.zag/...` byte-for-byte):
//!
//! ```text
//! ~/.zig/
//!   projects/<sanitized-project-path>/logs/
//!     index.json
//!     sessions/<zig_session_id>.jsonl
//!   sessions_index.json
//! ```

use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

use chrono::Utc;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::error::ZigError;
use crate::paths;

/// Heartbeat interval — mirrors zag's 10s default
/// (`zag-agent/src/session_log.rs:872`).
const HEARTBEAT_INTERVAL_SECS: u64 = 10;

/// Stream identifier for `step_output` events.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum OutputStream {
    Stdout,
    Stderr,
}

/// Final status of a zig session.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum SessionStatus {
    Success,
    Failure,
}

/// Event payload variants. The envelope (`SessionLogEvent`) carries `seq`,
/// `ts`, and `zig_session_id`; this enum carries the type-specific fields.
///
/// Mirrors zag's `LogEventKind` (`zag-agent/src/session_log.rs:99`) in
/// shape: `#[serde(tag = "type", rename_all = "snake_case")]`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum SessionEventKind {
    ZigSessionStarted {
        workflow_name: String,
        workflow_path: String,
        workspace_path: Option<String>,
        cwd: Option<String>,
        prompt: Option<String>,
        tier_count: usize,
    },
    TierStarted {
        tier_index: usize,
        step_names: Vec<String>,
    },
    StepStarted {
        step_name: String,
        tier_index: usize,
        zag_session_id: String,
        zag_command: String,
        model: Option<String>,
        prompt_preview: String,
    },
    StepOutput {
        step_name: String,
        stream: OutputStream,
        line: String,
    },
    StepCompleted {
        step_name: String,
        exit_code: i32,
        duration_ms: u64,
        saved_vars: Vec<String>,
    },
    StepFailed {
        step_name: String,
        exit_code: Option<i32>,
        attempt: u32,
        error: String,
    },
    StepSkipped {
        step_name: String,
        reason: String,
    },
    /// Periodic liveness indicator. Mirrors zag's `Heartbeat`
    /// (`zag-agent/src/session_log.rs:161`).
    Heartbeat {
        interval_secs: u64,
    },
    ZigSessionEnded {
        status: SessionStatus,
        duration_ms: u64,
    },
}

/// Event envelope written to the JSONL log. Field naming mirrors zag's
/// `AgentLogEvent` (`zag-agent/src/session_log.rs:182`): `seq`, `ts`, plus
/// a session id and a flattened kind discriminator.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionLogEvent {
    pub seq: u64,
    pub ts: String,
    pub zig_session_id: String,
    #[serde(flatten)]
    pub kind: SessionEventKind,
}

/// Per-project session index entry (`<project>/logs/index.json`).
///
/// Mirrors zag's `SessionLogIndexEntry` (`zag-agent/src/session_log.rs:201`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionLogIndexEntry {
    pub zig_session_id: String,
    pub workflow_name: String,
    pub workflow_path: String,
    pub log_path: String,
    pub started_at: String,
    #[serde(default)]
    pub ended_at: Option<String>,
    #[serde(default)]
    pub status: Option<SessionStatus>,
    #[serde(default)]
    pub workspace_path: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SessionLogIndex {
    pub sessions: Vec<SessionLogIndexEntry>,
}

/// Global cross-project index entry (`~/.zig/sessions_index.json`).
///
/// Mirrors zag's `GlobalSessionEntry` (`zag-agent/src/session_log.rs:229`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GlobalSessionEntry {
    pub zig_session_id: String,
    pub workflow_name: String,
    pub project: String,
    pub log_path: String,
    pub started_at: String,
    #[serde(default)]
    pub ended_at: Option<String>,
    #[serde(default)]
    pub status: Option<SessionStatus>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct GlobalSessionIndex {
    pub sessions: Vec<GlobalSessionEntry>,
}

// ---------------------------------------------------------------------
// Index I/O
// ---------------------------------------------------------------------

pub fn load_project_index(path: &Path) -> SessionLogIndex {
    if !path.exists() {
        return SessionLogIndex::default();
    }
    std::fs::read_to_string(path)
        .ok()
        .and_then(|s| serde_json::from_str(&s).ok())
        .unwrap_or_default()
}

pub fn save_project_index(path: &Path, index: &SessionLogIndex) -> Result<(), ZigError> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| ZigError::Io(format!("failed to create {}: {e}", parent.display())))?;
    }
    let json = serde_json::to_string_pretty(index)
        .map_err(|e| ZigError::Io(format!("failed to serialize project index: {e}")))?;
    std::fs::write(path, json)
        .map_err(|e| ZigError::Io(format!("failed to write {}: {e}", path.display())))?;
    Ok(())
}

pub fn load_global_index(path: &Path) -> GlobalSessionIndex {
    if !path.exists() {
        return GlobalSessionIndex::default();
    }
    std::fs::read_to_string(path)
        .ok()
        .and_then(|s| serde_json::from_str(&s).ok())
        .unwrap_or_default()
}

pub fn save_global_index(path: &Path, index: &GlobalSessionIndex) -> Result<(), ZigError> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| ZigError::Io(format!("failed to create {}: {e}", parent.display())))?;
    }
    let json = serde_json::to_string_pretty(index)
        .map_err(|e| ZigError::Io(format!("failed to serialize global index: {e}")))?;
    std::fs::write(path, json)
        .map_err(|e| ZigError::Io(format!("failed to write {}: {e}", path.display())))?;
    Ok(())
}

// ---------------------------------------------------------------------
// Query helpers
// ---------------------------------------------------------------------

/// List all sessions from the project index.
pub fn list_sessions() -> Result<Vec<SessionLogIndexEntry>, ZigError> {
    let index_path = paths::project_index_path(None)
        .ok_or_else(|| ZigError::Io("HOME environment variable not set".into()))?;
    let index = load_project_index(&index_path);
    Ok(index.sessions)
}

/// Read all events from a session JSONL log file.
pub fn read_session_events(log_path: &Path) -> Result<Vec<SessionLogEvent>, ZigError> {
    let content = std::fs::read_to_string(log_path)
        .map_err(|e| ZigError::Io(format!("failed to read {}: {e}", log_path.display())))?;

    let mut events = Vec::new();
    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let event: SessionLogEvent = serde_json::from_str(line)
            .map_err(|e| ZigError::Parse(format!("failed to parse session event: {e}")))?;
        events.push(event);
    }
    Ok(events)
}

/// Find a session by ID (or unique prefix) and return its index entry.
pub fn find_session(session_id: &str) -> Result<SessionLogIndexEntry, ZigError> {
    let sessions = list_sessions()?;
    let matches: Vec<_> = sessions
        .into_iter()
        .filter(|s| s.zig_session_id.starts_with(session_id))
        .collect();

    match matches.len() {
        0 => Err(ZigError::Io(format!("session not found: {session_id}"))),
        1 => Ok(matches.into_iter().next().unwrap()),
        _ => Err(ZigError::Io(format!(
            "ambiguous session prefix '{session_id}' matches {} sessions",
            matches.len()
        ))),
    }
}

// ---------------------------------------------------------------------
// Writer
// ---------------------------------------------------------------------

/// Append-only writer for a single zig session log file.
///
/// Mirrors zag's `SessionLogWriter` (`zag-agent/src/session_log.rs:344`).
/// Every emit increments `seq`, stamps `ts`, serializes one JSON line, and
/// flushes — so a tailer reading the file sees the event within one poll
/// cycle.
pub struct SessionWriter {
    zig_session_id: String,
    log_path: PathBuf,
    project_index_path: Option<PathBuf>,
    global_index_path: Option<PathBuf>,
    inner: Mutex<WriterInner>,
}

struct WriterInner {
    file: File,
    seq: u64,
}

impl SessionWriter {
    /// Create a new session: generate a UUID, ensure the project sessions
    /// dir, open the log file for append, emit `ZigSessionStarted`, and
    /// upsert both indexes.
    pub fn create(
        workflow_name: &str,
        workflow_path: &str,
        prompt: Option<&str>,
        tier_count: usize,
    ) -> Result<Self, ZigError> {
        let zig_session_id = Uuid::new_v4().to_string();

        let sessions_dir = paths::ensure_project_sessions_dir(None)?;
        let log_path = sessions_dir.join(format!("{zig_session_id}.jsonl"));

        let file = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&log_path)
            .map_err(|e| ZigError::Io(format!("failed to open {}: {e}", log_path.display())))?;

        let writer = Self {
            zig_session_id: zig_session_id.clone(),
            log_path: log_path.clone(),
            project_index_path: paths::project_index_path(None),
            global_index_path: paths::global_sessions_index_path(),
            inner: Mutex::new(WriterInner { file, seq: 0 }),
        };

        let cwd = std::env::current_dir()
            .ok()
            .map(|p| p.to_string_lossy().into_owned());
        let workspace_path = paths::project_dir(None).map(|p| p.to_string_lossy().into_owned());
        let started_at = now_rfc3339();

        writer.emit(SessionEventKind::ZigSessionStarted {
            workflow_name: workflow_name.to_string(),
            workflow_path: workflow_path.to_string(),
            workspace_path: workspace_path.clone(),
            cwd,
            prompt: prompt.map(str::to_string),
            tier_count,
        })?;

        writer.upsert_indexes(
            workflow_name,
            workflow_path,
            &workspace_path,
            &started_at,
            None,
        )?;

        Ok(writer)
    }

    /// The session id (UUID) for this writer.
    pub fn session_id(&self) -> &str {
        &self.zig_session_id
    }

    /// The on-disk log path.
    pub fn log_path(&self) -> &Path {
        &self.log_path
    }

    pub fn tier_started(&self, tier_index: usize, step_names: Vec<String>) -> Result<(), ZigError> {
        self.emit(SessionEventKind::TierStarted {
            tier_index,
            step_names,
        })
    }

    #[allow(clippy::too_many_arguments)]
    pub fn step_started(
        &self,
        step_name: &str,
        tier_index: usize,
        zag_session_id: &str,
        zag_command: &str,
        model: Option<&str>,
        prompt_preview: &str,
    ) -> Result<(), ZigError> {
        self.emit(SessionEventKind::StepStarted {
            step_name: step_name.to_string(),
            tier_index,
            zag_session_id: zag_session_id.to_string(),
            zag_command: zag_command.to_string(),
            model: model.map(str::to_string),
            prompt_preview: prompt_preview.to_string(),
        })
    }

    pub fn step_output(
        &self,
        step_name: &str,
        stream: OutputStream,
        line: &str,
    ) -> Result<(), ZigError> {
        self.emit(SessionEventKind::StepOutput {
            step_name: step_name.to_string(),
            stream,
            line: line.to_string(),
        })
    }

    pub fn step_completed(
        &self,
        step_name: &str,
        exit_code: i32,
        duration_ms: u64,
        saved_vars: Vec<String>,
    ) -> Result<(), ZigError> {
        self.emit(SessionEventKind::StepCompleted {
            step_name: step_name.to_string(),
            exit_code,
            duration_ms,
            saved_vars,
        })
    }

    pub fn step_failed(
        &self,
        step_name: &str,
        exit_code: Option<i32>,
        attempt: u32,
        error: &str,
    ) -> Result<(), ZigError> {
        self.emit(SessionEventKind::StepFailed {
            step_name: step_name.to_string(),
            exit_code,
            attempt,
            error: error.to_string(),
        })
    }

    pub fn step_skipped(&self, step_name: &str, reason: &str) -> Result<(), ZigError> {
        self.emit(SessionEventKind::StepSkipped {
            step_name: step_name.to_string(),
            reason: reason.to_string(),
        })
    }

    pub fn heartbeat(&self) -> Result<(), ZigError> {
        self.emit(SessionEventKind::Heartbeat {
            interval_secs: HEARTBEAT_INTERVAL_SECS,
        })
    }

    /// Emit `ZigSessionEnded` and stamp the indexes with `ended_at`/`status`.
    pub fn ended(&self, status: SessionStatus, duration_ms: u64) -> Result<(), ZigError> {
        self.emit(SessionEventKind::ZigSessionEnded {
            status,
            duration_ms,
        })?;
        self.stamp_ended(status)?;
        Ok(())
    }

    fn emit(&self, kind: SessionEventKind) -> Result<(), ZigError> {
        let mut inner = self
            .inner
            .lock()
            .map_err(|_| ZigError::Io("session writer mutex poisoned".into()))?;
        inner.seq += 1;
        let event = SessionLogEvent {
            seq: inner.seq,
            ts: now_rfc3339(),
            zig_session_id: self.zig_session_id.clone(),
            kind,
        };
        let line = serde_json::to_string(&event)
            .map_err(|e| ZigError::Io(format!("failed to serialize session event: {e}")))?;
        writeln!(inner.file, "{line}")
            .map_err(|e| ZigError::Io(format!("failed to write session event: {e}")))?;
        inner
            .file
            .flush()
            .map_err(|e| ZigError::Io(format!("failed to flush session log: {e}")))?;
        Ok(())
    }

    fn upsert_indexes(
        &self,
        workflow_name: &str,
        workflow_path: &str,
        workspace_path: &Option<String>,
        started_at: &str,
        ended_at: Option<String>,
    ) -> Result<(), ZigError> {
        let log_path_str = self.log_path.to_string_lossy().into_owned();

        if let Some(idx_path) = &self.project_index_path {
            let mut index = load_project_index(idx_path);
            index
                .sessions
                .retain(|e| e.zig_session_id != self.zig_session_id);
            index.sessions.push(SessionLogIndexEntry {
                zig_session_id: self.zig_session_id.clone(),
                workflow_name: workflow_name.to_string(),
                workflow_path: workflow_path.to_string(),
                log_path: log_path_str.clone(),
                started_at: started_at.to_string(),
                ended_at,
                status: None,
                workspace_path: workspace_path.clone(),
            });
            save_project_index(idx_path, &index)?;
        }

        if let Some(idx_path) = &self.global_index_path {
            let mut index = load_global_index(idx_path);
            index
                .sessions
                .retain(|e| e.zig_session_id != self.zig_session_id);
            index.sessions.push(GlobalSessionEntry {
                zig_session_id: self.zig_session_id.clone(),
                workflow_name: workflow_name.to_string(),
                project: workspace_path.clone().unwrap_or_default(),
                log_path: log_path_str,
                started_at: started_at.to_string(),
                ended_at: None,
                status: None,
            });
            save_global_index(idx_path, &index)?;
        }

        Ok(())
    }

    fn stamp_ended(&self, status: SessionStatus) -> Result<(), ZigError> {
        let ended_at = now_rfc3339();

        if let Some(idx_path) = &self.project_index_path {
            let mut index = load_project_index(idx_path);
            for entry in &mut index.sessions {
                if entry.zig_session_id == self.zig_session_id {
                    entry.ended_at = Some(ended_at.clone());
                    entry.status = Some(status);
                }
            }
            save_project_index(idx_path, &index)?;
        }

        if let Some(idx_path) = &self.global_index_path {
            let mut index = load_global_index(idx_path);
            for entry in &mut index.sessions {
                if entry.zig_session_id == self.zig_session_id {
                    entry.ended_at = Some(ended_at.clone());
                    entry.status = Some(status);
                }
            }
            save_global_index(idx_path, &index)?;
        }

        Ok(())
    }
}

// ---------------------------------------------------------------------
// Coordinator
// ---------------------------------------------------------------------

/// Wraps a `SessionWriter` in an `Arc` and runs a background thread that
/// emits a `Heartbeat` event every 10 seconds. The handle's `Drop` impl
/// stops the heartbeat thread and stamps `ended_at` defensively if
/// `finish()` was never called (crash/panic safety).
///
/// Mirrors zag's `SessionLogCoordinator`
/// (`zag-agent/src/session_log.rs:565`).
pub struct SessionCoordinator {
    writer: Arc<SessionWriter>,
    started: Instant,
    stop_flag: Arc<AtomicBool>,
    heartbeat: Option<JoinHandle<()>>,
    finished: bool,
}

impl SessionCoordinator {
    pub fn start(writer: SessionWriter) -> Self {
        let writer = Arc::new(writer);
        let stop_flag = Arc::new(AtomicBool::new(false));

        let hb_writer = Arc::clone(&writer);
        let hb_stop = Arc::clone(&stop_flag);
        let heartbeat = thread::spawn(move || {
            let interval = Duration::from_secs(HEARTBEAT_INTERVAL_SECS);
            // Sleep in short ticks so shutdown is responsive.
            let tick = Duration::from_millis(200);
            let mut elapsed = Duration::ZERO;
            while !hb_stop.load(Ordering::Relaxed) {
                thread::sleep(tick);
                elapsed += tick;
                if elapsed >= interval {
                    elapsed = Duration::ZERO;
                    let _ = hb_writer.heartbeat();
                }
            }
        });

        Self {
            writer,
            started: Instant::now(),
            stop_flag,
            heartbeat: Some(heartbeat),
            finished: false,
        }
    }

    pub fn writer(&self) -> Arc<SessionWriter> {
        Arc::clone(&self.writer)
    }

    /// Mark the session ended cleanly. Stops the heartbeat thread and
    /// emits `ZigSessionEnded`.
    pub fn finish(mut self, status: SessionStatus) -> Result<(), ZigError> {
        self.stop_flag.store(true, Ordering::Relaxed);
        if let Some(h) = self.heartbeat.take() {
            let _ = h.join();
        }
        let duration_ms = self.started.elapsed().as_millis() as u64;
        self.writer.ended(status, duration_ms)?;
        self.finished = true;
        Ok(())
    }
}

impl Drop for SessionCoordinator {
    fn drop(&mut self) {
        if self.finished {
            return;
        }
        // Crash/panic path: stop heartbeat and best-effort stamp the
        // indexes so `--latest`/`--active` resolution stays consistent.
        self.stop_flag.store(true, Ordering::Relaxed);
        if let Some(h) = self.heartbeat.take() {
            let _ = h.join();
        }
        let duration_ms = self.started.elapsed().as_millis() as u64;
        let _ = self.writer.ended(SessionStatus::Failure, duration_ms);
    }
}

fn now_rfc3339() -> String {
    Utc::now().to_rfc3339()
}

#[cfg(test)]
#[path = "session_tests.rs"]
mod tests;