Skip to main content

adk_devtools/
read_ledger.rs

1//! Digest-bearing read records (spec 3.1 §7.26, §10 D7).
2//!
3//! A read records the sha256 of what was read, and a write by the agent the sha256 of what
4//! it wrote. `edit_file` without `expect_sha256` uses that digest as its precondition, so an
5//! edit of a file that changed since it was read writes nothing. The records sit behind
6//! [`ReadLedger`] so a host persists them with the session: a held edit approved from a new
7//! process still finds the read that preceded it.
8
9use std::collections::HashMap;
10use std::sync::Mutex;
11
12use adk_core::{Result, ToolContext};
13use async_trait::async_trait;
14use sha2::{Digest as _, Sha256};
15
16/// How many (session, agent) scopes [`InMemoryReadLedger`] keeps before evicting the least
17/// recently used one.
18pub(crate) const READ_SCOPE_CAPACITY: usize = 1024;
19
20/// The session and agent a read is recorded for (spec 3.1 §10 D7).
21///
22/// Session ids are unique only within an app and user, so both are part of the key.
23///
24/// # Example
25///
26/// ```rust
27/// use adk_devtools::ReadScope;
28///
29/// let scope = ReadScope::new("app", "alice", "s1", "coder");
30/// assert_eq!(scope.agent, "coder");
31/// ```
32#[derive(Clone, Debug, PartialEq, Eq, Hash)]
33#[non_exhaustive]
34pub struct ReadScope {
35    /// The application.
36    pub app: String,
37    /// The user the session belongs to.
38    pub user: String,
39    /// The session.
40    pub session: String,
41    /// The agent that read the file.
42    pub agent: String,
43}
44
45impl ReadScope {
46    /// A scope from its four parts.
47    pub fn new(
48        app: impl Into<String>,
49        user: impl Into<String>,
50        session: impl Into<String>,
51        agent: impl Into<String>,
52    ) -> Self {
53        Self { app: app.into(), user: user.into(), session: session.into(), agent: agent.into() }
54    }
55
56    /// The scope of the call behind `ctx`, or `None` when it names no session.
57    pub fn of(ctx: &dyn ToolContext) -> Option<Self> {
58        let session = ctx.session_id();
59        if session.is_empty() {
60            return None;
61        }
62        Some(Self::new(ctx.app_name(), ctx.user_id(), session, ctx.agent_name()))
63    }
64}
65
66/// Where read records live (spec 3.1 §10 D7).
67///
68/// `path` is the file's path relative to the workspace root with `/` separators, and
69/// `sha256` its lowercase hex content digest. [`InMemoryReadLedger`] is the default; a host
70/// that resumes sessions in another process persists the records, as adk-harness does in
71/// its store.
72///
73/// # Example
74///
75/// ```rust
76/// use adk_devtools::{InMemoryReadLedger, ReadLedger, ReadScope};
77///
78/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
79/// let ledger = InMemoryReadLedger::new();
80/// let scope = ReadScope::new("app", "alice", "s1", "coder");
81/// ledger.record(&scope, "src/lib.rs", "ab12").await?;
82/// assert_eq!(ledger.digest(&scope, "src/lib.rs").await?.as_deref(), Some("ab12"));
83/// ledger.forget(&scope, "src/lib.rs").await?;
84/// assert_eq!(ledger.digest(&scope, "src/lib.rs").await?, None);
85/// # Ok::<(), adk_core::AdkError>(())
86/// # }).unwrap();
87/// ```
88#[async_trait]
89pub trait ReadLedger: Send + Sync {
90    /// Records that `scope` read or wrote `path` and saw content with digest `sha256`,
91    /// replacing an earlier record.
92    ///
93    /// # Errors
94    ///
95    /// Returns the store's error when the record cannot be written.
96    async fn record(&self, scope: &ReadScope, path: &str, sha256: &str) -> Result<()>;
97
98    /// The digest `scope` last recorded for `path`.
99    ///
100    /// # Errors
101    ///
102    /// Returns the store's error when the record cannot be read.
103    async fn digest(&self, scope: &ReadScope, path: &str) -> Result<Option<String>>;
104
105    /// Forgets `path` for `scope`: the file was deleted or moved away.
106    ///
107    /// # Errors
108    ///
109    /// Returns the store's error when the record cannot be removed.
110    async fn forget(&self, scope: &ReadScope, path: &str) -> Result<()>;
111}
112
113/// Read records in process memory, per scope, with least-recently-used eviction of scopes
114/// (spec 3.1 §10 D2, D7).
115///
116/// # Example
117///
118/// ```rust
119/// use std::sync::Arc;
120///
121/// use adk_devtools::{InMemoryReadLedger, Workspace};
122///
123/// let ws = Workspace::new("./my-repo").with_read_ledger(Arc::new(InMemoryReadLedger::new()));
124/// # let _ = ws;
125/// ```
126#[derive(Default)]
127pub struct InMemoryReadLedger {
128    inner: Mutex<Scopes>,
129}
130
131#[derive(Default)]
132struct Scopes {
133    /// Records per scope, with the tick of the scope's last use.
134    scoped: HashMap<ReadScope, (u64, HashMap<String, String>)>,
135    tick: u64,
136}
137
138impl Scopes {
139    /// The records of `scope`, created (evicting the least recently used scope at
140    /// capacity) if absent.
141    fn files(&mut self, scope: &ReadScope) -> &mut HashMap<String, String> {
142        self.tick += 1;
143        if !self.scoped.contains_key(scope)
144            && self.scoped.len() >= READ_SCOPE_CAPACITY
145            && let Some(oldest) = self
146                .scoped
147                .iter()
148                .min_by_key(|(_, (used, _))| *used)
149                .map(|(oldest, _)| oldest.clone())
150        {
151            self.scoped.remove(&oldest);
152        }
153        let entry = self.scoped.entry(scope.clone()).or_default();
154        entry.0 = self.tick;
155        &mut entry.1
156    }
157
158    /// The records of `scope` when it has any, marking it used.
159    fn existing(&mut self, scope: &ReadScope) -> Option<&mut HashMap<String, String>> {
160        self.tick += 1;
161        let tick = self.tick;
162        self.scoped.get_mut(scope).map(|entry| {
163            entry.0 = tick;
164            &mut entry.1
165        })
166    }
167}
168
169impl InMemoryReadLedger {
170    /// An empty ledger.
171    pub fn new() -> Self {
172        Self::default()
173    }
174
175    #[cfg(test)]
176    pub(crate) fn scopes(&self) -> usize {
177        self.inner.lock().map(|inner| inner.scoped.len()).unwrap_or_default()
178    }
179}
180
181#[async_trait]
182impl ReadLedger for InMemoryReadLedger {
183    async fn record(&self, scope: &ReadScope, path: &str, sha256: &str) -> Result<()> {
184        let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
185        inner.files(scope).insert(path.to_string(), sha256.to_string());
186        Ok(())
187    }
188
189    async fn digest(&self, scope: &ReadScope, path: &str) -> Result<Option<String>> {
190        let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
191        Ok(inner.existing(scope).and_then(|files| files.get(path).cloned()))
192    }
193
194    async fn forget(&self, scope: &ReadScope, path: &str) -> Result<()> {
195        let mut inner = self.inner.lock().unwrap_or_else(|e| e.into_inner());
196        if let Some(files) = inner.existing(scope) {
197            files.remove(path);
198        }
199        Ok(())
200    }
201}
202
203/// The lowercase hex sha256 of `bytes`, as read records, `expect_sha256` and the
204/// `apply_patch` report write it.
205///
206/// # Example
207///
208/// ```rust
209/// assert_eq!(
210///     adk_devtools::sha256_hex(b""),
211///     "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
212/// );
213/// ```
214pub fn sha256_hex(bytes: &[u8]) -> String {
215    use std::fmt::Write as _;
216    let mut out = String::with_capacity(64);
217    for byte in Sha256::digest(bytes) {
218        let _ = write!(out, "{byte:02x}");
219    }
220    out
221}