返回 CodeWhale
agent_run.rs
根目录 / crates / protocol / src / agent_run.rs
1 //! Dependency-neutral agent-run read model.
2 //!
3 //! [`AgentRunSnapshot`] is a uniform, serializable projection of "one unit of
4 //! agent work" regardless of which subsystem owns it: a direct sub-agent
5 //! worker, a workflow run, a fleet run, a core background job, or a managed
6 //! task. It carries serialized IDs, neutral enums, and scalar summaries only —
7 //! never handles, callbacks, or owner-internal types — so any surface can
8 //! consume it without depending on the owning subsystem.
9 //!
10 //! Ownership contract:
11 //! - Each owner keeps its own richer record type and maps it here through a
12 //! pure adapter function living in the owner's crate/module. This crate
13 //! depends on nothing new; owners depend on it, never the reverse.
14 //! - Adapters must apply the durable-outranks-live rule: when both a durable
15 //! record and a live in-memory handle exist, a terminal durable state always
16 //! wins over lagging live enrichment. Live state may only refine a run that
17 //! the durable record still considers in-flight.
18 //! - Adapters never fabricate values: unknown budgets and timestamps stay
19 //! `None`, and references are logical identifiers within the owner's
20 //! namespace — never filesystem paths and never secrets.
21 //!
22 //! This is a staging slice: the model compiles and is tested, but nothing
23 //! consumes it yet. Consumers arrive with later slices.
24
25 use serde::{Deserialize, Serialize};
26
27 use super::Status;
28
29 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
30 #[serde(rename_all = "snake_case")]
31 pub enum AgentLimitKind {
32 Step,
33 WallTime,
34 }
35
36 /// Which subsystem owns the run behind a snapshot.
37 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
38 #[serde(rename_all = "snake_case")]
39 pub enum RunSource {
40 /// A directly spawned sub-agent worker.
41 Direct,
42 /// A workflow VM run.
43 Workflow,
44 /// A fleet run reconstructed from the durable ledger.
45 Fleet,
46 /// A core background job.
47 CoreJob,
48 /// A managed background task.
49 Task,
50 }
51
52 /// Neutral lifecycle state of a run.
53 ///
54 /// The two wait variants beyond model/tool waits exist because real owner
55 /// state machines report them: workers can wait on user input, and jobs and
56 /// fleet runs can be explicitly paused. Collapsing those into `Running` or
57 /// `Queued` would misreport liveness, so the read model keeps them distinct.
58 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
59 #[serde(rename_all = "snake_case")]
60 pub enum RunState {
61 /// Accepted but not started.
62 Queued,
63 /// Spawn intent recorded; startup in progress.
64 Initializing,
65 /// Actively executing.
66 Running,
67 /// Blocked on a model response.
68 WaitingModel,
69 /// Blocked on a tool execution.
70 WaitingTool,
71 /// Blocked on user input.
72 WaitingInput,
73 /// Explicitly paused by the user or system.
74 Paused,
75 /// Cancellation or shutdown requested, not yet terminal.
76 Stopping,
77 /// Finished; see [`AgentRunSnapshot::terminal`] for the outcome.
78 Terminal,
79 }
80
81 impl Status for RunState {
82 fn is_terminal(&self) -> bool {
83 matches!(self, Self::Terminal)
84 }
85 fn is_active(&self) -> bool {
86 matches!(
87 self,
88 Self::Queued
89 | Self::Initializing
90 | Self::Running
91 | Self::WaitingModel
92 | Self::WaitingTool
93 | Self::WaitingInput
94 | Self::Stopping
95 )
96 }
97 fn is_paused(&self) -> bool {
98 matches!(self, Self::Paused)
99 }
100 }
101
102 /// Scalar budget/spend facts for a run.
103 ///
104 /// Every field is optional: owners report only what they actually track, and
105 /// adapters must not invent values for the rest.
106 #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
107 pub struct BudgetSummary {
108 /// Token ceiling configured for the run, if any.
109 #[serde(default, skip_serializing_if = "Option::is_none")]
110 pub token_budget: Option<u64>,
111 /// Tokens consumed so far, when the owner tracks spend.
112 #[serde(default, skip_serializing_if = "Option::is_none")]
113 pub tokens_used: Option<u64>,
114 /// Steps taken so far, when the owner counts steps.
115 #[serde(default, skip_serializing_if = "Option::is_none")]
116 pub steps_taken: Option<u32>,
117 /// Step ceiling configured for the run, if any.
118 #[serde(default, skip_serializing_if = "Option::is_none")]
119 pub max_steps: Option<u32>,
120 /// Wall-clock duration in milliseconds, when known.
121 #[serde(default, skip_serializing_if = "Option::is_none")]
122 pub duration_ms: Option<u64>,
123 }
124
125 /// How a terminal run ended.
126 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
127 #[serde(rename_all = "snake_case")]
128 pub enum TerminalOutcome {
129 /// Ended successfully.
130 Completed,
131 /// Ended with an error.
132 Failed,
133 /// Cancelled by the user or a parent.
134 Cancelled,
135 /// Interrupted (e.g. process restart) before completion.
136 Interrupted,
137 /// Stopped because it exhausted its own budget.
138 BudgetExhausted,
139 }
140
141 /// Scalar summary of a terminal run.
142 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
143 pub struct TerminalSummary {
144 pub outcome: TerminalOutcome,
145 /// Epoch milliseconds when the run ended, when the owner recorded it.
146 #[serde(default, skip_serializing_if = "Option::is_none")]
147 pub ended_at_ms: Option<i64>,
148 /// Short human-readable detail (result summary or error text).
149 /// Never raw logs, reasoning text, or secrets.
150 #[serde(default, skip_serializing_if = "Option::is_none")]
151 pub detail: Option<String>,
152 }
153
154 /// Category of a durable reference attached to a run.
155 #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
156 #[serde(rename_all = "snake_case")]
157 pub enum ReceiptKind {
158 /// A produced artifact.
159 Artifact,
160 /// A gate/verification result.
161 Gate,
162 /// A durable completion receipt.
163 Receipt,
164 /// An approval record.
165 Approval,
166 }
167
168 /// Reference to a durable artifact, gate, receipt, or approval.
169 ///
170 /// `reference` is a logical identifier within the owner's namespace — never
171 /// an absolute filesystem path, never secret-bearing.
172 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
173 pub struct ReceiptRef {
174 pub kind: ReceiptKind,
175 pub reference: String,
176 /// Optional short human-readable label.
177 #[serde(default, skip_serializing_if = "Option::is_none")]
178 pub label: Option<String>,
179 }
180
181 /// Dependency-neutral snapshot of a single agent run.
182 #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
183 pub struct AgentRunSnapshot {
184 /// Serialized run identifier in the owner's existing scheme.
185 pub run_id: String,
186 /// Serialized identifier of the parent run/thread, when the owner
187 /// records one.
188 #[serde(default, skip_serializing_if = "Option::is_none")]
189 pub parent: Option<String>,
190 /// Which subsystem owns this run.
191 pub source: RunSource,
192 /// Neutral lifecycle state.
193 pub state: RunState,
194 /// Scalar budget facts; defaults to all-unknown.
195 #[serde(default)]
196 pub budget: BudgetSummary,
197 /// Terminal outcome; present exactly when `state == Terminal`.
198 #[serde(default, skip_serializing_if = "Option::is_none")]
199 pub terminal: Option<TerminalSummary>,
200 /// Durable references produced by the run.
201 #[serde(default, skip_serializing_if = "Vec::is_empty")]
202 pub refs: Vec<ReceiptRef>,
203 }
204
205 impl AgentRunSnapshot {
206 /// `true` when the terminal summary and lifecycle state agree:
207 /// `state == Terminal` iff a terminal summary is present.
208 ///
209 /// Adapters uphold this by construction; tests assert it.
210 #[must_use]
211 pub fn is_coherent(&self) -> bool {
212 matches!(self.state, RunState::Terminal) == self.terminal.is_some()
213 }
214 }
215
216 #[cfg(test)]
217 mod tests {
218 use super::*;
219
220 fn full_snapshot() -> AgentRunSnapshot {
221 AgentRunSnapshot {
222 run_id: "agent_1234abcd".to_string(),
223 parent: Some("agent_00ff00ff".to_string()),
224 source: RunSource::Direct,
225 state: RunState::Terminal,
226 budget: BudgetSummary {
227 token_budget: Some(50_000),
228 tokens_used: Some(12_345),
229 steps_taken: Some(7),
230 max_steps: Some(40),
231 duration_ms: Some(93_000),
232 },
233 terminal: Some(TerminalSummary {
234 outcome: TerminalOutcome::Completed,
235 ended_at_ms: Some(1_800_000_000_000),
236 detail: Some("verified build".to_string()),
237 }),
238 refs: vec![ReceiptRef {
239 kind: ReceiptKind::Artifact,
240 reference: "runs/agent_1234abcd/result.md".to_string(),
241 label: Some("result".to_string()),
242 }],
243 }
244 }
245
246 fn minimal_snapshot() -> AgentRunSnapshot {
247 AgentRunSnapshot {
248 run_id: "job-42".to_string(),
249 parent: None,
250 source: RunSource::CoreJob,
251 state: RunState::Queued,
252 budget: BudgetSummary::default(),
253 terminal: None,
254 refs: Vec::new(),
255 }
256 }
257
258 #[test]
259 fn full_snapshot_round_trips() {
260 let snapshot = full_snapshot();
261 let json = serde_json::to_string(&snapshot).expect("serialize");
262 let back: AgentRunSnapshot = serde_json::from_str(&json).expect("deserialize");
263 assert_eq!(back, snapshot);
264 assert!(back.is_coherent());
265 }
266
267 #[test]
268 fn minimal_snapshot_round_trips_and_skips_empty_fields() {
269 let snapshot = minimal_snapshot();
270 let json = serde_json::to_string(&snapshot).expect("serialize");
271 // Optional/empty fields stay off the wire entirely.
272 assert!(!json.contains("parent"));
273 assert!(!json.contains("terminal"));
274 assert!(!json.contains("refs"));
275 assert!(!json.contains("token_budget"));
276 let back: AgentRunSnapshot = serde_json::from_str(&json).expect("deserialize");
277 assert_eq!(back, snapshot);
278 assert!(back.is_coherent());
279 }
280
281 #[test]
282 fn enum_wire_names_are_snake_case_and_stable() {
283 assert_eq!(
284 serde_json::to_string(&RunSource::CoreJob).unwrap(),
285 "\"core_job\""
286 );
287 assert_eq!(
288 serde_json::to_string(&RunState::WaitingModel).unwrap(),
289 "\"waiting_model\""
290 );
291 assert_eq!(
292 serde_json::to_string(&TerminalOutcome::BudgetExhausted).unwrap(),
293 "\"budget_exhausted\""
294 );
295 assert_eq!(
296 serde_json::to_string(&ReceiptKind::Gate).unwrap(),
297 "\"gate\""
298 );
299 // Every state deserializes back to itself.
300 for state in [
301 RunState::Queued,
302 RunState::Initializing,
303 RunState::Running,
304 RunState::WaitingModel,
305 RunState::WaitingTool,
306 RunState::WaitingInput,
307 RunState::Paused,
308 RunState::Stopping,
309 RunState::Terminal,
310 ] {
311 let json = serde_json::to_string(&state).unwrap();
312 let back: RunState = serde_json::from_str(&json).unwrap();
313 assert_eq!(back, state);
314 }
315 }
316
317 #[test]
318 fn run_state_status_trait_partitions_all_states() {
319 for state in [
320 RunState::Queued,
321 RunState::Initializing,
322 RunState::Running,
323 RunState::WaitingModel,
324 RunState::WaitingTool,
325 RunState::WaitingInput,
326 RunState::Paused,
327 RunState::Stopping,
328 RunState::Terminal,
329 ] {
330 let classifications = [state.is_terminal(), state.is_active(), state.is_paused()];
331 assert_eq!(
332 classifications.iter().filter(|flag| **flag).count(),
333 1,
334 "state {state:?} must be exactly one of terminal/active/paused"
335 );
336 }
337 }
338
339 #[test]
340 fn incoherent_snapshot_is_detectable() {
341 let mut snapshot = minimal_snapshot();
342 snapshot.terminal = Some(TerminalSummary {
343 outcome: TerminalOutcome::Completed,
344 ended_at_ms: None,
345 detail: None,
346 });
347 assert!(!snapshot.is_coherent());
348 }
349 }
350
350 lines RUST