Skip to main content

adk_harness/
mode.rs

1//! Harness modes and the stores that hold them (spec 3.1 §7.4).
2//!
3//! A session's mode lives in a harness-owned [`ModeStore`]. Session state holds a
4//! display mirror under [`MODE_STATE_KEY`] that the policy never reads, so no tool,
5//! client `stateDelta` or delegate merge can change the mode (spec 3.1 §9.2 I1).
6
7use std::collections::HashMap;
8use std::fmt;
9use std::path::PathBuf;
10use std::str::FromStr;
11
12use adk_core::{AdkError, ErrorCategory, ErrorComponent, Result};
13use async_trait::async_trait;
14use chrono::{DateTime, Utc};
15use serde::{Deserialize, Serialize};
16use serde_json::Value;
17use tokio::sync::RwLock;
18
19/// Session-state key of the mode's display mirror (spec 3.1 §7.4).
20///
21/// The policy never reads it; it exists so UIs can show the mode from
22/// `event.actions.state_delta`. The mode itself is the [`ModeStore`]'s, which
23/// `Harness::mode` reads: a run re-asserts the mirror from the store when it starts, and
24/// any value an event of the run writes under this key is replaced with the store's
25/// (spec 3.1 §6 D-3).
26///
27/// # Example
28///
29/// ```rust
30/// assert_eq!(adk_harness::MODE_STATE_KEY, "harness:mode");
31/// ```
32pub const MODE_STATE_KEY: &str = "harness:mode";
33
34/// The mirror value the store's record of a session warrants: its mode, revision and
35/// source, or the default mode when there is no record. `None` when the store cannot be
36/// read, so nothing is written from a guess.
37pub(crate) async fn mode_mirror(
38    store: &dyn ModeStore,
39    default_mode: HarnessMode,
40    (app, user, session): (&str, &str, &str),
41) -> Option<Value> {
42    match store.get(app, user, session).await {
43        Ok(Some(record)) => Some(
44            serde_json::json!({ "mode": record.mode, "revision": record.revision, "setBy": record.set_by }),
45        ),
46        Ok(None) => Some(
47            serde_json::json!({ "mode": default_mode, "revision": 0, "setBy": ModeSource::Default }),
48        ),
49        Err(_) => None,
50    }
51}
52
53/// What the harness lets a session do without asking (spec 3.1 §7.4).
54///
55/// Ordered from strictest to loosest: `ReadOnly` ⪰ `Plan` ⪰ `Ask` ⪰ `Auto`. `Ask` is the
56/// default. An unparseable mode is `ReadOnly` ([`HarnessMode::parse_lenient`]).
57///
58/// # Example
59///
60/// ```rust
61/// use adk_harness::HarnessMode;
62///
63/// assert_eq!(HarnessMode::default(), HarnessMode::Ask);
64/// assert!(HarnessMode::Plan.is_stricter_than(HarnessMode::Ask));
65/// assert_eq!(HarnessMode::parse_lenient("yolo"), HarnessMode::ReadOnly);
66/// assert_eq!("read-only".parse::<HarnessMode>().unwrap(), HarnessMode::ReadOnly);
67/// ```
68#[non_exhaustive]
69#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
70#[serde(rename_all = "snake_case")]
71pub enum HarnessMode {
72    /// Reads and todos only.
73    ReadOnly,
74    /// Reads, todos and `exit_plan_mode`; nothing that changes the workspace.
75    Plan,
76    /// Edits and the shell need approval unless a standing rule allows them.
77    #[default]
78    Ask,
79    /// Edits run without approval; the host shell still needs approval.
80    Auto,
81}
82
83impl HarnessMode {
84    /// Every mode, strictest first.
85    pub const ALL: [HarnessMode; 4] =
86        [HarnessMode::ReadOnly, HarnessMode::Plan, HarnessMode::Ask, HarnessMode::Auto];
87
88    /// The wire name: `read_only`, `plan`, `ask` or `auto`.
89    ///
90    /// # Example
91    ///
92    /// ```rust
93    /// assert_eq!(adk_harness::HarnessMode::ReadOnly.as_str(), "read_only");
94    /// ```
95    pub fn as_str(self) -> &'static str {
96        match self {
97            Self::ReadOnly => "read_only",
98            Self::Plan => "plan",
99            Self::Ask => "ask",
100            Self::Auto => "auto",
101        }
102    }
103
104    /// Rank in the mode lattice: higher is stricter.
105    ///
106    /// # Example
107    ///
108    /// ```rust
109    /// use adk_harness::HarnessMode;
110    ///
111    /// assert!(HarnessMode::ReadOnly.strictness() > HarnessMode::Auto.strictness());
112    /// ```
113    pub fn strictness(self) -> u8 {
114        match self {
115            Self::ReadOnly => 3,
116            Self::Plan => 2,
117            Self::Ask => 1,
118            Self::Auto => 0,
119        }
120    }
121
122    /// Whether `self` permits strictly less than `other`.
123    ///
124    /// # Example
125    ///
126    /// ```rust
127    /// use adk_harness::HarnessMode;
128    ///
129    /// assert!(HarnessMode::Ask.is_stricter_than(HarnessMode::Auto));
130    /// assert!(!HarnessMode::Ask.is_stricter_than(HarnessMode::Ask));
131    /// ```
132    pub fn is_stricter_than(self, other: Self) -> bool {
133        self.strictness() > other.strictness()
134    }
135
136    /// Parses a mode name, reading anything unknown as `ReadOnly` (spec 3.1 §9.2 I16).
137    ///
138    /// # Example
139    ///
140    /// ```rust
141    /// use adk_harness::HarnessMode;
142    ///
143    /// assert_eq!(HarnessMode::parse_lenient("auto"), HarnessMode::Auto);
144    /// assert_eq!(HarnessMode::parse_lenient("AUTO "), HarnessMode::ReadOnly);
145    /// ```
146    pub fn parse_lenient(value: &str) -> Self {
147        value.parse().unwrap_or(Self::ReadOnly)
148    }
149}
150
151impl fmt::Display for HarnessMode {
152    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
153        f.write_str(self.as_str())
154    }
155}
156
157impl FromStr for HarnessMode {
158    type Err = AdkError;
159
160    fn from_str(value: &str) -> Result<Self> {
161        match value {
162            "read_only" | "read-only" | "readonly" => Ok(Self::ReadOnly),
163            "plan" => Ok(Self::Plan),
164            "ask" => Ok(Self::Ask),
165            "auto" => Ok(Self::Auto),
166            other => Err(AdkError::new(
167                ErrorComponent::Agent,
168                ErrorCategory::InvalidInput,
169                "harness.mode.unknown",
170                format!("unknown harness mode '{other}'; use read-only, plan, ask or auto"),
171            )),
172        }
173    }
174}
175
176/// Who set a [`ModeRecord`] (spec 3.1 §7.4).
177///
178/// # Example
179///
180/// ```rust
181/// use adk_harness::ModeSource;
182///
183/// assert_eq!(serde_json::to_value(ModeSource::PlanApproval).unwrap(), "plan_approval");
184/// ```
185#[non_exhaustive]
186#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
187#[serde(rename_all = "snake_case")]
188pub enum ModeSource {
189    /// The harness default; no record was ever written.
190    Default,
191    /// A person, through `Harness::set_mode`.
192    User,
193    /// An approved `exit_plan_mode` call.
194    PlanApproval,
195    /// The operator's configuration.
196    Operator,
197    /// The harness tightened the mode itself, for example on a detected loop.
198    SystemTighten,
199}
200
201/// A session's mode as a [`ModeStore`] keeps it (spec 3.1 §7.4).
202///
203/// # Example
204///
205/// ```rust
206/// use adk_harness::{HarnessMode, ModeRecord, ModeSource};
207///
208/// let record = ModeRecord::new(HarnessMode::Plan, ModeSource::User);
209/// let json = serde_json::to_value(&record).unwrap();
210/// assert_eq!(json["mode"], "plan");
211/// assert_eq!(json["setBy"], "user");
212/// ```
213#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
214#[serde(rename_all = "camelCase")]
215pub struct ModeRecord {
216    /// The mode.
217    pub mode: HarnessMode,
218    /// Incremented on every change.
219    pub revision: u64,
220    /// Who set it.
221    pub set_by: ModeSource,
222    /// When it was set.
223    pub at: DateTime<Utc>,
224    /// The invocation that loosened the mode, which itself keeps running under the
225    /// stricter mode; the looser mode applies from the next invocation (spec 3.1 §9.2 I14).
226    #[serde(default, skip_serializing_if = "Option::is_none")]
227    pub effective_from: Option<String>,
228}
229
230impl ModeRecord {
231    /// A record of `mode`, set now by `set_by`, at revision 0.
232    ///
233    /// # Example
234    ///
235    /// ```rust
236    /// use adk_harness::{HarnessMode, ModeRecord, ModeSource};
237    ///
238    /// assert_eq!(ModeRecord::new(HarnessMode::Ask, ModeSource::Default).revision, 0);
239    /// ```
240    pub fn new(mode: HarnessMode, set_by: ModeSource) -> Self {
241        Self { mode, revision: 0, set_by, at: Utc::now(), effective_from: None }
242    }
243
244    /// Reads a stored record, treating anything unparseable as `ReadOnly` (spec 3.1 §7.4).
245    ///
246    /// # Example
247    ///
248    /// ```rust
249    /// use adk_harness::{HarnessMode, ModeRecord};
250    /// use serde_json::json;
251    ///
252    /// assert_eq!(ModeRecord::from_json_lenient(&json!({ "mode": "auto" })).mode, HarnessMode::ReadOnly);
253    /// assert_eq!(ModeRecord::from_json_lenient(&json!(42)).mode, HarnessMode::ReadOnly);
254    /// ```
255    pub fn from_json_lenient(value: &Value) -> Self {
256        match serde_json::from_value::<ModeRecord>(value.clone()) {
257            Ok(record) => record,
258            Err(error) => {
259                tracing::warn!(error = %error, "unparseable harness mode record; reading it as read_only");
260                let revision = value.get("revision").and_then(Value::as_u64).unwrap_or(0);
261                Self {
262                    mode: HarnessMode::ReadOnly,
263                    revision,
264                    set_by: ModeSource::SystemTighten,
265                    at: Utc::now(),
266                    effective_from: None,
267                }
268            }
269        }
270    }
271
272    /// The mode that governs `invocation_id`.
273    ///
274    /// An `exit_plan_mode` approval loosens the mode from the next invocation, so the
275    /// invocation named by [`effective_from`](Self::effective_from) still runs in Plan.
276    ///
277    /// # Example
278    ///
279    /// ```rust
280    /// use adk_harness::{HarnessMode, ModeRecord, ModeSource};
281    ///
282    /// let mut record = ModeRecord::new(HarnessMode::Ask, ModeSource::PlanApproval);
283    /// record.effective_from = Some("inv-1".into());
284    /// assert_eq!(record.mode_for_invocation("inv-1"), HarnessMode::Plan);
285    /// assert_eq!(record.mode_for_invocation("inv-2"), HarnessMode::Ask);
286    /// ```
287    pub fn mode_for_invocation(&self, invocation_id: &str) -> HarnessMode {
288        match &self.effective_from {
289            Some(from) if from == invocation_id => {
290                let held = if self.set_by == ModeSource::PlanApproval {
291                    HarnessMode::Plan
292                } else {
293                    HarnessMode::ReadOnly
294                };
295                if self.mode.is_stricter_than(held) { self.mode } else { held }
296            }
297            _ => self.mode,
298        }
299    }
300}
301
302/// Where a harness keeps each session's mode (spec 3.1 §7.4).
303///
304/// Keyed by (`app`, `user`, `session`). The policy reads it on every evaluation, so a
305/// tightening applies at the next tool call.
306///
307/// # Example
308///
309/// ```rust
310/// use adk_harness::{HarnessMode, InMemoryModeStore, ModeRecord, ModeSource, ModeStore};
311///
312/// # futures::executor::block_on(async {
313/// let store = InMemoryModeStore::new();
314/// store.set("app", "alice", "s1", ModeRecord::new(HarnessMode::Plan, ModeSource::User)).await?;
315/// assert_eq!(store.get("app", "alice", "s1").await?.unwrap().mode, HarnessMode::Plan);
316/// assert!(store.get("app", "alice", "s2").await?.is_none());
317/// # Ok::<(), adk_core::AdkError>(())
318/// # }).unwrap();
319/// ```
320#[async_trait]
321pub trait ModeStore: Send + Sync {
322    /// The session's record, if one was written.
323    async fn get(&self, app: &str, user: &str, session: &str) -> Result<Option<ModeRecord>>;
324    /// Replaces the session's record.
325    async fn set(&self, app: &str, user: &str, session: &str, record: ModeRecord) -> Result<()>;
326}
327
328type ScopeKey = (String, String, String);
329
330fn scope_key(app: &str, user: &str, session: &str) -> ScopeKey {
331    (app.to_string(), user.to_string(), session.to_string())
332}
333
334/// A [`ModeStore`] in process memory, the builder default (spec 3.1 §7.2).
335///
336/// # Example
337///
338/// ```rust
339/// let store = adk_harness::InMemoryModeStore::new();
340/// # let _ = store;
341/// ```
342#[derive(Debug, Default)]
343pub struct InMemoryModeStore {
344    records: RwLock<HashMap<ScopeKey, ModeRecord>>,
345}
346
347impl InMemoryModeStore {
348    /// An empty store.
349    pub fn new() -> Self {
350        Self::default()
351    }
352}
353
354#[async_trait]
355impl ModeStore for InMemoryModeStore {
356    async fn get(&self, app: &str, user: &str, session: &str) -> Result<Option<ModeRecord>> {
357        Ok(self.records.read().await.get(&scope_key(app, user, session)).cloned())
358    }
359
360    async fn set(&self, app: &str, user: &str, session: &str, record: ModeRecord) -> Result<()> {
361        self.records.write().await.insert(scope_key(app, user, session), record);
362        Ok(())
363    }
364}
365
366/// A [`ModeStore`] of one JSON file per session (spec 3.1 §7.4).
367///
368/// Files are written to a temporary sibling and renamed into place, with mode `0600` on
369/// Unix. The default root is `~/.adk/harness/modes`; file names are the SHA-256 of the
370/// (app, user, session) triple, so no identifier reaches the path.
371///
372/// # Example
373///
374/// ```rust
375/// use adk_harness::{FileModeStore, HarnessMode, ModeRecord, ModeSource, ModeStore};
376///
377/// # tokio_test_block_on(async {
378/// let dir = tempfile::tempdir()?;
379/// let store = FileModeStore::new(dir.path());
380/// store.set("app", "alice", "s1", ModeRecord::new(HarnessMode::Auto, ModeSource::User)).await?;
381/// let reopened = FileModeStore::new(dir.path());
382/// assert_eq!(reopened.get("app", "alice", "s1").await?.unwrap().mode, HarnessMode::Auto);
383/// # Ok::<(), Box<dyn std::error::Error>>(())
384/// # }).unwrap();
385/// # fn tokio_test_block_on<F: std::future::Future>(f: F) -> F::Output {
386/// #     tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(f)
387/// # }
388/// ```
389#[derive(Debug, Clone)]
390pub struct FileModeStore {
391    root: PathBuf,
392}
393
394impl FileModeStore {
395    /// A store under `root`, created on first write.
396    pub fn new(root: impl Into<PathBuf>) -> Self {
397        Self { root: root.into() }
398    }
399
400    /// A store under `~/.adk/harness/modes`.
401    ///
402    /// # Errors
403    ///
404    /// Returns a configuration error when the home directory cannot be determined.
405    pub fn in_home() -> Result<Self> {
406        Ok(Self::new(crate::fsutil::adk_home()?.join("harness").join("modes")))
407    }
408
409    fn path(&self, app: &str, user: &str, session: &str) -> PathBuf {
410        let name = crate::fsutil::sha256_hex(&format!("{app}\u{1f}{user}\u{1f}{session}"));
411        self.root.join(format!("{name}.json"))
412    }
413}
414
415#[async_trait]
416impl ModeStore for FileModeStore {
417    async fn get(&self, app: &str, user: &str, session: &str) -> Result<Option<ModeRecord>> {
418        let path = self.path(app, user, session);
419        let Some(bytes) = crate::fsutil::read_optional(&path).await? else {
420            return Ok(None);
421        };
422        let value = serde_json::from_slice::<Value>(&bytes).unwrap_or(Value::Null);
423        Ok(Some(ModeRecord::from_json_lenient(&value)))
424    }
425
426    async fn set(&self, app: &str, user: &str, session: &str, record: ModeRecord) -> Result<()> {
427        let path = self.path(app, user, session);
428        let bytes = serde_json::to_vec_pretty(&record)
429            .map_err(|error| crate::fsutil::serialize_error("mode record", &error))?;
430        crate::fsutil::write_atomic_private(&path, &bytes).await
431    }
432}
433
434/// A [`ModeStore`] in SQLite (spec 3.1 §7.1, feature `sqlite`).
435///
436/// Call [`migrate`](Self::migrate) once before use. The table is
437/// `adk_harness_modes`, distinct from every other store's tables.
438///
439/// # Example
440///
441/// ```rust,ignore
442/// let pool = sqlx::SqlitePool::connect("sqlite::memory:").await?;
443/// let store = adk_harness::SqliteModeStore::new(pool);
444/// store.migrate().await?;
445/// ```
446#[cfg(feature = "sqlite")]
447#[derive(Debug, Clone)]
448pub struct SqliteModeStore {
449    pool: sqlx::SqlitePool,
450    #[cfg(feature = "encrypted")]
451    envelope: Option<crate::encrypted::StoreEnvelope>,
452}
453
454#[cfg(feature = "sqlite")]
455impl SqliteModeStore {
456    /// A store over `pool`.
457    pub fn new(pool: sqlx::SqlitePool) -> Self {
458        Self {
459            pool,
460            #[cfg(feature = "encrypted")]
461            envelope: None,
462        }
463    }
464
465    /// Seals every record under `keyring` (spec 3.1 §7.12).
466    #[cfg(feature = "encrypted")]
467    #[must_use]
468    pub fn with_keyring(mut self, keyring: crate::encrypted::StoreKeyring) -> Self {
469        self.envelope = Some(crate::encrypted::StoreEnvelope::new(keyring, "modes"));
470        self
471    }
472
473    /// Re-seals every record a previous key sealed with the current key, seals records
474    /// written before a key was configured, and returns how many rows changed (spec 3.1
475    /// §7.12). Without a keyring, nothing changes.
476    ///
477    /// # Errors
478    ///
479    /// Returns `harness.store.decrypt_failed` when a row opens under no key the keyring
480    /// holds, or the database error.
481    #[cfg(feature = "encrypted")]
482    pub async fn rewrap(&self) -> Result<u64> {
483        let Some(envelope) = &self.envelope else {
484            return Ok(0);
485        };
486        let rows: Vec<(String, String, String, String)> =
487            sqlx::query_as("SELECT app_name, user_id, session_id, record FROM adk_harness_modes")
488                .fetch_all(&self.pool)
489                .await
490                .map_err(crate::fsutil::db_error)?;
491        let mut changed = 0;
492        for (app, user, session, text) in rows {
493            if let Some(resealed) = envelope.reseal_or_seal(&[&app, &user, &session], &text)? {
494                sqlx::query("UPDATE adk_harness_modes SET record = ? WHERE app_name = ? AND user_id = ? AND session_id = ?")
495                    .bind(resealed)
496                    .bind(&app)
497                    .bind(&user)
498                    .bind(&session)
499                    .execute(&self.pool)
500                    .await
501                    .map_err(crate::fsutil::db_error)?;
502                changed += 1;
503            }
504        }
505        Ok(changed)
506    }
507
508    #[cfg(feature = "encrypted")]
509    fn encode(&self, address: &[&str], text: String) -> Result<String> {
510        crate::encrypted::encode_row(self.envelope.as_ref(), address, text)
511    }
512
513    #[cfg(not(feature = "encrypted"))]
514    fn encode(&self, _address: &[&str], text: String) -> Result<String> {
515        Ok(text)
516    }
517
518    #[cfg(feature = "encrypted")]
519    fn decode(&self, address: &[&str], text: String) -> Result<String> {
520        crate::encrypted::decode_row(self.envelope.as_ref(), "modes", address, text)
521    }
522
523    #[cfg(not(feature = "encrypted"))]
524    fn decode(&self, _address: &[&str], text: String) -> Result<String> {
525        Ok(text)
526    }
527
528    /// Creates the store's table if it does not exist.
529    ///
530    /// # Errors
531    ///
532    /// Returns the database error when the statement fails.
533    pub async fn migrate(&self) -> Result<()> {
534        sqlx::query(
535            "CREATE TABLE IF NOT EXISTS adk_harness_modes (\
536                app_name TEXT NOT NULL, user_id TEXT NOT NULL, session_id TEXT NOT NULL, \
537                record TEXT NOT NULL, PRIMARY KEY (app_name, user_id, session_id))",
538        )
539        .execute(&self.pool)
540        .await
541        .map_err(crate::fsutil::db_error)?;
542        Ok(())
543    }
544}
545
546#[cfg(feature = "sqlite")]
547#[async_trait]
548impl ModeStore for SqliteModeStore {
549    async fn get(&self, app: &str, user: &str, session: &str) -> Result<Option<ModeRecord>> {
550        let row: Option<(String,)> = sqlx::query_as(
551            "SELECT record FROM adk_harness_modes WHERE app_name = ? AND user_id = ? AND session_id = ?",
552        )
553        .bind(app)
554        .bind(user)
555        .bind(session)
556        .fetch_optional(&self.pool)
557        .await
558        .map_err(crate::fsutil::db_error)?;
559        let Some((text,)) = row else {
560            return Ok(None);
561        };
562        let text = self.decode(&[app, user, session], text)?;
563        let value = serde_json::from_str::<Value>(&text).unwrap_or(Value::Null);
564        Ok(Some(ModeRecord::from_json_lenient(&value)))
565    }
566
567    async fn set(&self, app: &str, user: &str, session: &str, record: ModeRecord) -> Result<()> {
568        let text = serde_json::to_string(&record)
569            .map_err(|error| crate::fsutil::serialize_error("mode record", &error))?;
570        let text = self.encode(&[app, user, session], text)?;
571        sqlx::query(
572            "INSERT INTO adk_harness_modes (app_name, user_id, session_id, record) VALUES (?, ?, ?, ?) \
573             ON CONFLICT (app_name, user_id, session_id) DO UPDATE SET record = excluded.record",
574        )
575        .bind(app)
576        .bind(user)
577        .bind(session)
578        .bind(text)
579        .execute(&self.pool)
580        .await
581        .map_err(crate::fsutil::db_error)?;
582        Ok(())
583    }
584}
585
586/// Migrations of [`PostgresModeStore`], recorded in `_adk_harness_mode_migrations`.
587#[cfg(feature = "postgres")]
588const POSTGRES_MODE_MIGRATIONS: &[(i64, &str, &str)] = &[(
589    1,
590    "create harness mode table",
591    "CREATE TABLE IF NOT EXISTS adk_harness_modes (\
592        app_name TEXT NOT NULL, user_id TEXT NOT NULL, session_id TEXT NOT NULL, \
593        record TEXT NOT NULL, PRIMARY KEY (app_name, user_id, session_id))",
594)];
595
596/// A [`ModeStore`] in PostgreSQL, shared by every replica of a served harness (spec 3.1
597/// §7.4, §13 Q2; feature `postgres`).
598///
599/// The table is `adk_harness_modes`, keyed as the SQLite store's is by (`app_name`,
600/// `user_id`, `session_id`). Every [`get`](ModeStore::get) reads the row, so a mode one
601/// replica tightens applies at the next evaluation on every replica (spec 3.1 §9.2 I14).
602/// [`migrate`](Self::migrate) records its steps in `_adk_harness_mode_migrations` under an
603/// advisory lock, so replicas starting together migrate one at a time.
604///
605/// # Example
606///
607/// ```rust,no_run
608/// use adk_harness::{HarnessMode, ModeRecord, ModeSource, ModeStore, PostgresModeStore};
609///
610/// # async fn example() -> adk_core::Result<()> {
611/// let store = PostgresModeStore::connect("postgres://localhost/app").await?;
612/// store.migrate().await?;
613/// store.set("app", "alice", "s1", ModeRecord::new(HarnessMode::Plan, ModeSource::User)).await?;
614/// assert_eq!(store.get("app", "alice", "s1").await?.unwrap().mode, HarnessMode::Plan);
615/// # Ok(())
616/// # }
617/// ```
618#[cfg(feature = "postgres")]
619#[derive(Debug, Clone)]
620pub struct PostgresModeStore {
621    pool: sqlx::PgPool,
622}
623
624#[cfg(feature = "postgres")]
625impl PostgresModeStore {
626    /// A store over `pool`, such as the one the session service and the approval store use.
627    pub fn new(pool: sqlx::PgPool) -> Self {
628        Self { pool }
629    }
630
631    /// Connects to `database_url` with a pool of its own.
632    ///
633    /// # Errors
634    ///
635    /// Returns `harness.store.database` when the server cannot be reached.
636    pub async fn connect(database_url: &str) -> Result<Self> {
637        let pool = sqlx::PgPool::connect(database_url).await.map_err(crate::fsutil::db_error)?;
638        Ok(Self::new(pool))
639    }
640
641    /// Creates or upgrades the store's table.
642    ///
643    /// # Errors
644    ///
645    /// Returns the database error when a statement fails, or a version mismatch when the
646    /// database was migrated by a newer release.
647    pub async fn migrate(&self) -> Result<()> {
648        crate::fsutil::migrate_postgres(
649            &self.pool,
650            "_adk_harness_mode_migrations",
651            POSTGRES_MODE_MIGRATIONS,
652        )
653        .await
654    }
655}
656
657#[cfg(feature = "postgres")]
658#[async_trait]
659impl ModeStore for PostgresModeStore {
660    async fn get(&self, app: &str, user: &str, session: &str) -> Result<Option<ModeRecord>> {
661        let row: Option<(String,)> = sqlx::query_as(
662            "SELECT record FROM adk_harness_modes \
663             WHERE app_name = $1 AND user_id = $2 AND session_id = $3",
664        )
665        .bind(app)
666        .bind(user)
667        .bind(session)
668        .fetch_optional(&self.pool)
669        .await
670        .map_err(crate::fsutil::db_error)?;
671        Ok(row.map(|(text,)| {
672            let value = serde_json::from_str::<Value>(&text).unwrap_or(Value::Null);
673            ModeRecord::from_json_lenient(&value)
674        }))
675    }
676
677    async fn set(&self, app: &str, user: &str, session: &str, record: ModeRecord) -> Result<()> {
678        let text = serde_json::to_string(&record)
679            .map_err(|error| crate::fsutil::serialize_error("mode record", &error))?;
680        sqlx::query(
681            "INSERT INTO adk_harness_modes (app_name, user_id, session_id, record) \
682             VALUES ($1, $2, $3, $4) \
683             ON CONFLICT (app_name, user_id, session_id) DO UPDATE SET record = excluded.record",
684        )
685        .bind(app)
686        .bind(user)
687        .bind(session)
688        .bind(text)
689        .execute(&self.pool)
690        .await
691        .map_err(crate::fsutil::db_error)?;
692        Ok(())
693    }
694}
695
696/// A [`ModeStore`] in Redis, shared by every replica of a served harness (spec 3.1 §7.4,
697/// §13 Q2; feature `redis`).
698///
699/// One string per session at `<namespace>:{<app>}:mode:<user>:<session>` holds the
700/// record's JSON. The namespace is `adk:harness` unless
701/// [`with_namespace`](Self::with_namespace) sets another; the app segment is the key's
702/// hash tag, so every key of an app sits in one Redis Cluster slot. App, user and session
703/// segments are percent-encoded (`%`, `:`, `{`, `}`). Every [`get`](ModeStore::get) reads
704/// the key, so a mode one replica tightens applies at the next evaluation on every replica
705/// (spec 3.1 §9.2 I14).
706///
707/// # Example
708///
709/// ```rust,no_run
710/// use adk_harness::{HarnessMode, ModeRecord, ModeSource, ModeStore, RedisModeStore};
711///
712/// # async fn example() -> adk_core::Result<()> {
713/// let store = RedisModeStore::connect("redis://localhost:6379").await?;
714/// store.set("app", "alice", "s1", ModeRecord::new(HarnessMode::Plan, ModeSource::User)).await?;
715/// assert_eq!(store.get("app", "alice", "s1").await?.unwrap().mode, HarnessMode::Plan);
716/// # Ok(())
717/// # }
718/// ```
719#[cfg(feature = "redis")]
720#[derive(Debug, Clone)]
721pub struct RedisModeStore {
722    client: fred::prelude::Client,
723    namespace: String,
724}
725
726#[cfg(feature = "redis")]
727impl RedisModeStore {
728    /// A store over an initialized client, such as one shared with the rule store.
729    pub fn from_client(client: fred::prelude::Client) -> Self {
730        Self { client, namespace: crate::fsutil::REDIS_NAMESPACE.to_string() }
731    }
732
733    /// Connects to `url`.
734    ///
735    /// # Errors
736    ///
737    /// Returns `harness.store.database` when the server cannot be reached.
738    pub async fn connect(url: &str) -> Result<Self> {
739        Ok(Self::from_client(crate::fsutil::redis_connect(url).await?))
740    }
741
742    /// Keeps the store's keys under `namespace` instead of `adk:harness`, for example to
743    /// separate deployments that share a server.
744    #[must_use]
745    pub fn with_namespace(mut self, namespace: impl Into<String>) -> Self {
746        self.namespace = crate::fsutil::redis_namespace(&namespace.into());
747        self
748    }
749
750    fn key(&self, app: &str, user: &str, session: &str) -> String {
751        use crate::fsutil::redis_segment;
752        format!(
753            "{}:{{{}}}:mode:{}:{}",
754            self.namespace,
755            redis_segment(app),
756            redis_segment(user),
757            redis_segment(session)
758        )
759    }
760}
761
762#[cfg(feature = "redis")]
763#[async_trait]
764impl ModeStore for RedisModeStore {
765    async fn get(&self, app: &str, user: &str, session: &str) -> Result<Option<ModeRecord>> {
766        use fred::prelude::KeysInterface as _;
767        let text: Option<String> = self
768            .client
769            .get(self.key(app, user, session))
770            .await
771            .map_err(|error| crate::fsutil::redis_error("read a mode record", &error))?;
772        Ok(text.map(|text| {
773            let value = serde_json::from_str::<Value>(&text).unwrap_or(Value::Null);
774            ModeRecord::from_json_lenient(&value)
775        }))
776    }
777
778    async fn set(&self, app: &str, user: &str, session: &str, record: ModeRecord) -> Result<()> {
779        use fred::prelude::KeysInterface as _;
780        let text = serde_json::to_string(&record)
781            .map_err(|error| crate::fsutil::serialize_error("mode record", &error))?;
782        let () = self
783            .client
784            .set(self.key(app, user, session), text, None, None, false)
785            .await
786            .map_err(|error| crate::fsutil::redis_error("write a mode record", &error))?;
787        Ok(())
788    }
789}
790
791/// How a requested mode change relates to the current mode (spec 3.1 §7.4).
792///
793/// # Example
794///
795/// ```rust
796/// use adk_harness::{HarnessMode, ModeChange};
797///
798/// assert_eq!(ModeChange::between(HarnessMode::Ask, HarnessMode::Plan), ModeChange::Tighten);
799/// assert_eq!(ModeChange::between(HarnessMode::Plan, HarnessMode::Ask), ModeChange::Loosen);
800/// ```
801#[derive(Clone, Copy, Debug, PartialEq, Eq)]
802pub enum ModeChange {
803    /// The new mode is the current one.
804    Same,
805    /// The new mode is stricter; it applies at the next evaluation.
806    Tighten,
807    /// The new mode is looser; it needs `Harness::set_mode` or an approved
808    /// `exit_plan_mode` (spec 3.1 §7.4).
809    Loosen,
810}
811
812impl ModeChange {
813    /// Classifies a change from `from` to `to`.
814    pub fn between(from: HarnessMode, to: HarnessMode) -> Self {
815        if from == to {
816            Self::Same
817        } else if to.is_stricter_than(from) {
818            Self::Tighten
819        } else {
820            Self::Loosen
821        }
822    }
823}
824
825/// Whether `source` may loosen a mode (spec 3.1 §7.4): only a person through
826/// `Harness::set_mode` or an approved `exit_plan_mode`.
827pub(crate) fn may_loosen(source: ModeSource) -> bool {
828    matches!(source, ModeSource::User | ModeSource::PlanApproval)
829}
830
831/// Writes a mode change after checking the loosening rule and recording it, write-ahead.
832///
833/// Returns the stored record. A loosening by any source other than [`ModeSource::User`]
834/// or [`ModeSource::PlanApproval`] is refused with `harness.mode.loosening_refused` and
835/// recorded as `harness.mode.refused`.
836#[allow(clippy::too_many_arguments)]
837pub(crate) async fn write_mode_change(
838    store: &dyn ModeStore,
839    default_mode: HarnessMode,
840    scope: (&str, &str, &str),
841    to: HarnessMode,
842    source: ModeSource,
843    effective_from: Option<String>,
844    audit: Option<&crate::audit::HarnessAudit>,
845    cancelled_call_ids: &[String],
846) -> Result<ModeRecord> {
847    let (app, user, session) = scope;
848    let current = store.get(app, user, session).await?;
849    let from = current.as_ref().map_or(default_mode, |record| record.mode);
850    let change = ModeChange::between(from, to);
851    if change == ModeChange::Loosen && !may_loosen(source) {
852        if let Some(audit) = audit {
853            audit
854                .record(
855                    "harness.mode.refused",
856                    serde_json::json!({
857                        "from": from, "to": to, "initiator": source,
858                        "reason": "only Harness::set_mode or an approved exit_plan_mode loosens a mode",
859                    }),
860                )
861                .await?;
862        }
863        return Err(AdkError::new(
864            ErrorComponent::Agent,
865            ErrorCategory::Forbidden,
866            "harness.mode.loosening_refused",
867            format!(
868                "changing the mode from {from} to {to} loosens it; only Harness::set_mode or an \
869                 approved exit_plan_mode may do that"
870            ),
871        ));
872    }
873    let record = ModeRecord {
874        mode: to,
875        revision: current.map_or(1, |record| record.revision + 1),
876        set_by: source,
877        at: Utc::now(),
878        effective_from: effective_from.clone(),
879    };
880    if let Some(audit) = audit {
881        audit
882            .record(
883                "harness.mode.changed",
884                serde_json::json!({
885                    "from": from, "to": to, "initiator": source, "revision": record.revision,
886                    "effectiveFrom": effective_from, "cancelledHeldCallIds": cancelled_call_ids,
887                }),
888            )
889            .await?;
890    }
891    store.set(app, user, session, record.clone()).await?;
892    Ok(record)
893}
894
895#[cfg(test)]
896mod tests {
897    use super::*;
898
899    #[test]
900    fn unknown_json_reads_as_read_only() {
901        for value in [
902            serde_json::json!(null),
903            serde_json::json!({ "mode": "root" }),
904            serde_json::json!({ "mode": "auto", "revision": 3 }),
905            serde_json::json!("auto"),
906        ] {
907            assert_eq!(ModeRecord::from_json_lenient(&value).mode, HarnessMode::ReadOnly);
908        }
909    }
910
911    #[test]
912    fn a_complete_record_round_trips() {
913        let record = ModeRecord::new(HarnessMode::Auto, ModeSource::User);
914        let value = serde_json::to_value(&record).unwrap();
915        assert_eq!(ModeRecord::from_json_lenient(&value), record);
916    }
917
918    #[tokio::test]
919    async fn only_a_person_or_a_plan_approval_loosens_a_mode() {
920        let store = InMemoryModeStore::new();
921        let scope = ("app", "alice", "s1");
922        for source in [ModeSource::Operator, ModeSource::SystemTighten, ModeSource::Default] {
923            let refused = write_mode_change(
924                &store,
925                HarnessMode::Plan,
926                scope,
927                HarnessMode::Auto,
928                source,
929                None,
930                None,
931                &[],
932            )
933            .await
934            .unwrap_err();
935            assert_eq!(refused.code, "harness.mode.loosening_refused");
936        }
937        let tightened = write_mode_change(
938            &store,
939            HarnessMode::Plan,
940            scope,
941            HarnessMode::ReadOnly,
942            ModeSource::SystemTighten,
943            None,
944            None,
945            &[],
946        )
947        .await
948        .unwrap();
949        assert_eq!(tightened.revision, 1);
950        for source in [ModeSource::User, ModeSource::PlanApproval] {
951            let loosened = write_mode_change(
952                &store,
953                HarnessMode::Plan,
954                scope,
955                HarnessMode::Ask,
956                source,
957                None,
958                None,
959                &[],
960            )
961            .await
962            .unwrap();
963            assert_eq!(loosened.mode, HarnessMode::Ask);
964            store
965                .set("app", "alice", "s1", ModeRecord::new(HarnessMode::ReadOnly, ModeSource::User))
966                .await
967                .unwrap();
968        }
969    }
970
971    #[test]
972    fn the_loosening_invocation_keeps_the_stricter_mode() {
973        let mut record = ModeRecord::new(HarnessMode::Auto, ModeSource::PlanApproval);
974        record.effective_from = Some("inv".into());
975        assert_eq!(record.mode_for_invocation("inv"), HarnessMode::Plan);
976        record.set_by = ModeSource::User;
977        assert_eq!(record.mode_for_invocation("inv"), HarnessMode::ReadOnly);
978        assert_eq!(record.mode_for_invocation("other"), HarnessMode::Auto);
979    }
980}