1use std::collections::{HashMap, HashSet};
15use std::sync::{Arc, Mutex};
16
17use adk_core::ApprovalRequest;
18use adk_core::audit_log::{AuditLogStore, AuditRecord};
19use adk_core::principal::SubjectRef;
20use adk_kernel::control::{ControlClient, RecordLine};
21use async_trait::async_trait;
22use chrono::{DateTime, Utc};
23
24use crate::error::Result;
25use crate::origin::{Origin, SurfaceKind, Via};
26use crate::rules::Answer;
27
28pub const SURFACE_AUDIT_DECIDE: &str = "surface.decide";
30
31#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct AnswerRecord {
34 pub approval_id: String,
36 pub by: SubjectRef,
38 pub via: Via,
40 pub answer: Answer,
42 pub at: DateTime<Utc>,
44}
45
46#[async_trait]
48pub trait AnswerLog: Send + Sync {
49 async fn record(&self, record: &AnswerRecord) -> Result<()>;
51
52 async fn find(&self, approval_id: &str) -> Result<Option<AnswerRecord>>;
54
55 async fn since(&self, at: DateTime<Utc>) -> Result<Vec<AnswerRecord>> {
58 let _ = at;
59 Ok(Vec::new())
60 }
61
62 async fn find_for(&self, request: &ApprovalRequest) -> Result<Option<AnswerRecord>> {
66 self.find(&request.id).await
67 }
68}
69
70#[derive(Debug, Clone, Default)]
83pub struct InMemoryAnswerLog {
84 records: Arc<Mutex<HashMap<String, AnswerRecord>>>,
85}
86
87impl InMemoryAnswerLog {
88 pub fn new() -> Self {
90 Self::default()
91 }
92}
93
94#[async_trait]
95impl AnswerLog for InMemoryAnswerLog {
96 async fn record(&self, record: &AnswerRecord) -> Result<()> {
97 self.records
98 .lock()
99 .unwrap_or_else(|e| e.into_inner())
100 .insert(record.approval_id.clone(), record.clone());
101 Ok(())
102 }
103
104 async fn find(&self, approval_id: &str) -> Result<Option<AnswerRecord>> {
105 Ok(self.records.lock().unwrap_or_else(|e| e.into_inner()).get(approval_id).cloned())
106 }
107
108 async fn since(&self, at: DateTime<Utc>) -> Result<Vec<AnswerRecord>> {
109 let mut found: Vec<AnswerRecord> = self
110 .records
111 .lock()
112 .unwrap_or_else(|e| e.into_inner())
113 .values()
114 .filter(|record| record.at >= at)
115 .cloned()
116 .collect();
117 found.sort_by_key(|record| record.at);
118 Ok(found)
119 }
120}
121
122#[derive(Clone)]
132pub struct AuditAnswerLog {
133 store: Arc<dyn AuditLogStore>,
134 found: Arc<Mutex<HashMap<String, AnswerRecord>>>,
135 absent: Arc<Mutex<HashSet<String>>>,
136}
137
138impl std::fmt::Debug for AuditAnswerLog {
139 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
140 f.debug_struct("AuditAnswerLog").finish_non_exhaustive()
141 }
142}
143
144impl AuditAnswerLog {
145 pub fn new(store: Arc<dyn AuditLogStore>) -> Self {
147 Self { store, found: Arc::default(), absent: Arc::default() }
148 }
149
150 async fn scan(
153 &self,
154 approval_id: &str,
155 since: Option<DateTime<Utc>>,
156 ) -> Result<Option<AnswerRecord>> {
157 for log in self.store.logs().await? {
158 let mut end = self.store.size(&log).await?;
159 'log: while end > 0 {
160 let start = end.saturating_sub(AUDIT_PAGE);
161 let entries = self.store.read(&log, start..end).await?;
162 for entry in entries.iter().rev() {
163 let Some(text) = &entry.record else { continue };
164 let Ok(record) = serde_json::from_str::<AuditRecord>(text) else { continue };
165 if let Some(answer) = answer_of(&record, approval_id) {
166 return Ok(Some(answer));
167 }
168 if since.is_some_and(|since| record.ts < since) {
169 break 'log;
170 }
171 }
172 end = start;
173 }
174 }
175 Ok(None)
176 }
177
178 async fn scan_since(&self, at: DateTime<Utc>) -> Result<Vec<AnswerRecord>> {
180 let mut found = Vec::new();
181 for log in self.store.logs().await? {
182 let mut end = self.store.size(&log).await?;
183 'log: while end > 0 {
184 let start = end.saturating_sub(AUDIT_PAGE);
185 let entries = self.store.read(&log, start..end).await?;
186 for entry in entries.iter().rev() {
187 let Some(text) = &entry.record else { continue };
188 let Ok(record) = serde_json::from_str::<AuditRecord>(text) else { continue };
189 if record.ts < at - CLOCK_SLACK {
190 break 'log;
191 }
192 if record.ts < at {
193 continue;
194 }
195 let id =
196 record.ext.get("approvalId").and_then(|v| v.as_str()).map(str::to_string);
197 if let Some(answer) = id.and_then(|id| answer_of(&record, &id)) {
198 found.push(answer);
199 }
200 }
201 end = start;
202 }
203 }
204 found.sort_by_key(|record| record.at);
205 Ok(found)
206 }
207}
208
209const AUDIT_PAGE: u64 = 256;
211
212const CLOCK_SLACK: chrono::Duration = chrono::Duration::minutes(5);
215
216const RECORD_DELAY: chrono::Duration = chrono::Duration::minutes(5);
219
220const REMEMBERED: usize = 10_000;
222
223#[async_trait]
224impl AnswerLog for AuditAnswerLog {
225 async fn record(&self, _record: &AnswerRecord) -> Result<()> {
226 Ok(())
227 }
228
229 async fn find(&self, approval_id: &str) -> Result<Option<AnswerRecord>> {
230 self.scan(approval_id, None).await
231 }
232
233 async fn since(&self, at: DateTime<Utc>) -> Result<Vec<AnswerRecord>> {
234 self.scan_since(at).await
235 }
236
237 async fn find_for(&self, request: &ApprovalRequest) -> Result<Option<AnswerRecord>> {
238 if let Some(found) =
239 self.found.lock().unwrap_or_else(|e| e.into_inner()).get(&request.id).cloned()
240 {
241 return Ok(Some(found));
242 }
243 if self.absent.lock().unwrap_or_else(|e| e.into_inner()).contains(&request.id) {
244 return Ok(None);
245 }
246 let found = self.scan(&request.id, Some(request.created_at - CLOCK_SLACK)).await?;
247 match &found {
248 Some(answer) => {
249 let mut remembered = self.found.lock().unwrap_or_else(|e| e.into_inner());
250 if remembered.len() >= REMEMBERED {
251 remembered.clear();
252 }
253 remembered.insert(request.id.clone(), answer.clone());
254 }
255 None => {
256 let decided = request
257 .resolved_at
258 .or_else(|| request.decisions.last().map(|decision| decision.decided_at));
259 if request.state.is_terminal()
260 && decided.is_some_and(|at| at + RECORD_DELAY < Utc::now())
261 {
262 let mut remembered = self.absent.lock().unwrap_or_else(|e| e.into_inner());
263 if remembered.len() >= REMEMBERED {
264 remembered.clear();
265 }
266 remembered.insert(request.id.clone());
267 }
268 }
269 }
270 Ok(found)
271 }
272}
273
274pub(crate) fn answer_of(record: &AuditRecord, approval_id: &str) -> Option<AnswerRecord> {
276 if record.action != SURFACE_AUDIT_DECIDE {
277 return None;
278 }
279 let ext = &record.ext;
280 if ext.get("approvalId").and_then(|v| v.as_str()) != Some(approval_id)
281 || ext.get("outcome").and_then(|v| v.as_str()) != Some("decided")
282 {
283 return None;
284 }
285 let surface: SurfaceKind = serde_json::from_value(ext.get("surface")?.clone()).ok()?;
286 let origin: Origin = serde_json::from_value(ext.get("origin")?.clone()).ok()?;
287 let answer: Answer = serde_json::from_value(ext.get("answer")?.clone()).ok()?;
288 let by = record.actor.on_behalf_of.clone()?;
289 Some(AnswerRecord {
290 approval_id: approval_id.to_string(),
291 by,
292 via: Via { surface, origin },
293 answer,
294 at: record.ts,
295 })
296}
297
298pub const RECORD_LINES: usize = 500;
301
302#[derive(Clone)]
330pub struct RecordAnswerLog {
331 client: ControlClient,
332 given_here: InMemoryAnswerLog,
333}
334
335impl std::fmt::Debug for RecordAnswerLog {
336 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
337 f.debug_struct("RecordAnswerLog")
338 .field("endpoint", &self.client.endpoint())
339 .finish_non_exhaustive()
340 }
341}
342
343impl RecordAnswerLog {
344 pub fn new(client: ControlClient) -> Self {
346 Self { client, given_here: InMemoryAnswerLog::new() }
347 }
348}
349
350#[async_trait]
351impl AnswerLog for RecordAnswerLog {
352 async fn record(&self, record: &AnswerRecord) -> Result<()> {
353 self.given_here.record(record).await
354 }
355
356 async fn find(&self, approval_id: &str) -> Result<Option<AnswerRecord>> {
357 if let Some(found) = self.given_here.find(approval_id).await? {
358 return Ok(Some(found));
359 }
360 match self.client.record(Some(RECORD_LINES)).await {
361 Ok(lines) => Ok(lines.iter().find_map(|line| answer_of_line(line, approval_id))),
362 Err(error) => {
363 tracing::debug!(error = %error, "the kernel's record could not be read");
364 Ok(None)
365 }
366 }
367 }
368
369 async fn since(&self, at: DateTime<Utc>) -> Result<Vec<AnswerRecord>> {
370 let mut found: HashMap<String, AnswerRecord> = HashMap::new();
371 if let Ok(lines) = self.client.record(Some(RECORD_LINES)).await {
372 for line in lines.iter().filter(|line| line.at >= at) {
373 if let Some(answer) = line.target.as_deref().and_then(|id| answer_of_line(line, id))
374 {
375 found.insert(answer.approval_id.clone(), answer);
376 }
377 }
378 }
379 for answer in self.given_here.since(at).await? {
380 found.insert(answer.approval_id.clone(), answer);
381 }
382 let mut found: Vec<AnswerRecord> = found.into_values().collect();
383 found.sort_by_key(|record| record.at);
384 Ok(found)
385 }
386}
387
388#[derive(
391 Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
392)]
393#[serde(rename_all = "camelCase")]
394pub struct AnswerSummary {
395 pub since: DateTime<Utc>,
397 pub total: u32,
399 pub allowed_once: u32,
401 pub always_allowed: u32,
403 pub edited: u32,
405 pub denied: u32,
407 pub surfaces: Vec<SurfaceCount>,
409 pub text: String,
411}
412
413#[derive(
415 Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, schemars::JsonSchema,
416)]
417#[serde(rename_all = "camelCase")]
418pub struct SurfaceCount {
419 pub surface: SurfaceKind,
421 pub count: u32,
423}
424
425impl AnswerSummary {
426 pub fn of(since: DateTime<Utc>, records: &[AnswerRecord]) -> Self {
428 let count = |answer: Answer| {
429 u32::try_from(records.iter().filter(|record| record.answer == answer).count())
430 .unwrap_or(u32::MAX)
431 };
432 let mut surfaces: Vec<SurfaceCount> = Vec::new();
433 for record in records {
434 match surfaces.iter_mut().find(|entry| entry.surface == record.via.surface) {
435 Some(entry) => entry.count += 1,
436 None => surfaces.push(SurfaceCount { surface: record.via.surface, count: 1 }),
437 }
438 }
439 surfaces.sort_by_key(|entry| std::cmp::Reverse(entry.count));
440 let (allowed_once, always_allowed, edited, denied) = (
441 count(Answer::AllowOnce),
442 count(Answer::AlwaysAllow),
443 count(Answer::Edit),
444 count(Answer::Deny),
445 );
446 let total = u32::try_from(records.len()).unwrap_or(u32::MAX);
447 Self {
448 since,
449 total,
450 allowed_once,
451 always_allowed,
452 edited,
453 denied,
454 surfaces,
455 text: crate::words::answers_line(total, allowed_once, always_allowed, edited, denied),
456 }
457 }
458}
459
460pub(crate) fn answer_of_line(line: &RecordLine, approval_id: &str) -> Option<AnswerRecord> {
462 if line.action != SURFACE_AUDIT_DECIDE
463 || line.target.as_deref() != Some(approval_id)
464 || line.outcome.as_deref() != Some("decided")
465 {
466 return None;
467 }
468 let (surface, origin) = match line.how.as_deref()? {
469 "chat" => (
470 SurfaceKind::Chat,
471 Origin::Chat { channel: line.channel.clone().unwrap_or_else(|| "chat".into()) },
472 ),
473 "touch" => (SurfaceKind::Phone, Origin::Touch),
474 "pointer" => (SurfaceKind::Web, Origin::Pointer),
475 "keyboard" => (SurfaceKind::Terminal, Origin::Keyboard),
476 "voice" => (SurfaceKind::Voice, Origin::Voice),
477 _ => return None,
478 };
479 let answer = match line.decision.as_deref()? {
480 "approved" => Answer::AllowOnce,
481 "rejected" => Answer::Deny,
482 _ => return None,
483 };
484 Some(AnswerRecord {
485 approval_id: approval_id.to_string(),
486 by: SubjectRef::human(line.subject.clone()?),
487 via: Via { surface, origin },
488 answer,
489 at: line.at,
490 })
491}
492
493#[cfg(test)]
494mod tests {
495 use super::*;
496 use adk_core::audit_log::{
497 AuditActor, AuditAppend, AuditHash, AuditLogEntry, AuditRecordDraft, AuditRecordKind,
498 InMemoryAuditLogStore,
499 };
500 use serde_json::json;
501
502 fn entry(
503 seq: u64,
504 approval_id: &str,
505 outcome: &str,
506 origin: serde_json::Value,
507 ) -> AuditLogEntry {
508 let record = AuditRecordDraft::new(AuditRecordKind::Approval, SURFACE_AUDIT_DECIDE)
509 .actor(AuditActor::subject(SubjectRef::human("ana")))
510 .ext("approvalId", json!(approval_id))
511 .ext("outcome", json!(outcome))
512 .ext("answer", json!("allowOnce"))
513 .ext("surface", json!("chat"))
514 .ext("origin", origin)
515 .into_record("replica-1", seq, Utc::now(), None);
516 AuditLogEntry {
517 seq,
518 leaf_hash: AuditHash([seq as u8; 32]),
519 record: Some(serde_json::to_string(&record).unwrap()),
520 }
521 }
522
523 #[tokio::test]
524 async fn the_audit_log_says_how_a_decision_was_answered() {
525 let store = Arc::new(InMemoryAuditLogStore::new());
526 let telegram = json!({ "kind": "chat", "channel": "Telegram" });
527 store
528 .append(AuditAppend {
529 log_id: "replica-1".into(),
530 entries: vec![
531 entry(0, "apr_1", "decided", telegram.clone()),
532 entry(1, "apr_1", "already_decided", json!({ "kind": "pointer" })),
533 entry(2, "apr_2", "refused", telegram),
534 ],
535 nodes: vec![],
536 })
537 .await
538 .unwrap();
539 let log = AuditAnswerLog::new(store);
540 let found = log.find("apr_1").await.unwrap().unwrap();
541 assert_eq!(found.via.origin, Origin::Chat { channel: "Telegram".into() });
542 assert_eq!(found.by, SubjectRef::human("ana"));
543 assert_eq!(found.answer, Answer::AllowOnce);
544 assert!(log.find("apr_2").await.unwrap().is_none(), "a refused answer decided nothing");
545 }
546
547 #[tokio::test]
550 async fn the_audit_log_lists_the_answers_since_a_time() {
551 let store = Arc::new(InMemoryAuditLogStore::new());
552 let pointer = json!({ "kind": "pointer" });
553 store
554 .append(AuditAppend {
555 log_id: "replica-1".into(),
556 entries: vec![
557 entry(0, "apr_1", "decided", pointer.clone()),
558 entry(1, "apr_1", "already_decided", pointer.clone()),
559 entry(2, "apr_2", "refused", pointer.clone()),
560 entry(3, "apr_3", "decided", pointer),
561 ],
562 nodes: vec![],
563 })
564 .await
565 .unwrap();
566 let log = AuditAnswerLog::new(store);
567 let since = log.since(Utc::now() - chrono::Duration::hours(1)).await.unwrap();
568 assert_eq!(
569 since.iter().map(|answer| answer.approval_id.as_str()).collect::<Vec<_>>(),
570 ["apr_1", "apr_3"]
571 );
572 assert!(log.since(Utc::now() + chrono::Duration::hours(1)).await.unwrap().is_empty());
573 let memory = InMemoryAnswerLog::new();
574 for answer in &since {
575 memory.record(answer).await.unwrap();
576 }
577 assert_eq!(memory.since(Utc::now() - chrono::Duration::hours(1)).await.unwrap().len(), 2);
578 }
579
580 #[test]
584 fn a_record_line_says_how_a_decision_was_answered() {
585 let at = Utc::now();
586 let line = |id: &str, outcome: &str| {
587 RecordLine::new(7, at, SURFACE_AUDIT_DECIDE)
588 .with_subject("ana")
589 .with_decision("approved")
590 .with_outcome(outcome)
591 .with_how("chat", Some("Telegram"))
592 .with_target(id)
593 };
594 let found = answer_of_line(&line("apr_1", "decided"), "apr_1").unwrap();
595 assert_eq!(
596 found,
597 AnswerRecord {
598 approval_id: "apr_1".into(),
599 by: SubjectRef::human("ana"),
600 via: Via {
601 surface: SurfaceKind::Chat,
602 origin: Origin::Chat { channel: "Telegram".into() },
603 },
604 answer: Answer::AllowOnce,
605 at,
606 }
607 );
608 assert_eq!(found.via.phrase(), "in Telegram");
609 assert!(answer_of_line(&line("apr_1", "decided"), "apr_2").is_none());
610 assert!(answer_of_line(&line("apr_1", "refused"), "apr_1").is_none());
611 let control =
612 RecordLine::new(8, at, "kernel.control").with_subject("ana").with_target("apr_1");
613 assert!(answer_of_line(&control, "apr_1").is_none());
614 let touch = RecordLine::new(9, at, SURFACE_AUDIT_DECIDE)
615 .with_subject("ana")
616 .with_decision("rejected")
617 .with_outcome("decided")
618 .with_how("touch", None)
619 .with_target("apr_3");
620 let found = answer_of_line(&touch, "apr_3").unwrap();
621 assert_eq!((found.via.phrase(), found.answer), ("on your phone".to_string(), Answer::Deny));
622 }
623}