1use std::collections::BTreeMap;
17use std::sync::Arc;
18use std::sync::atomic::{AtomicU64, Ordering};
19
20use adk_auth::signed_audit::NoteVerifier;
21use adk_core::audit_log::{AuditActor, AuditRecorder, AuditTrail};
22use adk_core::principal::{SubjectKind, SubjectRef};
23use adk_core::{
24 ActingContext, AdkError, Clock, ErrorCategory, ErrorComponent, Result, SystemClock, ToolEffect,
25};
26use adk_harness::website::{LevelDecision, SITE_ROLLBACK, SiteRef, SiteRuntime, level_decision};
27use adk_kernel::charter::AutonomyLadder;
28use adk_site::host::SiteHost;
29use adk_site::migrate::claim::{DnsResolver, DomainClaim};
30use adk_site::migrate::http::HttpClient;
31use adk_site::migrate::probe::{Drift, DriftLocation, ProbeConfig, ProbeReport, Prober};
32use async_trait::async_trait;
33use awp_types::{AutonomyLevel, SiteState, Urgency};
34use chrono::{DateTime, Utc};
35use serde::{Deserialize, Serialize};
36use serde_json::json;
37use tokio::sync::Mutex;
38use uuid::Uuid;
39
40use crate::alarms::{Alarm, AlarmRouter};
41use crate::audit;
42
43pub const PROTECT_JOB: &str = "protect";
45
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
48#[serde(rename_all = "camelCase")]
49pub struct StatusRecord {
50 pub state: SiteState,
52 pub since: DateTime<Utc>,
54 pub reason: String,
56 #[serde(default, skip_serializing_if = "Option::is_none")]
58 pub release_seq: Option<u64>,
59}
60
61#[async_trait]
64pub trait StatusSink: Send + Sync {
65 async fn set(&self, site: Uuid, status: StatusRecord) -> Result<()>;
71
72 async fn get(&self, site: Uuid) -> Result<Option<StatusRecord>>;
78}
79
80#[derive(Debug, Default)]
82pub struct InMemoryStatusBoard {
83 statuses: Mutex<BTreeMap<Uuid, StatusRecord>>,
84}
85
86impl InMemoryStatusBoard {
87 pub fn new() -> Self {
89 Self::default()
90 }
91}
92
93#[async_trait]
94impl StatusSink for InMemoryStatusBoard {
95 async fn set(&self, site: Uuid, status: StatusRecord) -> Result<()> {
96 self.statuses.lock().await.insert(site, status);
97 Ok(())
98 }
99
100 async fn get(&self, site: Uuid) -> Result<Option<StatusRecord>> {
101 Ok(self.statuses.lock().await.get(&site).cloned())
102 }
103}
104
105#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
107#[serde(rename_all = "snake_case")]
108pub enum RollbackAuthority {
109 Standing,
111 Proposal,
113}
114
115#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
117#[serde(rename_all = "camelCase")]
118pub struct RollbackPlan {
119 pub to_release: u64,
121 pub authority: RollbackAuthority,
123 #[serde(default, skip_serializing_if = "Option::is_none")]
125 pub done: Option<u64>,
126}
127
128#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130#[serde(rename_all = "camelCase")]
131pub struct IncidentExit {
132 pub by: String,
134 pub decision: String,
136 pub at: DateTime<Utc>,
138}
139
140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142#[serde(rename_all = "camelCase")]
143pub struct Incident {
144 pub id: String,
146 pub site: Uuid,
148 pub opened_at: DateTime<Utc>,
150 pub drift: Vec<Drift>,
152 pub rollback: RollbackPlan,
154 #[serde(default, skip_serializing_if = "Option::is_none")]
156 pub area: Option<String>,
157 #[serde(default, skip_serializing_if = "Vec::is_empty")]
159 pub demoted: Vec<String>,
160 pub alarm: String,
162 #[serde(default, skip_serializing_if = "Option::is_none")]
164 pub closed: Option<IncidentExit>,
165}
166
167impl Incident {
168 pub fn guardian_turn(&self) -> String {
171 let paths: Vec<&str> = self.drift.iter().map(|d| d.path.as_str()).collect();
172 let act = match self.rollback.authority {
173 RollbackAuthority::Standing => format!(
174 "Roll the site back to signed release {} with site_rollback now.",
175 self.rollback.to_release
176 ),
177 RollbackAuthority::Proposal => format!(
178 "Your authority does not let you roll back alone: call site_rollback to \
179 release {} so the owner decides it, and say so in one sentence.",
180 self.rollback.to_release
181 ),
182 };
183 format!(
184 "Incident {}: {} served file(s) match no signed release ({}). {act} Then report \
185 what you did. The incident stays open until a person closes it.",
186 self.id,
187 paths.len(),
188 paths.join(", ")
189 )
190 }
191}
192
193pub struct IncidentPath {
195 site: SiteRef,
196 runtime: Arc<SiteRuntime>,
197 ladder: AutonomyLadder,
198 alarms: Arc<AlarmRouter>,
199 status: Arc<dyn StatusSink>,
200 clock: Arc<dyn Clock>,
201 audit: Option<AuditTrail>,
202 incidents: Mutex<BTreeMap<String, Incident>>,
203 tainted: Mutex<std::collections::BTreeSet<u64>>,
204 next: AtomicU64,
205}
206
207impl std::fmt::Debug for IncidentPath {
208 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
209 f.debug_struct("IncidentPath").field("site", &self.site).finish_non_exhaustive()
210 }
211}
212
213fn not_a_person(by: &SubjectRef) -> bool {
214 by.kind != SubjectKind::Human || adk_kernel::charter::is_agent_principal(&by.id)
215}
216
217impl IncidentPath {
218 pub fn new(
221 runtime: Arc<SiteRuntime>,
222 ladder: AutonomyLadder,
223 alarms: Arc<AlarmRouter>,
224 status: Arc<dyn StatusSink>,
225 ) -> Self {
226 Self {
227 site: runtime.site().clone(),
228 runtime,
229 ladder,
230 alarms,
231 status,
232 clock: Arc::new(SystemClock),
233 audit: None,
234 incidents: Mutex::new(BTreeMap::new()),
235 tainted: Mutex::new(std::collections::BTreeSet::new()),
236 next: AtomicU64::new(1),
237 }
238 }
239
240 #[must_use]
242 pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Self {
243 self.clock = clock;
244 self
245 }
246
247 #[must_use]
249 pub fn with_audit(mut self, trail: AuditTrail) -> Self {
250 self.audit = Some(trail);
251 self
252 }
253
254 pub async fn rollback_authority(&self) -> Result<RollbackAuthority> {
261 let level = self
262 .ladder
263 .level(self.site.id, PROTECT_JOB)
264 .await
265 .map_err(|e| AdkError::config(e.to_string()))?
266 .unwrap_or(AutonomyLevel::Propose);
267 let spec = adk_harness::website::spec(SITE_ROLLBACK);
268 Ok(match level_decision(level, spec, ToolEffect::NonIdempotent) {
269 LevelDecision::Allow => RollbackAuthority::Standing,
270 _ => RollbackAuthority::Proposal,
271 })
272 }
273
274 async fn set_status(&self, state: SiteState, reason: &str, release: Option<u64>) -> Result<()> {
275 let record = StatusRecord {
276 state,
277 since: self.clock.now(),
278 reason: reason.to_string(),
279 release_seq: release,
280 };
281 self.status.set(self.site.id, record).await?;
282 tracing::info!(site.state = ?state, reason, "site.status.changed");
283 audit::record(
284 self.audit.as_ref(),
285 audit::STATUS_CHANGED,
286 AuditActor::default(),
287 json!({ "site": self.site.id, "state": state, "reason": reason, "releaseSeq": release }),
288 )
289 .await;
290 Ok(())
291 }
292
293 pub async fn on_probe(&self, report: &ProbeReport) -> Result<Option<Incident>> {
304 if !report.drift_detected() {
305 return Ok(None);
306 }
307 if let Some(open) =
308 self.incidents.lock().await.values_mut().find(|incident| incident.closed.is_none())
309 {
310 open.drift.extend(report.drift.iter().cloned());
311 return Ok(Some(open.clone()));
312 }
313 let previous = self.runtime.pipeline().previous().await.map(|p| p.manifest.seq);
314 let Some(current) = report.checkpoint.or(previous) else {
315 return Err(AdkError::new(
316 ErrorComponent::Tool,
317 ErrorCategory::NotFound,
318 "website.incident.no_release",
319 "drift was found but no signed release is known to roll back to",
320 ));
321 };
322 let on_host = report.drift.iter().any(|drift| drift.location == DriftLocation::Host);
323 let to_release = {
324 let mut tainted = self.tainted.lock().await;
325 if on_host {
326 tainted.insert(current);
327 }
328 (1..=current).rev().find(|seq| !tainted.contains(seq)).unwrap_or(current)
329 };
330 self.open(report.drift.clone(), to_release, None).await.map(Some)
331 }
332
333 #[tracing::instrument(skip_all, name = "website.job.protect", fields(website.incident = tracing::field::Empty, site.id = %self.site.id))]
340 pub async fn open(
341 &self,
342 drift: Vec<Drift>,
343 to_release: u64,
344 area: Option<&str>,
345 ) -> Result<Incident> {
346 let id = format!("incident-{}", self.next.fetch_add(1, Ordering::Relaxed));
347 tracing::Span::current().record("website.incident", id.as_str());
348 self.set_status(SiteState::Incident, "drift_detected", Some(to_release)).await?;
349 let demoted = match area {
350 Some(area) => self
351 .ladder
352 .incident(self.site.id, area, &id)
353 .await
354 .map_err(|e| AdkError::config(e.to_string()))?
355 .into_iter()
356 .map(|job| job.job)
357 .collect(),
358 None => Vec::new(),
359 };
360 let authority = self.rollback_authority().await?;
361 let act = match authority {
362 RollbackAuthority::Standing => format!("rolling back to signed release {to_release}"),
363 RollbackAuthority::Proposal => {
364 format!("approve rolling back to signed release {to_release}")
365 }
366 };
367 let now = self.clock.now();
368 let mut alarm = Alarm::new(
369 self.site.id,
370 Urgency::P1,
371 "incident",
372 format!(
373 "Incident {id}: {} file(s) on {} match no signed release; {act}.",
374 drift.len(),
375 self.site.origin
376 ),
377 now,
378 );
379 alarm.id = format!("{id}-alarm");
380 self.alarms.raise(alarm.clone()).await;
381 let incident = Incident {
382 id: id.clone(),
383 site: self.site.id,
384 opened_at: now,
385 drift,
386 rollback: RollbackPlan { to_release, authority, done: None },
387 area: area.map(str::to_string),
388 demoted,
389 alarm: alarm.id,
390 closed: None,
391 };
392 self.incidents.lock().await.insert(id, incident.clone());
393 Ok(incident)
394 }
395
396 pub async fn rolled_back(&self, id: &str, served: u64) -> Result<Incident> {
403 let mut incidents = self.incidents.lock().await;
404 let incident = incidents.get_mut(id).ok_or_else(|| unknown(id))?;
405 incident.rollback.done = Some(served);
406 audit::record(
407 self.audit.as_ref(),
408 audit::ROLLBACK,
409 AuditActor::default(),
410 json!({ "site": self.site.id, "incident": id, "toRelease": incident.rollback.to_release, "releaseSeq": served }),
411 )
412 .await;
413 Ok(incident.clone())
414 }
415
416 pub async fn approve_rollback(&self, id: &str, by: &SubjectRef) -> Result<Incident> {
425 if not_a_person(by) {
426 return Err(forbidden(by, "approves a rollback"));
427 }
428 let planned = {
429 let incidents = self.incidents.lock().await;
430 incidents.get(id).ok_or_else(|| unknown(id))?.rollback.to_release
431 };
432 let mut failure = None;
433 for to in (1..=planned).rev() {
434 match self.runtime.pipeline().rollback(to).await {
435 Ok(published) => return self.rolled_back(id, published.staged.manifest.seq).await,
436 Err(error) => {
437 tracing::warn!(website.incident = id, to_release = to, error = %error, "release does not restore; trying the one before");
438 failure = Some(error);
439 }
440 }
441 }
442 Err(AdkError::new(
443 ErrorComponent::Tool,
444 ErrorCategory::Internal,
445 "website.incident.rollback",
446 format!(
447 "no signed release up to {planned} restores exactly: {}",
448 failure.map(|e| e.to_string()).unwrap_or_default()
449 ),
450 ))
451 }
452
453 pub async fn close(&self, id: &str, by: &SubjectRef, decision: &str) -> Result<Incident> {
461 if not_a_person(by) {
462 return Err(forbidden(by, "closes an incident"));
463 }
464 let (incident, served) = {
465 let mut incidents = self.incidents.lock().await;
466 let incident = incidents.get_mut(id).ok_or_else(|| unknown(id))?;
467 incident.closed = Some(IncidentExit {
468 by: by.id.clone(),
469 decision: decision.to_string(),
470 at: self.clock.now(),
471 });
472 let served = incident.rollback.done.unwrap_or(incident.rollback.to_release);
473 (incident.clone(), served)
474 };
475 if let Err(error) = self.alarms.acknowledge(&incident.alarm, by).await {
476 tracing::debug!(error = %error, "the incident's alarm was already acknowledged");
477 }
478 self.set_status(SiteState::Operational, "incident_closed", Some(served)).await?;
479 Ok(incident)
480 }
481
482 pub async fn incidents(&self) -> Vec<Incident> {
484 self.incidents.lock().await.values().cloned().collect()
485 }
486
487 pub async fn open_incident(&self) -> Option<Incident> {
489 self.incidents.lock().await.values().find(|i| i.closed.is_none()).cloned()
490 }
491}
492
493fn unknown(id: &str) -> AdkError {
494 AdkError::new(
495 ErrorComponent::Tool,
496 ErrorCategory::NotFound,
497 "website.incident.unknown",
498 format!("no incident {id}"),
499 )
500}
501
502fn forbidden(by: &SubjectRef, act: &str) -> AdkError {
503 AdkError::new(
504 ErrorComponent::Tool,
505 ErrorCategory::Forbidden,
506 "website.incident.not_a_person",
507 format!("{} is not a person; only a person {act} (spec 3.5 §7.20)", by.id),
508 )
509}
510
511pub struct GuardianProbe {
515 pub claim: DomainClaim,
517 pub resolver: Arc<dyn DnsResolver>,
519 pub host: Arc<dyn SiteHost>,
521 pub http: Arc<HttpClient>,
523 pub trusted: Vec<NoteVerifier>,
525 pub config: ProbeConfig,
527 pub audit: Option<(Arc<dyn AuditRecorder>, ActingContext)>,
529 pub incidents: Arc<IncidentPath>,
531}
532
533#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
535#[serde(rename_all = "camelCase")]
536pub struct ProbeOutcome {
537 pub report: ProbeReport,
539 #[serde(default, skip_serializing_if = "Option::is_none")]
541 pub incident: Option<Incident>,
542}
543
544impl GuardianProbe {
545 #[tracing::instrument(skip_all, name = "site.probe", fields(site.domain = %self.config.domain))]
552 pub async fn run(&self) -> Result<ProbeOutcome> {
553 let migrate = |e: adk_site::migrate::MigrateError| AdkError::config(e.to_string());
554 let proven =
555 self.claim.verify_dns(self.resolver.as_ref(), Utc::now()).await.map_err(migrate)?;
556 let mut prober = Prober::new(
557 self.host.clone(),
558 self.http.clone(),
559 self.resolver.clone(),
560 self.trusted.clone(),
561 &proven,
562 self.config.clone(),
563 )
564 .map_err(migrate)?;
565 if let Some((recorder, acting)) = &self.audit {
566 prober = prober.with_audit(recorder.clone(), acting.clone());
567 }
568 let report = prober.probe().await.map_err(migrate)?;
569 let incident = self.incidents.on_probe(&report).await?;
570 Ok(ProbeOutcome { report, incident })
571 }
572}