1use 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
19pub const MODE_STATE_KEY: &str = "harness:mode";
33
34pub(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#[non_exhaustive]
69#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
70#[serde(rename_all = "snake_case")]
71pub enum HarnessMode {
72 ReadOnly,
74 Plan,
76 #[default]
78 Ask,
79 Auto,
81}
82
83impl HarnessMode {
84 pub const ALL: [HarnessMode; 4] =
86 [HarnessMode::ReadOnly, HarnessMode::Plan, HarnessMode::Ask, HarnessMode::Auto];
87
88 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 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 pub fn is_stricter_than(self, other: Self) -> bool {
133 self.strictness() > other.strictness()
134 }
135
136 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#[non_exhaustive]
186#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
187#[serde(rename_all = "snake_case")]
188pub enum ModeSource {
189 Default,
191 User,
193 PlanApproval,
195 Operator,
197 SystemTighten,
199}
200
201#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
214#[serde(rename_all = "camelCase")]
215pub struct ModeRecord {
216 pub mode: HarnessMode,
218 pub revision: u64,
220 pub set_by: ModeSource,
222 pub at: DateTime<Utc>,
224 #[serde(default, skip_serializing_if = "Option::is_none")]
227 pub effective_from: Option<String>,
228}
229
230impl ModeRecord {
231 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 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 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#[async_trait]
321pub trait ModeStore: Send + Sync {
322 async fn get(&self, app: &str, user: &str, session: &str) -> Result<Option<ModeRecord>>;
324 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#[derive(Debug, Default)]
343pub struct InMemoryModeStore {
344 records: RwLock<HashMap<ScopeKey, ModeRecord>>,
345}
346
347impl InMemoryModeStore {
348 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#[derive(Debug, Clone)]
390pub struct FileModeStore {
391 root: PathBuf,
392}
393
394impl FileModeStore {
395 pub fn new(root: impl Into<PathBuf>) -> Self {
397 Self { root: root.into() }
398 }
399
400 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#[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 pub fn new(pool: sqlx::SqlitePool) -> Self {
458 Self {
459 pool,
460 #[cfg(feature = "encrypted")]
461 envelope: None,
462 }
463 }
464
465 #[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 #[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 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#[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#[cfg(feature = "postgres")]
619#[derive(Debug, Clone)]
620pub struct PostgresModeStore {
621 pool: sqlx::PgPool,
622}
623
624#[cfg(feature = "postgres")]
625impl PostgresModeStore {
626 pub fn new(pool: sqlx::PgPool) -> Self {
628 Self { pool }
629 }
630
631 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 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#[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 pub fn from_client(client: fred::prelude::Client) -> Self {
730 Self { client, namespace: crate::fsutil::REDIS_NAMESPACE.to_string() }
731 }
732
733 pub async fn connect(url: &str) -> Result<Self> {
739 Ok(Self::from_client(crate::fsutil::redis_connect(url).await?))
740 }
741
742 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
802pub enum ModeChange {
803 Same,
805 Tighten,
807 Loosen,
810}
811
812impl ModeChange {
813 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
825pub(crate) fn may_loosen(source: ModeSource) -> bool {
828 matches!(source, ModeSource::User | ModeSource::PlanApproval)
829}
830
831#[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}