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;
42use crate::session::memory_sink::MemoryFailureCategory;
43
44/// Per-session durable-memory degradation status (#2425).
45///
46/// Why: the turn recorder is fail-open by design — a failed `chat_turn_append`
47/// or `memory_remember` is logged and dropped so the turn still completes. That
48/// makes a session whose durable history is silently thinning indistinguishable
49/// from a healthy one at the operator surface. This is the retained counterpart
50/// to those per-turn warnings: `session.get_transcript` reports how much of the
51/// session's history failed to land.
52/// What: `total_failed_turns` counts every degraded turn for the session's
53/// lifetime; `consecutive_failed_turns` is the current streak and resets to `0`
54/// on the next durable turn; `latest_failure_category`/`latest_failure_at`
55/// describe the most recent degradation in LOGICAL turn order, not arrival
56/// order. `unrecorded_outcomes` counts outcomes that could not be folded in at
57/// all (see [`super::registry`]'s `record_memory_durability`) — a non-zero
58/// value means the three counters above UNDER-report.
59/// Every field is `#[serde(default)]`, so a transcript serialised before #2425
60/// still deserialises.
61/// Test: `registry_tests::memory_durability_retains_counts_resets_streak_and_warns_at_one_and_three`,
62/// `registry_tests::outcome_beyond_the_reorder_bound_is_counted_as_unrecorded`,
63/// `transcript::tests::old_transcript_json_defaults_memory_durability_status`.
64#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
65pub struct MemoryDurabilityStatus {
66    #[serde(default)]
67    pub total_failed_turns: u64,
68    #[serde(default)]
69    pub consecutive_failed_turns: u32,
70    #[serde(default)]
71    pub latest_failure_category: Option<MemoryFailureCategory>,
72    #[serde(default)]
73    pub latest_failure_at: Option<DateTime<Utc>>,
74    /// Outcomes discarded before they reached the counters above (#2425).
75    #[serde(default)]
76    pub unrecorded_outcomes: u64,
77}
78
79/// A serialisable snapshot of one occupied goal slot, as
80/// `TranscriptRecord.goals` and `session.get_goals` (#2350) expose it.
81///
82/// Why: `agent_loop::goals::GoalSlot` carries the slot's content but not its
83/// own index (it lives at a position in `GoalSlots`'s internal array); the
84/// wire shape needs the 1-based `slot` alongside the content so a client can
85/// refer back to it in a subsequent `session.set_goal`/`session.clear_goal`
86/// call without re-deriving the index.
87/// What: `slot` (1-based), `text`, `source`, `updated_at` — field-for-field
88/// from `GoalSlot` plus the index `GoalSlots::occupied` pairs it with.
89/// Test: `session::registry_tests::get_transcript_round_trips_goal_state`,
90/// `session::registry_tests::get_goals_returns_operator_and_model_sources`.
91#[derive(Debug, Clone, Serialize, Deserialize)]
92pub struct GoalSlotRecord {
93    pub slot: usize,
94    pub text: String,
95    pub source: GoalSource,
96    pub updated_at: DateTime<Utc>,
97}
98
99impl GoalSlotRecord {
100    /// Build a `GoalSlotRecord` from an `agent_loop::goals::GoalSlots::occupied`
101    /// pair.
102    ///
103    /// Why: the one place that maps the in-process `GoalSlot` shape onto the
104    /// wire DTO, so `session::registry`'s `get_transcript`/`get_goals` can
105    /// never independently drift on field mapping.
106    /// What: copies `slot`/`text`/`source`/`updated_at` verbatim.
107    pub fn from_slot(slot: usize, goal: GoalSlot) -> Self {
108        Self {
109            slot,
110            text: goal.text,
111            source: goal.source,
112            updated_at: goal.updated_at,
113        }
114    }
115}
116
117/// The full stored run record for one session, as `session.get_transcript`
118/// returns it.
119///
120/// Why: see module docs — this is the read-only DTO wrapping whatever
121/// `SessionRegistry::set_run_outcome` last stored (or the all-empty default
122/// for a session that has never run a task).
123/// What: field-for-field passthrough of `SessionEntry`'s transcript/usage/
124/// cost, plus the `session_id` for a self-describing response (the wire
125/// method already takes `session_id` as a param, but echoing it back keeps
126/// the result self-contained for a caller inspecting the JSON alone).
127/// `mode` (#2059) mirrors `Session.mode` — the same field, read at
128/// `get_transcript` time. `compaction_events` (#2349) mirrors
129/// `agent_loop::Transcript::compaction_events()` on the session's
130/// `pm_transcript` — `0` when that transcript has never fired the #2308
131/// threshold compactor, or the session has never run. (#2350) `goals` mirrors
132/// `session.get_goals` — empty when the session has no `pm_transcript` yet
133/// (never run a task) or simply has no goal set.
134/// Test: `session::registry_tests::get_transcript_returns_stored_record`,
135/// `session::registry_tests::get_transcript_on_never_run_session_is_empty`,
136/// `session::registry_tests::get_transcript_reports_compaction_events`,
137/// `session::registry_tests::get_transcript_round_trips_goal_state`.
138#[derive(Debug, Clone, Serialize, Deserialize)]
139pub struct TranscriptRecord {
140    pub session_id: String,
141    pub turns: Vec<TurnRecord>,
142    pub usage: TokenUsage,
143    pub cost_usd: Option<f64>,
144    pub mode: Option<HarnessMode>,
145    pub compaction_events: u32,
146    #[serde(default)]
147    pub goals: Vec<GoalSlotRecord>,
148    /// (#2425) Durable-memory degradation status for this session.
149    #[serde(default)]
150    pub memory_durability: MemoryDurabilityStatus,
151}
152
153#[cfg(test)]
154mod tests {
155    use super::*;
156
157    /// (#2349) `compaction_events` must round-trip through JSON exactly like
158    /// every other field — this is the wire contract every
159    /// `session.get_transcript` caller (the CLI thin client, external RPC
160    /// clients) relies on.
161    #[test]
162    fn compaction_events_round_trips_through_json() {
163        let record = TranscriptRecord {
164            session_id: "s-1".to_string(),
165            turns: vec![],
166            usage: TokenUsage::default(),
167            cost_usd: None,
168            mode: None,
169            compaction_events: 7,
170            goals: vec![],
171            memory_durability: MemoryDurabilityStatus::default(),
172        };
173
174        let json = serde_json::to_value(&record).expect("serialize");
175        assert_eq!(json["compaction_events"], 7);
176
177        let round_tripped: TranscriptRecord = serde_json::from_value(json).expect("deserialize");
178        assert_eq!(round_tripped.compaction_events, 7);
179    }
180
181    /// (#2425) A transcript serialised before `memory_durability` existed must
182    /// still deserialise — the field is additive, so every `#[serde(default)]`
183    /// on it has to hold for the nested struct as well as the outer one.
184    #[test]
185    fn old_transcript_json_defaults_memory_durability_status() {
186        let old = serde_json::json!({
187            "session_id": "s-1",
188            "turns": [],
189            "usage": {"prompt_tokens": 0, "completion_tokens": 0,
190                      "cache_read_tokens": 0, "cache_creation_tokens": 0},
191            "cost_usd": null,
192            "mode": null,
193            "compaction_events": 0,
194            "goals": []
195        });
196        let record: TranscriptRecord = serde_json::from_value(old).expect("old transcript");
197        assert_eq!(record.memory_durability, MemoryDurabilityStatus::default());
198    }
199}