Skip to main content

adk_harness/shell/
ledger.rs

1//! The per-session shell ledger behind unsandboxed retries (spec 3.1 §7.9).
2
3use std::collections::HashMap;
4use std::fmt;
5
6use adk_core::Result;
7use async_trait::async_trait;
8use chrono::{DateTime, Utc};
9use serde::{Deserialize, Serialize};
10use tokio::sync::RwLock;
11
12/// One `bash` call, as the shell ledger records it (spec 3.1 §7.9).
13///
14/// # Example
15///
16/// ```rust
17/// use adk_harness::ShellLedgerEntry;
18///
19/// let entry = ShellLedgerEntry::new("call-1", "cargo test", true, Some(101));
20/// assert!(entry.failed());
21/// assert!(entry.retried_by.is_none());
22/// ```
23#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
24#[serde(rename_all = "camelCase")]
25pub struct ShellLedgerEntry {
26    /// The call's function call ID.
27    pub function_call_id: String,
28    /// The command as run.
29    pub command: String,
30    /// Whether it ran under a sandbox.
31    pub sandboxed: bool,
32    /// The enforcer it ran under.
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub enforcer: Option<String>,
35    /// Exit code; `None` when the command was killed or timed out.
36    pub exit_code: Option<i32>,
37    /// Whether stderr suggests the sandbox denied something.
38    #[serde(default)]
39    pub denial_suspected: bool,
40    /// The call that retried it unsandboxed, once one has.
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub retried_by: Option<String>,
43    /// When it finished.
44    pub at: DateTime<Utc>,
45}
46
47impl ShellLedgerEntry {
48    /// An entry for a finished call.
49    pub fn new(
50        function_call_id: impl Into<String>,
51        command: impl Into<String>,
52        sandboxed: bool,
53        exit_code: Option<i32>,
54    ) -> Self {
55        Self {
56            function_call_id: function_call_id.into(),
57            command: command.into(),
58            sandboxed,
59            enforcer: None,
60            exit_code,
61            denial_suspected: false,
62            retried_by: None,
63            at: Utc::now(),
64        }
65    }
66
67    /// Whether the command failed: a non-zero exit, a kill or a timeout.
68    pub fn failed(&self) -> bool {
69        self.exit_code != Some(0)
70    }
71
72    /// Digest of the failed call an unsandboxed retry names: call ID, command, enforcer and
73    /// exit code, as `sha256:<hex>` (spec 3.1 §9.3 `failureDigest`).
74    ///
75    /// # Example
76    ///
77    /// ```rust
78    /// use adk_harness::ShellLedgerEntry;
79    ///
80    /// let one = ShellLedgerEntry::new("c1", "make", true, Some(2));
81    /// let other = ShellLedgerEntry::new("c1", "make", true, Some(1));
82    /// assert_ne!(one.digest(), other.digest());
83    /// ```
84    pub fn digest(&self) -> String {
85        let failure = serde_json::json!({
86            "functionCallId": self.function_call_id,
87            "command": self.command,
88            "sandboxed": self.sandboxed,
89            "enforcer": self.enforcer,
90            "exitCode": self.exit_code,
91            "denialSuspected": self.denial_suspected,
92        });
93        format!("sha256:{}", crate::fsutil::sha256_hex(&failure.to_string()))
94    }
95}
96
97/// Where the harness records each session's `bash` calls (spec 3.1 §7.9).
98///
99/// An unsandboxed retry is authorized only against a failed sandboxed call recorded here,
100/// and [`mark_retried`](Self::mark_retried) lets exactly one retry consume it
101/// (spec 3.1 §9.2 I25).
102///
103/// # Example
104///
105/// ```rust
106/// use adk_harness::{InMemoryShellLedger, ShellLedger, ShellLedgerEntry};
107///
108/// # futures::executor::block_on(async {
109/// let ledger = InMemoryShellLedger::new();
110/// ledger.record("app", "u", "s", ShellLedgerEntry::new("c1", "make", true, Some(2))).await?;
111/// assert!(ledger.mark_retried("app", "u", "s", "c1", "c2").await?);
112/// assert!(!ledger.mark_retried("app", "u", "s", "c1", "c3").await?);
113/// # Ok::<(), adk_core::AdkError>(())
114/// # }).unwrap();
115/// ```
116#[async_trait]
117pub trait ShellLedger: fmt::Debug + Send + Sync {
118    /// Records a finished call, replacing an earlier entry with the same call ID.
119    async fn record(
120        &self,
121        app: &str,
122        user: &str,
123        session: &str,
124        entry: ShellLedgerEntry,
125    ) -> Result<()>;
126    /// The entry for `function_call_id`, if recorded.
127    async fn get(
128        &self,
129        app: &str,
130        user: &str,
131        session: &str,
132        function_call_id: &str,
133    ) -> Result<Option<ShellLedgerEntry>>;
134    /// Marks the entry as retried by `by`. Returns `true` only for the first retry of a
135    /// recorded entry.
136    async fn mark_retried(
137        &self,
138        app: &str,
139        user: &str,
140        session: &str,
141        function_call_id: &str,
142        by: &str,
143    ) -> Result<bool>;
144}
145
146type LedgerKey = (String, String, String, String);
147
148/// A [`ShellLedger`] in process memory, the default (spec 3.1 §7.9).
149///
150/// # Example
151///
152/// ```rust
153/// let ledger = adk_harness::InMemoryShellLedger::new();
154/// # let _ = ledger;
155/// ```
156#[derive(Debug, Default)]
157pub struct InMemoryShellLedger {
158    entries: RwLock<HashMap<LedgerKey, ShellLedgerEntry>>,
159}
160
161impl InMemoryShellLedger {
162    /// An empty ledger.
163    pub fn new() -> Self {
164        Self::default()
165    }
166}
167
168fn key(app: &str, user: &str, session: &str, call: &str) -> LedgerKey {
169    (app.to_string(), user.to_string(), session.to_string(), call.to_string())
170}
171
172#[async_trait]
173impl ShellLedger for InMemoryShellLedger {
174    async fn record(
175        &self,
176        app: &str,
177        user: &str,
178        session: &str,
179        entry: ShellLedgerEntry,
180    ) -> Result<()> {
181        self.entries.write().await.insert(key(app, user, session, &entry.function_call_id), entry);
182        Ok(())
183    }
184
185    async fn get(
186        &self,
187        app: &str,
188        user: &str,
189        session: &str,
190        function_call_id: &str,
191    ) -> Result<Option<ShellLedgerEntry>> {
192        Ok(self.entries.read().await.get(&key(app, user, session, function_call_id)).cloned())
193    }
194
195    async fn mark_retried(
196        &self,
197        app: &str,
198        user: &str,
199        session: &str,
200        function_call_id: &str,
201        by: &str,
202    ) -> Result<bool> {
203        let mut entries = self.entries.write().await;
204        match entries.get_mut(&key(app, user, session, function_call_id)) {
205            Some(entry) if entry.retried_by.is_none() => {
206                entry.retried_by = Some(by.to_string());
207                Ok(true)
208            }
209            _ => Ok(false),
210        }
211    }
212}
213
214/// A [`ShellLedger`] in SQLite (spec 3.1 §7.1, feature `sqlite`).
215///
216/// Call [`migrate`](Self::migrate) once before use. The table is
217/// `adk_harness_shell_ledger`.
218///
219/// # Example
220///
221/// ```rust,ignore
222/// let ledger = adk_harness::SqliteShellLedger::new(pool);
223/// ledger.migrate().await?;
224/// ```
225#[cfg(feature = "sqlite")]
226#[derive(Debug, Clone)]
227pub struct SqliteShellLedger {
228    pool: sqlx::SqlitePool,
229    #[cfg(feature = "encrypted")]
230    envelope: Option<crate::encrypted::StoreEnvelope>,
231}
232
233#[cfg(feature = "sqlite")]
234impl SqliteShellLedger {
235    /// A ledger over `pool`.
236    pub fn new(pool: sqlx::SqlitePool) -> Self {
237        Self {
238            pool,
239            #[cfg(feature = "encrypted")]
240            envelope: None,
241        }
242    }
243
244    /// Seals every record under `keyring` (spec 3.1 §7.12).
245    #[cfg(feature = "encrypted")]
246    #[must_use]
247    pub fn with_keyring(mut self, keyring: crate::encrypted::StoreKeyring) -> Self {
248        self.envelope = Some(crate::encrypted::StoreEnvelope::new(keyring, "shell-ledger"));
249        self
250    }
251
252    /// Re-seals every record a previous key sealed with the current key, seals records
253    /// written before a key was configured, and returns how many rows changed (spec 3.1
254    /// §7.12). Without a keyring, nothing changes.
255    ///
256    /// # Errors
257    ///
258    /// Returns `harness.store.decrypt_failed` when a row opens under no key the keyring
259    /// holds, or the database error.
260    #[cfg(feature = "encrypted")]
261    pub async fn rewrap(&self) -> Result<u64> {
262        let Some(envelope) = &self.envelope else {
263            return Ok(0);
264        };
265        let rows: Vec<(String, String, String, String, String)> = sqlx::query_as("SELECT app_name, user_id, session_id, function_call_id, entry FROM adk_harness_shell_ledger")
266            .fetch_all(&self.pool)
267            .await
268            .map_err(crate::fsutil::db_error)?;
269        let mut changed = 0;
270        for (app, user, session, call, text) in rows {
271            if let Some(resealed) =
272                envelope.reseal_or_seal(&[&app, &user, &session, &call], &text)?
273            {
274                sqlx::query("UPDATE adk_harness_shell_ledger SET entry = ? WHERE app_name = ? AND user_id = ? AND session_id = ? AND function_call_id = ?")
275                    .bind(resealed)
276                    .bind(&app)
277                    .bind(&user)
278                    .bind(&session)
279                    .bind(&call)
280                    .execute(&self.pool)
281                    .await
282                    .map_err(crate::fsutil::db_error)?;
283                changed += 1;
284            }
285        }
286        Ok(changed)
287    }
288
289    #[cfg(feature = "encrypted")]
290    fn encode(&self, address: &[&str], text: String) -> Result<String> {
291        crate::encrypted::encode_row(self.envelope.as_ref(), address, text)
292    }
293
294    #[cfg(not(feature = "encrypted"))]
295    fn encode(&self, _address: &[&str], text: String) -> Result<String> {
296        Ok(text)
297    }
298
299    #[cfg(feature = "encrypted")]
300    fn decode(&self, address: &[&str], text: String) -> Result<String> {
301        crate::encrypted::decode_row(self.envelope.as_ref(), "shell-ledger", address, text)
302    }
303
304    #[cfg(not(feature = "encrypted"))]
305    fn decode(&self, _address: &[&str], text: String) -> Result<String> {
306        Ok(text)
307    }
308
309    /// Creates the ledger's table if it does not exist.
310    ///
311    /// # Errors
312    ///
313    /// Returns the database error when the statement fails.
314    pub async fn migrate(&self) -> Result<()> {
315        sqlx::query(
316            "CREATE TABLE IF NOT EXISTS adk_harness_shell_ledger (\
317                app_name TEXT NOT NULL, user_id TEXT NOT NULL, session_id TEXT NOT NULL, \
318                function_call_id TEXT NOT NULL, entry TEXT NOT NULL, retried_by TEXT, \
319                PRIMARY KEY (app_name, user_id, session_id, function_call_id))",
320        )
321        .execute(&self.pool)
322        .await
323        .map_err(crate::fsutil::db_error)?;
324        Ok(())
325    }
326}
327
328#[cfg(feature = "sqlite")]
329#[async_trait]
330impl ShellLedger for SqliteShellLedger {
331    async fn record(
332        &self,
333        app: &str,
334        user: &str,
335        session: &str,
336        entry: ShellLedgerEntry,
337    ) -> Result<()> {
338        let text = serde_json::to_string(&entry)
339            .map_err(|error| crate::fsutil::serialize_error("shell ledger entry", &error))?;
340        let text = self.encode(&[app, user, session, &entry.function_call_id], text)?;
341        sqlx::query(
342            "INSERT INTO adk_harness_shell_ledger \
343             (app_name, user_id, session_id, function_call_id, entry, retried_by) VALUES (?, ?, ?, ?, ?, ?) \
344             ON CONFLICT (app_name, user_id, session_id, function_call_id) \
345             DO UPDATE SET entry = excluded.entry",
346        )
347        .bind(app)
348        .bind(user)
349        .bind(session)
350        .bind(&entry.function_call_id)
351        .bind(text)
352        .bind(entry.retried_by.as_deref())
353        .execute(&self.pool)
354        .await
355        .map_err(crate::fsutil::db_error)?;
356        Ok(())
357    }
358
359    async fn get(
360        &self,
361        app: &str,
362        user: &str,
363        session: &str,
364        function_call_id: &str,
365    ) -> Result<Option<ShellLedgerEntry>> {
366        let row: Option<(String, Option<String>)> = sqlx::query_as(
367            "SELECT entry, retried_by FROM adk_harness_shell_ledger \
368             WHERE app_name = ? AND user_id = ? AND session_id = ? AND function_call_id = ?",
369        )
370        .bind(app)
371        .bind(user)
372        .bind(session)
373        .bind(function_call_id)
374        .fetch_optional(&self.pool)
375        .await
376        .map_err(crate::fsutil::db_error)?;
377        let Some((text, retried_by)) = row else {
378            return Ok(None);
379        };
380        let text = self.decode(&[app, user, session, function_call_id], text)?;
381        Ok(serde_json::from_str::<ShellLedgerEntry>(&text).ok().map(|mut entry| {
382            entry.retried_by = retried_by;
383            entry
384        }))
385    }
386
387    async fn mark_retried(
388        &self,
389        app: &str,
390        user: &str,
391        session: &str,
392        function_call_id: &str,
393        by: &str,
394    ) -> Result<bool> {
395        let result = sqlx::query(
396            "UPDATE adk_harness_shell_ledger SET retried_by = ? \
397             WHERE app_name = ? AND user_id = ? AND session_id = ? AND function_call_id = ? \
398             AND retried_by IS NULL",
399        )
400        .bind(by)
401        .bind(app)
402        .bind(user)
403        .bind(session)
404        .bind(function_call_id)
405        .execute(&self.pool)
406        .await
407        .map_err(crate::fsutil::db_error)?;
408        Ok(result.rows_affected() == 1)
409    }
410}