Skip to main content

trusty_code/session/
transcript.rs

1//! `session.get_transcript`'s response shape (#2058).
2//!
3//! Why: `SessionRegistry::set_run_outcome` (#2056) already persists a
4//! finished execution's turn-by-turn transcript, aggregate token usage, and
5//! priced cost onto the `SessionEntry` — this is the M1 cut-line's "inspect
6//! transcript" verb, exposing that stored record over the wire without
7//! recomputing anything. Kept as its own small file (rather than growing
8//! `registry.rs`) so the wire shape has one obvious home and stays decoupled
9//! from the registry's storage/locking internals.
10//! What: [`TranscriptRecord`] is a plain, `Serialize`+`Deserialize` DTO
11//! (#2060: the `Deserialize` half lets `tcode`'s CLI thin client — see
12//! `crate::cli_client` — parse `session.get_transcript`'s JSON-RPC result
13//! straight back into this type rather than picking fields off a raw
14//! `serde_json::Value`): `session_id`,
15//! the ordered `turns` (each already `role`/`model`/`text`/`tool_calls`/
16//! `usage` — see `crate::run_task::TurnRecord`), the aggregate `usage`, and
17//! `cost_usd` exactly as stored (`None` either because pricing was
18//! unavailable for the run, or because no run has ever completed on this
19//! session — the two cases are indistinguishable here by design, matching
20//! `RunReport::cost_usd`'s existing convention). A session that has never
21//! run a task returns `turns: []`, `usage` all-zero, `cost_usd: null` — a
22//! valid, empty transcript, not an error. `mode` (#2059) is the resolved
23//! `HarnessMode` `task.run` set via `SessionRegistry::set_mode` — `None` for
24//! the same "never run" case. `compaction_events` (#2349, epic #2343) is the
25//! session's `pm_transcript`'s cumulative count of #2308 threshold-compactor
26//! fires — `0` for a never-run session, and the field epic #2343's success
27//! metric ("500+ turn session with `compaction_events == 0`") reads. (#2350)
28//! `goals` is a serialisable snapshot of the session's 5 fixed goal slots at
29//! the moment `get_transcript` was called, so a client round-tripping
30//! `session.get_transcript` sees the same goal state `session.get_goals`
31//! reports, with no separate call needed.
32//! Test: `session::registry_tests::get_transcript_*`,
33//! `session::registry_tests::get_transcript_round_trips_goal_state`.
34
35use chrono::{DateTime, Utc};
36use serde::{Deserialize, Serialize};
37
38use crate::agent_loop::{GoalSlot, GoalSource};
39use crate::mode::HarnessMode;
40use crate::perf::TokenUsage;
41use crate::run_task::TurnRecord;
42
43/// A serialisable snapshot of one occupied goal slot, as
44/// `TranscriptRecord.goals` and `session.get_goals` (#2350) expose it.
45///
46/// Why: `agent_loop::goals::GoalSlot` carries the slot's content but not its
47/// own index (it lives at a position in `GoalSlots`'s internal array); the
48/// wire shape needs the 1-based `slot` alongside the content so a client can
49/// refer back to it in a subsequent `session.set_goal`/`session.clear_goal`
50/// call without re-deriving the index.
51/// What: `slot` (1-based), `text`, `source`, `updated_at` — field-for-field
52/// from `GoalSlot` plus the index `GoalSlots::occupied` pairs it with.
53/// Test: `session::registry_tests::get_transcript_round_trips_goal_state`,
54/// `session::registry_tests::get_goals_returns_operator_and_model_sources`.
55#[derive(Debug, Clone, Serialize, Deserialize)]
56pub struct GoalSlotRecord {
57    pub slot: usize,
58    pub text: String,
59    pub source: GoalSource,
60    pub updated_at: DateTime<Utc>,
61}
62
63impl GoalSlotRecord {
64    /// Build a `GoalSlotRecord` from an `agent_loop::goals::GoalSlots::occupied`
65    /// pair.
66    ///
67    /// Why: the one place that maps the in-process `GoalSlot` shape onto the
68    /// wire DTO, so `session::registry`'s `get_transcript`/`get_goals` can
69    /// never independently drift on field mapping.
70    /// What: copies `slot`/`text`/`source`/`updated_at` verbatim.
71    pub fn from_slot(slot: usize, goal: GoalSlot) -> Self {
72        Self {
73            slot,
74            text: goal.text,
75            source: goal.source,
76            updated_at: goal.updated_at,
77        }
78    }
79}
80
81/// The full stored run record for one session, as `session.get_transcript`
82/// returns it.
83///
84/// Why: see module docs — this is the read-only DTO wrapping whatever
85/// `SessionRegistry::set_run_outcome` last stored (or the all-empty default
86/// for a session that has never run a task).
87/// What: field-for-field passthrough of `SessionEntry`'s transcript/usage/
88/// cost, plus the `session_id` for a self-describing response (the wire
89/// method already takes `session_id` as a param, but echoing it back keeps
90/// the result self-contained for a caller inspecting the JSON alone).
91/// `mode` (#2059) mirrors `Session.mode` — the same field, read at
92/// `get_transcript` time. `compaction_events` (#2349) mirrors
93/// `agent_loop::Transcript::compaction_events()` on the session's
94/// `pm_transcript` — `0` when that transcript has never fired the #2308
95/// threshold compactor, or the session has never run. (#2350) `goals` mirrors
96/// `session.get_goals` — empty when the session has no `pm_transcript` yet
97/// (never run a task) or simply has no goal set.
98/// Test: `session::registry_tests::get_transcript_returns_stored_record`,
99/// `session::registry_tests::get_transcript_on_never_run_session_is_empty`,
100/// `session::registry_tests::get_transcript_reports_compaction_events`,
101/// `session::registry_tests::get_transcript_round_trips_goal_state`.
102#[derive(Debug, Clone, Serialize, Deserialize)]
103pub struct TranscriptRecord {
104    pub session_id: String,
105    pub turns: Vec<TurnRecord>,
106    pub usage: TokenUsage,
107    pub cost_usd: Option<f64>,
108    pub mode: Option<HarnessMode>,
109    pub compaction_events: u32,
110    #[serde(default)]
111    pub goals: Vec<GoalSlotRecord>,
112}
113
114#[cfg(test)]
115mod tests {
116    use super::*;
117
118    /// (#2349) `compaction_events` must round-trip through JSON exactly like
119    /// every other field — this is the wire contract every
120    /// `session.get_transcript` caller (the CLI thin client, external RPC
121    /// clients) relies on.
122    #[test]
123    fn compaction_events_round_trips_through_json() {
124        let record = TranscriptRecord {
125            session_id: "s-1".to_string(),
126            turns: vec![],
127            usage: TokenUsage::default(),
128            cost_usd: None,
129            mode: None,
130            compaction_events: 7,
131            goals: vec![],
132        };
133
134        let json = serde_json::to_value(&record).expect("serialize");
135        assert_eq!(json["compaction_events"], 7);
136
137        let round_tripped: TranscriptRecord = serde_json::from_value(json).expect("deserialize");
138        assert_eq!(round_tripped.compaction_events, 7);
139    }
140}