ag_contracts/activity.rs
1//! Provider-observed activity for display, independent of telemetry capture.
2
3use std::time::{Duration, SystemTime};
4
5/// A bounded display snapshot of one observed provider operation.
6///
7/// Match updates by `(attempt_id, id)`. Retries use new attempt identities.
8/// Names describe tools, MCP `server/tool` pairs, or explicitly invoked
9/// skills, never inferred file reads. Optional input and output previews are
10/// display-only: they must not be replayed to providers or implicitly exported
11/// as telemetry.
12#[derive(Clone, Debug, Eq, PartialEq)]
13pub struct ActivityEvent {
14 /// Unique provider attempt identity, including retries and repairs.
15 pub attempt_id: String,
16 /// Process exit code when the provider reports one.
17 pub exit_code: Option<i64>,
18 /// Structured, display-only facts the provider reported about the
19 /// operation, boxed to keep events small.
20 pub facts: Box<ActivityFacts>,
21 /// Provider operation identity within the attempt.
22 pub id: String,
23 /// Bounded command or argument preview, when reported by the provider.
24 pub input: Option<String>,
25 /// Provider-independent operation category.
26 pub kind: ActivityKind,
27 /// Bounded tool, MCP `server/tool`, or skill identity suitable for display.
28 pub name: String,
29 /// Time this snapshot was observed by the adapter.
30 pub observed_at: SystemTime,
31 /// Bounded result preview, updated as output arrives when supported. An
32 /// adapter may fill it only for failed operations, with the result's
33 /// last lines.
34 pub output: Option<String>,
35 /// Provider parent operation identity, scoped to the same attempt.
36 pub parent_id: Option<String>,
37 /// Latest lifecycle state the provider reported; see [`Self::outcome`]
38 /// for the state to display.
39 pub status: ActivityStatus,
40}
41
42impl ActivityEvent {
43 /// Exit status of a pipeline stage that `SIGPIPE` ended because a later
44 /// stage stopped reading, as `git log | head` reports for `git log`.
45 const SIGPIPE_STATUS: i64 = 128 + 13;
46
47 /// Returns the state to display: the provider's [`Self::status`], except
48 /// that a completed operation whose own exit status is nonzero, or that
49 /// a signal terminated, failed.
50 ///
51 /// A [`ActivityKind::Search`] that exits with 1 found no match and stays
52 /// completed. Every other exit status, including 1 from a search run as
53 /// an [`ActivityKind::Command`], is judged as is.
54 pub fn outcome(&self) -> ActivityStatus {
55 let exit_code = self.effective_exit_code();
56 let found_nothing = self.kind == ActivityKind::Search && exit_code == Some(1);
57 let failed = self.facts.signal.is_some()
58 || (!found_nothing && exit_code.is_some_and(|code| code != 0));
59 if self.status == ActivityStatus::Completed && failed {
60 ActivityStatus::Failed
61 } else {
62 self.status
63 }
64 }
65
66 /// Returns the operation's own exit status: the first nonzero status of
67 /// its final pipeline's stages, so `cargo test | tail` reports the
68 /// status of `cargo test`, else [`Self::exit_code`]. A stage before the
69 /// last that exited with 141 (`SIGPIPE`) only stopped because a later
70 /// stage stopped reading, so it is skipped.
71 pub fn effective_exit_code(&self) -> Option<i64> {
72 let stages = &self.facts.pipe_status;
73 let last = stages.len().saturating_sub(1);
74 stages
75 .iter()
76 .enumerate()
77 .find(|(index, status)| {
78 **status != 0 && !(*index < last && **status == Self::SIGPIPE_STATUS)
79 })
80 .map(|(_, status)| *status)
81 .or(self.exit_code)
82 }
83}
84
85/// Structured facts about one operation, each present only when the
86/// provider reports it. Text fields are bounded single lines.
87#[derive(Clone, Debug, Default, Eq, PartialEq)]
88pub struct ActivityFacts {
89 /// Lines a file change added and removed.
90 pub diff_stat: Option<DiffStat>,
91 /// Time the operation took.
92 pub duration: Option<Duration>,
93 /// Why a failed operation failed, when the provider says.
94 pub failure: Option<ActivityFailure>,
95 /// Line range a file read covered.
96 pub lines: Option<LineRange>,
97 /// Exit statuses of each stage of a command's final pipeline, first
98 /// stage first, when it had more than one. Display-only: the command can
99 /// influence it.
100 pub pipe_status: Vec<i64>,
101 /// First line of the provider's explanation of a failure, such as
102 /// `hunk 1 context mismatch at line 1216`.
103 pub reason: Option<String>,
104 /// Signal that terminated a command.
105 pub signal: Option<i64>,
106 /// What the operation acted on: a path, a search query, or a command
107 /// flattened to one line.
108 pub target: Option<String>,
109}
110
111/// Why an operation failed.
112#[derive(Clone, Copy, Debug, Eq, PartialEq)]
113pub enum ActivityFailure {
114 /// The user or an approval policy denied it, so it did not run.
115 Denied,
116 /// It ran, or tried to, and failed, such as an execution error or a run
117 /// that ended in an error while it was open.
118 Error,
119 /// The tool refused the call, such as malformed arguments, a path
120 /// outside the repository, or a patch that does not apply.
121 Rejected,
122 /// It took too long: a command hit its deadline, or an approval was not
123 /// decided in time.
124 TimedOut,
125 /// The tool does not exist or the turn does not offer it.
126 Unavailable,
127}
128
129/// Lines a file change added and removed.
130#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
131pub struct DiffStat {
132 /// Lines added.
133 pub added: u64,
134 /// Lines removed.
135 pub removed: u64,
136}
137
138/// One-based line range of a file read.
139#[derive(Clone, Copy, Debug, Eq, PartialEq)]
140pub struct LineRange {
141 /// First line read.
142 pub first: u64,
143 /// Last line read, when the read was limited.
144 pub last: Option<u64>,
145}
146
147/// Category of explicitly observed activity.
148#[derive(Clone, Copy, Debug, Eq, PartialEq)]
149pub enum ActivityKind {
150 /// Command execution.
151 Command,
152 /// File modification.
153 FileChange,
154 /// Directory or path listing.
155 List,
156 /// Model Context Protocol server tool invocation, named `server/tool`.
157 Mcp,
158 /// File content read.
159 Read,
160 /// Repository text or file-name search.
161 Search,
162 /// Named skill invocation.
163 Skill,
164 /// Built-in, dynamic, or subagent tool invocation.
165 Tool,
166 /// Provider web search.
167 WebSearch,
168}
169
170impl ActivityKind {
171 /// Returns whether the kind only inspects the repository: a read, a
172 /// search, or a listing.
173 pub fn is_exploration(self) -> bool {
174 matches!(self, Self::List | Self::Read | Self::Search)
175 }
176}
177
178/// Lifecycle state for an observed operation.
179#[derive(Clone, Copy, Debug, Eq, PartialEq)]
180pub enum ActivityStatus {
181 /// Provider reported that the operation started.
182 Running,
183 /// Provider reported successful completion.
184 Completed,
185 /// Provider reported failure.
186 Failed,
187 /// Attempt ended without an observed terminal result, including
188 /// cancellation.
189 Interrupted,
190}
191
192#[cfg(test)]
193#[path = "activity_test.rs"]
194mod tests;