gent-link 0.2.16

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
//! Replay the checkpoint in a completed Gent delivery. Replacement history
//! supplies model context. The original rollout still contains the admissions,
//! tool receipts and goal decisions on both sides of the checkpoint.
use super::*;

fn previous(rows: &mut ReverseLines<'_>, line: &mut Vec<u8>) -> Result<Option<Record<Event>>> {
    Ok(if rows.previous(line)? {
        Some(serde_json::from_slice(line)?)
    } else {
        None
    })
}

#[derive(Deserialize)]
struct Checkpoint {
    resume_metadata: Resume,
}
#[derive(Deserialize)]
struct Resume {
    last_started_turn_id: String,
    turn_attribution: Scope,
}
#[derive(Deserialize)]
struct Scope {
    turn_id: String,
    root_turn_id: String,
    parent_turn_id: Option<String>,
    initiating_agent_path: Option<serde::de::IgnoredAny>,
    turn_trigger: Option<String>,
}
#[derive(Deserialize)]
struct Snapshot {
    full: bool,
}

pub(super) fn confirm(
    rows: &mut ReverseLines<'_>,
    line: &mut Vec<u8>,
    receipt: &Event,
    thread: &str,
    turn: &Completed,
    admission: &mut Admission,
) -> Result<bool> {
    let (Some(start), Some(end)) = (receipt.started_at_ms, receipt.completed_at_ms) else {
        return Ok(false);
    };
    if receipt.thread_id.as_deref() != Some(thread)
        || receipt.turn_id.as_ref() != Some(&turn.id)
        || !receipt.item.as_ref().is_some_and(|i| {
            i.id.as_deref().is_some_and(|id| !id.is_empty())
                && i.questions.is_none()
                && i.kind.is_none()
                && i.status.is_none()
                && i.internal_chat_message_metadata_passthrough.is_none()
        })
        || start > end
        || start.div_euclid(1000) < turn.started
        || end.div_euclid(1000) > turn.ended
    {
        return Ok(false);
    }
    loop {
        let Some(row) = previous(rows, line)? else {
            return Ok(false);
        };
        let p = row.payload;
        if !p.belongs_to(thread, &turn.id) || p.internal_chat_message_metadata_passthrough.is_some()
        {
            return Ok(false);
        }
        match (row.r#type.as_str(), p.r#type.as_str()) {
            ("event_msg", "token_count") => {}
            ("event_msg", "thread_settings_applied") if p.thread_id.as_deref() == Some(thread) => {}
            ("turn_context", "")
                if p.turn_id.as_ref() == Some(&turn.id)
                    && p.root_turn_id.as_ref() == Some(&turn.id) =>
            {
                break;
            }
            _ => return Ok(false),
        }
    }
    if !previous(rows, line)?.is_some_and(|r| {
        r.r#type == "world_state"
            && r.payload.belongs_to(thread, &turn.id)
            && r.payload
                .internal_chat_message_metadata_passthrough
                .is_none()
    }) || !serde_json::from_slice::<Record<Snapshot>>(line).is_ok_and(|r| r.payload.full)
        || !previous(rows, line)?.is_some_and(|r| {
            r.r#type == "compacted"
                && r.payload.belongs_to(thread, &turn.id)
                && r.payload
                    .internal_chat_message_metadata_passthrough
                    .is_none()
        })
    {
        return Ok(false);
    }
    let Ok(row) = serde_json::from_slice::<Record<Checkpoint>>(line) else {
        return Ok(false);
    };
    let resume = row.payload.resume_metadata;
    let scope = resume.turn_attribution;
    if resume.last_started_turn_id != turn.id
        || scope.turn_id != turn.id
        || scope.root_turn_id != turn.id
        || scope.parent_turn_id.is_some()
        || scope.initiating_agent_path.is_some()
        || scope.turn_trigger.is_some_and(|s| s != "user")
    {
        return Ok(false);
    }

    // Codex can record an exec proposal during compaction and resume without
    // dispatching it. Only consume the immediately preceding scoped proposal
    // across the two usage counters. Paired calls follow the normal reader.
    let mut probe = rows.clone();
    for (kind, event) in [("event_msg", "token_count"), ("token_usage_record", "")] {
        let Some(row) = previous(&mut probe, line)? else {
            return Ok(true);
        };
        let p = row.payload;
        if row.r#type != kind
            || p.r#type != event
            || !p.belongs_to(thread, &turn.id)
            || p.internal_chat_message_metadata_passthrough.is_some()
            || kind == "token_usage_record"
                && (p.thread_id.as_deref() != Some(thread)
                    || p.turn_id.as_ref() != Some(&turn.id)
                    || p.root_turn_id.as_ref() != Some(&turn.id))
        {
            return Ok(true);
        }
    }
    let Some(row) = previous(&mut probe, line)? else {
        return Ok(true);
    };
    let p = row.payload;
    if row.r#type == "response_item"
        && p.r#type == "custom_tool_call"
        && p.name.as_deref() == Some("exec")
        && p.namespace.is_none()
        && p.status.as_deref() == Some("completed")
        && p.belongs_to(thread, &turn.id)
        && p.id.as_deref().is_some_and(|id| !id.is_empty())
        && p.call_id
            .as_deref()
            .is_some_and(|id| !id.is_empty() && !admission.outputs.contains_key(id))
        && let Some(meta) = p.internal_chat_message_metadata_passthrough
        && meta.turn_id.as_ref() == Some(&turn.id)
        && meta.executed_tool_calls.is_none()
        && meta.tool_calls_complete.is_none()
        && meta.content_item_kinds.is_none()
        && let Some(time) = meta.create_time.filter(|t| t.is_finite())
        && (start..=end).contains(&((time * 1000.0) as i64))
    {
        admission.work(Some((time * 1000.0) as i64));
        *rows = probe;
    }
    Ok(true)
}